diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b2f8295e70..0eb14d96f0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -9,15 +9,42 @@ on: jobs: build: - runs-on: ubuntu-latest + runs-on: ubuntu-latest-8-cores steps: # Checkout the code - uses: actions/checkout@v2 # Setup node with version 12.x and NPM registry url - - uses: actions/setup-node@v1 + - uses: actions/setup-node@v3 with: node-version: "16.14.1" + cache: 'npm' + # Cache Docusaurus artifacts for faster build times + - name: Cache Docusaurus artifacts + id: cache-docusaurus + uses: actions/cache@v3 + with: + key: ${{ runner.os }}-build-docusaurus + path: | + .docusaurus + build + - if: ${{ steps.cache-docusaurus.outputs.cache-hit != 'true' }} + name: State of Docusaurus cache + continue-on-error: true + run: echo "Docusaurus cache miss, resulting build will be slower" + # Cache node_modules for faster build times + - name: Cache node_modules + id: cache-node-modules + env: + cache-name: cache-node-modules + uses: actions/cache@v3 + with: + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/yarn.lock') }} + path: node_modules + - if: ${{ steps.cache-node-modules.outputs.cache-hit != 'true' }} + name: State of node_modules cache + continue-on-error: true + run: echo "Package dependencies changed, unable to use node_modules cache" # Run npm install to install project packages - run: yarn install --frozen-lockfile # npm run build to build the project diff --git a/CONTENT_DISCLAIMER.md b/CONTENT_DISCLAIMER.md new file mode 100644 index 0000000000..e3d20ca22b --- /dev/null +++ b/CONTENT_DISCLAIMER.md @@ -0,0 +1,7 @@ +## Third-Party Content Disclaimer + +The Polygon Wiki contains third-party content, including websites, products, and services, for informational purposes only. + +Polygon Labs does not endorse, warrant, or make any representations regarding the accuracy, quality, reliability, or legality of any third-party products, services, or websites. + +The Polygon Wiki serves as an industry public good and is made available under the [MIT open source license](LICENSE). However, the Wiki maintainers reserve the right to deny any content about third-party applications, products, or services that is deemed inappropriate or potentially fraudulent. While the maintainers make efforts to ensure the accuracy and reliability of information presented in the Wiki, users are advised to exercise their own discretion and conduct their own due diligence before making any decisions based on information obtained from third-party content on the Wiki. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000..45fb445953 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Polygon Wiki + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index d9265ac6ed..1a78c66668 100755 --- a/README.md +++ b/README.md @@ -1,189 +1,7 @@ -

- -

+## Archiving Repository -
-

Polygon Wiki

-

Previously Matic Network

-
+Polygon Wiki is moved from `matic-docs` to the new `wiki` repo under Polygon organization. You can check out the new repository [here](https://github.com/0xPolygon/wiki). -
+We recommend contributors to migrate their forks and ⭐️ the new repository. For instructions on how to contribute to the `wiki` repo, check out the [README](https://github.com/0xPolygon/wiki/blob/main/README.md) file. -

- - - - src="https://img.shields.io/github/issues/maticnetwork/matic-docs"> - - - - - - -

- -Polygon is a scaling solution for public blockchains that combines the best of Ethereum and sovereign blockchains -to offer a full-stack scaling solution. - -The [Polygon Wiki](https://wiki.polygon.technology/) is built using [Docusaurus](https://docusaurus.io/), -a modern static website generator to build optimized websites quickly. - -## How to Contribute to Polygon Wiki - -We believe one of the things that makes Polygon unique is its coherent design, and we seek to retain this defining -characteristic. We have defined some guidelines to ensure new contributions only ever enhance the -Wiki from the outset. - -### Requirements - -* Install [Node.js](https://nodejs.org/en/download/) version >= 12.13 -* Install [Yarn](https://yarnpkg.com/getting-started/install) version >= 1.5 - -> Note that on macOS you also need Xcode and Command Line Tools. - -### Run the Wiki locally - -1. Fork the repo. - > For help, refer to [GitHub Docs: Fork a repo](https://help.github.com/en/articles/fork-a-repo). - -2. Clone your forked repo. - - ``` - git clone git@github.com:[your_github_handle]/matic-docs - ``` - -3. Navigate into the cloned folder. - - ``` - cd matic-docs - ``` - -4. Link your cloned repo to the upstream repo. - > For help, see [GitHub Docs: Configuring a remote for a fork](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/configuring-a-remote-for-a-fork). - - ``` - git remote add upstream https://github.com/maticnetwork/matic-docs - ``` - -5. If you have already cloned the repository, be sure to sync your fork with the latest changes. - > For help, refer to [GitHub Docs: Syncing a fork](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/syncing-a-fork). - - ``` - git checkout master - git fetch upstream - git merge upstream/master - ``` - -6. Install the dependencies. - - ``` - yarn install - ``` - - The site is built using Docusaurus. You may need to install Docusaurus before running the Wiki locally. - - ``` - yarn add docusaurus - ``` - - Alternatively, you can upgrade Docusaurus. - - ``` - yarn upgrade @docusaurus/core@latest @docusaurus/preset-classic@latest - ``` - -7. Run the Wiki locally. - The following command will start a local development server and open a browser window. - Most changes are reflected live without having to restart the server. - - ``` - yarn start - ``` - -### Make changes using Git GUI and code editor - -After running the Wiki locally on your machine, use a code editor to apply your changes before submitting -your PR. Note that you must have a GitHub account and an understanding of Markdown syntax. - -1. Create a new branch for your changes. - - ``` - git checkout -b [new_branch_name] - ``` - -2. Commit your changes. Please be sure to review our [Git Rules](https://wiki.polygon.technology/docs/contribute/orientation#git-rules). - In the commit message, please reference the issue it resolves. - For help, see [GitHub Docs: Linking a pull request to an issue using a keyword](https://docs.github.com/en/free-pro-team@latest/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword). - - ``` - git commit -m "brief description of changes [Fixes #1234]" - ``` - -3. Push to your forked repository. - - ``` - git push - ``` - -4. Submit a PR against the `master` branch of the `maticnetwork/matic-docs` repo - -5. Add a title to your PR. - > For example, if you want to suggest edits to the "Getting Started" page, name your PR: *Update /docs/develop/getting-started.md*. - -6. Add a description to your PR. Please reference the issue it resolves. - > For help, see [GitHub Docs: Linking a pull request to an issue using a keyword](https://docs.github.com/en/free-pro-team@latest/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword). - -7. Write a brief description of the changes you have made. If possible, include screenshots and references. - -You can apply UI changes, sidebar, and configuration design through the following files: - -- To modify the **Sidebar** navigation, edit **sidebars.js** -- To modify the website page layout, edit **docusaurus.config.js** -- To modify the blocks structure and the footer links, edit **src/pages/index.js** - -### Making changes using the Wiki website - -You can easily submit an edit suggestion. Note that you must have a GitHub account and good knowledge of Markdown syntax. - -1. Navigate to the [Polygon Wiki page](https://wiki.polygon.technology/) that you want to edit. -2. Scroll down until the end of that page -3. Click on the link: **Edit this page**. It will forward you to the same page (Markdown format) hosted on GitHub. -4. On the related GitHub page, click the pencil icon (similar to ) near the upper right corner of the file -5. Apply your edits by modifying the Markdown file -6. After you finish, scroll down until the end of that page to create a pull request -7. Add a title to your PR. For example, if you want to suggest edits to the "Getting Started" page, name your PR: - *Update /docs/develop/getting-started.md*. -8. Add a description to your PR. Please reference the issue it resolves. - > For help, see [GitHub Docs: Linking a pull request to an issue using a keyword](https://docs.github.com/en/free-pro-team@latest/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword). -9. Write a brief description of the changes you have made. If possible, include screenshots and references. -10. Click on the green button **Propose changes** to submit your changes. Note that submitting a change will write - it to a new branch in your fork. - -One of the Wiki maintainers will review your PR and either accept it or submit our review. -Acceptable PRs will be approved & merged into the `master` branch. - -## Submit an Issue - -- Create a [new issue](https://github.com/maticnetwork/matic-docs/issues/new/choose) to report a bug, request a feature, - or suggest changes. -- Comment on the issue if you want to be assigned to it so [our team can assign the issue to you](https://github.blog/2019-06-25-assign-issues-to-issue-commenters/). -- If you do not have a specific contribution in mind, you can also browse current issues. -- Issues that additionally have the `good first issue` label are considered ideal for first-timers. - -## Build - -This command generates static content into the `build` directory and can be served using any static content hosting -service: - -``` -yarn build -``` - -## Deployment - -If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the -`gh-pages` branch. - -``` -GIT_USER=[your_github_handle] USE_SSH=true yarn deploy -``` +`matic-docs` will remain available as a read-only repository. \ No newline at end of file diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000000..d8e87e74ee --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,17 @@ +# Polygon Technology Security Information + +## Link to vulnerability disclosure details (Bug Bounty). +- Websites and Applications: https://hackerone.com/polygon-technology +- Smart Contracts: https://immunefi.com/bounty/polygon + +## Languages that our team speaks and understands. +Preferred-Languages: en + +## Security-related job openings at Polygon. +https://polygon.technology/careers + +## Polygon security contact details. +security@polygon.technology + +## The URL for accessing the security.txt file. +Canonical: https://polygon.technology/security.txt diff --git a/archive/edge/README.md b/archive/edge/README.md new file mode 100644 index 0000000000..6f1c8b4332 --- /dev/null +++ b/archive/edge/README.md @@ -0,0 +1,7 @@ +# [ARCHIVED] Polygon Edge documentation + +We would like to inform you that the Polygon Edge documentation (for version 0.6.2 and earlier) has been archived and will no longer be maintained. Please note that the new Polygon Supernets documentation will only document the latest version of the Edge client, starting from version 0.7.x where the beta version of Supernets was first introduced. + +The Polygon Labs developer team has been hard at work gathering and incorporating community feedback into Polygon Supernets, and we highly recommend that you refer to the new documentation to ensure you have access to the most up-to-date information and features. + +Please note that the repository for older versions of the Polygon Edge (version 0.6.2 and earlier) will continue to exist, and users will have the ability to fork and do as they please, subject to applicable open-source license terms. diff --git a/archive/edge/bn-edge/additional-features/blockscout.md b/archive/edge/bn-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..88ba9c371d --- /dev/null +++ b/archive/edge/bn-edge/additional-features/blockscout.md @@ -0,0 +1,397 @@ +--- +id: blockscout +title: BlockScout +description: Polygon Edge-এর সাথে কাজ করার জন্য একটি BlockScout ইনস্ট্যান্স কীভাবে সেট আপ করবেন। +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## সংক্ষিপ্ত বিবরণ {#overview} +Polygon-Edge-এর সাথে কাজ করার জন্য BlockScout ইনস্ট্যান্স কীভাবে কম্পাইল ও ডিপ্লয় করতে হয় তা বিস্তারিতভাবে এই নির্দেশিকাটিতে বর্ণনা করা হয়েছে। BlockScout-এর নিজস্ব [ডকুমেন্টেশন](https://docs.blockscout.com/for-developers/manual-deployment) আছে, কিন্তু এই নির্দেশিকাটিতে BlockScout ইনস্ট্যান্স কিভাবে সেটআপ করতে হয় সে সম্পর্কে সহজ কিন্তু ধাপে-ধাপে বিস্তারিতভাবে বর্ণনা করা হয়েছে। + +## এনভায়রনমেন্ট {#environment} +* অপারেটিং সিস্টেম: Ubuntu Server 20.04 LTS সুডো পারমিশন সহ [ডাউনলোড লিঙ্ক](https://releases.ubuntu.com/20.04/) +* সার্ভার হার্ডওয়্যার: 8CPU / 16GB RAM / 50GB HDD (LVM) +* ডাটাবেস সার্ভার: 2 CPU / 4GB RAM / 100GB SSD / PostgreSQL 13.4 সহ ডেডিকেটেড সার্ভার + +### DB সার্ভার {#db-server} +এই নির্দেশিকা অনুসরণ করার প্রয়োজনীয়তা হচ্ছে একটি ডাটাবেস সার্ভার, ডাটাবেস এবং DB ব্যবহারকারী কনফিগার করা থাকতে হবে। PostgreSQL সার্ভার কীভাবে ডিপ্লয় এবং কনফিগার করতে হবে সে সম্পর্কে এই নির্দেশিকাটিতে বিস্তারিতভাবে বর্ণনা করা হবে না। +এ কাজ কিভাবে করতে হয়, তার জন্য অনেক গাইড আছে, উদাহরণস্বরূপ, [DigitalOcean Guide](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart) + +:::info সতর্কবার্তা +এই গাইডটি আপনাকে একটি ইন্সট্যান্সে কীভাবে BlockScout স্থাপন করা এবং চালাতে হয়, তা নিয়ে সাহায্য করে, যা মোটেই একটি আদর্শ সেটাপ নয়। প্রোডাকশনের জন্য, আপনার সম্ভবত আর্কিটেকচারে রিভার্স্‌ প্রক্সি, লোড ব্যালেন্সার, স্কেলেবিলিটি অপশন ইত্যাদি নিয়ে আসা উচিৎ। +::: + +# BlackScout ডিপ্লয়মেন্ট প্রক্রিয়া {#blockscout-deployment-procedure} + +## পার্ট 1 - ডিপেন্ডেন্সি ইনস্টল করুন {#part-1-install-dependencies} +আমরা শুরু করার আগে, BlockScout যেসমস্ত বাইনারির উপর নির্ভরশীল, সেসব ইন্সটল করা আছে কি না তা নিশ্চিত করতে হবে। + +### সিস্টেম আপডেট এবং আপগ্রেড করুন {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### erlang repos যোগ করুন {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### NodeJS repo যোগ করুন {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### Rust ইনস্টল করুন {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### Erlang এর প্রয়োজনীয় সংস্করণ ইনস্টল করুন {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### Elixir এর প্রয়োজনীয় সংস্করণ ইনস্টল করুন {#install-required-version-of-elixir} +Elixir এর সংস্করণ অবশ্যই `1.13`হতে হবে। আমরা যদি অফিশিয়াল repo থেকে এই সংস্করণ ইন্সটল করার চেষ্টা করি, তাহলে `erlang` `Erlang/OTP 25`-এ আপডেট হয়ে যাবে, তবে আমরা সেটি চাই না। +এই কারণবশত, আমাদের GitHub রিলিজেস পেইজ থেকে নির্দিষ্ট precompiled `elixir`সংস্করণটি ইনস্টল করতে হবে। + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +এখন আমাদেরকে`exlixir` সিস্টেম বাইনারি সঠিকভাবে ইন্সটল করতে হবে। +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +`elixir`এবং `erlang`সঠিকভাবে ইন্সটল করা কি না তা যাচাই করুন`elixir -v`। আউটপুটটি নিচের মত হওয়া উচিত: +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning +`Erlang/OTP`-এর ভার্সন অবশ্যই `24` এবং `Elixir`-এর ভার্সন `1.13.*` হতে হবে। যদি তা না হয়ে থাকে, তাহলে আপনি BlockScout চালানোর সময়ে এবং/অথবা কম্পাইল করার সময়ে সমস্যার সম্মুখীন হতে পারেন। + +::: +:::info + +অফিশিয়াল ***[BlockScout-এর প্রয়োজনীয়তার পৃষ্ঠাটি](https://docs.blockscout.com/for-developers/information-and-settings/requirements)*** দেখুন + +::: + +### NodeJS ইনস্টল করুন {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### Cargo ইনস্টল করুন {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### অন্যান্য ডিপেন্ডেন্সি ইনস্টল করুন {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### আপনি চাইলে আপনার DB কানেকশন দেখতে postgresql ক্লায়েন্ট ইন্সটল করতে পারেন {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## পার্ট 2 - এনভায়রনমেন্ট ভেরিয়েবল সেট করুন {#part-2-set-environment-variables} +BlockScout কম্পাইলেশন শুরু করার পূর্বে, আমাদের এনভায়রনমেন্ট ভ্যারিয়েবল সেট করতে হবে। এই নির্দেশিকাতে, আমরা শুধু কাজ করার মতো ন্যূনতম বিষয়গুলোই সেট করব। +ভেরিয়েবল সম্পূর্ণ তালিকা যা আপনি খুঁজে পেতে পারেন [এখানে](https://docs.blockscout.com/for-developers/information-and-settings/env-variables) + +### ডাটাবেস সংযোগকে এনভায়রনমেন্ট ভ্যারিয়েবল হিসেবে সেট করুন {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +এখন প্রদত্ত প্যারামিটারের সাথে আপনার DB কানেকশন পরীক্ষা করুন। যেহেতু আপনি PG env vars প্রদান করেছেন, আপনি ডাটাবেসের সাথে সংযোগ করতে পারবেন শুধুমাত্র এগুলো রান করেঃ +```bash +psql +``` + +ডাটাবেসটি সঠিকভাবে কনফিগার করা হলে, আপনার এই psql promt-টি দেখতে পাওয়া উচিৎঃ +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +অন্যথায়, আপনি নিচের মত একটি ত্রুটি দেখতে পারেন: +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +যদি এটি হয়ে থাকে, তাহলে [এসকল ডক](https://ubuntu.com/server/docs/databases-postgresql) আপনাকে সাহায্য করতে পারে। + +:::info DB কানেকশন + +পরবর্তী অংশে যাওয়ার আগে নিশ্চিত হয়ে নিন যে, আপনি DB কানেকশনের সাথে সম্পর্কিত সকল সমস্যার সমাধান করেছেন৷ +আপনাকে BlockScout ব্যবহারকারীকে সুপার ইউজার সুবিধা প্রদান করতে হবে। + +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## পার্ট 3 - BlockScout ক্লোন এবং কম্পাইল {#part-3-clone-and-compile-blockscout} +অবশেষে আমরা BlockScout ইন্সটলেশনের কাজ শুরু করতে পারবো। + +### BlockScout রেপো ক্লোন করুন {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### প্রোডাকশন বিল্ড রক্ষা করতে গোপন কী বেস তৈরি করুন {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +সর্বশেষ লাইনে, আপনি কিছু এলোমেলো অক্ষরের একটি দীর্ঘ স্ট্রিং দেখতে পাবেন। +পরবর্তী ধাপের পূর্বে, এটা আপনার `SECRET_KEY_BASE`এনভায়রনমেন্ট ভ্যারিয়েবল হিসাবে সেট হওয়া উচিৎ। উদাহরণস্বরূপ: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### প্রোডাকশন মোড সেট করুন {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### কম্পাইল করুন {#compile} +ক্লোন ডিরেক্টরিতে Cd করুন এবং কম্পাইল করা শুরু করুন + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info +আপনি যদি আগে ডিপ্লয় করে থাকেন, তাহলে পূর্বের বিল্ড থেকে স্ট্যাটিক অ্যাসেটসমূহ মুছে ফেলুন ***mix phx.digest.clean*** +::: + +### ডাটাবেস মাইগ্রেট করুন {#migrate-databases} +:::info + +আপনি আপনার DB কানেকশনটি সঠিকভাবে সেটআপ করে না করে থাকলে এই অংশটি ফেইল করবে, কারণ হয়তো আপনি প্যারামিটার প্রদান করেননি +অথবা আপনি DATABASE_URL এনভায়রনমেন্ট ভ্যারিয়েবলে ভুল প্যারামিটার দিয়েছেন। ডাটাবেস ব্যবহারকারীর সুপারইউজার সুবিধা থাকতে হবে। +::: +```bash +mix do ecto.create, ecto.migrate +``` + +যদি আপনাকে প্রথমে ডাটাবেস ড্রপ করতে হয়, তাহলে রান করুন, +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### npm dependencies ইনস্টল করুন এবং ফ্রন্টএন্ড অ্যাসেট কম্পাইল করুন {#install-npm-dependencies-and-compile-frontend-assets} +আপনাকে ডিরেক্টরিটিকে ফোল্ডার পরিবর্তন করতে হবে, যাতে ফ্রন্টএন্ড অ্যাসেট থাকে। + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info ধৈর্য ধরুন + +এসব অ্যাসেট কম্পাইলেশনে কয়েক মিনিট সময় লাগতে পারে এবং এটি কোন আউটপুট প্রদর্শন করবে না। +এটা দেখে মনে হতে পারে যে প্রক্রিয়াটি থেমে আছে, কিন্তু ধৈর্য ধরুন। কম্পাইল প্রক্রিয়া শেষ হলে আউটপুট দেখতে কিছুটা এরকম হতে পারে: `webpack 5.69.1 compiled with 3 warnings in 104942 ms` + +::: + +### স্ট্যাটিক অ্যাসেট তৈরি করুন {#build-static-assets} +এই ধাপের জন্য আপনাকে আপনার BlockScout ক্লোন ফোল্ডারের রুটে ফিরতে হবে। +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### স্ব-স্বাক্ষরিত সার্টিফিকেট তৈরি করুন {#generate-self-signed-certificates} +:::info + +আপনি যদি `https` ব্যবহার না করেন, তবে আপনি এই ধাপটি এড়িয়ে যেতে পারেন। + +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## পার্ট 4 - BlockScout সার্ভিস তৈরি এবং রান করুন {#part-4-create-and-run-blockscout-service} +এই অংশে আমাদের একটি সিস্টেম সার্ভিস সেট আপ করতে হবে কারণ আমরা চাই যে BlockScout ব্যাকগ্রাউন্ডে চলুক এবং সিস্টেম রিবুট করার পরে অব্যাহত থাকুক। + +### সার্ভিস ফাইল তৈরি করুন {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### সার্ভিস ফাইল এডিট করুন {#edit-service-file} +এই ফাইলটি সম্পাদনা করতে এবং সার্ভিসটি কনফিগার করতে আপনার পছন্দের Linux টেক্সট এডিটর ব্যবহার করুন৷ +```bash +sudo vi /etc/systemd/system/explorer.service +``` +explorer.service ফাইলের বিষয়বস্তু দেখতে এরকম হবে: +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### সিস্টেম বুটে সার্ভিস শুরু হওয়া এনেবল করুন। {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### আপনার BlockScout ক্লোন ফোল্ডারটি system-wide স্থানে সরান {#move-your-blockscout-clone-folder-to-system-wide-location} +আপনি BlockScout রেপো থেকে যে ফোল্ডারটি ক্লোন করেছেন এবং সমস্ত অ্যাসেট কম্পাইল করেছেন তাতে BlockScout সার্ভিসের অ্যাক্সেস থাকতে হবে। +```bash +sudo mv ~/blockscout /usr/local +``` + +### env vars ফাইল তৈরি করুন যা BlockScout সার্ভিসের দ্বারা ব্যবহার করা হবে {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info +`SECRET_KEY_BASE` ব্যবহার করুন যা আপনি পার্ট 3-তে তৈরি করেছেন। +::: +ফাইলটি সংরক্ষণ করুন এবং প্রস্থান করুন। + +### সর্বশেষে, BlockScout সার্ভিস চালু করুন {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## পার্ট 5 - আপনার BlockScout ইনস্ট্যান্সের ফাংশনালিটি পরীক্ষা করুন {#part-5-test-out-the-functionality-of-your-blockscout-instance} +এখন শুধু BlockScout সার্ভিস চলছে কিনা যাচাই করা বাকি রয়েছে। +এটি দিয়ে সার্ভিস স্ট্যাটাস দেখুন: +```bash +sudo systemctl status explorer.service +``` + +সার্ভিস আউটপুট চেক করতে: +```bash +sudo journalctl -u explorer.service -f +``` + +নতুন কোন লিসেনিং পোর্ট আছে কিনা তা দেখতে পারেন এভাবেঃ +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +আপনার লিসেনিং পোর্টের একটি তালিকা পাওয়া উচিৎ এবং তালিকায় এরকম কিছু থাকা উচিৎ: +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +BlockScout ওয়েব সার্ভিসটি env ফাইলে সংজ্ঞায়িত পোর্ট এবং প্রোটোকল চালায়। এই উদাহরণে এটি `4000`(http) এ রান করে। +যদি সবকিছু ঠিক থাকে, তাহলে আপনাকে BlockScout ওয়েব পোর্টালটি অ্যাক্সেস করতে পারবেন এখানে `http://:4000`। + +## বিবেচনাসমূহ {#considerations} +সেরা পারফরম্যান্সের জন্য, একটি ডেডিকেটেড/লোকাল `polygon-edge` ফুল আর্কাইভ নন-ভ্যালিডেটর নোড থাকা বাঞ্ছনীয় +যা শুধুমাত্র BlockScout প্রশ্নের জন্য ব্যবহৃত হবে । এই নোডের API `json-rpc`সবার কাছে উন্মুক্ত করতে হবে না, কারণ BlockScout ব্যাকএন্ড থেকে সমস্ত প্রশ্ন করে। + + +## চূড়ান্ত ভাবনা {#final-thoughts} +আমরা এইমাত্র একটি একক BlockScout ইন্সট্যান্স স্থাপন করেছি, যা ভালভাবে কাজ করে, কিন্তু প্রোডাকশনের জন্য আপনার Nginx এর মত একটি রিভার্স্‌ প্রক্সির পিছনে এই ইন্সট্যান্সটি রাখার কথা বিবেচনা করা উচিত। আপনার ব্যবহারের উপর ভিত্তি করে আপনি ডাটাবেস এবং ইনস্ট্যান্স স্কেলেবিলিটির বিষয়ে ভাবতে পারেন। + +আপনার অবশ্যই অফিসিয়াল [BlockScout ডকুমেন্টেশনটি](https://docs.blockscout.com/) দেখা উচিৎ কারণ সেখানে অনেক কাস্টমাইজেশন অপশন আছে। \ No newline at end of file diff --git a/archive/edge/bn-edge/additional-features/chainbridge/definitions.md b/archive/edge/bn-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..db7ae2e3f5 --- /dev/null +++ b/archive/edge/bn-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,220 @@ +--- +id: definitions +title: সাধারণ সংজ্ঞা +description: chainBridge-এ ব্যবহৃত শব্দের সাধারণ সংজ্ঞা +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## রিলেয়ার {#relayer} +Chainbridge একটি রিলেয়ার ধরনের ব্রিজ। রিলেয়ারের ভূমিকা হলো কোনো অনুরোধ বাস্তবায়নের জন্য ভোট দেওয়া (যেমন কতগুলো টোকেন বার্ন/রিলিজ করতে হবে)। এটি প্রতিটি চেইনের ইভেন্টগুলো পর্যবেক্ষণ করে এবং চেইন থেকে `Deposit` ইভেন্ট পাবার পর গন্তব্য চেইনের ব্রিজ চুক্তিতে একটি প্রস্তাবের জন্য ভোট দেয়। পর্যাপ্ত সংখ্যক ভোট জমা দেওয়ার পর প্রস্তাবকে এক্সিকিউট করার ক্ষেত্রে ব্রিজ চুক্তিতে রিলেয়ারকে একটি পদ্ধতি বলা হয়। ব্রিজটি হ্যান্ডলার চুক্তিকে এক্সিকিউশন ডেলিগেট করে। + + +## চুক্তির ধরন {#types-of-contracts} +ChainBridge-এ, প্রতিটি চেইনে তিন ধরনের চুক্তি রয়েছে, যাকে ব্রিজ/হ্যান্ডলার/টার্গেট বলা হয়। + +| **ধরন** | **বিবরণ** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| ব্রিজ চুক্তি | একটি ব্রিজ চুক্তি যা অনুরোধ, ভোট, এক্সিকিউশন পরিচালনা করে তাকে প্রতিটি চেইনে ডিপ্লয় করতে হবে। একটি ট্রান্সফার শুরু করতে ব্যবহারকারীরা ব্রিজে `deposit` কল করবেন এবং ব্রিজ টার্গেট চুক্তির সাথে সংশ্লিষ্ট হ্যান্ডলার চুক্তিকে প্রক্রিয়াটি ডেলিগেট করবে। টার্গেট চুক্তি কল করতে হ্যান্ডলার চুক্তি সফল হলে রিলেয়ারেকে জানানোর জন্য ব্রিজ চুক্তি একটি `Deposit` ইভেন্ট ইমিট করে। | +| হ্যান্ডলার চুক্তি | একটি ডিপোজিট বা প্রস্তাব এক্সিকিউট করতে এই চুক্তিটি টার্গেট চুক্তির সাথে ইন্টারঅ্যাক্ট করে। এটি ব্যবহারকারীর অনুরোধ যাচাই করে, টার্গেট চুক্তি কল করে এবং টার্গেট চুক্তির জন্য কিছু সেটিংসের বিষয়ে সহায়তা প্রদান করে। প্রতিটি টার্গেট চুক্তি কল করতে নির্দিষ্ট হ্যান্ডলার চুক্তি রয়েছে, যেগুলোর ভিন্ন ভিন্ন ইন্টারফেস রয়েছে। হ্যান্ডলার চুক্তির পরোক্ষ কল ব্রিজটিকে যেকোনো ধরনের এসেট বা ডেটা ট্রান্সফারে সক্ষম করে তুলে। বর্তমানে, ChainBridge দ্বারা বাস্তবায়িত তিন ধরনের হ্যান্ডলার চুক্তি রয়েছে: ERC20Handler, ERC721Handler, এবং GenericHandler। | +| টার্গেট চুক্তি | এসেট পরিচালনাকারী চুক্তি এবং বিভিন্ন চেইনে ট্রান্সফার করা মেসেজগুলি বিনিময় করা যাবে। সেতুর প্রতিটি দিক থেকে এই চুক্তির সাথে ইন্টারঅ্যাকশন করা হবে। | + +
+ +![ChainBridge আর্কিটেকচার](/img/edge/chainbridge/architecture.svg) +*ChainBridge আর্কিটেকচার* + +
+ +
+ +![ERC20 টোকেন ট্রান্সফারের ওয়ার্কফ্লো](/img/edge/chainbridge/erc20-workflow.svg) +*উদাহরণস্বরূপ, একটি ERC20 টোকেন ট্রান্সফারের ওয়ার্কফ্লো* + +
+ +## অ্যাকাউন্টের ধরন {#types-of-accounts} + +শুরু করার আগে, অনুগ্রহ করে নিশ্চিত করুন যে লেনদেনের জন্য অ্যাকাউন্টে পর্যাপ্ত নেটিভ টোকেন রয়েছে। Polygon Edge-এ, জেনেসিস ব্লক তৈরি করার সময় আপনি অ্যাকাউন্টগুলিতে আগে থেকে মাইন করা ব্যালেন্স অ্যাসাইন করতে পারবেন। + +| **ধরন** | **বিবরণ** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| অ্যাডমিন | এই অ্যাকাউন্টটিকে ডিফল্টরূপে অ্যাডমিনের ভূমিকা দেওয়া হবে। | +| ব্যবহারকারী | প্রেরক/প্রাপক অ্যাকাউন্ট এসেট পাঠায়/গ্রহণ করে। প্রেরক অ্যাকাউন্ট টোকেন ট্রান্সফার অনুমোদন করার সময় এবং কোনো ট্রান্সফার শুরু করতে ব্রিজ চুক্তিতে ডিপোজিট কল করার সময়ে গ্যাস ফি প্রদান করে। | + +:::info অ্যাডমিন ভূমিকা + +কিছু নির্দিষ্ট কর্ম শুধুমাত্র অ্যাডমিন ভূমিকার অ্যাকাউন্ট দিয়েই করা যাবে। ডিফল্টরূপে, ব্রিজ চুক্তির ডিপ্লয়ারের অ্যাডমিন ভূমিকা থাকে। অন্য অ্যাকাউন্টকে অ্যাডমিন ভূমিকা কীভাবে প্রদান করবেন বা তা অপসারণ করবে সে সম্পর্কে নীচ থেকে জানতে পারবেন। + +### অ্যাডমিন ভূমিকা যোগ করুন {#add-admin-role} + +একজন এডমিন যোগ করেছে + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### অ্যাডমিন ভূমিকা অপসারণ করুন {#revoke-admin-role} + +একজন এডমিন অপসারণ করেছেন + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## `admin` অ্যাকাউন্ট দ্বারা অনুমোদিত অপারেশনগুলি নিম্নরূপ। {#account-are-as-below} + +### রিসোর্স সেট করুন {#set-resource} + +একটি হ্যান্ডলারের জন্য চুক্তি ঠিকানাসহ একটি রিসোর্স আইডি নিবন্ধন করুন। + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### চুক্তি বার্ন/মিন্টযোগ্য করুন {#make-contract-burnable-mintable} + +কোনো হ্যান্ডলারের মধ্যে একটি টোকেন চুক্তিকে মিন্ট/বার্নযোগ্য হিসেবে সেট করুন। + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### প্রস্তাব বাতিল করুন {#cancel-proposal} + +এক্সিকিউশনের জন্য প্রস্তাব বাতিল করুন + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### পজ/আনপজ {#pause-unpause} + +ডিপোজিট, প্রস্তাব সৃষ্টি, ভোটিং এবং ডিপোজিট এক্সিকিউশন সাময়িকভাবে পজ করুন। + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### ফি পরিবর্তন {#change-fee} + +ব্রিজ চুক্তিতে যে ফি প্রদান করতে হবে তা পরিবর্তন করুন + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### একটি রিলেয়ার যোগ/অপসারণ করুন {#add-remove-a-relayer} + +নতুন রিলেয়ার হিসাবে একটি অ্যাকাউন্ট যোগ করুন বা রিলেয়ার থেকে একটি অ্যাকাউন্ট অপসারণ করুন + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### রিলেয়ার থ্রেশহোল্ড পরিবর্তন করুন {#change-relayer-threshold} + +একটি প্রস্তাব এক্সিকিউশন করার জন্য প্রয়োজনীয় ভোটের সংখ্যা পরিবর্তন করুন + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## চেইন আইডি {#chain-id} + +চেইনব্রিজ `chainId` হচ্ছে একটি দৈবচয়ন ভিত্তিক মান যা ব্লকচেইন নেটওয়ার্কের মধ্যে পার্থক্য করার জন্য ব্রিজে ব্যবহৃত হয় এবং এটি uint8 এর পরিসীমার মধ্যে হতে হবে। নেটওয়ার্কের চেইন আইডি নিয়ে বিভ্রান্তি এড়াতে এগুলো আলাদা হয়ে থাকে। এই মান অনন্য হতে হবে, তবে নেটওয়ার্কের আইডির মত একই হতে হবে না। + +এই উদাহরণে আমরা `chainId`-এ `99`সেট করেছি কারণ মুম্বাই টেস্টনেটের চেইন আইডি হচ্ছে `80001`, যা একটি uint8 দিয়ে উপস্থাপন করা যাবে না। + +## রিসোর্স আইডি {#resource-id} + +একটি রিসোর্স আইডি একটি ক্রস চেইন পরিবেশে একটি অনন্য 32-বাইট মান, যা বিভিন্ন নেটওয়ার্কের মধ্যে ট্রান্সফার হওয়া কিছু নির্দিষ্ট এসেটের (রিসোর্স) সাথে সম্পর্কিত। + +রিসোর্স আইডি দৈবচয়ন ভিত্তিক, তবে প্রথা হিসাবে শেষ বাইটে উৎস চেইনের (যে নেটওয়ার্ক থেকে এই এসেটটির উৎপত্তি হয়েছে) চেইন আইডি থাকে। + +## Polygon PoS-এর JSON-RPC URL {#json-rpc-url-for-polygon-pos} + +এই নির্দেশিকায় আমরা https://rpc-mumbai.matic.today ব্যবহার করব, যা Polygon দ্বারা প্রদত্ত একটি পাবলিক JSON-RPC URL এবং এটিতে ট্রাফিক বা রেট-লিমিট থাকতে পারে। এটি শুধুমাত্র Polygon মুম্বাই টেস্টনেটের সাথে সংযোগ করতে ব্যবহার করা হবে। আমরা আপনাকে আপনার JSON-RPC URL পেতে একটি বহিরাগত পরিষেবা যেমন Infura ব্যবহারের পরামর্শ দিচ্ছি কারণ চুক্তি ডিপ্লয় করলে JSON-RPC অনেক কুয়েরি/অনুরোধ পাঠিয়ে থাকে। + +## টোকেন ট্রান্সফার প্রসেস করার বিভিন্ন পদ্ধতি {#ways-of-processing-the-transfer-of-tokens} +বিভিন্ন চেইনের মধ্যে ERC20 টোকেন ট্রান্সফার করার সময়, তাদের দুটি ভিন্ন মোডে প্রক্রিয়া করা যেতে পারে: + +### লক/রিলিজ মোড {#lock-release-mode} +উৎস চেইন: আপনি যে টোকেন প্রেরণ করছেন তা হ্যান্ডলার চুক্তির মধ্যে লক করা হবে।
+গন্তব্য চেইন: উৎস চেইনে আপনার পাঠানো টোকেনের সম পরিমাণ টোকেন আনলক করা হবে এবং গন্তব্য চেইনের প্রাপক অ্যাকাউন্টে হ্যান্ডলার চুক্তি থেকে তা ট্রান্সফার করা হবে। + +### বার্ন/মিন্ট মোড {#burn-mint-mode} +উৎস চেইন: আপনি যে টোকেন প্রেরণ করছেন তা বার্ন করা হবে।
+গন্তব্য চেইন : সোর্স চেইনে আপনি যে পরিমাণ টোকেন প্রেরণ এবং বার্ন করেছেন তার একই পরিমাণ গন্তব্য চেইনে মিন্ট করা হবে এবং প্রাপক অ্যাকাউন্টে পাঠানো হবে। + +আপনি প্রতিটি চেইন বিভিন্ন মোড ব্যবহার করতে পারেন। এর মানে হচ্ছে আপনি মেইন চেইনে টোকেন লক করতে পারবেন এবং ট্রান্সফারের জন্য সাবচেইনে টোকেন মিন্ট করতে পারবেন। উদাহরণস্বরূপ, মোট সাপ্লাই বা মিন্ট শিডিউল নিয়ন্ত্রণ করা হলে টোকেন লক/রিলিজ করাই বুদ্ধিমানের কাজ হতে পারে। সাবচেইনের চুক্তিটিকে মেইন চেইনে সাপ্লাই অনুসরণ করতে হলে টোকেন মিন্ট/বার্ন করতে হবে। + +ডিফল্ট মোড হচ্ছে লক/রিলিজ মোড। আপনি যদি টোকেন মিন্ট/বার্নযোগ্য করতে চান, তাহলে আপনাকে `adminSetBurnable` পদ্ধতি কল করতে হবে। আপনি যদি এক্সিকিউশনে থাকা টোকেন মিন্ট করতে চান, তাহলে আপনাকে ERC20 হ্যান্ডলার চুক্তিকে `minter` ভূমিকা প্রদান করতে হবে। + + diff --git a/archive/edge/bn-edge/additional-features/chainbridge/overview.md b/archive/edge/bn-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..a6bd50dee7 --- /dev/null +++ b/archive/edge/bn-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: সংক্ষিপ্ত বিবরণ +description: ChainBridge ওভারভিউ +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## ChainBridge কী? {#what-is-chainbridge} + +ChainBridge একটি মডুলার, মাল্টি-ডিরেকশনাল ব্লকচেইন ব্রিজ যা EVM ও Substrate সমর্থিত চেইন সমর্থন করে এবং ChainSafe দ্বারা নির্মিত। এটি ব্যবহারকারীদের দুটি ভিন্ন চেইনের মধ্যে সকল প্রকারের এসেট বা মেসেজ ট্রান্সফারের সুবিধা প্রদান করে। + +ChainBridge সম্পর্কে আরও জানতে, দয়া করে প্রথমে এটির ডেভেলাপারদের প্রদত্ত [অফিসিয়াল ডকুমেন্টগুলো](https://chainbridge.chainsafe.io/) দেখুন। + +এই নির্দেশিকাটি Polygon Edge-এ Chainbridge ইন্টিগ্রেট করতে সহায়তা প্রদানের উদ্দেশ্যে নির্মাণ করা হয়েছে। এটি একটি চলমান Polygon PoS (মুম্বাই টেস্টনেট) এবং একটি স্থানীয় Polygon Edge নেটওয়ার্কের মধ্যে একটি ব্রিজ সেটআপ করার প্রক্রিয়াটিকে বর্ণনা করে। + +## আবশ্যকতা {#requirements} + +এই নির্দেশিকায়, আপনি Polygon Edge নোড, একটি ChainBridge রিলেয়ার ([এখানে](/docs/edge/additional-features/chainbridge/definitions) আরো জানতে পারবেন) এবং cb-sol-cli টুল রান করবেন। cb-sol-cli টুল হচ্ছে স্থানীয়ভাবে চুক্তি ডিপ্লয় করার, রিসোর্স নিবন্ধ করার এবং ব্রিজের সেটিংস পরিবর্তন করার একটি CLI টুল ([এটিও](https://chainbridge.chainsafe.io/cli-options/#cli-options) দেখতে পারেন)। সেটআপ শুরু করার আগে নিম্নলিখিত এনভায়রনমেন্টগুলো প্রয়োজন: + +* Go: >= 1.17 +* Node.js >= 16.13.0 +* Git + + +তাছাড়া, কিছু অ্যাপ্লিকেশন চালানোর জন্য আপনাকে নিম্নলিখিত রিপোজিটরিগুলো সংস্করণ সহ ক্লোন করতে হবে। + +* [Polygon Edge](https://github.com/0xPolygon/polygon-edge): `develop` ব্রাঞ্চে +* [ChainBridge](https://github.com/ChainSafe/ChainBridge): v1.1.5 +* [ChainBridge ডিপ্লয় টুল](https://github.com/ChainSafe/chainbridge-deploy): `f2aa093` `main` ব্রাঞ্চে + + +পরবর্তী বিভাগে এগিয়ে যাওয়ার আগে আপনাকে একটি Polygon Edge নেটওয়ার্ক সেটআপ করতে হবে। আরো বিস্তারিত জানার জন্য, অনুগ্রহ করে [স্থানীয় সেটআপ](/docs/edge/get-started/set-up-ibft-locally) বা [ক্লাউড সেটআপ](/docs/edge/get-started/set-up-ibft-on-the-cloud) দেখুন \ No newline at end of file diff --git a/archive/edge/bn-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/bn-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..6929486a2b --- /dev/null +++ b/archive/edge/bn-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,142 @@ +--- +id: setup-erc20-transfer +title: ERC20 টোকেন ট্রান্সফার +description: ChainBridge-এ ERC-20 ট্রান্সফার কিভাবে সেটআপ করবেন +keywords: + - docs + - polygon + - edge + - Bridge +--- + +এপর্যন্ত, আমরা Polygon PoS এবং Polygon Edge চেইনের মধ্যে অ্যাসেট/ডেটা বিনিময়ের জন্য একটি ব্রিজ স্থাপন করেছি। এই বিভাগটি আপনাকে একটি ERC20 ব্রিজ সেটআপ করতে এবং বিভিন্ন ব্লকচেইনের মধ্যে টোকেন পাঠাতে নির্দেশনা প্রদান করবে। + +## স্টেপ 1: রিসোর্স আইডি নিবন্ধন করুন {#step-1-register-resource-id} + +প্রথমত, আপনি একটি রিসোর্স আইডি নিবন্ধন করবেন যা একটি ক্রস-চেইন এনভায়রনমেন্টে সংস্থানগুলিকে সংযুক্ত করে। একটি রিসোর্স আইডি হল একটি 32-বাইটের ভ্যালু যা অবশ্যই এই ব্লকচেইনের মধ্যে স্থানান্তর করা অ্যাসেটের জন্য অনন্য হতে হবে। রিসোর্স আইডিগুলোর নির্দিষ্ট কোনো ক্রম নেই, তবে তাদের শেষ বাইটে প্রথা হিসেবে হোম চেইনের চেইন আইডি থাকতে পারে (হোম চেইন বলতে যে নেটওয়ার্ক থেকে এই রিসোর্সগুলি পাওয়া হয়েছে তাকে বুঝানো হয়েছে)। + +রিসোর্স আইডি নিবন্ধন করতে, আপনি `cb-sol-cli bridge register-resource` কমান্ডটি ব্যবহার করতে পারেন। আপনাকে `admin` অ্যাকাউন্টের ব্যক্তিগত কী দিতে হবে। + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (ঐচ্ছিক) চুক্তিগুলি মিন্টযোগ্য/বার্নযোগ্য করুন {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## স্টেপ 2: ERC20 টোকেন ট্রান্সফার {#step-2-transfer-erc20-token} + +আমরা Polygon PoS চেইন থেকে Polygon Edge চেইনে ERC20 টোকেন পাঠাব। + +প্রথমত, মিন্ট করার মাধ্যমে আপনি টোকেন পাবেন। একটি`minter` রোল সহ অ্যাকাউন্ট নতুন টোকেন মিন্ট করতে পারে। ERC20 চুক্তি ডিপ্লয় করা অ্যাকাউন্টে ডিফল্টরূপে `minter` রোলটি থাকে। অন্যান্য অ্যাকাউন্টগুলোকে `minter` রোলের মেম্বার হিসেবে উল্লেখ করতে, আপনাকে `cb-sol-cli erc20 add-minter` কমান্ডটি রান করতে হবে। + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +বর্তমান ব্যালেন্স চেক করতে, আপনি `cb-sol-cli erc20 balance`কমান্ডটি ব্যবহার করতে পারেন। + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +পরবর্তী, আপনাকে ERC20 হ্যান্ডলার দ্বারা অ্যাকাউন্ট থেকে ERC20 টোকেন ট্রান্সফার অনুমোদন করতে হবে। + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +টোকেনগুলো Polygon Edge চেইনে স্থানান্তর করতে, আপনি `deposit`কল করবেন। + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +ডিপোজিট লেনদেন সফল হওয়ার পরে, রিলেয়ার ইভেন্টটি পাবে এবং প্রস্তাবের পক্ষে ভোট দেবে। প্রয়োজনীয় সংখ্যক ভোট পাওয়ার পরে এটি Polygon Edge চেইনে প্রাপকের অ্যাকাউন্টে টোকেন পাঠানোর জন্য একটি লেনদেন সম্পাদন করে। + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +এক্সিকিউশন লেনদেন সফলভাবে সম্পন্ন হবার পর আপনি Polygon Edge চেইনে টোকেন পাবেন। + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/bn-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/bn-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..e1e0713ada --- /dev/null +++ b/archive/edge/bn-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,134 @@ +--- +id: setup-erc721-transfer +title: ERC721 NFT ট্রান্সফার +description: ChainBridge-এ ERC-20 tranfer কিভাবে সেটআপ করতে হয় +keywords: + - docs + - polygon + - edge + - Bridge +--- + +এই বিভাগটি আপনাকে একটি ERC721 ব্রিজ সেটআপ করার এবং ব্লকচেইন নেটওয়ার্কগুলির মধ্যে NFT পাঠানোর নির্দেশনা প্রদান করবে। + +## স্টেপ 1: রিসোর্স আইডি নিবন্ধন করুন {#step-1-register-resource-id} + +আপনাকে প্রথমে উভয় চেইনের ব্রিজ চুক্তিতে ERC721 টোকেনের জন্য রিসোর্স আইডি নিবন্ধন করতে হবে। + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (ঐচ্ছিক) চুক্তিগুলি মিন্টেবল/বার্নেবল করুন {#optional-make-contracts-mintable-burnable} + +টোকেনগুলো মিন্টেবল/বার্নেবল করে তৈরি করতে, আপনাকে নিম্নোক্ত কমান্ডগুলো কল করতে হবেঃ + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## ধাপ 2: NFT ট্রান্সফার করুন {#step-2-transfer-nft} + +প্রথমত, আপনার প্রয়োজন হলে আপনি একটি NFT মিন্ট করবেন। + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +NFT-এর মালিক কে জানতে, আপনি `cb-sol-cli erc721 owner` ব্যবহার করতে পারেন + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +তারপর, আপনি ERC721 হ্যান্ডলার দিয়ে NFT-এর ট্রান্সফার অনুমোদন করবেন + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +সর্বশেষে, আপনি ট্রান্সফার শুরু করবেন + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +রিলেয়ার ইভেন্টটি পাবেন এবং প্রস্তাবের জন্য ভোট দিবেন। প্রয়োজনীয় সংখ্যক ভোট পাওয়ার পরে এটি Polygon Edge চেইনে প্রাপকের অ্যাকাউন্টে NFT পাঠানোর জন্য একটি লেনদেন সম্পাদন করে। + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +এক্সিকিউশন সম্পন্ন হওয়ার পর আপনি Polygon Edge নেটওয়ার্কে NFT এর মালিককে চেক করতে পারেন। + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/bn-edge/additional-features/chainbridge/setup.md b/archive/edge/bn-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..080e300d95 --- /dev/null +++ b/archive/edge/bn-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,198 @@ +--- +id: setup +title: সেটআপ +description: কিভাবে সেটআপ chainBridge করবেন +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## চুক্তি ডিপ্লয় করা {#contracts-deployment} + +এই বিভাগে আপনি `cb-sol-cli` দিয়ে Polygon PoS এবং Polygon Edge-এ প্রয়োজনীয় চুক্তিসমূহ ডিপ্লয় করবেন। + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +প্রথমত, আমরা `cb-sol-cli deploy` কমান্ড দিয়ে Polygon PoS চেইনে চুক্তি ডিপ্লয় করব। `--all` ফ্ল্যাগ ব্রিজ, ERC20 হ্যান্ডলার, ERC721 হ্যান্ডলার, জেনেরিক হ্যান্ডলার, ERC20 এবং ERC721 চুক্তিসহ সকল চুক্তি ডিপ্লয় করার কমান্ড তৈরি করে। এছাড়াও, এটি ডিফল্ট রিলেয়ার অ্যাকাউন্ট ঠিকানা এবং থ্রেশহোল্ড সেট করবে + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +chainID এবং JSON-RPC URL সম্পর্কে জানুন [এখানে](/docs/edge/additional-features/chainbridge/definitions) + +:::caution + +`cb-sol-cli`-এ গ্যাসের ডিফল্ট মূল্য হচ্ছে `20000000` (`0.02 Gwei`)। কোনো লেনদেনে গ্যাসের উপযুক্ত মূল্য সেট করতে, অনুগ্রহ করে `--gasPrice` আর্গুমেন্ট ব্যবহার করে মান সেট করুন। + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +ব্রিজ চুক্তি ডিপ্লয় করতে প্রায় 0x3f97b8 (4167608) গ্যাস খরচ করে। অনুগ্রহ করে নিশ্চিত করুন যে ব্লক তৈরি করা হচ্ছে তাতে চুক্তি তৈরির লেনদেন ধারণ করার জন্য পর্যাপ্ত ব্লক গ্যাস সীমা রয়েছে। Polygon Edge-এর ব্লক গ্যাস সীমা পরিবর্তন করা সম্পর্কে আরও জানতে, দয়া করে +[লোকাল সেটআপ](/docs/edge/get-started/set-up-ibft-locally) ভিজিট করুন + +::: + +চুক্তি ডিপ্লয় করা সম্পন্ন হলে আপনি নিম্নলিখিত ফলাফল পাবেন: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +এখন আমরা Polygon Edge চেইনে চুক্তি ডিপ্লয় করতে পারব। + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +টার্মিনালের আউটপুটগুলোর সঙ্গে ডিপ্লয় করা স্মার্ট চুক্তির ঠিকানাটিও সংরক্ষণ করুন, কারণ পরবর্তী ধাপে এইগুলো আমাদের প্রয়োজন হবে। + +## রিলেয়ার সেটআপ {#relayer-setup} + +এই বিভাগে, আপনি 2 চেইনের মধ্যে ডেটা বিনিময় করতে একটি রিলেয়ার চালু করবেন। + +প্রথমত, আমাদের ChainBridge রিপোজিটরিটি ক্লোন এবং তৈরি করতে হবে। + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +তারপর, আপনাকে `config.json` তৈরি করতে হবে এবং প্রতিটি চেইনের জন্য JSON-RPC URL, রিলেয়ার ঠিকানা এবং চুক্তির ঠিকানা সেট করতে হবে। + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +একটি রিলেয়ার চালু করতে, আপনাকে রিলেয়ার অ্যাকাউন্ট ঠিকানার সাথে সংশ্লিষ্ট প্রাইভেট কী'টি ইম্পোর্ট করতে হবে। প্রাইভেট কী ইম্পোর্ট করার সময় আপনাকে পাসওয়ার্ড লিখতে হবে। ইম্পোর্ট সফল হলে কী'টি `keys/
.key` এ সংরক্ষিত হবে। + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +তারপরে, আপনি রিলেয়ার চালু করতে পারেন। আপনি শুরুতে কী সংরক্ষণ করতে যে পাসওয়ার্ড বেছে নিয়েছিলেন সেটিই আপনাকে আবার লিখতে হবে। + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +রিলেয়ার চালু হবার পর এটি প্রতিটি চেইনের নতুন ব্লক দেখা শুরু করবে। diff --git a/archive/edge/bn-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/bn-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..b016eb7645 --- /dev/null +++ b/archive/edge/bn-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,255 @@ +--- +id: use-case-erc20-bridge +title: ব্যবহারের ক্ষেত্র - ERC20 ব্রিজ +description: ERC20 চুক্তি ব্রিজ করার উদাহরণ +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +এই বিভাগটির উদ্দেশ্য হচ্ছে আপনাকে ব্যবহারিক কাজের ক্ষেত্রে ERC20 ব্রিজ সেটআপ প্রক্রিয়া দেখানো। + +এই নির্দেশিকায়, আপনি মুম্বাই Polygon PoS টেস্টনেট এবং Polygon Edge লোকাল চেইন ব্যবহার করবেন। অনুগ্রহ করে নিশ্চিত করুন যে আপনার মুম্বাইয়ের জন্য JSON-RPC এন্ডপয়েন্ট আছে এবং আপনি লোকাল এনভায়রনমেন্টে Polygon Edge সেটআপ করেছেন। আরও বিস্তারিত জানতে, অনুগ্রহ করে [লোকাল সেটআপ](/docs/edge/get-started/set-up-ibft-locally) বা [ক্লাউড সেটআপ](/docs/edge/get-started/set-up-ibft-on-the-cloud) দেখুন। + +## দৃশ্যকল্প {#scenario} + +ইতোমধ্যেই পাবলিক চেইনে (Polygon PoS) ডিপ্লয় করা কোনো ERC20 টোকেনের একটি ব্রিজ সেটআপ করার জন্য এই দৃশ্যটি দেওয়া হয়েছে যাতে পাবলিক থেকে প্রাইভেট চেইনে (Polygon Edge) কম খরচে ট্রান্সফার করা সম্ভব হয়। এই ক্ষেত্রে, টোকেনের মোট সাপ্লাই পাবলিক চেইনে বলা আছে এবং শুধুমাত্র পাবলিক চেইন থেকে প্রাইভেট চেইনে ট্রান্সফার করা টোকেনের পরিমাণই প্রাইভেট চেইনে উপস্থিত থাকবে। সেই কারণে, আপনাকে পাবলিক চেইনে লক/রিলিজ এবং প্রাইভেট চেইনে বার্ন/মিন্ট মোড ব্যবহার করতে হবে। + +পাবলিক চেইন থেকে প্রাইভেট চেইনে টোকেন পাঠানোর সময়ে টোকেনগুলো পাবলিক চেইনের ERC20 হ্যান্ডলার চুক্তিতে লক হয়ে যাবে এবং একই পরিমাণ টোকেন প্রাইভেট চেইনে মিন্ট করা হবে। অন্যদিকে, প্রাইভেট চেইন থেকে পাবলিক চেইনে ট্রান্সফার করার ক্ষেত্রে, প্রাইভেট চেইনে যে পরিমাণ টোকেন বার্ন করা হবে তার সমপরিমাণ টোকেন ERC20 হ্যান্ডলার চুক্তি দিয়ে পাবলিক চেইনে ছাড়া হবে। + +## চুক্তি {#contracts} + +ChainBridge-এর তৈরি চুক্তির পরিবর্তে একটি সহজ ERC20 চুক্তি দিয়ে ব্যাখ্যা করা। বার্ন/মিন্ট মোডের জন্য, নিম্নলিখিত ERC20 পদ্ধতির পাশাপাশি ERC20 চুক্তিতে `mint` এবং `burnFrom` পদ্ধতিও থাকতে হবে: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +সমস্ত কোড এবং স্ক্রিপ্ট Github Repo [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example)-এ আছে। + +## ধাপ1: ব্রিজ এবং ERC20 হ্যান্ডলার চুক্তি ডিপ্লয় করুন {#step1-deploy-bridge-and-erc20-handler-contracts} + +প্রথমত, আপনি উভয় চেইনে `cb-sol-cli` ব্যবহার করে ব্রিজ এবং ERC20Handler চুক্তি ডিপ্লয় করবেন। + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +আপনি নিচের মতো ব্রিজ এবং ERC20Handler চুক্তির ঠিকানা পাবেন: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## ধাপ2: আপনার ERC20 চুক্তি ডিপ্লয় করুন {#step2-deploy-your-erc20-contract} + +আপনি আপনার ERC20 চুক্তি ডিপ্লয় করবেন। এই উদাহরণটি আপনাকে হার্ডহ্যাট প্রজেক্ট [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example)-এ দিক-নির্দেশনা প্রদান করবে। + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +অনুগ্রহ করে `.env` ফাইল তৈরি করুন এবং নিম্নলিখিত মান সেট করুন। + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +পরবর্তীতে আপনি উভয় চেইনে ERC20 চুক্তি ডিপ্লয় করবেন। + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +ডিপ্লয়মেন্ট সফল হওয়ার পরে, আপনি নিচের মতো একটি চুক্তির ঠিকানা পাবেন: + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## ধাপ3: ব্রিজে রিসোর্স আইডি নিবন্ধন করুন {#step3-register-resource-id-in-bridge} + +আপনি একটি রিসোর্স আইডি নিবন্ধন করবেন যা একটি ক্রস-চেইন এনভায়রনমেন্টে রিসোর্সগুলিকে সংযুক্ত করে। আপনাকে উভয় চেইনে একই রিসোর্স আইডি সেট করতে হবে। + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## ধাপ4: Edge-এর ERC20 ব্রিজে মিন্ট/বার্ন মোড সেট করুন {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +ব্রিজ Polygon Edge-এ বার্ন/মিন্ট মোড হিসাবে কাজ করার আশা রাখে। আপনি `cb-sol-cli` ব্যবহার করে বার্ন/মিন্ট মোড সেট করবেন। + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +এবং আপনাকে ERC20 হ্যান্ডলার চুক্তিতে একটি মিন্টার এবং বার্নার রোল দিতে হবে। + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## ধাপ5: টোকেন মিন্ট করুন {#step5-mint-token} + +আপনি মুম্বাই চেইনে নতুন ERC20 টোকেন মিন্ট করবেন। + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +লেনদেনটি সফল হওয়ার পরে, অ্যাকাউন্টটিতে মিন্ট করা টোকেন চলে যাবে। + +## ধাপ6: ERC20 ট্রান্সফার শুরু করুন {#step6-start-erc20-transfer} + +এই ধাপ শুরু করার আগে, অনুগ্রহ করে নিশ্চিত করুন যে আপনি একটি রিলেয়ার চালু করেছেন। আরও বিস্তারিত জানতে, অনুগ্রহ করে [সেটআপ](/docs/edge/additional-features/chainbridge/setup) দেখুন। + +মুম্বাই থেকে Edge-এ টোকেন ট্রান্সফার করার সময়, মুম্বাইয়ের ERC20 হ্যান্ডলার চুক্তি অ্যাকাউন্ট থেকে টোকেন উইথড্র করে। ট্রান্সফার করার আগে আপনি অনুমোদন কল করবেন। + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +সবশেষে, আপনি `cb-sol-cli` ব্যবহার করে মুম্বাই থেকে Edge-এ টোকেন ট্রান্সফার করা শুরু করবেন। + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +ডিপোজিট লেনদেন সফল হওয়ার পরে, রিলেয়ার ইভেন্টটি পাবে এবং প্রস্তাবের পক্ষে ভোট দেবে। প্রয়োজনীয় সংখ্যক ভোট পাওয়ার পরে এটি Polygon Edge চেইনে প্রাপকের অ্যাকাউন্টে টোকেন পাঠানোর জন্য একটি লেনদেন সম্পাদন করে। + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +এক্সিকিউশন লেনদেন সফলভাবে সম্পন্ন হবার পর আপনি Polygon Edge চেইনে টোকেন পাবেন। diff --git a/archive/edge/bn-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/bn-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..95ddadac5d --- /dev/null +++ b/archive/edge/bn-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,308 @@ +--- +id: use-case-erc721-bridge +title: ব্যবহারিক ক্ষেত্র - ERC721 ব্রিজ +description: ERC721 চুক্তি ব্রিজ করার উদাহরণ +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +এই বিভাগটির উদ্দেশ্য হচ্ছে আপনাকে ব্যবহারিক কাজের ক্ষেত্রে ERC20 ব্রিজ সেটআপ প্রক্রিয়া দেখানো। + +এই নির্দেশিকায়, আপনি মুম্বাই Polygon PoS টেস্টনেট এবং Polygon Edge লোকাল চেইন ব্যবহার করবেন। অনুগ্রহ করে নিশ্চিত করুন যে আপনার মুম্বাইয়ের জন্য JSON-RPC এন্ডপয়েন্ট আছে এবং আপনি লোকাল এনভায়রনমেন্টে Polygon Edge সেটআপ করেছেন। আরও বিস্তারিত জানতে, অনুগ্রহ করে [লোকাল সেটআপ](/docs/edge/get-started/set-up-ibft-locally) বা [ক্লাউড সেটআপ](/docs/edge/get-started/set-up-ibft-on-the-cloud) দেখুন। + +## দৃশ্যকল্প {#scenario} + +এই উদাহরণটিতে ব্যবহারকারীদের নিয়মিত ব্যবহারের ক্ষেত্রে প্রাইভেট চেইনে (Polygon Edge) স্বল্প-খরচের ট্রান্সফার সক্ষম করতে ইতোমধ্যেই পাবলিক চেইনে (Polygon PoS) ডিপ্লয় করা ERC721 NFT-এর জন্য ব্রিজ সেটআপের বিষয়টি দেখানো হয়েছে। এইসব ক্ষেত্রে, পাবলিক চেইন সংজ্ঞায়িত মূল মেটাডেটা এবং পাবলিক চেইনে ট্রান্সফারকৃত NFT-গুলোই শুধুমাত্র প্রাইভেট চেইনে থাকতে পারবে। সেই কারণে, আপনাকে পাবলিক চেইনে লক/রিলিজ এবং প্রাইভেট চেইনে বার্ন/মিন্ট মোড ব্যবহার করতে হবে। + +পাবলিক চেইন থেকে প্রাইভেট চেইনে NFT পাঠানোর সময়ে NFT পাবলিক চেইনের ERC20 হ্যান্ডলার চুক্তিতে লক হয়ে যাবে এবং সেই একই NFT প্রাইভেট চেইনে মিন্ট করা হবে। অন্যদিকে, প্রাইভেট চেইন থেকে পাবলিক চেইনে ট্রান্সফার করার ক্ষেত্রে, প্রাইভেট চেইনে যে NFT বার্ন করা হবে সেই একই NFT ERC20 হ্যান্ডলার চুক্তি থেকে পাবলিক চেইনে ছাড়া হবে। + +## চুক্তি {#contracts} + +ChainBridge-এর তৈরি চুক্তির পরিবর্তে একটি সহজ ERC721 চুক্তি দিয়ে ব্যাখ্যা করা। বার্ন/মিন্ট মোডের জন্য, ERC721-এ সংজ্ঞায়িত নিচের পদ্ধতিগুলোর পাশাপাশি ERC721 চুক্তিতে অবশ্যই `mint` এবং `burn` থাকতে হবে: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +সমস্ত কোড এবং স্ক্রিপ্ট Github রেপো [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example)-এ আছে। + +## ধাপ 1: ব্রিজ এবং ERC721 হ্যান্ডলার চুক্তি ডিপ্লয় করুন {#step1-deploy-bridge-and-erc721-handler-contracts} + +প্রথমত, আপনি উভয় চেইনে `cb-sol-cli` ব্যবহার করে ব্রিজ এবং ERC20Handler চুক্তি ডিপ্লয় করবেন। + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +আপনি নিচের মতো ব্রিজ এবং ERC721Handler চুক্তির ঠিকানা পাবেন: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## ধাপ 2: আপনার ERC721 চুক্তি ডিপ্লয় করুন {#step2-deploy-your-erc721-contract} + +আপনি আপনার ERC721 চুক্তি ডিপ্লয় করবেন। এই উদাহরণটি আপনাকে হার্ডহ্যাট প্রজেক্ট [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example)-এ দিক-নির্দেশনা প্রদান করবে। + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +অনুগ্রহ করে `.env` ফাইল তৈরি করুন এবং নিম্নলিখিত মান সেট করুন। + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +তারপর, আপনি উভয় চেইনে ERC20 চুক্তি ডিপ্লয় করবেন। + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +ডিপ্লয়মেন্ট সফল হওয়ার পরে, আপনি নিচের মতো একটি চুক্তির ঠিকানা পাবেন: + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## ধাপ3: ব্রিজে রিসোর্স আইডি নিবন্ধন করুন {#step3-register-resource-id-in-bridge} + +আপনি একটি রিসোর্স আইডি নিবন্ধন করবেন যা একটি ক্রস-চেইন এনভায়রনমেন্টে রিসোর্সগুলিকে সংযুক্ত করে। + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## ধাপ4: Edge-এর ERC721 ব্রিজে মিন্ট/বার্ন মোড সেট করুন {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +ব্রিজ Edge-এ বার্ন/মিন্ট মোড হিসেবে কাজ করার প্রত্যাশা রাখে। আপনি বার্ন/মিন্ট মোড সেট করবেন। + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +তাছাড়া, আপনাকে ERC721 হ্যান্ডলার চুক্তিতে একটি মিন্টার এবং বার্নার ভূমিকা প্রদান করতে হবে। + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## ধাপ 5: NFT মিন্ট করুন {#step5-mint-nft} + +আপনি মুম্বাই চেইনে নতুন ERC721 NFT মিন্ট করবেন। + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +লেনদেনটি সফল হওয়ার পরে, অ্যাকাউন্টটিতে মিন্ট করা NFT চলে যাবে। + +## ধাপ6: ERC721 ট্রান্সফার শুরু করুন {#step6-start-erc721-transfer} + +এই ধাপটি শুরু করার আগে, দয়া করে রিলেয়ার চালু করার বিষয়টি নিশ্চিত করুন। আরও বিস্তারিত জানতে, অনুগ্রহ করে [সেটআপ](/docs/edge/additional-features/chainbridge/setup) দেখুন। + +মুম্বাই থেকে Edge-এ NFT ট্রান্সফার করার সময়, মুম্বাইয়ের ERC721 হ্যান্ডলার চুক্তি আপনার অ্যাকাউন্ট থেকে NFT উইথড্র করে। ট্রান্সফার করার আগে আপনি অনুমোদন কল করবেন। + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +সবশেষে, আপনি মুম্বাই থেকে Edge-এ NFT ট্রান্সফার করা শুরু করবেন। + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +ডিপোজিট লেনদেন সফল হওয়ার পরে, রিলেয়ার ইভেন্টটি পাবে এবং প্রস্তাবের পক্ষে ভোট দেবে। +প্রয়োজনীয় সংখ্যক ভোট সাবমিট হবার পরে এটি Polygon Edge চেইনে প্রাপক অ্যাকাউন্টে NFT পাঠাতে একটি লেনদেন এক্সিকিউট করে। + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +এক্সিকিউশন লেনদেন সফলভাবে সম্পন্ন হবার পর আপনি Polygon Edge চেইনে NFT পাবেন। diff --git a/archive/edge/bn-edge/additional-features/permission-contract-deployment.md b/archive/edge/bn-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..2afd320465 --- /dev/null +++ b/archive/edge/bn-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,86 @@ +--- +id: permission-contract-deployment +title: অনুমতি স্মার্ট চুক্তি ডিপ্লয়মেন্ট +description: কীভাবে অনুমতি স্মার্ট চুক্তি ডিপ্লয়মেন্ট যোগ করবেন। +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +এই নির্দেশিকায় কিভাবে স্মার্ট চুক্তিতে ডিপ্লয় করা যায় এমন ঠিকানা হোয়াইটলিস্ট করা যা সে বিষয়ে বিস্তারিত আলোচনা করেছে। +কখনো কখনো নেটওয়ার্ক অপারেটররা ব্যবহারকারীদের নেটওয়ার্কের উদ্দেশ্যের সাথে সম্পর্ক নেই এমন স্মার্ট চুক্তি ডিপ্লয় করা থেকে বিরত রাখতে চান। নেটওয়ার্ক অপারেটররা যা করতে পারেন: + +1. স্মার্ট চুক্তি ডিপ্লয়মেন্টের জন্য ঠিকানা হোয়াইটলিস্ট করতে পারেন +2. স্মার্ট চুক্তি ডিপ্লয়মেন্টের জন্য হোয়াইটলিস্ট থেকে ঠিকানা অপসারণ করতে পারেন + +## ভিডিও প্রেজেন্টেশন {#video-presentation} + +[![অনুমতি চুক্তি ডিপ্লয়মেন্ট - ভিডিও](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## কীভাবে এটি ব্যবহার করবেন? {#how-to-use-it} + + +আপনি [CLI কমান্ড](/docs/edge/get-started/cli-commands#whitelist-commands) পৃষ্ঠাতে ডিপ্লয়মেন্ট হোয়াইটলিস্ট করা সম্পর্কিত সকল cli কমান্ড খুঁজে পেতে পারেন। + +* `whitelist show`: হোয়াইটলিস্ট তথ্য দেখায় +* `whitelist deployment --add`: চুক্তি ডিপ্লয়মেন্ট হোয়াইটলিস্টে একটি নতুন ঠিকানা যোগ করে +* `whitelist deployment --remove`: চুক্তি ডিপ্লয়মেন্ট হোয়াইটলিস্ট থেকে একটি নতুন ঠিকানা অপসারণ করে + +#### ডিপ্লয়মেন্ট হোয়াইটলিস্টে থাকা সমস্ত ঠিকানা দেখান {#show-all-addresses-in-the-deployment-whitelist} + +ডিপ্লয়মেন্ট হোয়াইটলিস্ট থেকে ঠিকানা খুঁজে পাওয়ার 2টি পদ্ধতি রয়েছে। +1. `genesis.json` দেখতে পারেন, এখানে হোয়াইটলিস্ট সংরক্ষণ করা হয় +2. `whitelist show` এক্সিকিউট করতে পারেন, এটি Polygon Edge দ্বারা সমর্থিত সকল হোয়াইটলিস্টের তথ্য প্রিন্ট করে + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### ডিপ্লয়মেন্ট হোয়াইটলিস্টে একটি ঠিকানা যোগ করুন {#add-an-address-to-the-deployment-whitelist} + +ডিপ্লয়মেন্ট হোয়াইটলিস্টে একটি নতুন ঠিকানা যোগ করতে `whitelist deployment --add [ADDRESS]` CLI কমান্ড এক্সিকিউট করুন। হোয়াইটলিস্টে থাকা ঠিকানার সংখ্যায় কোনো সীমা নেই। শুধুমাত্র যেসব ঠিকানা কন্ট্রাক্ট ডিপ্লয়মেন্ট হোয়াইটলিস্টে আছে, সেগুলো চুক্তি ডিপ্লয় করতে পারে। হোয়াইটলিস্ট খালি থাকলে যেকোনো ঠিকানা ডিপ্লয়মেন্ট করতে পারবে + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### ডিপ্লয়মেন্ট হোয়াইটলিস্ট থেকে একটি ঠিকানা অপসারণ করুন {#remove-an-address-from-the-deployment-whitelist} + +ডিপ্লয়মেন্ট হোয়াইটলিস্ট থেকে একটি ঠিকানা অপসারণ করতে `whitelist deployment --remove [ADDRESS]` CLI কমান্ড এক্সিকিউট করুন। শুধুমাত্র যেসব ঠিকানা কন্ট্রাক্ট ডিপ্লয়মেন্ট হোয়াইটলিস্টে আছে, সেগুলো চুক্তি ডিপ্লয় করতে পারে। হোয়াইটলিস্ট খালি থাকলে যেকোনো ঠিকানা ডিপ্লয়মেন্ট করতে পারবে + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/bn-edge/architecture/modules/blockchain.md b/archive/edge/bn-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..72d08ccd15 --- /dev/null +++ b/archive/edge/bn-edge/architecture/modules/blockchain.md @@ -0,0 +1,160 @@ +--- +id: blockchain +title: ব্লকচেইন +description: Polygon Edge-এর ব্লকচেইন এবং স্টেট মডিউলের ব্যাখ্যা। +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +Polygon Edge-এর অন্যতম প্রধান মডিউল হচ্ছে **ব্লকচেইন** এবং **স্টেট**।
+ +**ব্লকচেইন** খুবই শক্তিশালী একটি বস্তু যা ব্লক পুনর্বিন্যাসের কাজটি সম্পন্ন করে থাকে। এর মানে হচ্ছে যে ব্লকচেইনে কোনো নতুন ব্লক অন্তর্ভুক্ত করার সময় এটি সকল লজিক সংক্রান্ত কাজগুলো সম্পন্ন করে থাকে। + +**স্টেট** *স্টেট ট্রানজিশন* অবজেক্টের প্রতিনিধিত্ব করে। এটি নতুন ব্লক অন্তুর্ভুক্ত করা হলে স্টেট পরিবর্তনের বিষয়টিকে পরিচালনা করে থাকে।
অন্যান্য কাজের মধ্যে, **স্টেট** নিম্নলিখিতগুলোও সম্পাদন করে থাকে: +* লেনদেন এক্সিকিউট করা +* EVM এক্সিকিউট করা +* Merkle ট্রি পরিবর্তন করা +* আরও অনেক কিছু সম্পাদন করে থেকে, যা সংশ্লিষ্ট **স্টেট** বিভাগে বর্ণনা করা হয়েছে 🙂 + +মূল বিষয় হচ্ছে এই 2টি অংশ একসাথে সংযুক্ত এবং ক্লায়েন্টে কর্মক্ষমতা নিশ্চিত করতে এইগুলো একসাথে খুবই ঘনিষ্টভাবে কাজ করে।
উদাহরণস্বরূপ, যখন **ব্লকচেইন** লেয়ার একটি নতুন ব্লক পায় (এবং কোনও পুনর্বিন্যাস না করতে হয়), এটি একটি স্টেট ট্রানজিশন সম্পাদন করার জন্য **স্টেট** কল করে। + +**ব্লকচেইন** কনসেনসাস সংক্রান্ত কিছু বিষয়ও পরিচালনা করে থাকে (যেমন, *এই ethHash কি সঠিক?*, *এই PoW কি সঠিক?*)।
সংক্ষেপে, **এটি লজিকের প্রধান কোর যাতে সমস্ত ব্লক অন্তর্ভুক্ত থাকে**। + +## *WriteBlocks* + +ব্লকচেইন লেয়ার সম্পর্কিত সবচেয়ে গুরুত্বপূর্ণ অংশ হচ্ছে **WriteBlocks**** পদ্ধতি: + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +*WriteBlocks* পদ্ধতি হচ্ছে ব্লকচেইনে ব্লক লিখার এন্ট্রি পয়েন্ট। একটি প্যারামিটার হিসাবে, এটি ব্লকের পরিসীমা নিয়ে থাকে।
+প্রথমত, ব্লক যাচাই করা হয়। তারপর, তাদের চেইনে লিখা হয়। + +প্রকৃত *স্টেট ট্রানজিশন* *WriteBlocks*-এর মধ্যে *processBlock* পদ্ধতি কল করে সম্পাদন করা হয়। + +এছাড়াও, যেহেতু এটি ব্লকচেইনে ব্লক লেখার এন্ট্রি পয়েন্ট, তাই অন্যান্য মডিউলগুলোও (যেমন **Sealer**) এই পদ্ধতির সুবিধা গ্রহণ করে থাকে। + +## ব্লকচেইন সাবস্ক্রিপশন {#blockchain-subscriptions} + +ব্লকচেইন-সংক্রান্ত পরিবর্তন মনিটর করার একটি মেকানিজম থাকা খুবই গুরুত্বপূর্ণ।
+**সাবস্ক্রিপশন** ঠিক সেই কাজটিই সম্পাদন করে থাকে। + +সাবস্ক্রিপশন হচ্ছে ব্লকচেইন ইভেন্ট স্ট্রিমে ঘুরে আসার এবং অবিলম্বে কার্যকরী ডেটা পাওয়ার একটি উপায়। + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +**ব্লকচেইন ইভেন্টে** প্রকৃত চেইন করা সকল পরিবর্তন সংক্রান্ত তথ্য রয়েছে। এতে পুনর্বিন্যাসের পাশাপাশি নতুন ব্লকও অন্তর্ভুক্ত রয়েছে: + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip রিফ্রেশার + +আপনার কি মনে আছে কখন আমরা [CLI কমান্ডে](/docs/edge/get-started/cli-commands) ***মনিটর*** কমান্ড উল্লেখ করেছি? + +ব্লকচেইন ইভেন্টগুলো হচ্ছে Polygon Edge-এ ঘটা মূল ইভেন্ট এবং সহজে ট্রান্সফারের জন্য সেগুলোকে পরে প্রোটোকল বাফার মেসেজ ফরম্যাটে ম্যাপ করা হয়। + +::: \ No newline at end of file diff --git a/archive/edge/bn-edge/architecture/modules/consensus.md b/archive/edge/bn-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..993f4be9c5 --- /dev/null +++ b/archive/edge/bn-edge/architecture/modules/consensus.md @@ -0,0 +1,510 @@ +--- +id: consensus +title: কনসেনসাস +description: Polygon Edge-এর কনসেনসাস মডিউলের ব্যাখ্যা। +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +**কনসেনসাস** মডিউল কনসেনসাস মেকানিজমের জন্য একটি ইন্টারফেস প্রদান করে। + +বর্তমানে, নিম্নলিখিত কনসেনসাস ইঞ্জিনগুলো পাওয়া যাচ্ছে: +* **IBFT PoA** +* **IBFT PoS** + +Polygon Edge একটি মডুলারিটি এবং প্লাগ্যাবিলিটির স্টেট বজায় রাখতে চাচ্ছে।
+তাই মূল কনসেনসাস লজিকটি অ্যাবস্ট্র্যাক্ট করা হয়েছে, যাতে ব্যবহারযোগ্যতা এবং ব্যবহারের আরামদায়কতার সাথে কোনো আপোষ করা ছাড়াই +সেটির উপরে নতুন কনসেনসাস মেকানিজম তৈরি করা যায়। + +## কনসেনসাস ইন্টারফেস {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + +***কনসেনসাস*** ইন্টারফেস হচ্ছে উল্লিখিত অ্যাবস্ট্রাকশনের মূল বিষয়।
+* **VerifyHeader** পদ্ধতি একটি সহায়ক ফাংশন উপস্থাপন করে যা কনসেনসাস লেয়ারটিকে **ব্লকচেইন** লেয়ারে প্রকাশ করে +এটি হেডার যাচাইকরণ পরিচালনা করে থাকে +* **স্টার্ট** পদ্ধতিটি শুধু কনসেনসাস প্রক্রিয়া এবং এর সাথে সংশ্লিষ্ট সবকিছু চালু করে। এই কাজগুলোর মধ্যে অন্তর্ভুক্ত রয়েছে সিঙ্ক্রোনাইজেশন, +সিলিং এবং অন্যান্য যা সম্পন্ন করতে হবে +* **ক্লোজ** পদ্ধতিটি কনসেনসাস সংযোগ বন্ধ করে + +## কনসেনসাস কনফিগারেশন {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +আপনি ডেটা সংরক্ষণ করতে কনসেনসাস প্রোটোকল একটি কাস্টম লোকেশন পাঠাতে চাইতে পারেন বা +কনসেনসাস মেকানিজমে ব্যবহারের জন্য একটি কাস্টম কী-ভ্যালু ম্যাপ চাইতে পারেন। এটি ***Config*** স্ট্রাক্টের মাধ্যমে অর্জন করা যেতে পারে, +যা একটি নতুন কনসেনসাস ইনস্ট্যান্স তৈরি হওয়ার পর রিড হয়। + +## IBFT {#ibft} + +### ExtraData {#extradata} + +অন্যান্য ফিল্ডের মধ্যে ব্লকচেইন হেডার অবজেক্টে **ExtraData** নামক একটি ফিল্ড আছে। + +IBFT এই অতিরিক্ত ফিল্ড ব্যবহার করে নিম্নলিখিত প্রশ্নগুলোর উত্তর প্রদান করার মাধ্যমে ব্লক বিষয়ক অপারেশনাল তথ্য সংরক্ষণ করে: +* "কে এই ব্লকটি স্বাক্ষর করেছেন?" +* "কারা এই ব্লকের যাচাইকারী?" + +IBFT-এর এই অতিরিক্ত ক্ষেত্রগুলো নিচে সংজ্ঞায়িত করা হয়েছে: +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### সাইনিং ডেটা {#signing-data} + +IBFT-তে নোড সাইন করার জন্য, এটি *signHash* পদ্ধতি ব্যবহার করে: +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +আরেকটি উল্লেখযোগ্য পদ্ধতি হল *VerifyCommittedFields* পদ্ধতি, যা কমিট করা সিলগুলো বৈধ যাচাইকারীদের কাছ থেকে আসার বিষয়টি নিশ্চিত করে: +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### স্ন্যাপশট {#snapshots} + +স্ন্যাপশট, নামেই প্রতীয়মান, যেকোনো ব্লক উচ্চতায় (সংখ্যা) সিস্টেমের একটি *স্ন্যাপশট* বা *স্টেট* প্রদান করে থাকে। + +স্ন্যাপশটের ভিতর একটি নোডের সেট থাকে যেগুলোতে যাচাইকারীদের পাশাপাশি ভোটের তথ্য থাকে (যাচাইকারীরা অন্যান্য যাচাইকারীদের ভোট দিতে পারেন)। যাচাইকারীরা **মাইনার** হেডার ফিল্ডে ভোটের তথ্য অন্তর্ভুক্ত করে এবং **নোন্স** ফিল্ডের মান পরিবর্তন করে: +* নোডটি কোনো যাচাইকারীকে অপসারণ করতে চাইলে নোন্স **সব 1s** হয় +* নোডটি কোনো যাচাইকারীকে যোগ করতে চাইলে নোন্স **সব 0s** হয় + +স্ন্যাপশট ***processHeaders*** পদ্ধতি ব্যবহার করে গণনা করা হয়: + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +এই পদ্ধতিটি সাধারণত 1 হেডারের সাথে কল করা হয়, কিন্তু একাধিক হেডারের সাথেও তার ফ্লো একই হয়।
+প্রতিটি পাসড-ইন হেডারের জন্য, IBFT-কে যাচাই করতে হয় যে হেডারের প্রস্তাবকই যাচাইকারী। সাম্প্রতিকতম স্ন্যাপশট নিয়ে +এবং নোডটি যাচাইকারীর সেটের মধ্যে রয়েছে কিনা তা যাচাই করার মাধ্যমে এটি খুব সহজেই করা যেতে পারে। + +পরবর্তীতে, নোন্স চেক করা হয়। ভোটটি অন্তর্ভুক্ত এবং ট্যালি করা হয়েছে - যদি পর্যাপ্ত ভোট থাকে, তাহলে যাচাইকারীর সেট থেকে +একটি নোড যোগ/বাদ দেওয়া হয় এবং তারপর নতুন স্ন্যাপশট সংরক্ষণ করা হয়। + +#### স্ন্যাপশট স্টোর {#snapshot-store} + +স্ন্যাপশট সার্ভিস **স্ন্যাপশট স্টোর** নামক একটি এন্টিটি পরিচালনা ও আপডেট করে থাকে, যা সমস্ত বিদ্যমান স্ন্যাপশটের তালিকা সংরক্ষণ করে। +এটি ব্যবহার করে, সার্ভিসটি দ্রুত খুঁজে বের করতে পারে যে কোন স্ন্যাপশট কোন ব্লক উচ্চতার সাথে সম্পর্কিত। +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### IBFT স্টার্টআপ {#ibft-startup} + +IBFT শুরু করতে, Polygon Edge এর প্রথমে IBFT ট্রান্সপোর্ট সেট আপ করতে হবে: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +এটি মূলত IBFT proto দিয়ে একটি নতুন টপিক তৈরি করে যাতে নতুন একটি প্রোটো বাফ মেসেজ অন্তর্ভুক্ত থাকে।
+মেসেজগুলো যাচাইকারীদের ব্যবহারের উদ্দেশ্যে তৈরি করা হয়েছে। Polygon Edge তারপর টপিকটিতে সাবস্ক্রাইব করে এবং সেই অনুযায়ী মেসেজ পরিচালনা করে। + +#### MessageReq {#messagereq} + +যাচাইকারীদের দ্বারা বিনিময়কৃত মেসেজ: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +**MessageReq** এর মধ্যকার **ভিউ** ফিল্ডটি চেইনের ভিতরে বর্তমান নোডের অবস্থানকে নির্দেশ করে। +এটির একটি *রাউন্ড* এবং একটি *সিকুয়েন্স* অ্যাট্রিবিউট আছে। +* **রাউন্ড** দিয়ে উচ্চতার জন্য প্রস্তাবকের রাউন্ডকে নির্দেশ করা হয় +* **সিকুয়েন্স** দিয়ে ব্লকচেইনের উচ্চতাকে নির্দেশ করা হয় + +IBFT ইমপ্লিমেন্টেশনে ফাইল করা *msgQueue* মেসেজ অনুরোধ সংরক্ষণ করার উদ্দেশ্যে আছে। এটি মেসেজ সাজায় *ভিউ* দিয়ে (প্রথমে সিকুয়েন্স দিয়ে, তারপর রাউন্ড দিয়ে)। এছাড়াও, IBFT ইমপ্লিমেন্টেশন সিস্টেমের বিভিন্ন স্টেটের জন্য বিভিন্ন কিউয়ের অধিকার সংরক্ষণ করে। + +### IBFT স্টেট {#ibft-states} + +স্টার্ট পদ্ধতি ব্যবহার করে কনসেনসাস মেকানিজম **শুরু** হবার পর এটি একটি ইনফিনিট লুপ রান করে, যা একটি স্টেট মেশিনকে সিমুলেট করে: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### SyncState {#syncstate} + +সমস্ত নোড প্রাথমিকভাবে **সিঙ্ক** স্টেটে শুরু হয়। + +এর কারণ হল ব্লকচেইন থেকে ফ্রেশ ডেটা নিয়ে আসতে হয়। ক্লায়েন্টকে জানতে হয় যে এটি যাচাইকারী কিনা, +বর্তমান স্ন্যাপশট খুঁজুন। এই স্টেট যেকোন পেন্ডিং ব্লকের সমাধান করে। + +সিঙ্ক শেষ হওয়ার পরে এবং ক্লায়েন্ট এটিকে একজন যাচাইকারী হিসেবে নির্ধারণ করলে, এটিকে **AcceptState**-এ ট্রান্সফার করতে হবে। +ক্লায়েন্টটি যাচাইকারী **না** হলে এটি সিঙ্ক করা চালিয়ে যাবে এবং **SyncState**-এ থাকবে + +#### AcceptState {#acceptstate} + +**Accept** স্টেট সবসময়ই স্ন্যাপশট এবং যাচাইকারীর সেট চেক করে। বর্তমান নোডটি ভ্যালিডেটর সেটে না থাকলে +এটি **Sync** স্টেটে ফিরে চলে যায়। + +অন্যদিকে, নোডটি যাচাইকারী **হলে** এটি প্রস্তাবককে হিসাব করে। যদি জানা যায় যে বর্তমান নোডটিই +প্রস্তাবক, তাহলে এটি একটি ব্লক তৈরি করে এবং প্রথমে প্রস্তুতি-পূর্ব এবং পরবর্তীতে প্রস্তুতি মেসেজ পাঠায়। + +* প্রস্তুতি-পূর্ব মেসেজ - প্রস্তাবক থেকে যাচাইকারীদের প্রস্তাব সম্পর্কে অবগত করার মেসেজ +* প্রস্তুতি মেসেজ - যে মেসেজে যাচাইকারীরা কোনো প্রস্তাবে সম্মতি পোষণ করেন। সকল নোড সমস্ত প্রস্তুতি মেসেজ পেয়ে থাকে। +* কমিট মেসেজ - যে মেসেজে প্রস্তাবের কমিটের তথ্য থাকে + +বর্তমান নোডটি যাচাইকারী **না হলে** এটি পূর্বে দেখানো কিউ থেকে একটি মেসেজ পড়তে *getNextMessage* পদ্ধতি ব্যবহার করে।
+এটি প্রস্তুতি-পূর্ব মেসেজের জন্য অপেক্ষা করে। সবকিছু ঠিক-ঠাক আছে নিশ্চিত হবার পরে নোডটি **যাচাই** স্টেটে চলে যায়। + +#### ValidateState {#validatestate} + +**যাচাই** স্টেট যথেষ্ট সহজ - এখানে নোডগুলো শুধু মেসেজ পড়ে এবং তাদের লোকাল স্ন্যাপশট স্টেটে যোগ করে। diff --git a/archive/edge/bn-edge/architecture/modules/json-rpc.md b/archive/edge/bn-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..11a725d0ad --- /dev/null +++ b/archive/edge/bn-edge/architecture/modules/json-rpc.md @@ -0,0 +1,181 @@ +--- +id: json-rpc +title: JSON RPC +description: Polygon Edge-এর JSON RPC মডিউলের ব্যাখ্যা। +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +**JSON RPC** মডিউল **JSON RPC API লেয়ার** ইমপ্লিমেন্ট করে, যা dApp ডেভেলপাররা ব্লকচেইনের সাথে ইন্টারঅ্যাক্ট করতে +ব্যবহার করে। + +এটি স্ট্যান্ডার্ড **[json-rPC এন্ডপয়েন্ট](https://eth.wiki/json-rpc/API)**, সেইসাথে ওয়েবসকেট এন্ডপয়েন্টও +সমর্থন করে। + +## ব্লকচেইন ইন্টারফেস {#blockchain-interface} + +Polygon Edge তার এন্ডপয়েন্ট ডেলিভার করতে, JSON RPC মডিউলের ব্যবহার করা সকল পদ্ধতি সংজ্ঞায়িত করতে ***ব্লকচেইন ইন্টারফেস*** +ব্যবহার করে। + +ব্লকচেইন ইন্টারফেস **[মিনিমাল](/docs/edge/architecture/modules/minimal)** সার্ভার দিয়ে ইমপ্লিমেন্ট করা হয়। এটি হচ্ছে ভিত্তি ইমপ্লিমেন্টেশন +যা JSON RPC লেয়ার পাস করা হয়। + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## ETH এন্ডপয়েন্ট {#eth-endpoints} + +সমস্ত স্ট্যান্ডার্ড JSON RPC এন্ডপয়েন্ট এতে প্রয়োগ করা হয়: + +````bash +jsonrpc/eth_endpoint.go +```` + +## ফিল্টার ম্যানেজার {#filter-manager} + +**ফিল্টার ম্যানেজার** একটি পরিষেবা যা JSON RPC সার্ভারের পাশাপাশি রান করে। + +এটি ব্লকচেইনে ব্লক ফিল্টার করতে সহায়তা প্রদান করে।
+বিশেষ করে, এতে **লগ** এবং **ব্লক** লেভেল ফিল্টার উভয়ই অন্তর্ভুক্ত। + +ফিল্টার ম্যানেজার সাবস্ক্রিপশন ইভেন্টে ব্যাপকভাবে নির্ভর করে, যা +[ব্লকচেইন](blockchain#blockchain-subscriptions) বিভাগে উল্লেখ করা হয়েছিল + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +ফিল্টার ম্যানেজার ইভেন্ট *রান* পদ্ধতিতে প্রেরিত করা হয়: + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## 📜 রিসোর্স {#resources} +* **[Ethereum JSON-RPC](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/bn-edge/architecture/modules/minimal.md b/archive/edge/bn-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..d2e37e85bb --- /dev/null +++ b/archive/edge/bn-edge/architecture/modules/minimal.md @@ -0,0 +1,119 @@ +--- +id: minimal +title: মিনিমাল +description: Polygon Edge-এর মিনিমাল মডিউলের ব্যাখ্যা। +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +আগেই উল্লেখ করা হয়েছে যে Polygon Edge হচ্ছে বিভিন্ন মডিউলের একটি সেট, যেগুলো সব একে অপরের সাথে সংযুক্ত।
+উদাহরণস্বরূপ, **ব্লকচেইন** **স্টেট** অথবা **সিঙ্ক্রোনাইজেশন**-এর সাথে সংযুক্ত এবং এগুলো **ব্লকচেইনে** নতুন ব্লক পাইপ করে। + +**মিনিমাল** হচ্ছে এই আন্তঃসংযুক্ত মডিউলের মূল ভিত্তি।
+এটি Polygon Edge-এ পরিচালিত সকল পরিষেবার কেন্দ্রীয় হাব হিসেবে কাজ করে। + +## স্টার্টআপ ম্যাজিক {#startup-magic} + +সেইসব কাজ ছাড়াও মিনিমাল নিম্নোক্ত কাজগুলো সম্পাদন করে থাকে: +* ডেটা ডিরেক্টরি সেট আপ করা +* libp2p কমিউনিকেশনের জন্য একটি কীস্টোর তৈরি করা +* স্টোরেজ +* কনসেনসাস সেটআপ করা +* GRPC, JSON RPC এবং সিঙ্ক্রোনাইজেশন দিয়ে ব্লকচেইন অবজেক্ট সেটআপ করা + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/bn-edge/architecture/modules/networking.md b/archive/edge/bn-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..50ace76c0e --- /dev/null +++ b/archive/edge/bn-edge/architecture/modules/networking.md @@ -0,0 +1,79 @@ +--- +id: networking +title: নেটওয়ার্কিং +description: Polygon Edge-এর নেটওয়ার্কিং মডিউলের ব্যাখ্যা। +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +দরকারী তথ্য বিনিময় করতে একটি নোডকে তার নেটওয়ার্কের মধ্যে অন্যান্য নোডের সাথে যোগাযোগ করতে হবে।
+এই কাজটি সম্পন্ন করতে, Polygon Edge বহুল-পরীক্ষিত **libp2p** ফ্রেমওয়ার্ক ব্যবহার করে। + +**libp2p** ব্যবহারের প্রধান কারণগুলি হচ্ছে: +* **গতি** - devp2p (GETH এবং অন্যান্য ক্লায়েন্ট এটি ব্যবহার করে) এর তুলনায় libp2p-তে অনেক বেশি পারফর্ম্যান্স পাওয়া যায় +* **এক্সটেনসিবিলিটি** - এটি সিস্টেমের অন্যান্য ফিচারগুলোর জন্য একটি দুর্দান্ত বেস হিসাবে কাজ করে +* **মডুলারিটি** - libp2p Polygon Edge-এর মতোই প্রকৃতিগতভাবেই মডুলার। এটি অনেক ফ্লেক্সিবিলিটি প্রদান করে, বিশেষ করে যখন Polygon Edge-এর কিছু অংশ সোয়াপযোগ্য হতে হয় + +## GRPC {#grpc} + +Polygon Edge **libp2p**-এর পাশাপাশি **GRPC** প্রোটোকলও ব্যবহার করে।
+কার্যতভাবে, Polygon Edge বেশ কয়েকটি GRPC প্রোটোকল ব্যবহার করে, যা পরবর্তীতে বর্ণনা করা হবে। + +GRPC লেয়ারটি সকল রিকুয়েস্ট/রিপ্লাই প্রোটোকল অ্যাবস্ট্র্যাক্ট করতে এবং Polygon Edge এর জন্য প্রয়োজনীয় স্ট্রিমিং প্রোটোকল সহজ করতে সহায়তা করে। + +GRPC *সার্ভিস* এবং *মেসেজ স্ট্রাকচার* সংজ্ঞায়িত করতে **প্রোটোকল বাফারের** উপর নির্ভরশীল।
সার্ভিস এবং স্ট্রাকচারগুলো *.proto* ফাইলগুলিতে সংজ্ঞায়িত করা হয়েছে, যেগুলো কম্পাইল করা আছে এবং এগুলো ভাষা-অজ্ঞেয়বাদী। + +পূর্বে আমরা উল্লেখ করেছি যে Polygon Edge বেশ কয়েকটি GRPC প্রোটোকল ব্যবহার করে।
+নোড অপারেটরের জন্য সামগ্রিক UX বুস্ট করতে এটি করা হয়েছিল, যা GETH এবং Parity এর মতো ক্লায়েন্টগুলোতে প্রায়ই ল্যাগ করে। + +নোড অপারেটর লগ থেকে প্রয়োজনীয় তথ্য খুঁজে বের করার পরিবর্তে GRPC সার্ভিস কল করে সিস্টেমে কী ঘটছে সে সম্পর্কে আরো ভালো ওভারভিউ পাবেন। + +### নোড অপারেটরের জন্য GRPC {#grpc-for-node-operators} + +নিম্নলিখিত বিভাগটি পরিচিত মনে হতে পারে কারণ এটি [CLI কমান্ড](/docs/edge/get-started/cli-commands) বিভাগে সংক্ষিপ্তভবে উল্লেখ করা হয়েছে। + +**নোড অপারেটরদের** ব্যবহারেরে জন্য তৈরি GRPC সার্ভিস এমনভাবে সংজ্ঞায়িত করা হয়েছে কারণ: +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip + +CLI কমান্ডগুলো এসব সার্ভিস পদ্ধতিগুলোর ইমপ্লিমেন্টেশনকে কল করে। + +এই পদ্ধতিগুলি ***minimal/system_service.go***-তে ইমপ্লিমেন্ট করা হয়েছে। + +::: + +### অন্যান্য নোডের জন্য GRPC {#grpc-for-other-nodes} + +Polygon Edge অন্যান্য নোডের ব্যবহারের জন্য বেশ কয়েকটি সার্ভিস পদ্ধতি ইমপ্লিমেন্ট করে।
+উল্লিখিত সার্ভিসটি **[প্রোটোকল](docs/edge/architecture/modules/consensus)** বিভাগে বর্ণনা করা হয়েছে। + +## 📜 রিসোর্স {#resources} +* **[প্রোটোকল বাফার](https://developers.google.com/protocol-buffers)** +* **[libp2p](https://libp2p.io/)** +* **[GRPC](https://grpc.io/)** diff --git a/archive/edge/bn-edge/architecture/modules/other-modules.md b/archive/edge/bn-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..fcd962efe7 --- /dev/null +++ b/archive/edge/bn-edge/architecture/modules/other-modules.md @@ -0,0 +1,36 @@ +--- +id: other-modules +title: অন্যান্য মডিউল +description: Polygon Edge-এর কিছু মডিউলের ব্যাখ্যা। +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## ক্রিপ্টো {#crypto} + +**ক্রিপ্টো** মডিউলের মধ্যে ক্রিপ্টো ইউটিলিটি ফাংশন রয়েছে। + +## চেইন {#chain} + +**চেইন** মডিউলের মধ্যে চেইন প্যারামিটার আছে (অ্যাক্টিভ ফর্ক, কনসেনসাস ইঞ্জিন ইত্যাদি।) + +* **চেইন** - আগে থেকে নির্ধারিত চেইন কনফিগারেশন (মেইননেট, goerli, ibft) + +## হেল্পার {#helper} + +**হেল্পার** মডিউলে হেল্পার প্যাকেজ রয়েছে। + +* **dao** - Dao utils +* **enode** - Enode এনকোডিং/ডিকোডিং ফাংশন +* **হেক্স** - হেক্স এনকোডিং/ডিকোডিং ফাংশন +* **ipc** - IPC সংযোগ ফাংশন +* **keccak** - Keccak ফাংশন +* **rlputil** - Rlp এনকোডিং/ডিকোডিং হেল্পার ফাংশন + +## কমান্ড {#command} + +**কমান্ড** মডিউলে CLI কমান্ডের ইন্টারফেস রয়েছে। \ No newline at end of file diff --git a/archive/edge/bn-edge/architecture/modules/sealer.md b/archive/edge/bn-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..59babe6a39 --- /dev/null +++ b/archive/edge/bn-edge/architecture/modules/sealer.md @@ -0,0 +1,73 @@ +--- +id: sealer +title: সিলার +description: Polygon Edge-এর সিলার মডিউলটির ব্যাখ্যা। +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +**Sealer** একটি এন্টিটি যা লেনদেনসমূহ সংগ্রহ করে এবং একটি নতুন ব্লক তৈরি করে।
+তারপর, সেই ব্লকটি সিল করা জন্য **কনসেনসাস** মডিউলে পাঠানো হয়। + +চূড়ান্ত সিলিং লজিকটি **কনসেনসাস** মডিউলে অবস্থিত। + +## প্রক্রিয়া রান করুন {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution কাজ চলছে + +**সিলার** এবং **কনসেনসাস** মডিউলগুলো অদূর ভবিষ্যতে একত্রিত করে একটি একক এনটিটিতে পরিণত করা হতে পারে। + +নতুন মডিউলটি বিভিন্ন ধরণের কনসেনসাস মেকানিজমের জন্য মডুলার লজিককে অন্তর্ভুক্ত করবে, যার জন্য বিভিন্ন ধরনের সিলিং ইমপ্লিমেন্টেশন প্রয়োজন: +* **PoS** (প্রুফ অফ স্টেক) +* **PoA** (প্রুফ অব অথোরিটি) + +বর্তমানে, **সিলার** এবং **কনসেনসাস** মডিউলগুলো PoW (প্রুফ অফ ওয়ার্ক) দিয়েও কাজ করে। + +::: \ No newline at end of file diff --git a/archive/edge/bn-edge/architecture/modules/state.md b/archive/edge/bn-edge/architecture/modules/state.md new file mode 100644 index 0000000000..ea06d34175 --- /dev/null +++ b/archive/edge/bn-edge/architecture/modules/state.md @@ -0,0 +1,248 @@ +--- +id: state +title: স্টেট +description: Polygon Edge-এর স্টেট মডিউলের ব্যাখ্যা। +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +স্টেট **কীভাবে** কাজ করে তা সত্যিকার অর্থে বুঝতে আপনাকে অবশ্যই Ethereum সম্পর্কে কিছু মৌলিক ধারণা থাকতে হবে।
+ +আমরা **[স্টেট ইন Ethereum নির্দেশিকাটি](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)** পড়ার পরামর্শ দিয়ে থাকি। + +## সংক্ষিপ্ত বিবরণ {#overview} + +এখন যেহেতু আমরা নিজেদের মৌলিক Ethereum ধারণাগুলির সাথে পরিচিত করে নিয়েছি, তাই পরবর্তী ওভারভিউ আমাদের জন্য অনেকটা সহজ হয়ে যাবে বলে আশা করছি। + +আমরা উল্লেখ করেছি যে **ওয়ার্ল্ড স্টেট ট্রি**-তে বিদ্যমান সকল Ethereum অ্যাকাউন্ট রয়েছে।
+এই অ্যাকাউন্টগুলো মার্কেল ট্রি-এর পাতা। প্রতিটি পাতায় **অ্যাকাউন্ট স্টেট** জড়িত তথ্য এনকোড করা আছে। + +এটির সাহায্যে Polygon Edge একটি নির্দিষ্ট সময়ের জন্য একটি নির্দিষ্ট মার্কেল ট্রি পেতে পারে।
+উদাহরণস্বরূপ, আমরা ব্লক 10-এ স্টেটের হ্যাশ পেতে পারি। + +মার্কেল ট্রিকে কোনো কোনো সময়ে ***স্ন্যাপশট*** বলা হয়। + +আমরা **স্টেট ট্রি** অথবা **স্টোরেজ ট্রি** এর জন্য ***স্ন্যাপশট*** পেতে পারি - আসলে তারা একই জিনিস।
+একমাত্র পার্থক্য হচ্ছে পাতাগুলো কী নির্দেশ করে: + +* স্টোরেজ ট্রি-এর ক্ষেত্রে পাতাগুলোতে একটি আর্বিট্রারি স্টেট থাকে, যা আমরা প্রক্রিয়া করতে পারি না বা সেখানে কী আছে জানতে পারি না +* স্টেট ট্রি-এর ক্ষেত্রে, পাতাগুলো অ্যাকাউন্টকে নির্দেশ করে + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + +**স্ন্যাপশট** ইন্টারফেসটি নিম্নোক্তভাবে সংজ্ঞায়িত করা যায়: + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +*অবজেক্ট স্ট্রাক্ট* দ্বারা কমিট করা তথ্য সংজ্ঞায়িত করা হয়েছে: + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +মার্কেল ট্রি-এর ইমপ্লিমেন্টেশন *state/immutable-trie* ফোল্ডারে রয়েছে।
+*state/immutable-trie/state.go* **স্টেট** ইন্টারফেসকে ইমপ্লিমেন্ট করে। + +*state/immutable-trie/trie.go* হচ্ছে মেইন মার্কেল ট্রি অবজেক্ট। এটি মার্কেল ট্রি-এর একটি অপ্টিমাইজড সংস্করনের প্রতিনিধিত্ব করে, +যা যতটা সম্ভব মেমরির পুনঃব্যবহার করে। + +## এক্সিকিউটর {#executor} + +একটি ব্লক কীভাবে বর্তমান স্টেটকে পরিবর্তন করবে সে বিষয়ে সিদ্ধান্ত নিতে Polygon Edge-এর প্রয়োজনীয় সকল তথ্য *state/executor.go*-তে অন্তর্ভুক্ত +রয়েছে। *ProcessBlock*-এর ইমপ্লিমেন্টেশন এখানে আছে। + +*Apply* পদ্ধতিটি আসল স্টেট ট্রানজিশনটি করে। এক্সিকিউটর EVM-কে কল করে। + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## রানটাইম {#runtime} + +একটি স্টেট ট্রানজিশন এক্সিকিউট করা হলে যে প্রধান মডিউল সে ট্রানজিশনটি এক্সিকিউট করে সেটি হচ্ছে EVM (এটি +স্টেট/রানটাইম/evm-এর মধ্যে অবস্থিত)। + +**ডিসপ্যাচ টেবিলটি** **opcode** এবং নির্দেশনার মধ্যে ম্যাচ করার চেষ্টা করে। + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +*Run* লুপ হচ্ছে EVM-কে চালিত করার মূল লজিক।
+ +এটি EVM-এর প্রধান এন্ট্রি পয়েন্ট। এটি একটি লুপ করে এবং বর্তমান অপকোড চেক করে, নির্দেশনা নিয়ে আসে, এটি কার্যকর করা যায় কিনা +তা পরীক্ষা করে, গ্যাস খরচ করে এবং নির্দেশনাটি ব্যর্থ বা বন্ধ না হওয়া পর্যন্ত তা এক্সিকিউট করতে থাকে। + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/bn-edge/architecture/modules/storage.md b/archive/edge/bn-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..e89468a629 --- /dev/null +++ b/archive/edge/bn-edge/architecture/modules/storage.md @@ -0,0 +1,117 @@ +--- +id: storage +title: স্টোরেজ +description: Polygon Edge-এর স্টোরেজ মডিউলের ব্যাখ্যা। +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +Polygon Edge বর্তমানে ডেটা স্টোরেজের জন্য **LevelDB** এবং **in-memory** ডেটা স্টোর ব্যবহার করে। + +Polygon Edge এর মধ্য দিয়ে, যখন মডিউলগুলোর যখন অন্তর্নিহিত ডেটা স্টোরের সাথে ইন্টারঅ্যাক্ট করার প্রয়োজন হয়, তাদের জানতে হয়না যে তারা কোন DB ইঞ্জিন বা সার্ভিসের সাথে ইন্টারঅ্যাক্ট করছে। + +DB লেয়ারটি **স্টোরেজ** নামক একটি মডিউলের মধ্যে অ্যাবস্ট্র্যাক্ট হয়ে থাকে, যা মডিউলের কোয়েরি করা ইন্টারফেসগুলো এক্সপোর্ট করে। + +প্রতিটি DB লেয়ার, আপাতত শুধুমাত্র **LevelDB**, এই পদ্ধতিগুলো আলাদাভাবে ইমপ্লিমেন্ট করে, এটা নিশ্চিত করতে যে তারা তাদের ইমপ্লিমেন্টেশনের সাথে ফিট হচ্ছে। + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### Prefixes {#prefixes} + +LevelDB স্টোরেজের কুয়েরিংকে ডিটার্মিনিস্টিক করতে এবং কী স্টোরেজ ক্ল্যাশিং এড়াতে, Polygon Edge +ডেটা সংরক্ষণের সময়ে Prefix এবং sub-prefix ব্যবহার করে + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## ভবিষ্যৎ পরিকল্পনা {#future-plans} + +নিকটবর্তী ভবিষ্যতে কিছু জনপ্রিয় DB সলিউশন যোগ করার পরিকল্পনা আছে, যেমন: +* PostgreSQL +* MySQL + + +## 📜 রিসোর্স {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/bn-edge/architecture/modules/syncer.md b/archive/edge/bn-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..6851bb3d99 --- /dev/null +++ b/archive/edge/bn-edge/architecture/modules/syncer.md @@ -0,0 +1,67 @@ +--- +id: syncer +title: সিঙ্কার +description: Polygon Edge-এর সিঙ্কার মডিউলের ব্যাখ্যা। +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +এই মডিউলে সিঙ্ক্রোনাইজেশন প্রোটোকলের লজিকটি অন্তর্ভুক্ত রয়েছে। চলমান নেটওয়ার্কে একটি নতুন নোড সিঙ্ক করার জন্য অথবা যে নোডগুলো কনসেনসাসে (অ-যাচাইকারী) অংশগ্রহণ করে না সেগুলোর জন্য নতুন ব্লক যাচাই/ইনসার্ট করতে এটি ব্যবহার করা হয়। + +Polygon Edge নেটওয়ার্কিং লেয়ারের জন্য **libp2p** ব্যবহার করে এবং এর উপরে **gRPC** রান করে। + +Polygon Edge-এ মূলত 2 ধরণের সিঙ্ক আছে: +* বাল্ক সিঙ্ক - একবারে একটি বড় পরিসরের ব্লক সিঙ্ক করে +* ওয়াচ সিঙ্ক - প্রতি ব্লক ভিত্তিতে সিঙ্ক করে + +### বাল্ক সিঙ্ক {#bulk-sync} + +বাল্ক সিঙ্কের ধাপগুলো বাল্ক সিঙ্কের লক্ষ্য পূরণের জন্য বেশ সহজবোধ্য - পিছিয়ে না পরার তাগিদে, যত তাড়াতাড়ি সম্ভব, অন্য পিয়ার থেকে যত বেশি ব্লক (যদি থাকে) সিঙ্ক করা সম্ভব হয় তত বেশি ব্লক সিঙ্ক করা। + +এটি বাল্ক সিঙ্ক প্রসেসের ফ্লো: + +1. ** নোডটির বাল্ক সিঙ্ক প্রয়োজন কিনা তা নির্ধারণ করুন ** - এই ধাপে, নোডটি পিয়ার ম্যাপ পরীক্ষা করে দেখে যে নোডের কাছে লোকালি যে ব্লক নাম্বার আছে তার চেয়ে বড় ব্লক নাম্বার অন্য কারও আছে কিনা +2. ** সেরা পিয়ার খুঁজে বের করা (সিঙ্ক পিয়ার ম্যাপ ব্যবহার করে) ** - এই ধাপে নোডটি উপরের উদাহরণে উল্লিখিত মানদণ্ডের উপর ভিত্তি করে সিঙ্ক করার জন্য সেরা পিয়ার খুঁজে বের করে। +3. ** একটি বাল্ক সিঙ্ক স্ট্রিম খুলুন ** - এই ধাপে নোডটি সাধারণ ব্লক নম্বর থেকে ব্লককে বাল্ক সিঙ্ক করার জন্য সেরা পিয়ারের কাছে একটি gRPC স্ট্রিম খোলে +4. ** বাল্ক পাঠানোর পরে সেরা পিয়ারটি স্ট্রিম বন্ধ করে দেয় ** - এই ধাপে নোডটি যে সেরা পিয়ারের সাথে সিঙ্ক করছে সে সমস্ত ব্লকগুলো পাঠানোর সাথে সাথেই স্ট্রিমটি বন্ধ করে দেয় +5. ** বাল্ক সিঙ্কিং শেষ হওয়ার পরে, নোডটি যাচাইকারী কিনা তা দেখা ** - এই ধাপে, স্ট্রিমটি সেরা পিয়ার বন্ধ করে দেয় এবং নোডটি বাল্ক সিঙ্ক করার পরে সে নিজে একজন যাচাইকারী কিনা তা যাচাই করে। + * যদি তারা যাচাইকারী হয়ে থাকে, তবে তারা সিঙ্ক স্টেট থেকে বের হয়ে কনসেনসাসে অংশগ্রহণ করা শুরু করবে + * যদি তারা যাচাইকারী না হয়, তাহলে তারা ** ওয়াচ সিঙ্কে ** থাকা চালিয়ে যাবে + +### ওয়াচ সিঙ্ক {#watch-sync} + +:::info +নোডটি যদি একটি যাচাইকারী না হয়ে নেটওয়ার্কের একটি সাধারণ অ-যাচাইকারী নোড হয় যা শুধু আসন্ন ব্লকের অপেক্ষা করে, শুধুমাত্র তাহলেই ওয়াচ সিঙ্কিং-এর ধাপটি এক্সিকিউট হয়। + +::: + +ওয়াচ সিঙ্কের আচরণ বেশ সহজবোধ্য, নোডটি ইতিমধ্যে বাকি নেটওয়ার্কের সাথে সিঙ্ক করা আছে এবং তাকে কেবলমাত্র নতুন ব্লক পার্স করতে হবে যেগুলো আসন্ন। + +ওয়াচ সিঙ্ক প্রসেসের ফ্লো নিচে দেওয়া হলো: + +1. ** পিয়ারের স্ট্যাটাস আপডেট হলে নতুন ব্লক যোগ করা ** - এই স্টেপে নোডটি নতুন ব্লক ইভেন্ট হওয়ার প্রতীক্ষা করে, যখন সে একটি নতুন ব্লক পায় তখন সে একটি gRPC ফাংশন কল রান করে, ব্লকটি নেয় এবং লোকাল স্টেট আপডেট করে। +2. ** সর্বশেষ ব্লকটি সিঙ্ক করার পরে নোডটি যাচাইকারী কিনা তা যাচাই করা ** + * যদি তা হয়, তাহলে সিঙ্ক স্টেট থেকে বের হন + * যদি তা না হয়, তাহলে নতুন ব্লক ইভেন্টের প্রতীক্ষা করা চালিয়ে যান + +## পারফর্ম্যান্স রিপোর্ট {#perfomance-report} + +:::info + +** এক মিলিয়ন ব্লক ** একটি লোকাল মেশিনে সিঙ্ক করে এর পারফরমেন্স যাচাই করা হয়েছে + +::: + +| নাম | ফলাফল | +|----------------------|----------------| +| 1M ব্লক সিঙ্ক করা | ~ 25 মিনিট | +| 1M ব্লক ট্রান্সফার করা | ~ 1 মিনিট | +| GRPC কলের সংখ্যা | 2 | +| টেস্ট কভারেজ | ~ 93% | \ No newline at end of file diff --git a/archive/edge/bn-edge/architecture/modules/txpool.md b/archive/edge/bn-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..b4ac6760f8 --- /dev/null +++ b/archive/edge/bn-edge/architecture/modules/txpool.md @@ -0,0 +1,231 @@ +--- +id: txpool +title: TxPool +description: Polygon Edge-এর TxPool মডিউলের ব্যাখ্যা। +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +TxPool মডিউল লেনদেন পুল বাস্তবায়নের প্রতিনিধিত্ব করে, যেখানে সিস্টেমের বিভিন্ন অংশ থেকে লেনদেন +যোগ করা হয়। এই মডিউলটি নোড অপারেটরদের জন্য বিভিন্ন দরকারী ফিচার প্রকাশ করে, যা বর্ণনা করা হয়েছে। + +## অপারেটর কমান্ড {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +নোড অপারেটররা এই GRPC এন্ডপয়েন্টগুলো কুয়েরি করতে পারবেন, ঠিক যেমনটা **[CLI কমান্ড](/docs/edge/get-started/cli-commands#transaction-pool-commands)** বিভাগে বর্ণনা করা হয়েছে। + +## লেনদেন প্রসেস করা {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +***addImpl*** পদ্ধতিটি **TxPool** মডিউলের জন্য খুবই গুরুত্বপূর্ণ একটি পদ্ধতি। +এটি সিস্টেমে লেনদেন যোগ করার কেন্দ্র হিসেবে কাজ করে এবং এটিকে GRPC সার্ভিস, JSON RPC এন্ডপয়েন্ট +ও **gossip** প্রোটোকলের মাধ্যমে যেখান থেকে ক্লায়েন্ট লেনদেন পায় সেখান থেকে কল করা যাবে। + +এটি একটি **ctx** আর্গুমেন্ট গ্রহণ করে, যা কেবল লেনদেনটি কোন কনটেক্সট থেকে যোগ করা হচ্ছে তা নির্দেশ করে (GRPC, JSON RPC...)।
+অন্যান্য প্যারামিটার হচ্ছে পুলে যোগ করা হবে এমন লেনদেনের তালিকা। + +এখানে যে বিষয়টির প্রতি নজর দিতে হবে তা হচ্ছে লেনদেনের ভিতরে থাকা **প্রাপক** ফিল্ডটি। +* যদি **প্রাপক** ফিল্ড **খালি** হয়, তাহলে সেটিকে একটি আনএনক্রিপ্টেড/আনঅ্যাসাইন্ড লেনদেন হিসাবে গণ্য করা হয়। এই ধরনের লেনদেন শুধুমাত্র +ডেভেলাপমেন্ট মোডে গ্রহণ করা হয় +* যদি **প্রাপক** ফিল্ড **খালি** না হয়, তার মানে হচ্ছে সেটি একটি স্বাক্ষরিত লেনদেন, তাই স্বাক্ষর যাচাই করা হয়েছিল + +এই সমস্ত যাচাইয়ের পরে, লেনদেন বৈধ বলে গণ্য করা হয়। + +## ডেটা স্ট্রাকচার {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +TxPool অবজেক্টে **কিউ** এবং **সাজানো** তালিকা নিয়ে বিভ্রান্তি সৃষ্টি হতে পারে। +* **কিউ** - অ্যাকাউন্ট লেনদেনের একটি সাজানো তালিকার হিপ বাস্তবায়ন (nonce দ্বারা) +* **সাজানো** - সমস্ত বর্তমান প্রোমোটেড লেনদেনের সাজানো তালিকা (সমস্ত এক্সিকিউটযোগ্য লেনদেন)। গ্যাস মূল্য দ্বারা সাজানো + +## গ্যসের সীমা সংক্রান্ত ত্রুটি ব্যবস্থাপনা {#gas-limit-error-management} + +আপনি কোনো লেনদেন সাবমিট করলে TxPool সেটি তিনটি উপায়ে প্রসেস করে থাকে। + +1. সমস্ত পেন্ডিং লেনদেন একটি ব্লকের মধ্যে ফিট হচ্ছে +2. একটি বা একাধিক পেন্ডিং লেনদেন একটি ব্লকে ফিট হচ্ছে না +3. একটি বা একাধিক পেন্ডিং লেনদেন কখনোই কোনো ব্লকে ফিট হবে না + +এখানে, **_ফিট_** শব্দের মানে হচ্ছে যে লেনদেনের একটি গ্যাস সীমা আছে যা TxPool-এর অবশিষ্ট গ্যাসের তুলনায় কম। + +প্রথম দৃশ্যকল্পে কোনো ত্রুটি দেখা দেয়নি। + +### দ্বিতীয় দৃশ্যকল্প {#second-scenario} + +- TxPool-এর অবশিষ্ট গ্যাস শেষ ব্লকের গ্যাস সীমায় সেট করা হয়েছে, ধরে নিচ্ছি তা **5000** +- প্রথম লেনদেন প্রক্রিয়া করা হয়েছে এবং TxPool-এর **3000** গ্যাস খরচ হয়েছে + - TxPool-এর অবশিষ্ট গ্যাস এখন **2000** +- একটি দ্বিতীয় লেনদেন সাবমিট করা হয়েছে এবং এটিও প্রথমটির মত একই - উভয়েই 3000 ইউনিট গ্যাস খরচ করে +- যেহেতু TxPool-এর অবশিষ্ট গ্যাস লেনদেনের গ্যাসের তুলনায় **কম**, তাই এটিকে বর্তমান ব্লকের মধ্যে প্রক্রিয়া করা +যাবে না + - এটি একটি পেন্ডিং লেনদেনের কিউয়ের মধ্যে রেখে দেওয়া হয়েছে যাতে পরবর্তী ব্লকে এটি প্রসেস করা যায় +- প্রথম ব্লক লেখা হয়েছে, এটিকে **ব্লক #1** নামে ডাকা যাক +- TxPool-এর অবশিষ্ট গ্যাস প্যারেন্ট ব্লক - **ব্লক #1**-এর গ্যাস সীমায় সেট করা হয়েছে +- TxPool-এর পেন্ডিং লেনদেনের কিউয়ের মধ্যে যে লেনদেনটি রাখা হয়েছিল সেটি এখন প্রসেস করা হয়েছে এবং ব্লকে লিখা হয়েছে + - TxPool-এর অবশিষ্ট গ্যাস এখন **2000** +- দ্বিতীয় ব্লক লিখা হয়েছে +- ... + +![TxPool-এর ত্রুটির দৃশ্যকল্প #1](/img/edge/txpool-error-1.png) + +### তৃতীয় দৃশ্যকল্প {#third-scenario} +- TxPool-এর অবশিষ্ট গ্যাস শেষ ব্লকের গ্যাস সীমায় সেট করা হয়েছে, ধরে নিচ্ছি তা **5000** +- প্রথম লেনদেন প্রক্রিয়া করা হয়েছে এবং TxPool-এর **3000** গ্যাস খরচ হয়েছে + - TxPool-এর অবশিষ্ট গ্যাস এখন **2000** +- একটি দ্বিতীয় লেনদেন সাবমিট করা হয়েছে এবং তার গ্যাস ক্ষেত্রে **6000** সেট করা হয়েছে। +- যেহেতু ব্লকের গ্যাস সীমা লেনদেনের গ্যাসের তুলনায় **কম**, তাই এই লেনদেনটি বাতিল করা হয়েছে + - এটি কখনোই কোন ব্লকে ফিট করা যাবে না +- প্রথম ব্লক লিখা হয়েছে +- ... + + +![TxPool-এর ত্রুটি দৃশ্যকল্প #2](/img/edge/txpool-error-2.png) + +> আপনি নিম্নলিখিত ত্রুটি পেলে এই বিষয়টি ঘটে: +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## ব্লক গ্যাস টার্গেট {#block-gas-target} + +কিছু কিছু পরিস্থিতিতে নোড চলমান চেইনে ব্লকের গ্যাস সীমার নিচে বা একটি নির্দিষ্ট টার্গেটের মধ্যে রাখতে চাইতে পারেন। + +নোড অপারেটর কোনো নির্দিষ্ট নোডে টার্গেট গ্যাসের সীমা সেট করে দিতে পারেন, যা নতুন তৈরি ব্লকে সেই সীমা প্রয়োগ করার চেষ্টা করবে। +অন্যান্য নোডের বড় একটি অংশেরও যদি একটি অনুরূপ (বা একই) টার্গেট গ্যাস সীমা সেট করা থাকে, তাহলে ব্লকের গ্যাস সীমা সবসময় +ব্লক গ্যাসের কাছাকাছি উঠা-নামা করবে এবং নতুন ব্লক তৈরি হলে ধীরে ধীরে সেটির দিকে এগিয়ে যাবে (সর্বোচ্চ `1/1024 * parent block gas limit`)। + +### উদাহরণ দৃশ্যকল্প {#example-scenario} + +* নোড অপারেটর একটি একক নোডের ব্লকের গ্যাস সীমা সেট করেছেন `5000` +* অন্যান্য নোডগুলোকেও `5000`-এ কনফিগার করা হয়, তবে একক নোডটিকে `7000`-এ কনফিগার করা হয় +* `5000`-এ সেট করা নোডগুলো যদি প্রস্তাবক হয়ে যায়, তাহলে তারা গ্যাসের সীমা ইতোমধ্যেই টার্গেটে আছে কিনা তা যাচাই করবে +* যদি গ্যাসের সীমা টার্গেটে না থাকে (বেশি/কম হয়), তাহলে প্রস্তাবক নোড টার্গেটের দিকে ব্লক গ্যাস টার্গেট সর্বোচ্চতে সেট করবে (1/1024 * প্যারেন্ট গ্যাসের সীমা) + 1. উদাহরণ: `parentGasLimit = 4500` এবং `blockGasTarget = 5000`, প্রস্তাবক নতুন ব্লকের জন্য `4504.39453125` (`4500/1024 + 4500`) পদ্ধতিতে গ্যাসের সীমা গণনা করবে + 2. উদাহরণ: `parentGasLimit = 5500` এবং `blockGasTarget = 5000`, প্রস্তাবক নতুন ব্লকের জন্য `5494.62890625` (`5500 - 5500/1024`) পদ্ধতিতে গ্যাসের সীমা গণনা করবে +* এটি চেইনে ব্লকের গ্যাস সীমা টার্গেটে থাকার বিষয়টিকে নিশ্চিত করে, কারণ একক প্রস্তাবক যিনি টার্গেট `7000`-এ কনফিগার করেছেন তিনি সীমাটি খুব বেশি বাড়াতে পারবেন না এবং নোডের সংখ্যাগরিষ্ঠরা +যারা টার্গেট `5000`-এ সেট করেছেন তারা চাইবেন যে টার্গেট এখানেই রাখতে \ No newline at end of file diff --git a/archive/edge/bn-edge/architecture/modules/types.md b/archive/edge/bn-edge/architecture/modules/types.md new file mode 100644 index 0000000000..4005814b07 --- /dev/null +++ b/archive/edge/bn-edge/architecture/modules/types.md @@ -0,0 +1,41 @@ +--- +id: types +title: Types +description: Polygon Edge-এ Types মডিউলটির ব্যাখ্যা। +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +**Types** মডিউলটি বিভিন্ন প্রকারের কোর অবজেক্ট ইমপ্লিমেন্ট করে, যেমন: + +* **Address** +* **Hash** +* **Header** +* অনেকগুলো হেল্পার ফাংশন + +## RLP Encoding / Decoding {#rlp-encoding-decoding} + +অন্যান্য ক্লায়েন্ট, যেমন GETH এর মত, Polygon Edge এনকোডিং-এর জন্য রিফ্লেকশন ব্যবহার করেনা।
রিফ্লেকশন ব্যবহার পছন্দনীয় না কারণ তা পার্ফরমেন্স +হ্রাস করে এবং স্কেলিং কঠিন করে। + +**Types** মডিউলটি FastRLP প্যাকেজে ব্যবহার করে, RLP marshaling এবং unmarshalling এর জন্য একটি সহজে ব্যবহারযোগ্য ইন্টারফেস প্রদান করে। + +Marshaling *MarshalRLPWith* এবং *MarshalRLPTO* পদ্ধতির মাধ্যমে করা হয়ে থাকে। অনুরূপ পদ্ধতিগুলো আছে +unmarshalling-এর জন্য। + +এই পদ্ধতিগুলো ম্যানুয়ালি ব্যবহার করার কারণে, Polygon Edge-এর রিফ্লেকশন ব্যবহার করতে হয়না। *rlp_marshal.go* এ, আপনি Marshaling-এর পদ্ধতিগুলো খুঁজে পেতে পারেন: + +* **Bodies** +* **Blocks** +* **Headers** +* **Receipts** +* **Logs** +* **Transactions** \ No newline at end of file diff --git a/archive/edge/bn-edge/architecture/overview.md b/archive/edge/bn-edge/architecture/overview.md new file mode 100644 index 0000000000..586b6e4ebd --- /dev/null +++ b/archive/edge/bn-edge/architecture/overview.md @@ -0,0 +1,61 @@ +--- +id: overview +title: আর্কিটেকচারের ওভারভিউ +sidebar_label: Overview +description: Polygon Edge আর্কিটেকচারের ভূমিকা। +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +আমরা *মডুলার* সফ্টওয়্যার তৈরির ধারণা নিয়ে শুরু করেছি। + +এই বিষয়টি আপনি Polygon Edge-এর সকল স্থানে লক্ষ্য করে থাকবেন। নীচে আপনি বিল্ট আর্কিটেকচার এবং লেয়ারিং-এর +একটি সংক্ষিপ্ত ওভারভিউ পাবেন। + +## Polygon Edge লেয়ার {#polygon-edge-layering} + +![Polygon Edge আর্কিটেকচার](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +এইসব কিছু বেস নেটওয়ার্কিং লেয়ারে শুরু হয়, যেগুলো **libp2p** ব্যবহার করে। আমরা এই প্রযুক্তি ব্যবহারের সিদ্ধান্ত নিয়েছি কারণ এটি +Polygon Edge-এর ডিজাইনিং ধারণার সাথে সঙ্গতিপূর্ণ। Libp2p হল: + +- মডুলার +- প্রসারণযোগ্য +- দ্রুততর + +সবচেয়ে গুরুত্বপূর্ণ হচ্ছে এটি আরো উন্নত ফিচারের খুব ভালো একটি ভিত্তি হিসেবে কাজ করে, যা আমরা পরবর্তীতে উল্লেখ করব। + + +## সিঙ্ক্রোনাইজেশন এবং কনসেনসাস {#synchronization-consensus} +সিঙ্ক্রোনাইজেশন এবং কনসেনসাস প্রোটোকল দুটিকে আলাদা করার ফলে মডুলারিটি এবং **কাস্টম** সিঙ্ক ও কনসেনসাস মেকানিজম ইমপ্লিমেন্টেশনের সুবিধা লাভ করা যায় - তবে এটি নির্ভর করবে ক্লায়েন্ট কিভাবে রান করা হচ্ছে তার উপর। + +Polygon Edge শুরু থেকেই প্লাগযোগ্য কনসেনসাস অ্যালগরিদম প্রদানের জন্য ডিজাইন করা হয়েছে। + +সমর্থিত কনসেনসাস অ্যালগরিদমের বর্তমান তালিকা: + +* IBFT PoA +* IBFT PoS + +## ব্লকচেইন {#blockchain} +ব্লকচেইন লেয়ার হচ্ছে কেন্দ্রীয় লেয়ার যা Polygon Edge সিস্টেমের সবকিছু পরিচালনা করে থাকে। এটি সংশ্লিষ্ট *মডিউল* বিভাগে আরো বিস্তারিতভাবে বর্ণনা করা হয়েছে। + +## স্টেট {#state} +স্টেট অভ্যন্তরীণ লেয়ারটিতে স্টেট ট্রানজিশন লজিক থাকে। এটি নতুন ব্লক অন্তর্ভুক্ত করা হলে কিভাবে স্টেট পরিবর্তন হয় সে বিষয়টি পরিচালনা করে। এটি সংশ্লিষ্ট *মডিউল* বিভাগে আরো বিস্তারিতভাবে বর্ণনা করা হয়েছে। + +## JSON RPC {#json-rpc} +JSON RPC লেয়ার হচ্ছে একটি API লেয়ার যা dApp ডেভেলপাররা ব্লকচেইনের সঙ্গে ইন্টারঅ্যাক্ট করতে ব্যবহার করে। এটি সংশ্লিষ্ট *মডিউল* বিভাগে আরো বিস্তারিতভাবে বর্ণনা করা হয়েছে। + +## TxPool {#txpool} +TxPool লেয়ার লেনদেন পুলকে নির্দেশ করছে এবং এটি সিস্টেমের অন্যান্য মডিউলের সঙ্গে ঘনিষ্ঠভাবে সংযুক্ত আছে, কারণ লেনদেন একাধিক এন্ট্রি পয়েন্ট থেকে যোগ করা যায়। + +## GRPC {#grpc} +gRPC, বা Google রিমোট প্রসেসরস কল, হচ্ছে একটি শক্তসমর্থ ওপেন সোর্স RPC ফ্রেমওয়ার্ক যা প্রাথমিকভাবে গুগল স্কেলেবল এবং দ্রুত API তৈরি করতে তৈরি করে। GRPC লেয়ার অপারেটর ইন্টার‍্যাকশনের জন্য খুবই গুরুত্বপূর্ণ। এর মাধ্যমে নোড অপারেটররা সহজেই ক্লায়েন্টের সঙ্গে ইন্টারঅ্যাক্ট করতে পারেন, ফলে UX আরো উপভোগ্য হয়ে উঠে। diff --git a/archive/edge/bn-edge/community/propose-new-feature.md b/archive/edge/bn-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..4a64e5ae07 --- /dev/null +++ b/archive/edge/bn-edge/community/propose-new-feature.md @@ -0,0 +1,60 @@ +--- +id: propose-new-feature +title: একটি নতুন ফিচার প্রস্তাব করুন +description: "একটি নতুন ফিচার প্রস্তাব করার PR টেমপ্লেট এবং নির্দেশাবলী।" +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +আপনি যদি কোন সংশোধন যোগ করতে চান বা শুধুমাত্র কোড দিয়ে অবদান রাখতে চান, তাহলে প্রথমে টিমের সাথে যোগাযোগ করার জন্য বিশেষভাবে উৎসাহ প্রদান করা হচ্ছে।
+Polygon Edge তুলনামূলকভাবে মৌলিক ফিচারের প্রস্তাবনা টেমপ্লেট ব্যবহার করে, যা সংক্ষিপ্ত এবং সুনির্দিষ্ট। + +## PR টেমপ্লেট {#pr-template} + +### বিবরণ {#description} + +এই PR-এর মধ্যে কী করা হয়েছিল অনুগ্রহ করে তার একটি বিস্তারিত বিবরণ প্রদান করুন + +### পরিবর্তনে অন্তর্ভুক্ত আছে {#changes-include} + +- [ ] Bugfix (নন-ব্রেকিং পরিবর্তন যা সমস্যা সমাধান করে) +- [ ] Hotfix (পরিবর্তন যা জরুরি এবং তাৎক্ষণিক সমাধান প্রয়োজন এমন সমস্যা সমাধান করে থাকে) +- [ ] নতুন ফিচার (নন-ব্রেকিং পরিবর্তন যা ফাংশনালিটি যোগ করে) +- [ ]ব্রেকিং পরিবর্তন (পরিবর্তন যা পূর্ববর্তী সংস্করণ সমর্থন করে না এবং/অথবা বর্তমান ফাংশনালিটি পরিবর্তন করে) + +### ব্রেকিং পরিবর্তন {#breaking-changes} + +কোনো ব্রেকিং পরিবর্তন করা হলে দয়া করে এই বিভাগটি সম্পন্ন করুন, অন্যথায় এটি মুছে ফেলুন + +### চেকলিস্ট {#checklist} + +- [ ] আমি নিজেকে এই PR-টি অ্যাসাইন করেছি +- [ ] আমি অন্তত 1 জন রিভিউয়ার যোগ করেছি +- [ ] আমি প্রাসঙ্গিক লেবেলটি যোগ করেছি +- [ ] আমি অফিসিয়াল ডকুমেন্টেশনটি আপডেট করেছি +- [ ] আমি কোডে পর্যাপ্ত ডকুমেন্টেশন যোগ করেছি + +### টেস্টিং {#testing} + +- [ ] আমি অফিসিয়াল টেস্ট স্যুট দিয়ে এই কোডটি টেস্ট করেছি +- [ ] আমি নিজে এই কোড পরীক্ষা করেছি + +## ম্যানুয়াল টেস্ট {#manual-tests} + +আপনি এই ফাংশনালিটির জন্য ম্যানুয়াল টেস্ট রান করে থাকলে এই বিভাগটি সম্পন্ন করুন, অন্যথায় এটি মুছে ফেলুন + +### ডকুমেন্টেশন আপডেট {#documentation-update} + +অনুগ্রহ করে এই বিভাগে ডকুমেন্টেশন আপডেট PR লিঙ্ক করুন যদি থাকে, নাহলে এটি মুছে ফেলুন + +### অতিরিক্ত মন্তব্য {#additional-comments} + +আপনার যদি কোনো অতিরিক্ত মন্তব্য থাকে তাহলে অনুগ্রহ করে এই বিভাগে পোস্ট করুন, অন্যথায় এটি মুছে ফেলুন \ No newline at end of file diff --git a/archive/edge/bn-edge/community/report-bug.md b/archive/edge/bn-edge/community/report-bug.md new file mode 100644 index 0000000000..42818efa38 --- /dev/null +++ b/archive/edge/bn-edge/community/report-bug.md @@ -0,0 +1,55 @@ +--- +id: report-bug +title: একটি সমস্যার রিপোর্ট করুন +description: Polygon Edge-এর সমস্যা রিপোর্ট করার টেমপ্লেট এবং নির্দেশাবলী। +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +কখনো কখনো জিনিস নষ্ট হয়ে যায়।
+আপনি সম্মুখীন হতে পারেন এমন যেকোনো সমস্যার ব্যাপারে সর্বদা টিমের সাথে যোগাযোগ রাখুন।
+Polygon Edge GitHub পৃষ্ঠায়, আপনি নতুন কোনো ইস্যু ফাইল করতে পারবেন এবং টিমের সাথে সেটি নিয়ে আলোচনা করতে পারবেন। + +## ইস্যু টেমপ্লেট {#issue-template} + +## [ইস্যুর বিষয়] + +### বিবরণ {#description} + +এখানে আপনার সমস্যাটিকে যতটা সম্ভব বিস্তারিতভাবে বর্ণনা করুন + +### আপনার এনভায়রনমেন্ট {#your-environment} + +* OS এবং সংস্করণ +* Polygon Edge-এর সংস্করণ +* যে ব্রাঞ্চে সমস্যাটি দেখা দিয়েছে + +### পুনরুত্পাদনের ধাপ {#steps-to-reproduce} + +* এই সমস্যাটি কিভাবে পুনরুত্পাদন করতে হবে তা আমাদের বলুন
+* সমস্যা কোথায়, আপনি যদি জানেন বলুন
+* কোন কমান্ডের কারণে সমস্যাটি ট্রিগার করেছে, যদি কোনো থাকে + +### প্রত্যাশিত আচরণ {#expected-behaviour} + +আমাদের বলুন কী ঘটা উচিত ছিল + +### প্রকৃত আচরণ {#actual-behaviour} + +পরিবর্তে কী ঘটেছে তা আমাদের বলুন + +### লগ {#logs} + +সমস্যাটির উল্লেখ করা যেকোনো লগ এখানে পেস্ট করুন, যদি তা থাকে + +### প্রস্তাবিত সমাধান {#proposed-solution} + +এই সমস্যাটি সমাধানের বিষয়ে যদি আপনার কোনো প্রস্তাব থাকে, তাহলে এখানে লিখুন যাতে আমরা এটি নিয়ে আলোচনা শুরু করতে পারি \ No newline at end of file diff --git a/archive/edge/bn-edge/configuration/manage-private-keys.md b/archive/edge/bn-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..30e9c7c3e2 --- /dev/null +++ b/archive/edge/bn-edge/configuration/manage-private-keys.md @@ -0,0 +1,76 @@ +--- +id: manage-private-keys +title: প্রাইভেট কী পরিচালনা করুন +description: "প্রাইভেট কী কীভাবে পরিচালনা করতে হয় এবং কী ধরনের কী আছে।" +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +Polygon Edge-এর দুই ধরনের প্রাইভেট কী রয়েছে যা এটি সরাসরি পরিচালনা করে: + +* **কনসেনসাস মেকানিজমের জন্য ব্যবহৃত প্রাইভেট কী** +* **libp2p দ্বারা নেটওয়ার্কিং-এর জন্য ব্যবহৃত প্রাইভেট কী** +* **(ঐচ্ছিক) যাচাইকারীদের স্বাক্ষর একত্র করতে কনসেনসাস মেকানিজমের ব্যবহারের জন্য BLS প্রাইভেট কী** + +বর্তমানে, Polygon Edge সরাসরি অ্যাকাউন্ট পরিচালনার জন্য সাপোর্ট প্রদান করে না। + +[ব্যাকআপ এবং রিস্টোর নির্দেশিকায়](/docs/edge/working-with-node/backup-restore) উল্লিখিত ডিরেক্টরি স্ট্রাকচার অনুসারে +Polygon Edge এই উল্লিখিত কী ফাইলগুলোকে দুটো স্বতন্ত্র ডিরেক্টরিতে জমা রাখে - **কনসেনসাস** এবং **keystore**। + +## কী ফরম্যাট {#key-format} + +প্রাইভেট কীগুলো সহজ **Base64 ফর্ম্যাটে** স্টোর করা হয়, যাতে সেটি মানুষের পড়ার যোগ্য এবং সহজে বহনযোগ্য হয়। + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info কী-এর ধরন + +Polygon Edge-এর ভিতরে তৈরি এবং ব্যবহৃত সকল প্রাইভেট কী ফাইল [secp256k1](https://en.bitcoin.it/wiki/Secp256k1) কার্ভ সহ ECDSA-এর উপর নির্ভরশীল। + +যেহেতু কার্ভটি স্ট্যান্ডার্ড নয়, তাই এটি কোন স্ট্যান্ডার্ডাইজড PEM ফর্ম্যাটে এনকোড এবং সংরক্ষণ করা যাবে না। এই কী টাইপের অনুরূপ নয় এমন কী ইমপোর্ট করা সমর্থিত নয়। + +::: +## Consensus প্রাইভেট কী {#consensus-private-key} + +*কনসেনসাস প্রাইভেট কী* হিসাবে উল্লিখিত প্রাইভেট কী'কে **যাচাইকারীর প্রাইভেট** হিসাবেও উল্লেখ করা হয়। যখন নোড নেটওয়ার্কে একটি যাচাইকারী হিসেবে কাজ করে এবং নতুন ডেটা সাইন করে তখন এই প্রাইভেট কী ব্যবহার করা হয়। + +প্রাইভেট কী ফাইলটি `consensus/validator.key`-এ অবস্থিত এবং উল্লেখিত [কী ফর্ম্যাট](/docs/edge/configuration/manage-private-keys#key-format) অনুসরণ করে। + +:::warning + +যাচাইকারীর প্রাইভেট কী প্রতিটি যাচাইকারী নোডের জন্য ইউনিক। একই কী সব যাচাইকারীদের মধ্যে ভাগ করা উচিত না, কারণ এটি আপনার চেইনে নিরাপত্তা জনিত সমস্যা সৃষ্টি করতে পারে। +::: + +## নেটওয়ার্কিং প্রাইভেট কী {#networking-private-key} + +নেটওয়ার্কিং এর জন্য উল্লিখিত প্রাইভেট কী ফাইলটি libp2p দ্বারা ব্যবহৃত হয়, যাতে সংশ্লিষ্ট PeerID তৈরি করা যায় এবং নোডটিকে নেটওয়ার্কে অংশগ্রহণের অনুমতি দেয়া যায়। + +এটি `keystore/libp2p.key`-এ অবস্থিত এবং উল্লেখ করা [কী ফর্ম্যাট](/docs/edge/configuration/manage-private-keys#key-format) অনুসরণ করে। + +## BLS সিক্রেট কী {#bls-secret-key} + +কনসেনসাস লেয়ারে কমিটেড সিলগুলো একত্রিত করতে BLS সিক্রেট কী ফাইলটি ব্যবহার করা হয়। BLS দ্বারা একত্রিত কমিটেড সিলগুলোর আকার সিরিয়ালিজড কমিটেড ECDSA স্বাক্ষরগুলোর থেকে ছোট। + +BLS ফিচারটি ঐচ্ছিক এবং BLS ব্যবহার করবেন কিনা তা আপনি নির্বাচন করবেন। আরও বিস্তারিত জানতে [BLS](/docs/edge/consensus/bls) পড়ুন। + +## ইম্পোর্ট / এক্সপোর্ট {#import-export} + +যেহেতু কী ফাইলগুলো সাধারণ Base64 আকারে ডিস্কে সংরক্ষণ করা, তাই এগুলো সহজেই ব্যাকআপ বা ইম্পোর্ট করা যায়। + +:::caution কী ফাইলগুলো পরিবর্তন করা + +ইতোমধ্যে সেটআপকৃত / চলমান নেটওয়ার্কের কী ফাইলগুলিতে করা যে কোন ধরনের পরিবর্তন নেটওয়ার্ক/কনসেনসাসে গুরুতর সমস্যার সৃষ্টি করতে পারে, +কারণ কনসেনসাস এবং পিয়ার ডিসকভারি মেকানিজম এই কীগুলো থেকে প্রাপ্ত ডেটা নোড-নির্দিষ্ট স্টোরেজে সংরক্ষণ করে এবং সংযোগ শুরু করতে ও কনসেনসাস লজিক +সম্পাদন করতে এই ডেটার উপর নির্ভর করে + +::: \ No newline at end of file diff --git a/archive/edge/bn-edge/configuration/prometheus-metrics.md b/archive/edge/bn-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..889fa636b0 --- /dev/null +++ b/archive/edge/bn-edge/configuration/prometheus-metrics.md @@ -0,0 +1,35 @@ +--- +id: prometheus-metrics +title: Prometheus মেট্রিক্স +description: "Polygon Edge-এর জন্য Prometheus মেট্রিক্স কীভাবে সক্ষম করবেন।" +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +Polygon Edge Prometheus মেট্রিক্স রিপোর্ট এবং পরিবেশন করতে পারে, যা Prometheus সংগ্রাহক(গণ) দ্বারা ব্যবহার করা যেতে পারে। + +Prometheus মেট্রিক্স ডিফল্টরূপে নিষ্ক্রিয় করা থাকে। কনফিগ ফাইলে `--prometheus` ফ্ল্যাগ বা `Telemetry.prometheus` ক্ষেত্র ব্যবহার করে শ্রোতা ঠিকানা নির্দিষ্ট করার মাধ্যমে এটি সক্রিয় করা যাবে। +মেট্রিক্স নির্দিষ্ট ঠিকানায় `/metrics`-এর অধীনে পরিবেশন করা হবে। + +## উপলভ্য মেট্রিক্স {#available-metrics} + +নিম্নলিখিত মেট্রিক্স পাওয়া যাচ্ছে: + +| **নাম** | **ধরন** | **বিবরণ** | +|-----------------------------------------------|---------------|-------------------------------------------------| +| txpool_pending_transactions | গেজ | TxPool-এ পেন্ডিং থাকা লেনদেনের সংখ্যা | +| consensus_validators | গেজ | যাচাইকারীর সংখ্যা | +| consensus_rounds | গেজ | রাউন্ডের সংখ্যা | +| consensus_num_txs | গেজ | সর্বশেষ ব্লকে লেনদেনের সংখ্যা | +| consensus_block_interval | গেজ | এই ব্লক এবং শেষ ব্লকের মধ্যকার সময়ের পার্থক্য সেকেন্ডে | +| network_peers | গেজ | সংযুক্ত পিয়ারের সংখ্যা | +| network_outbound_connections_count | গেজ | আউটবাউন্ড সংযোগের সংখ্যা | +| network_inbound_connections_count | গেজ | ইনবাউন্ড সংযোগের সংখ্যা | +| network_pending_outbound_connections_count | গেজ | পেন্ডিং আউটবাউন্ড সংযোগের সংখ্যা | +| network_pending_inbound_connections_count | গেজ | পেন্ডিং ইনবাউন্ড সংযোগের সংখ্যা | \ No newline at end of file diff --git a/archive/edge/bn-edge/configuration/sample-config.md b/archive/edge/bn-edge/configuration/sample-config.md new file mode 100644 index 0000000000..262c260cbc --- /dev/null +++ b/archive/edge/bn-edge/configuration/sample-config.md @@ -0,0 +1,149 @@ +--- +id: sample-config +title: সার্ভার কনফিগ ফাইল +description: "একটি কনফিগারেশন ফাইল ব্যবহার করে Polygon Edge সার্ভার শুরু করুন।" +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# সার্ভার কনফিগারেশন ফাইল {#server-configuration-file} +শুধু ফ্ল্যাগ ব্যবহার করার পরিবর্তে, বিভিন্ন কনফিগারেশন অপশন সহ একটি কনফিগারেশন ফাইল ব্যবহার করে সার্ভার শুরু করা যেতে পারে। একটি কনফিগ ফাইল দিয়ে সার্ভার শুরু করার কমান্ড: `polygon-edge server --config ` + +## ডিফল্ট কনফিগারেশন সহ কনফিগ ফাইল এক্সপোর্ট করুন {#export-config-file-with-default-configuration} +Polygon Edge সার্ভারের জন্য ডিফল্ট সেটিংস সহ একটি কনফিগারেশন ফাইল হয় `yaml` অথবা `json` ফাইল ফরম্যাটে এক্সপোর্ট করা যাবে। একটি কনফিগারেশন ফাইল ব্যবহার করে সার্ভার চালানোর জন্য এই ফাইলটি একটি টেমপ্লেট হিসাবে ব্যবহার করা যাবে। + +### YAML {#yaml} +`yaml` ফরম্যাটে কনফিগ ফাইল তৈরি করতে: +```bash +polygon-edge server export --type yaml +``` +বা শুধু +```bash +polygon-edge server export +``` +`default-config.yaml` নামে কনফিগ ফাইলটি সেই ডিরেক্টরিতে তৈরি হবে যেখান থেকে এই কমান্ড রান করা হয়েছে। + +ফাইলের উদাহরণ: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +`json` ফরম্যাটে কনফিগ ফাইল তৈরি করতে: +```bash +polygon-edge server export --type json +``` +`default-config.json` নামে কনফিগ ফাইলটি সেই ডিরেক্টরিতে তৈরি হবে যেখান থেকে এই কমান্ড রান করা হয়েছে। + +ফাইলের উদাহরণ: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +এই প্যারামিটারগুলো কীভাবে ব্যবহার করতে হয় তা জানতে [CLI কমান্ড](/docs/edge/get-started/cli-commands) বিভাগটি দেখুন। + +### Typescript schema {#typescript-schema} + +কনফিগারেশন ফাইলের জন্য নিম্নোক্তটি হলো নমুনা ফরম্যাট। বৈশিষ্ট্যের ধরণ (`string`,,`number`) `boolean` প্রকাশ করার জন্য এটি TypeScript-এ লেখা আছে, এটি থেকে আপনি আপনার কনফিগারেশন পেতে পারেন। এটি উল্লেখযোগ্য যে, সকল বৈশিষ্ট্য যে ঐচ্ছিক তা প্রকাশ করতে `type-fest`-এর `PartialDeep` টাইপ ব্যবহার করা হয়। + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/bn-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/bn-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..09a6f83775 --- /dev/null +++ b/archive/edge/bn-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,135 @@ +--- +id: set-up-aws-ssm +title: AWS SSM (সিস্টেম ম্যানেজার) সেট আপ করুন +description: "Polygon Edge এর জন্য AWS SSM (সিস্টেম ম্যানেজার) সেট আপ করুন।" +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +বর্তমানে, Polygon Edge 2টি প্রধান রানটাইমকে সিক্রেট রাখা নিয়ে চিন্তিত: +* নোডটি যদি একটি যাচাইকারী হয়, তাহলে সেটি **যাচাইকারীর প্রাইভেট কী** ব্যবহার করে +* অন্যান্য পিয়ারদের সাথে অংশগ্রহন এবং যোগাযোগ করার জন্য libp2p **নেটওয়ার্কিং প্রাইভেট কী** ব্যবহার করে + +অতিরিক্ত তথ্যের জন্য, [প্রাইভেট কী পরিচালনার](/docs/edge/configuration/manage-private-keys) নির্দেশিকাটি পড়ুন + +Polygon Edge-এর মডিউলগুলোর জানার **দরকার নেই কীভাবে তথ্য গোপন রাখতে হয়**। তাছাড়া, কোনো সিক্রেটকে কোনো দূরবর্তী সার্ভার নাকি +স্থানীয়ভাবে নোডের ডিস্কে সংরক্ষণ করা হচ্ছে তা নিয়ে মডিউলকে চিন্তা করতে হবে না। + +সিক্রেট-কিপিং সম্পর্কে একটি মডিউলের যা জানার দরকার তা হল **কীভাবে সিক্রেট ব্যবহার করতে হয় তা জানা**, **কোন সিক্রেট পেতে হবে +বা সংরক্ষণ করতে হবে তা জানা**। এই ক্রিয়াকলাপগুলির সূক্ষ্ম ইমপ্লিমেন্টেশনের বিস্তারিত `SecretsManager`-এর উপর অর্পণ করা হয়, যা অবশ্যই একটি অ্যাবস্ট্র্যাকশন। + +Polygon Edge শুরু করা নোড অপারেটরটি এখন সে যেই সিক্রেট ম্যানেজার ব্যবহার করতে চায় তা নির্দিষ্ট করতে পারে এবং +সঠিক সিক্রেট ম্যানেজারটিকে ইনস্ট্যানশিয়েট করার সাথে সাথেই মডিউলগুলি উল্লিখিত ইন্টারফেসের মাধ্যমে সিক্রেট নিয়ে কাজ করে - +সেটি একটি ডিস্ক নাকি সার্ভারে সংরক্ষণ করা হয়েছে সে ব্যাপারে কোনো চিন্তা ছাড়াই। + +এই নিবন্ধটিতে Polygon Edge-কে +[AWS সিস্টেম ম্যানেজার প্যারামিটার স্টোর](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) দিয়ে সুন্দরভাবে পরিচালনা করার প্রয়োজনীয় পদক্ষেপসমূহের বিস্তারিত আলোচনা করা হয়েছে। + +:::info পূর্ববর্তী নির্দেশিকা + +আমরা আপনাকে **পরামর্শ দিচ্ছি** যে আপনি [**লোকাল সেটআপ**](/docs/edge/get-started/set-up-ibft-locally) +এবং [**ক্লাউড সেটআপ**](/docs/edge/get-started/set-up-ibft-on-the-cloud) নিবন্ধগুলো আগে পড়ে নিবেন। + +::: + + +## পূর্বশর্ত {#prerequisites} +### IAM পলিসি {#iam-policy} +ব্যবহারকারীকে একটি IAM পলিসি তৈরি করতে হবে যা AWS সিস্টেম ম্যানেজার প্যারামিটার স্টোরকে রিড/রাইট কার্যাবলী করতে দিবে। IAM পলিসি সফলভাবে তৈরি করার পরে, ব্যবহারকারীকে এটিকে EC2 ইনস্ট্যান্সে যোগ করতে হবে যা Polygon Edge সার্ভারটি চালাচ্ছে। IAM পলিসিকে দেখতে কিছুটা এরকম হবে: +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +AWS SSM IAM রোল সম্পর্কে আরও তথ্য আপনি [AWS docs](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html) এ খুঁজে পাবেন। + +এগিয়ে যাওয়ার আগে প্রয়োজনীয় তথ্য: +* **রিজিওন** (সিস্টেম ম্যানেজার এবং নোড যেই অঞ্চলে থাকে) +* **প্যারামিটার পাথ** (আর্বিট্রারি পাথ যেখানে রাখা হবে, উদাহরণস্বরূপ`/polygon-edge/nodes`) + +## ধাপ 1 - সিক্রেট ম্যানেজার কনফিগারেশন তৈরি করুন {#step-1-generate-the-secrets-manager-configuration} + +Polygon Edge-কে AWS SSM-এর সাথে অবিচ্ছিন্ন যোগাযোগ রাখতে এটিকে ইতোমধ্যে জেনারেট করা একটি কনফিগ ফাইল পার্স করতে হবে +যা AWS SSM-এ সিক্রেট স্টোরেজের জন্য প্রয়োজনীয় সকল তথ্য রাখে। + +কনফিগারেশন তৈরি করতে, নিম্নলিখিত কমান্ড চালান: + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +বর্তমান প্যারামিটার: +* `PATH` হচ্ছে সেই পাথ যেখানে কনফিগারেশন ফাইল এক্সপোর্ট করতে হবে। ডিফল্ট `./secretsManagerConfig.json` +* `NODE_NAME` হচ্ছে বর্তমান নোডের নাম যার জন্য AWS SSM কনফিগারেশন সেট আপ করা হচ্ছে। এটি একটি আর্বিট্রারি মান হতে পারে। ডিফল্ট `polygon-edge-node` +* `REGION` এমন একটি রিজিওন যেখানে AWS SSM থাকে। এটিকে AWS SSM ব্যবহার করা নোডের মতো একই রিজিওনের হতে হবে। +* `SSM_PARAM_PATH` হচ্ছে সেই পাথের নাম যেখানে সিক্রেট সংরক্ষণ করা হবে। উদাহরণস্বরূপ, যদি `--name node1` এবং `ssm-parameter-path=/polygon-edge/nodes` +নির্দিষ্ট করা হয়, তাহলে সিক্রেট সংরক্ষণ করা হবে `/polygon-edge/nodes/node1/` নামে + +:::caution নোডের নাম +নোডের নাম নির্দিষ্ট করার সময় সতর্ক থাকুন। + +Polygon Edge নির্দিষ্ট নোড নাম ব্যবহার করে তাদের জেনারেট করা সিক্রেটের ট্র্যাক রাখে এবং তা AWS SSM-এ ব্যবহার করে। একটি বিদ্যমান নোডের নাম নির্দিষ্ট করলে AWS SSM-এ সিক্রেট রাইট করার ক্ষেত্রে ব্যর্থতা ঘটতে পারে। + +নিম্নলিখিত বেস পাথে সিক্রেট সংরক্ষণ করা হয়: `SSM_PARAM_PATH/NODE_NAME` + +::: + +## ধাপ 2 - কনফিগারেশন ব্যবহার করে সিক্রেট কী চালু করুন {#step-2-initialize-secret-keys-using-the-configuration} + +এখন যেহেতু কনফিগারেশন ফাইল উপস্থিত আছে, আমরা ধাপ 1-এ সেটআপ করা কনফিগারেশন ফাইলটি দিয়ে প্রয়োজনীয় সিক্রেট কী +চালু করতে পারি `--config` ব্যবহার করে: + +```bash +polygon-edge secrets init --config +``` + +`PATH` প্যারামটি হল ধাপ 1-এ আগেই তৈরি করা সিক্রেট ম্যানেজার প্যারামের অবস্থান। + +:::info IAM পলিসি + +রিড/রাইট অপারেশনের অনুমতি দেয়া IAM পলিসিটি সঠিকভাবে কনফিগার করা না হলে এবং/অথবা এই কমান্ড চালিয়ে EC2 ইনস্ট্যান্সে সংযুক্ত না করলে এই ধাপটি ব্যর্থ হবে। + +::: + +## ধাপ 3 - জেনেসিস ফাইল তৈরি করুন {#step-3-generate-the-genesis-file} + +জেনেসিস ফাইল [**লোকাল সেটআপ**](/docs/edge/get-started/set-up-ibft-locally) +এবং [**ক্লাউড সেটআপ**](/docs/edge/get-started/set-up-ibft-on-the-cloud) নির্দেশিকার মত একই পদ্ধতিতে তৈরি হবে বলে আশা করা হচ্ছে, তবে কিছু ছোট-খাট পরিবর্তন থাকতে পারে। + +যেহেতু লোকাল ফাইল সিস্টেমের পরিবর্তে AWS SSM ব্যবহার করা হচ্ছে, তাই যাচাইকারীর ঠিকানা `--ibft-validator` ফ্ল্যাগ দিয়ে যোগ করা উচিত: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## ধাপ 4 - Polygon Edge ক্লায়েন্ট শুরু করুন {#step-4-start-the-polygon-edge-client} + +এখন যেহেতু কী সেটআপ করা হয়ে গেছে এবং জেনেসিস ফাইল জেনারেট করা হয়েছে, তাই এই প্রসেসের চূড়ান্ত ধাপ হবে +`server` কমান্ড দিয়ে Polygon Edge শুরু করা। + +`server` কমান্ডটি পূর্বে উল্লিখিত নির্দেশিকাগুলোর মতো একই পদ্ধতিতে ব্যবহার করা হয়েছে, কিছু ছোট-খাট সংযোজন সহ - `--secrets-config` ফ্ল্যাগ: +```bash +polygon-edge server --secrets-config ... +``` + +`PATH` প্যারামটি হচ্ছে ধাপ 1-এ আগেই তৈরি করা সিক্রেট ম্যানেজার প্যারামের অবস্থান। \ No newline at end of file diff --git a/archive/edge/bn-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/bn-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..c6f3966ae2 --- /dev/null +++ b/archive/edge/bn-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,121 @@ +--- +id: set-up-gcp-secrets-manager +title: GCP সিক্রেট ম্যানেজার সেটআপ করুন +description: "Polygon Edge-এর জন্য GCP সিক্রেট ম্যানেজার সেটআপ করুন।" +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +বর্তমানে, Polygon Edge 2টি প্রধান রানটাইমকে সিক্রেট রাখা নিয়ে চিন্তিত: +* নোডটি যদি একটি যাচাইকারী হয়, তাহলে সেটি **যাচাইকারীর প্রাইভেট কী** ব্যবহার করে +* অন্যান্য পিয়ারদের সাথে অংশগ্রহন এবং যোগাযোগ করার জন্য libp2p **নেটওয়ার্কিং প্রাইভেট কী** ব্যবহার করে + +অতিরিক্ত তথ্যের জন্য, [প্রাইভেট কী পরিচালনার](/docs/edge/configuration/manage-private-keys) নির্দেশিকাটি পড়ুন + +Polygon Edge-এর মডিউলগুলোর জানার **দরকার নেই কীভাবে তথ্য গোপন রাখতে হয়**। তাছাড়া, কোনো সিক্রেটকে কোনো দূরবর্তী সার্ভার নাকি +স্থানীয়ভাবে নোডের ডিস্কে সংরক্ষণ করা হচ্ছে তা নিয়ে মডিউলকে চিন্তা করতে হবে না। + +সিক্রেট-কিপিং সম্পর্কে একটি মডিউলের যা জানার দরকার তা হল **কীভাবে সিক্রেট ব্যবহার করতে হয় তা জানা**, **কোন সিক্রেট পেতে হবে +বা সংরক্ষণ করতে হবে তা জানা**। এই ক্রিয়াকলাপগুলির সূক্ষ্ম ইমপ্লিমেন্টেশনের বিস্তারিত `SecretsManager`-এর উপর অর্পণ করা হয়, যা অবশ্যই একটি অ্যাবস্ট্র্যাকশন। + +Polygon Edge শুরু করা নোড অপারেটরটি এখন সে যেই সিক্রেট ম্যানেজার ব্যবহার করতে চায় তা নির্দিষ্ট করতে পারে এবং +সঠিক সিক্রেট ম্যানেজারটিকে ইনস্ট্যানশিয়েট করার সাথে সাথেই মডিউলগুলি উল্লিখিত ইন্টারফেসের মাধ্যমে সিক্রেট নিয়ে কাজ করে - +সেটি একটি ডিস্ক নাকি সার্ভারে সংরক্ষণ করা হয়েছে সে ব্যাপারে কোনো চিন্তা ছাড়াই। + +এই নিবন্ধটিতে [GCP সিক্রেট ম্যানেজার](https://cloud.google.com/secret-manager) দিয়ে Polygon Edge পরিচালনা করার প্রয়োজনীয় পদক্ষেপগুলোর বিস্তারিত বর্ণনা করা হয়েছে। + +:::info পূর্ববর্তী নির্দেশিকা + +আমরা আপনাকে **পরামর্শ দিচ্ছি** যে আপনি [**লোকাল সেটআপ**](/docs/edge/get-started/set-up-ibft-locally) +এবং [**ক্লাউড সেটআপ**](/docs/edge/get-started/set-up-ibft-on-the-cloud) নিবন্ধগুলো আগে পড়ে নিবেন। + +::: + + +## পূর্বশর্ত {#prerequisites} +### GCP বিলিং অ্যাকাউন্ট {#gcp-billing-account} +GCP সিক্রেট ম্যানেজার ব্যবহার করতে ব্যবহারকারীকে GCP পোর্টালে [বিলিং অ্যাকাউন্ট](https://console.cloud.google.com/) সক্ষম করতে হবে। +GCP প্ল্যাটফর্মে নতুন Google অ্যাকাউন্টকে বিনামূল্যের ট্রায়ালের রাজা হিসাবে শুরু করতে কিছু ফান্ড প্রদান করা হয়। +আরও তথ্য [GCP ডক্স](https://cloud.google.com/free) + +### সিক্রেট ম্যানেজার API {#secrets-manager-api} +ব্যবহারকারী GCP সিক্রেট ম্যানেজার API ব্যবহার করার পূর্বে এটি সক্ষম করে নিতে হবে। +এই কাজটি [সিক্রেট ম্যানেজার API পোর্টাল](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com) ব্যবহার করে করা যাবে। +আরও তথ্য: [সিক্রেট ম্যানেজার কনফিগার করা](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + +### GCP ক্রেডেনশিয়াল {#gcp-credentials} +সবশেষে, ব্যবহারকারীকে নতুন ক্রেডেনশিয়াল তৈরি করতে হবে যা প্রমাণীকরণের জন্য ব্যবহার করা হবে। +এই কাজটি [এখানে](https://cloud.google.com/secret-manager/docs/reference/libraries) পোস্ট করা নির্দেশাবলী অনুসরণ করে করা যেতে পারে। +ক্রেডেনশিয়াল ধারণকারী json ফাইলটি GCP সিক্রেট ম্যানেজার ব্যবহারের প্রয়োজন রয়েছে এমন সব নোডে ট্রান্সফার করতে হবে। + +এগিয়ে যাওয়ার আগে প্রয়োজনীয় তথ্য: +* **প্রজেক্ট আইডি** (GCP প্ল্যাটফর্মে সংজ্ঞায়িত প্রজেক্ট আইডি) +* **ক্রেডেনশিয়াল ফাইলের অবস্থান** (ক্রেডেনশিয়াল ধারণকারী json ফাইলের পাথ) + +## ধাপ 1 - সিক্রেট ম্যানেজার কনফিগারেশন তৈরি করুন {#step-1-generate-the-secrets-manager-configuration} + +Polygon Edge-কে GCP SM-এর সাথে অবিচ্ছিন্ন যোগাযোগ রাখতে এটিকে ইতোমধ্যে জেনারেট করা একটি কনফিগ ফাইল পার্স করতে হবে +যা GCP SM-এ সিক্রেট স্টোরেজের জন্য প্রয়োজনীয় সকল তথ্য রাখে। + +কনফিগারেশন তৈরি করতে, নিম্নলিখিত কমান্ড চালান: + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +বর্তমান প্যারামিটার: +* `PATH` হচ্ছে সেই পাথ যেখানে কনফিগারেশন ফাইল এক্সপোর্ট করতে হবে। ডিফল্ট `./secretsManagerConfig.json` +* `NODE_NAME` হচ্ছে বর্তমান নোডের নাম যার জন্য GCP SM কনফিগারেশন সেট আপ করা হচ্ছে। এটি একটি আর্বিট্রারি মান হতে পারে। ডিফল্ট `polygon-edge-node` +* `PROJECT_ID` হচ্ছে অ্যাকাউন্ট সেটআপ এবং সিক্রেট ম্যানেজার API অ্যাক্টিভেশনের সময় ব্যবহারকারী দ্বারা GCP কনসোলে সংজ্ঞায়িত করা প্রজেক্ট আইডি। +* `GCP_CREDS_FILE` হচ্ছে ক্রেডেনশিয়াল ধারণকারী json ফাইলের পাথ যা সিক্রেট ম্যানেজারে রিড/রাইট অ্যাক্সেস প্রদান করবে। + +:::caution নোডের নাম + +নোডের নাম নির্দিষ্ট করার সময় সতর্ক থাকুন। + +Polygon Edge নির্দিষ্ট নোড নাম ব্যবহার করে তাদের জেনারেট করা সিক্রেটের ট্র্যাক রাখে এবং তা GCP SM-এ ব্যবহার করে। +একটি বিদ্যমান নোডের নাম নির্দিষ্ট করা হলে GCP SM সিক্রেট রাইট করতে ব্যর্থ হতে পারে। + +নিম্নলিখিত বেস পাথে সিক্রেট সংরক্ষণ করা হয়: `projects/PROJECT_ID/NODE_NAME` + +::: + +## ধাপ 2 - কনফিগারেশন ব্যবহার করে সিক্রেট কী চালু করুন {#step-2-initialize-secret-keys-using-the-configuration} + +এখন যেহেতু কনফিগারেশন ফাইল উপস্থিত আছে, আমরা ধাপ 1-এ সেটআপ করা কনফিগারেশন ফাইলটি দিয়ে প্রয়োজনীয় সিক্রেট কী +চালু করতে পারি `--config` ব্যবহার করে: + +```bash +polygon-edge secrets init --config +``` + +`PATH` প্যারামটি হচ্ছে ধাপ 1-এ আগেই তৈরি করা সিক্রেট ম্যানেজার প্যারামের অবস্থান। + +## ধাপ 3 - জেনেসিস ফাইল তৈরি করুন {#step-3-generate-the-genesis-file} + +জেনেসিস ফাইল [**লোকাল সেটআপ**](/docs/edge/get-started/set-up-ibft-locally) +এবং [**ক্লাউড সেটআপ**](/docs/edge/get-started/set-up-ibft-on-the-cloud) নির্দেশিকার মত একই পদ্ধতিতে তৈরি হবে বলে আশা করা হচ্ছে, তবে কিছু ছোট-খাট পরিবর্তন থাকতে পারে। + +যেহেতু লোকাল ফাইল সিস্টেমের পরিবর্তে GCP SM ব্যবহার করা হচ্ছে, তাই যাচাইকারীর ঠিকানা `--ibft-validator` ফ্ল্যাগ দিয়ে যোগ করা উচিত: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## ধাপ 4 - Polygon Edge ক্লায়েন্ট শুরু করুন {#step-4-start-the-polygon-edge-client} + +এখন যেহেতু কী সেটআপ করা হয়ে গেছে এবং জেনেসিস ফাইল জেনারেট করা হয়েছে, তাই এই প্রসেসের চূড়ান্ত ধাপ হবে +`server` কমান্ড দিয়ে Polygon Edge শুরু করা। + +`server` কমান্ডটি পূর্বে উল্লিখিত নির্দেশিকাগুলোর মতো একই পদ্ধতিতে ব্যবহার করা হয়েছে, কিছু ছোট-খাট সংযোজন সহ - `--secrets-config` ফ্ল্যাগ: +```bash +polygon-edge server --secrets-config ... +``` + +`PATH` প্যারামটি হচ্ছে ধাপ 1-এ আগেই তৈরি করা সিক্রেট ম্যানেজার প্যারামের অবস্থান। \ No newline at end of file diff --git a/archive/edge/bn-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/bn-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..50b0d34fff --- /dev/null +++ b/archive/edge/bn-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,118 @@ +--- +id: set-up-hashicorp-vault +title: Hashicorp ভল্ট সেটআপ করুন +description: "Polygon Edge-এর জন্য Hashicorp ভল্ট সেটআপ করুন।" +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +বর্তমানে, Polygon Edge 2টি প্রধান রানটাইমকে সিক্রেট রাখা নিয়ে চিন্তিত: +* নোডটি যদি একটি যাচাইকারী হয়, তাহলে সেটি **যাচাইকারীর প্রাইভেট কী** ব্যবহার করে +* অন্যান্য পিয়ারদের সাথে অংশগ্রহন এবং যোগাযোগ করার জন্য libp2p **নেটওয়ার্কিং প্রাইভেট কী** ব্যবহার করে + +:::warning + +যাচাইকারীর প্রাইভেট কী প্রতিটি যাচাইকারী নোডের জন্য ইউনিক। একই কী সব যাচাইকারীদের মধ্যে ভাগ করা উচিত না, কারণ এটি আপনার চেইনে নিরাপত্তা জনিত সমস্যা সৃষ্টি করতে পারে। + +::: + +অতিরিক্ত তথ্যের জন্য, [প্রাইভেট কী পরিচালনার](/docs/edge/configuration/manage-private-keys) নির্দেশিকাটি পড়ুন + +Polygon Edge-এর মডিউলগুলোর জানার **দরকার নেই কীভাবে তথ্য গোপন রাখতে হয়**। তাছাড়া, কোনো সিক্রেটকে কোনো দূরবর্তী সার্ভার নাকি +স্থানীয়ভাবে নোডের ডিস্কে সংরক্ষণ করা হচ্ছে তা নিয়ে মডিউলকে চিন্তা করতে হবে না। + +সিক্রেট-কিপিং সম্পর্কে একটি মডিউলের যা জানার দরকার তা হল **কীভাবে সিক্রেট ব্যবহার করতে হয় তা জানা**, **কোন সিক্রেট পেতে হবে +বা সংরক্ষণ করতে হবে তা জানা**। এই ক্রিয়াকলাপগুলির সূক্ষ্ম ইমপ্লিমেন্টেশনের বিস্তারিত `SecretsManager`-এর উপর অর্পণ করা হয়, যা অবশ্যই একটি অ্যাবস্ট্র্যাকশন। + +Polygon Edge শুরু করা নোড অপারেটরটি এখন সে যেই সিক্রেট ম্যানেজার ব্যবহার করতে চায় তা নির্দিষ্ট করতে পারে এবং +সঠিক সিক্রেট ম্যানেজারটিকে ইনস্ট্যানশিয়েট করার সাথে সাথেই মডিউলগুলি উল্লিখিত ইন্টারফেসের মাধ্যমে সিক্রেট নিয়ে কাজ করে - +সেটি একটি ডিস্ক নাকি সার্ভারে সংরক্ষণ করা হয়েছে সে ব্যাপারে কোনো চিন্তা ছাড়াই। + +এই নিবন্ধটিতে [Hashicorp ভল্ট দিয়ে](https://www.vaultproject.io/) Polygon Edge পরিচালনা করার প্রয়োজনীয় পদক্ষেপগুলোর বিস্তারিত বর্ণনা করা হয়েছে। + +:::info পূর্ববর্তী নির্দেশিকা + +আমরা আপনাকে **পরামর্শ দিচ্ছি** যে আপনি [**লোকাল সেটআপ**](/docs/edge/get-started/set-up-ibft-locally) +এবং [**ক্লাউড সেটআপ**](/docs/edge/get-started/set-up-ibft-on-the-cloud) নিবন্ধগুলো আগে পড়ে নিবেন। + +::: + + +## পূর্বশর্ত {#prerequisites} + +এই নিবন্ধটি অনুমান করে যে Hashicorp Vault সার্ভারের একটি কার্যকরী ইনস্ট্যান্স ইতোমধ্যে **সেট আপ করা হয়েছে**। + +তাছাড়া, Polygon Edge-এর জন্য ব্যবহৃত Hashicorp Vault সার্ভারের **KV স্টোরেজ সক্ষম** থাকাটা খুবই গুরুত্বপূর্ণ। + +এগিয়ে যাওয়ার আগে প্রয়োজনীয় তথ্য: +* **সার্ভার URL** (Hashicorp Vault সার্ভারের API URL) +* **টোকেন** (KV স্টোরেজ ইঞ্জিনে অ্যাক্সেসের জন্য ব্যবহৃত অ্যাক্সেস টোকেন) + +## ধাপ 1 - সিক্রেট ম্যানেজার কনফিগারেশন তৈরি করুন {#step-1-generate-the-secrets-manager-configuration} + +Polygon Edge-কে ভল্ট সার্ভারের সাথে অবিচ্ছিন্ন যোগাযোগ রাখতে এটিকে ইতোমধ্যে জেনারেট করা একটি কনফিগ ফাইল পার্স করতে হবে +যা ভল্টে সিক্রেট স্টোরেজের জন্য প্রয়োজনীয় সকল তথ্য রাখে। + +কনফিগারেশন তৈরি করতে, নিম্নলিখিত কমান্ড চালান: + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +বর্তমান প্যারামিটার: +* `PATH` হচ্ছে সেই পাথ যেখানে কনফিগারেশন ফাইল এক্সপোর্ট করতে হবে। ডিফল্ট `./secretsManagerConfig.json` +* `TOKEN` হচ্ছে [পূর্বশর্ত বিভাগে](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) পূর্বে উল্লিখিত অ্যাক্সেস টোকেন +* `SERVER_URL` হচ্ছে ভল্ট সার্ভারের API URL, এটিও [পূর্বশর্ত বিভাগে](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) উল্লেখ করা হয়েছে। +* `NODE_NAME` হচ্ছে বর্তমান নোডের নাম যার জন্য Vault কনফিগারেশন সেট আপ করা হচ্ছে। এটি একটি আর্বিট্রারি মান হতে পারে। ডিফল্ট `polygon-edge-node` + +:::caution নোডের নাম + +নোডের নাম নির্দিষ্ট করার সময় সতর্ক থাকুন। + +Polygon Edge নির্দিষ্ট নোড নাম ব্যবহার করে তাদের জেনারেট করা সিক্রেটের ট্র্যাক রাখে এবং তা ভল্ট ইনস্ট্যান্সে ব্যবহার করে। +একটি বিদ্যমান নোড নাম নির্দিষ্ট করা হলে ভল্ট সার্ভারে তথ্য ওভাররিটেন সমস্যা দেখা দিতে পারে। + +নিম্নলিখিত বেস পাথে সিক্রেট সংরক্ষণ করা হয়: `secrets/node_name` + +::: + +## ধাপ 2 - কনফিগারেশন ব্যবহার করে সিক্রেট কী চালু করুন {#step-2-initialize-secret-keys-using-the-configuration} + +এখন যেহেতু কনফিগারেশন ফাইল উপস্থিত আছে, আমরা ধাপ 1-এ সেটআপ করা কনফিগারেশন ফাইলটি দিয়ে প্রয়োজনীয় সিক্রেট কী +চালু করতে পারি `--config` ব্যবহার করে: + +```bash +polygon-edge secrets init --config +``` + +`PATH` প্যারামটি হচ্ছে ধাপ 1-এ আগেই তৈরি করা সিক্রেট ম্যানেজার প্যারামের অবস্থান। + +## ধাপ 3 - জেনেসিস ফাইল তৈরি করুন {#step-3-generate-the-genesis-file} + +জেনেসিস ফাইল [**লোকাল সেটআপ**](/docs/edge/get-started/set-up-ibft-locally) +এবং [**ক্লাউড সেটআপ**](/docs/edge/get-started/set-up-ibft-on-the-cloud) নির্দেশিকার মত একই পদ্ধতিতে তৈরি হবে বলে আশা করা হচ্ছে, তবে কিছু ছোট-খাট পরিবর্তন থাকতে পারে। + +যেহেতু লোকাল ফাইল সিস্টেমের পরিবর্তে Hashicorp ভল্ট ব্যবহার করা হচ্ছে, তাই যাচাইকারীর ঠিকানা `--ibft-validator` ফ্ল্যাগ দিয়ে যোগ করা উচিত: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## ধাপ 4 - Polygon Edge ক্লায়েন্ট শুরু করুন {#step-4-start-the-polygon-edge-client} + +এখন যেহেতু কী সেটআপ করা হয়ে গেছে এবং জেনেসিস ফাইল জেনারেট করা হয়েছে, তাই এই প্রসেসের চূড়ান্ত ধাপ হবে +`server` কমান্ড দিয়ে Polygon Edge শুরু করা। + +`server` কমান্ডটি পূর্বে উল্লিখিত নির্দেশিকাগুলোর মতো একই পদ্ধতিতে ব্যবহার করা হয়েছে, কিছু ছোট-খাট সংযোজন সহ - `--secrets-config` ফ্ল্যাগ: +```bash +polygon-edge server --secrets-config ... +``` + +`PATH` প্যারামটি হচ্ছে ধাপ 1-এ আগেই তৈরি করা সিক্রেট ম্যানেজার প্যারামের অবস্থান। \ No newline at end of file diff --git a/archive/edge/bn-edge/consensus/bls.md b/archive/edge/bn-edge/consensus/bls.md new file mode 100644 index 0000000000..e68b70a289 --- /dev/null +++ b/archive/edge/bn-edge/consensus/bls.md @@ -0,0 +1,143 @@ +--- +id: bls +title: BLS +description: "BLS মোড সম্পর্কিত ব্যাখ্যা এবং নির্দেশাবলী।" +keywords: + - docs + - polygon + - edge + - bls +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +BLS (BLS) নামেও পরিচিত BLS হল একটি ক্রিপ্টোগ্রাফিক স্বাক্ষর স্কিম যা একটি ব্যবহারকারী তা যাচাই করতে পারবেন যে একটি signer সত্যি signer । এটি একটি স্বাক্ষর স্কিম যা একাধিক স্বাক্ষর aggregate aggregate করতে পারে। Polygon Edge-এ IBFT কনসেনসাস মোডে আরো ভালো নিরাপত্তা প্রদান করতে ডিফল্টরূপে BLS ব্যবহার করা হয়। BLS একাধিক স্বাক্ষরকে একটি একক বাইট অ্যারেতে একত্রিত করতে পারে এবং ফলশ্রুতিতে ব্লকের হেডার সাইজ ছোট করতে পারে। প্রতিটি চেইন BLS ব্যবহার করবে না কি করবে না তা নির্ণয় করতে পারে। BLS মোড সক্রিয় থাকা বা না থাকা নির্বিশেষে ECDSA কী ব্যবহার করা হয়। + +## ভিডিও প্রেজেন্টেশন {#video-presentation} + +[![bls - ভিডিও](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## BLS ব্যবহার করে একটি নতুন চেইন কীভাবে সেটআপ করবেন {#how-to-setup-a-new-chain-using-bls} + +আরো বিস্তারিতভাবে সেটআপের নির্দেশাবলী পেতে [লোকাল সেটআপ](/docs/edge/get-started/set-up-ibft-locally)/ [ক্লাউড সেটআপ](/docs/edge/get-started/set-up-ibft-on-the-cloud) বিভাগসমূহ পড়ুন। + +## একটি বিদ্যমান ECDSA PoA চেইন থেকে BLS PoA চেইনে কীভাবে মাইগ্রেট করবেন {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +একটি বিদ্যমান PoA চেইনে BLS মোড কীভাবে ব্যবহার করবেন তা এই বিভাগে বর্ণনা করা হয়েছে। +একটি PoA চেইনে BLS এনাবেল করতে নিম্নলিখিত পদক্ষেপগুলো আবশ্যকীয়। + +1. সকল নোড বন্ধ করুন +2. যাচাইকারীদের জন্য BLS কী তৈরি করুন +3. genesis.json এ একটি ফর্ক সেটিং যোগ করুন +4. সকল নোড পুনরায় চালু করুন + +### 1. সকল নোড বন্ধ করুন {#1-stop-all-nodes} + +Ctrl + c (Control + C) চেপে যাচাইকারীদের সমস্ত প্রক্রিয়া বন্ধ করুন। অনুগ্রহ করে সর্বশেষ ব্লক উচ্চতা (ব্লক কমিটেড লগের সর্বোচ্চ ক্রম নম্বর) মনে রাখুন। + +### 2. BLS কী তৈরি করুন {#2-generate-the-bls-key} + +`secrets init` এর সাথে `--bls` দিয়ে একটি BLS কী তৈরি হয়। বিদ্যমান ECDSA ও নেটওয়ার্ক কী রাখতে এবং একটি নতুন BLS কী যোগ করতে, `--ecdsa` এবং `--network` নিষ্ক্রিয় করতে হবে। + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. ফর্ক সেটিং যোগ করুন {#3-add-fork-setting} + +`ibft switch` কমান্ড একটি ফর্ক সেটিং যোগ করে, যা `genesis.json`-এর মধ্যে বিদ্যমান চেইনে BLS সক্রিয় করে। + +PoA নেটওয়ার্কের জন্য, যাচাইকারীদের কমান্ড দেওয়ার প্রয়োজন হবে। `genesis` কমান্ড অনুযায়ী, যাচাইকারীকে নির্দিষ্ট করতে `--ibft-validators-prefix-path` বা `--ibft-validator` ফ্ল্যাগ ব্যবহার করা যেতে পারে। + +চেইন কোন উচ্চতা থেকে BLS ব্যবহার করা শুরু করেছে তা `--from` ফ্ল্যাগ দিয়ে নির্দিষ্ট করুন। + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. সকল নোড পুনরায় চালু করুন {#4-restart-all-nodes} + +`server` কমান্ড দ্বারা সকল নোড পুনরায় চালু করুন। পূর্ববর্তী ধাপে উল্লেখিত `from`-এ ব্লক তৈরি করার পরে, চেইনটি BLS সক্রিয় করে এবং নিম্নোক্তভাবে লগ প্রদর্শন করে: + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +এছাড়াও, ব্লক তৈরির পর কোন যাচাইকরণ মোড ব্যবহার করে প্রতিটি ব্লক তৈরি করা হয়েছে তা লগে দেখা যায়। + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## একটি বিদ্যমান ECDSA PoS চেইন থেকে একটি BLS PoS চেইনে কীভাবে মাইগ্রেট করবেন {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +একটি বিদ্যমান PoS চেইনে BLS মোড কীভাবে ব্যবহার করবেন তা এই বিভাগে বর্ণনা করা হয়েছে। +PoS চেইনে BLS সক্রিয় করতে নিম্নলিখিত পদক্ষেপগুলো আবশ্যকীয়। + +1. সকল নোড বন্ধ করুন +2. যাচাইকারীদের জন্য BLS কী তৈরি করুন +3. genesis.json এ একটি ফর্ক সেটিং যোগ করুন +4. BLS পাবলিক কী নিবন্ধন করতে স্টেকিং চুক্তি কল করুন +5. সকল নোড পুনরায় চালু করুন + +### 1. সকল নোড বন্ধ করুন {#1-stop-all-nodes-1} + +Ctrl + c (Control + C) চেপে যাচাইকারীদের সমস্ত প্রক্রিয়া বন্ধ করুন। অনুগ্রহ করে সর্বশেষ ব্লক উচ্চতা (ব্লক কমিটেড লগের সর্বোচ্চ ক্রম নম্বর) মনে রাখুন। + +### 2. BLS কী তৈরি করুন {#2-generate-the-bls-key-1} + +`secrets init`-এর সাথে `--bls` ফ্ল্যাগ দিয়ে BLS কী তৈরি করে। বিদ্যমান ECDSA ও নেটওয়ার্ক কী রাখতে এবং একটি নতুন BLS কী যোগ করতে, `--ecdsa` এবং `--network` নিষ্ক্রিয় করতে হবে। + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. ফর্ক সেটিং যোগ করুন {#3-add-fork-setting-1} + +`ibft switch` কমান্ড একটি ফর্ক সেটিং যোগ করে, যা `genesis.json`-এ চেইনের মধ্যখান থেকে BLS-কে সক্রিয় করে। + +চেইনটি কোন উচ্চতা থেকে BLS মোড ব্যবহার করা শুরু করে `from` ফ্ল্যাগ দিয়ে নির্দিষ্ট করুন এবং `development` ফ্ল্যাগ দিয়ে চুক্তিটি আপডেট করা উচ্চতা নির্দিষ্ট করুন। + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. স্টেকিং চুক্তিতে BLS পাবলিক কী নিবন্ধন করুন {#4-register-bls-public-key-in-staking-contract} + +ফর্ক যোগ এবং যাচাইকারীদের পুনরায় চালু করার পরে, BLS পাবলিক কী নিবন্ধন করতে প্রতিটি যাচাইকারীকে স্টেকিং চুক্তিতে `registerBLSPublicKey` কল করতে হবে। এটি অবশ্যই `--from`-এ উচ্চতা নির্দিষ্ট করার আগে `--deployment`-এ উচ্চতা নির্দিষ্ট করে তারপর করতে হবে। + +BLS পাবলিক কী নিবন্ধন করার স্ক্রিপ্টটি [স্টেকিং স্মার্ট চুক্তি রেপোতে](https://github.com/0xPolygon/staking-contracts) সংজ্ঞায়িত করা হয়েছে। + +`BLS_PUBLIC_KEY`-কে `.env` ফাইলে নিবন্ধন করার জন্য সেট করুন। অন্যান্য প্যারামিটার সম্পর্কে আরও বিস্তারিত জানতে [pos-stake-unstake](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) পড়ুন। + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +নিম্নলিখিত কমান্ড `.env`-তে প্রদত্ত BLS পাবলিক কী'কে চুক্তিতে নিবন্ধন করে। + +```bash +npm run register-blskey +``` + +:::warning যাচাইকারীদের BLS পাবলিক কী ম্যানুয়ালি নিবন্ধন করতে হবে + +BLS মোডে, যাচাইকারীদের অবশ্যই নিজস্ব অ্যাড্রেস এবং BLS পাবলিক কী থাকতে হবে। কনসেনসাস যখন চুক্তি থেকে যাচাইকারীর তথ্য নিয়ে আসে, তখন কনসেনসাস BLS পাবলিক কী নিবন্ধন না করা যাচাইকারীদের উপেক্ষা করে। +::: + +### 5. সকল নোড পুনরায় চালু করুন {#5-restart-all-nodes} + +`server` কমান্ড দ্বারা সকল নোড পুনরায় চালু করুন। পূর্ববর্তী ধাপে উল্লেখিত `from`-এ ব্লক তৈরি হওয়ার পরে চেইনটি BLS-কে সক্রিয় করে। diff --git a/archive/edge/bn-edge/consensus/migration-to-pos.md b/archive/edge/bn-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..a741fb2aa9 --- /dev/null +++ b/archive/edge/bn-edge/consensus/migration-to-pos.md @@ -0,0 +1,41 @@ +--- +id: migration-to-pos +title: PoA থেকে PoS-এ মাইগ্রেশন +description: "PoA থেকে PoS IBFT এবং PoS IBFT থেকে PoA-তে মাইগ্রেট করার পদ্ধতি।" +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +এই বিভাগে আপনি ব্লকচেইন রিসেট করা ছাড়াই একটি চলমান ক্লাস্টারে PoA থেকে PoS IBFT এবং PoS IBFT থেকে PoA-তে মাইগ্রেট করার বিষয়ে নির্দেশনা পাবেন। + +## PoS-এ কীভাবে মাইগ্রেট করতে হয় {#how-to-migrate-to-pos} + +আপনাকে সকল নোড বন্ধ করতে হবে, `ibft switch` কমান্ড দ্বারা genesis.json এর মধ্যে ফর্ক কনফিগারেশন যোগ করতে হবে এবং নোডটি পুনরায় শুরু করতে হবে। + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution ECDSA ব্যবহার করার সময় স্যুইচিং করা +ECDSA, ব্যবহার করার সময়, `--ibft-validator-type`ফ্ল্যাগ সুইচটিতে যোগ করা আবশ্যক, যেখানে ECDSA ব্যবহার করা হ. । যদি অন্তর্ভুক্ত না থাকলে, এজ স্বয়ংক্রিয়ভাবে BLS এ স্যুইচ করবে। + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::PoS-এ স্যুইচ করতে, আপনাকে 2 ব্লক উচ্চতা নির্দিষ্ট করতে হবে: `deployment`এবং `from``deployment`। To া To া `from`To । স্টেকিং চুক্তিটি প্রি-ডিপ্লয়েড চুক্তির মত `deployment`-এর `0x0000000000000000000000000000000000001001` ঠিকানায় ডিপ্লয় করা হবে। + +স্টেকিং চুক্তি সম্পর্কে আরও বিস্তারিত জানতে, অনুগ্রহ করে [প্রুফ অফ স্টেক](/docs/edge/consensus/pos-concepts) দেখুন। + +:::warning যাচাইকারীদের নিজে স্টেক করতে হবে + +প্রতিটি যাচাইকারীকে PoS-এর শুরুতে যাচাইকারী হতে চুক্তি `deployment`-এ ডিপ্লয় হবার পর এবং `from`-এ ডিপ্লয় হবার আগে স্টেক করতে হবে। প্রতিটি যাচাইকারী PoS-এর শুরুতে স্ট্যাকিং চুক্তি সেট দ্বারা নিজস্ব যাচাইকারী সেট আপডেট করবে। + +স্টেকিং সম্পর্কে আরও জানতে, অনুগ্রহ করে **[সেটআপ করুন এবং প্রুফ অফ স্টেক ব্যবহার করুন](/docs/edge/consensus/pos-stake-unstake)** ভিজিট করুন। + +::: diff --git a/archive/edge/bn-edge/consensus/poa.md b/archive/edge/bn-edge/consensus/poa.md new file mode 100644 index 0000000000..025ec31a3c --- /dev/null +++ b/archive/edge/bn-edge/consensus/poa.md @@ -0,0 +1,109 @@ +--- +id: poa +title: প্রুফ অব অথোরিটি (PoA) +description: "প্রুফ অব অথোরিটি সম্পর্কিত ব্যাখ্যা এবং নির্দেশাবলী।" +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +IBFT PoA হচ্ছে Polygon Edge-এর ডিফল্ট কনসেনসাস প্রক্রিয়া। PoA-তে, যাচাইকারীরা ব্লক তৈরি করা এবং সেগুলোকে একটি সিরিজ আকারে ব্লকচেইনে যোগ করার দায়িত্ব পালন করে থাকেন। + +সব যাচাইকারী মিলে একটি ডাইনামিক যাচাইকারীর-সেট তৈরি করে, যেখানে একটি ভোটিং প্রক্রিয়া ব্যবহারের মাধ্যমে সেট থেকে যাচাইকারীদের যোগ করা বা বাদ দেওয়া যেতে পারে। এর মানে হচ্ছে যাচাইকারীদের যাচাইকারী-সেট থেকে ভোট দিয়ে সেটের ভিতরে নেয়া/বাইরে বের করে দেওয়া যেতে পারে যদি যাচাইকারী নোডের সংখ্যাগরিষ্ঠরা (51%) একজন নির্দিষ্ট যাচাইকারীকে সেটে/সেট থেকে যোগ/বাদ দিতে ভোট দেয়। এভাবে, অসৎ যাচাইকারীদের সনাক্ত করা যায় এবং নেটওয়ার্ক থেকে সরানো যায়, একই সাথে নতুন বিশ্বাসযোগ্য যাচাইকারীদের নেটওয়ার্কে যুক্ত করা যায়। + +সমস্ত যাচাইকারী পরবর্তী ব্লক (রাউন্ড-রবিন পদ্ধতিতে) প্রস্তাব করার সুযোগ পায় এবং ব্লকচেইনে ব্লকটিকে যাচাই/ইনসার্ট করতে যাচাইকারীদের একটি একটি বিশাল অংশকে (2/3-এর বেশি) সেই ব্লকটিকে অনুমোদন করতে হয়। + +এছাড়াও, যাচাইকারীদের পাশাপাশি ব্লক তৈরিতে অংশগ্রহণ না করা অ-যাচাইকারীরাও ব্লক যাচাই প্রক্রিয়ায় অংশগ্রহণ করতে পারে। + +## যাচাইকারীর সেটে একজন যাচাইকারী যোগ করা {#adding-a-validator-to-the-validator-set} + +কিভাবে 4 যাচাইকারী নোড সহ সক্রিয় IBFT নেটওয়ার্কে নতুন একটি যাচাইকারী নোড যোগ করতে হয় তা এই নির্দেশিকায় বর্ণনা করা হয়েছে। যদি আপনার জন্য হবে তাহলে [লোকাল সেটআপ](/edge/get-started/set-up-ibft-locally.md) / [ক্লাউড সেটআপ](/edge/get-started/set-up-ibft-on-the-cloud.md) বিভাগে নেটওয়ার্ক সেট আপ করতে সাহায্য করুন। + +### ধাপ 1: IBFT-এর জন্য ডেটা ফোল্ডার চালু করুন এবং নতুন নোডের জন্য ভ্যালিডেটর কী​ তৈরি করুন {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +নতুন নোডে IBFT দিয়ে সুন্দরভাবে কাজ চালিয়ে যেতে হলে, প্রথমে আপনাকে ডেটা ফোল্ডারগুলি চালু করতে হবে এবং কী তৈরি করতে হবে: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +এই কমান্ডটি যাচাইকারীর কী (ঠিকানা) এবং নোড আইডি প্রিন্ট করবে। পরবর্তী ধাপের জন্য আপনার যাচাইকারীর কী (অ্যাড্রেস) প্রয়োজন হবে। + +### ধাপ 2: অন্য যাচাইকারী নোড থেকে নতুন ক্যান্ডিডেট প্রস্তাব করুন {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +নতুন নোডকে যাচাইকারী হিসেবে গণ্য করার জন্য অন্তত 51% যাচাইকারীকে তার জন্য প্রস্তাব করতে হবে। + +বর্তমান যাচাইকারী নোড থেকে grpc ঠিকানা: 127.0.0.1:10000 এ নতুন যাচাইকারী (`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`) প্রস্তাব করার উদাহরণ: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +IBFT কমান্ডগুলির গঠন [CLI কমান্ড](/docs/edge/get-started/cli-commands) বিভাগে বর্ণনা করা হয়েছে। + +:::info BLS পাবলিক কী + +BLS পাবলিক কী শুধুমাত্র BLS দিয়ে চালিত নেটওয়ার্কে প্রয়োজন হয়, BLS মোডে না চলা নেটওয়ার্কে `--bls`-এর প্রয়োজন নেই। + +::: + +### ধাপ 3: ক্লায়েন্ট নোড রান করুন {#step-3-run-the-client-node} + +যেহেতু এই উদাহরণে আমরা এমন নেটওয়ার্ক চালানোর চেষ্টা করছি যেখানে সমস্ত নোড একই মেশিনে রয়েছে, তাই পোর্ট কনফ্লিক্ট এড়াতে আমাদের সতর্ক থাকতে হবে। + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +সব ব্লক ফেচ করার পর, আপনার কনসোলে দেখতে পাবেন যে একটি নতুন নোড যাচাই প্রক্রিয়ায় অংশগ্রহণ করছে + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info একজন অ-যাচাইকারীকে যাচাইকারী হিসেবে প্রস্তাব করা + +স্বাভাবিকভাবে, একজন অ-যাচাইকারী ভোটিং প্রক্রিয়ার মাধ্যমে যাচাইকারী হতে পারেন, কিন্তু ভোটিং প্রক্রিয়ার পর সফলভাবে যাচাইকারীর-সেটে যোগ হতে নোডটিকে `--seal`ফ্ল্যাগ সহ রিস্টার্ট করতে হবে। + +::: + +## যাচাইকারীর-সেট থেকে একজন যাচাইকারীকে অপসারণ করা {#removing-a-validator-from-the-validator-set} + +এই কাজটি খুবই সহজ। যাচাইকারীর-সেট থেকে একটি যাচাইকারী নোড অপসারণ করতে অধিকাংশ যাচাইকারী নোডে এই কমান্ডটিকে সম্পাদন করতে হবে। + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info BLS পাবলিক কী + +BLS পাবলিক কী শুধুমাত্র BLS দিয়ে চালিত নেটওয়ার্কে প্রয়োজন হয়, BLS মোডে না চলা নেটওয়ার্কে `--bls`-এর প্রয়োজন নেই। + +::: + +কমান্ডগুলো সম্পাদন করার পরে লক্ষ্য করে থাকবেন যে যাচাইকারীর সংখ্যা কমে গিয়েছে (এই লগ উদাহরণের ক্ষেত্রে 4 থেকে 3 হয়েছে) + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/bn-edge/consensus/pos-concepts.md b/archive/edge/bn-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..09ffdb7da7 --- /dev/null +++ b/archive/edge/bn-edge/consensus/pos-concepts.md @@ -0,0 +1,118 @@ +--- +id: pos-concepts +title: প্রুফ অফ স্টেক +description: "প্রুফ অব স্টেক সম্পর্কিত ব্যাখ্যা এবং নির্দেশাবলী।" +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +এই বিভাগটি বর্তমানে Polygon Edge-এর প্রুফ অফ স্টেকে (PoS) উপস্থিত কিছু ধারণার একটি ভালো ওভারভিউ +ওভারভিউ প্রদান করবে বলে আশা করা হচ্ছে। + +বিদ্যমান PoA IBFT ইমপ্লিমেন্টেশনের বিকল্প হচ্ছে Polygon Edge-এর প্রুফ অফ স্টেক (PoS) ইমপ্লিমেন্টেশন, +যা নোড অপারেটররা চেইন শুরু করার সময় সহজেই দুটি চেইনের মধ্যে যেকোনো একটি বেছে নিতে পারেন। + +## PoS-এর ফিচার {#pos-features} + +প্রুফ অফ স্টেক ইমপ্লিমেন্টেশনের মূল লজিকটি +**[স্ট্যাকিং স্মার্ট কন্ট্রাক্ট।](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)** + +একটি PoS মেকানিজমের Polygon Edge চেইনটি চালু করা হলে এই চুক্তিটি আগে থেকেই ডিপ্লয় করা থাকে এবং `0x0000000000000000000000000000000000001001` ঠিকানায় উপলভ্য থাকে +`0` ব্লকের। + +### Epochs {#epochs} + +Polygon Edge-এ Epochs-কে PoS-এর অতিরিক্ত কনসেপ্ট হিসেবে চালু করা হয়েছে। + +Epoch-কে (ব্লকে) একটি বিশেষ সময় কাল হিসেবে বিবেচনা করা হয় যেখানে নির্দিষ্ট কিছু যাচাইকারীর একটি সেট ব্লক নির্মাণ করতে পারে। +তাদের দৈর্ঘ্য পরিবর্তন করা যায়, অর্থাৎ নোড অপারেটররা জেনেসিস জেনারেশনের সময় একটি epoch এর দৈর্ঘ্য কনফিগার করতে পারেন। + +প্রতিটি epoch শেষে, একটি _epoch ব্লক_ তৈরি হয় এবং সেই ঘটনার পরে একটি নতুন epoch শুরু হয়। epoch ব্লক সম্পর্কে +আরও জানতে, [Epoch ব্লক](/docs/edge/consensus/pos-concepts#epoch-blocks) বিভাগটি দেখুন। + +প্রতিটি epoch এর শেষে যাচাইকারীর সেট আপডেট করা হয়। epoch ব্লক তৈরি করার সময় স্টেকিং স্মার্ট চুক্তি থেকে নোডগুলো +একটি যাচাইকারীর সেটকে কুয়েরি করে এবং প্রাপ্ত ডেটা স্থানীয় স্টোরেজে সংরক্ষণ করে। এই কুয়েরি এবং সংরক্ষণ চক্র প্রতিটি epoch এর শেষে পুনরাবৃত্তি হয়। + +মূলত, এটি স্টেকিং স্মার্ট চুক্তির যাচাইকারীর সেটের ঠিকানাগুলোর উপরে সম্পূর্ণ নিয়ন্ত্রণ থাকার বিশয়টি নিশ্চিত করে এবং +তা নোডগুলোকে শুধুমাত্র 1টি দায়িত্ব প্রদান করে - epoch-এর সময় সাম্প্রতিকতম যাচাইকারীর সেটের তথ্য নিয়ে আসার জন্য +চুক্তিটিকে কুয়েরি করার। এটি একক নোডের একটি যাচাইকারীর সেটের দায়িত্ব নেয়ার বোঝা কমিয়ে দেয়। + +### স্টেকিং {#staking} + +ঠিকানাগুলো `stake` পদ্ধতি ব্যবহার করে এবং লেনদেনে স্টেক করা পরিমাণের একটি মান নির্দিষ্ট করে +স্টেকিং স্মার্ট চুক্তিতে ফান্ড স্টেক করতে পারেন: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +স্টেকিং স্মার্ট চুক্তিতে ফান্ড স্টেক করে ঠিকানাগুলো যাচাইকারীর সেটে অন্তর্ভুক্ত হতে পারে এবং ফলশ্রুতিতে +ব্লক তৈরি প্রক্রিয়ায় অংশগ্রহণ করতে পারে। + +:::info স্টেকিং-এর থ্রেশহোল্ড + +বর্তমানে, যাচাইকারীর সেটে অন্তর্ভুক্ত হওয়ার জন্য সর্বনিম্ন থ্রেশহোল্ড হচ্ছে `1 ETH` স্টেক করা + +::: + +### আনস্টেকিং {#unstaking} + +যেসব ঠিকানা ফান্ড স্টেক করেছে, তারা তাদের **সমস্ত স্টেক করা ফান্ড একত্রে আনস্টেক করতে পারবেন**। + +স্টেকিং স্মার্ট চুক্তিতে `unstake` পদ্ধতি কল করে আনস্টেকিং করা যেতে পারে: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +ফান্ড আনস্টেক করার পরে, স্টেকিং স্মার্ট চুক্তি থেকে ঠিকানাগুলোকে সরিয়ে ফেলা হয় এবং সেগুলোকে +পরবর্তী epoch-এর সময় আর যাচাইকারী হিসেবে গণ্য করা হবে না। + +## Epoch ব্লক {#epoch-blocks} + +**Epoch ব্লক** Polygon Edge-এ IBFT-এর PoS ইমপ্লিমেন্টেশনের একটি কনসেপ্ট হিসেবে চালু করা হয়েছে। + +মূলত, epoch ব্লকগুলো বিশেষ ব্লক যাতে কোন **লেনদেন থাকে না** এবং শুধুমাত্র **epoch-এর শেষ দিকেই** ঘটে। উদাহরণস্বরূপ, যদি **epoch আকার** ব্লক সেট করা `50`হয়, তাহলে epoch ব্লক `50`ব্লক হতে হবে , `100``150`এবং তাই হবে। + +তাদের অতিরিক্ত লজিক সম্পাদন করতে ব্যবহার করা হয় যা নিয়মিত ব্লক প্রোডাকশনের সময় ঘটে না। + +সবচেয়ে গুরুত্বপূর্ণ বিষয় হচ্ছে, তারা নোডের একটি নির্দেশনা হিসেবে কাজ করে যে **সাম্প্রতিকতম যাচাইকারীর সেটের তথ্য নিয়ে আসতে হবে** +স্টেকিং স্মার্ট চুক্তি থেকে। + +Epoch ব্লকে যাচাইকারীর সেট আপডেট করার পর, স্টেকিং স্মার্ট চুক্তি থেকে সর্বশেষ তথ্য নিয়ে এসে আবার আপডেট না হওয়া পর্যন্ত, যাচাইকারীর সেট (পরিবর্তিত বা অপরিবর্তিত যাই হোক না কেন) পরবর্তী `epochSize - 1` ব্লকের জন্য +ব্যবহার করা হয়। + +জেনেসিস ফাইল তৈরি করার সময় Epoch এর দৈর্ঘ্য (ব্লকে) একটি বিশেষ ফ্ল্যাগ `--epoch-size` ব্যবহার করে পরিবর্তন করা যায়: + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +Polygon Edge-এ একটি epoch-এর ডিফল্ট আকার হচ্ছে `100000` ব্লক। + +## চুক্তির প্রি-ডিপ্লয়মেন্ট {#contract-pre-deployment} + +Polygon Edge _প্রি-ডিপ্লয়_ করে +[স্টেকিং স্মার্ট চুক্তি](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)-কে +`0x0000000000000000000000000000000000001001` ঠিকানার মধ্যে **জেনেসিস তৈরির** সময়। + +এটি কোন চলমান EVM ছাড়াই জেনেসিস কমান্ডে পাস করা কনফিগারেশন ভ্যালু ব্যবহার করে, সরাসরি ব্লকচেইনের স্মার্ট চুক্তির অবস্থা +পরিবর্তনের মাধ্যমে তা করে থাকে। diff --git a/archive/edge/bn-edge/consensus/pos-stake-unstake.md b/archive/edge/bn-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..e6e2fe6b8f --- /dev/null +++ b/archive/edge/bn-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,174 @@ +--- +id: pos-stake-unstake +title: প্রুফ অফ স্টেক (PoS) এর সেটআপ এবং ব্যবহার +description: "স্টেক, আনস্টেক এবং অন্যান্য স্টেকিং সম্পর্কিত নির্দেশাবলী।" +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +Polygon Edge-এর সাথে একটি প্রুফ অফ স্টেক নেটওয়ার্ক সেট আপ করার বিষয়ে এই গাইডটি বিস্তারিতভাবে বর্ণনা করে, নোডগুলির জন্য ফান্ড কীভাবে স্টেক করতে হয় যাতে তারা ভ্যালিডেটর হয়ে ওঠে এবং কীভাবে ফান্ড আনস্টেক করতে হয়। + +এটি পড়তে এবং মধ্য দিয়ে যেতে **অত্যন্ত উৎসাহিত** করা হয় [লোকাল সেটআপ](/docs/edge/get-started/set-up-ibft-locally) +/ [ক্লাউড সেটআপ](/docs/edge/get-started/set-up-ibft-on-the-cloud) বিভাগসমূহ পড়ার জন্য, +PoS নির্দেশিকার সাথে এগিয়ে যাওয়ার আগে। এই বিভাগসমূহে Polygon Edge-এর সাথে একটি প্রুফ অফ অথরিটি (PoA) ক্লাস্টার শুরু করার জন্য প্রয়োজনীয় পদক্ষেপগুলোর +রূপরেখা পাবেন। + +বর্তমানে, স্টেকিং স্মার্ট চুক্তিতে ফান্ড স্টেক করার ক্ষেত্রে যাচাইকারীর সংখ্যার কোনও সীমা নেই। + +## স্টেকিং স্মার্ট চুক্তি {#staking-smart-contract} + +স্টেকিং স্মার্ট চুক্তির রেপো [এখানে](https://github.com/0xPolygon/staking-contracts) অবস্থিত। + +এতে প্রয়োজনীয় টেস্টিং স্ক্রিপ্ট, ABI ফাইল এবং সবচেয়ে গুরুত্বপূর্ণভাবে, এতে স্মার্ট চুক্তিটিই রয়েছে। + +## একটি N নোড ক্লাস্টার সেটআপ করা {#setting-up-an-n-node-cluster} + +Polygon Edge দিয়ে একটি নেটওয়ার্ক সেটআপ করার প্রক্রিয়া +[লোকাল সেটআপ](/docs/edge/get-started/set-up-ibft-locally) +/ [ক্লাউড সেটআপ](/docs/edge/get-started/set-up-ibft-on-the-cloud) বিভাগসমূহে বর্ণনা করা হয়েছে। + +একটি PoS এবং PoA ক্লাস্টার সেটআপ এর মধ্যে একমাত্র **পার্থক্য** হল জেনেসিস জেনারেশনের অংশটি। + +**একটি PoS ক্লাস্টারের জন্য জেনেসিস ফাইল তৈরি করার সময়, একটি অতিরিক্ত ফ্ল্যাগ প্রয়োজন `--pos`**: + +```bash +polygon-edge genesis --pos ... +``` + +## একটি epoch-এর দৈর্ঘ্য সেট করা {#setting-the-length-of-an-epoch} + +Epochs সম্পর্কে [Epoch ব্লক](/docs/edge/consensus/pos-concepts#epoch-blocks) বিভাগে বিস্তারিতভাবে বর্ণনা করা আছে। + +জেনেসিস ফাইল তৈরি করার সময়, একটি ক্লাস্টারের (ব্লকে) জন্য epoch-এর আকার সেট করতে, একটি অতিরিক্ত ফ্ল্যাগ +নির্দিষ্ট আছে `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +এই মানটি জেনেসিস ফাইলে epoch-এর আকার `50` ব্লকে নির্দিষ্ট করেছে। + +একটি epoch (ব্লকে) এর আকারের ডিফল্ট মান হচ্ছে `100000`। + +:::info epoch এর দৈর্ঘ্য কমানো + +[Epoch ব্লক](/docs/edge/consensus/pos-concepts#epoch-blocks) বিভাগের বর্ণনা অনুসারে, +নোডগুলিতে যাচাইকারীর সেট আপডেট করতে epoch ব্লক ব্যবহার করা হয়। + +ব্লকে, epoch এর ডিফল্ট দৈর্ঘ্য (`100000`) যাচাইকারীর সেট আপডেটের জন্য একটি দীর্ঘ সময় হতে পারে। যেহেতু প্রতিটি নতুন ব্লক যোগ করতে +~2s সময়ের প্রয়োজন হয়, তাই যাচাইকারীর সেটটিতে পরিবর্তন হতে আনুমানিক ~55.5h সময়ের প্রয়োজন হবে। + +epoch দৈর্ঘ্যের জন্য একটি কম মান সেট করা এটি নিশ্চিত করে যে ভ্যালিডেটর সেটটি আরও ঘন ঘন আপডেট হবে। +::: + +## স্টেকিং স্মার্ট চুক্তির স্ক্রিপ্ট ব্যবহার করা {#using-the-staking-smart-contract-scripts} + +### পূর্বশর্ত {#prerequisites} + +স্টেকিং স্মার্ট চুক্তি রেপো একটি হার্ডহ্যাট প্রকল্প, যার জন্য NPM-এর প্রয়োজন হয়। + +এটি সঠিকভাবে চালু করতে, মূল ডিরেক্টরিতে রান করুন: + +```bash +npm install +```` + +### প্রদত্ত সহায়ক স্ক্রিপ্ট সেটআপ করা {#setting-up-the-provided-helper-scripts} + +ডিপ্লয়েড স্টেকিং স্মার্ট চুক্তির সাথে ইন্টের‍্যাক্ট করার স্ক্রিপ্টগুলি আছে +[স্টেকিং স্মার্ট চুক্তি রেপোতে](https://github.com/0xPolygon/staking-contracts)। + +স্মার্ট চুক্তির রেপো লোকেশনে নিম্নলিখিত প্যারামিটারের সাথে একটি `.env` ফাইল তৈরি করুন: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +প্যারামিটারগুলি যেখানে আছে: + +* **JSONRPC_URL** - চলমান নোডের JSON-RPC এন্ডপয়েন্ট +* **PRIVATE_KEYS** - স্টেকার ঠিকানার প্রাইভেট কী। +* **STAKING_CONTRACT_ADDRESS** - স্টেকিং স্মার্ট চুক্তির ঠিকানা ( +ডিফল্ট `0x0000000000000000000000000000000000001001`) +* **BLS_PUBLIC_KEY** - স্টেকারের BLS পাবলিক কী। শুধুমাত্র BLS দিয়ে চলমান নেটওয়ার্কের ক্ষেত্রে প্রয়োজন + +### ফান্ড স্টেক করা {#staking-funds} + +:::info স্টেকিং ঠিকানা + +স্টেকিং স্মার্ট চুক্তিটি প্রি-ডিপ্লয়েড আছে +`0x0000000000000000000000000000000000001001` ঠিকানায়। + +স্টেকিং-এর সাথে যে কোনও ধরণের ইন্টারঅ্যাকশন স্টেকিং স্মার্ট চুক্তির মাধ্যমে নির্দিষ্ট ঠিকানায় করা হয়। + +স্টেকিং স্মার্ট চুক্তি সম্পর্কে আরও জানতে, অনুগ্রহ করে +**[স্ট্যাকিং স্মার্ট কন্ট্রাক](/docs/edge/consensus/pos-concepts#contract-pre-deployment)** বিভাগটিতে যান। + +::: + +কোনো অ্যাড্রেসকে যাচাইকারীর সেটের একটি অংশ হতে, একটি থ্রেশহোল্ডের উপরে একটি নির্দিষ্ট পরিমাণ ফান্ড স্টেক করতে হবে। + +বর্তমানে, যাচাইকারীর সেটের অংশ হওয়ার জন্য ডিফল্ট থ্রেশহোল্ড হচ্ছে `1 ETH`। + +স্টেকিং স্মার্ট চুক্তির `stake` পদ্ধতি কল করে এবং একটি মান `>= 1 ETH` নির্দিষ্ট করে স্টেক করা শুরু করা যেতে পারে। + +`.env` ফাইলটি সেটআপের পরে +যা [পূর্ববর্তী সেকশনে](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) উল্লেখ করা হয়েছিল এবং +PoS মোডে চেইন শুরু করার পর, স্টেকিং স্মার্ট চুক্তির রেপোতে নিম্নলিখিত কমান্ড ব্যবহার করে স্টেক করা যেতে পারে: + +```bash +npm run stake +``` + +`stake` হার্ডহ্যাট স্ক্রিপ্টটি ডিফল্ট পরিমাণ হিসেবে `1 ETH` স্টেক করে, যা `scripts/stake.ts` ফাইলে সংশোধন করে পরিবর্তন করা +যেতে পারে। + +যদি স্টেক করা ফান্ড `>= 1 ETH` হয়, তাহলে স্ট্যাকিং স্মার্ট চুক্তির যাচাইকারীর সেট আপডেট করা হয় এবং ঠিকানাটি +পরবর্তী epoch থেকে শুরু হওয়া যাচাইকারীর সেটের অংশ হয়ে যাবে। + +:::info BLS কী রেজিস্টার করা +যদি নেটওয়ার্ক BLS মোডে চলমান হয়, তবে নোডকে ভ্যালিডেটর হতে হলে তাদের স্টেকিং এর পরে, তাদের BLS পাবলিক কী নিবন্ধন করতে হবে + +এটি নিম্নলিখিত কমান্ড ব্যবহার করে সম্পাদন করা যাবে: + +```bash +npm run register-blskey +``` +::: + +### ফান্ড আনস্টেক করা {#unstaking-funds} + +স্টেক থাকা ঠিকানাগুলো **শুধুমাত্র একবারে তাদের সমস্ত ফান্ড আনস্টেক** করতে পারে। + +`.env` ফাইলটি সেটআপের পরে +যা [পূর্ববর্তী বিভাগে](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) +উল্লেখ করা হয়েছিল এবং PoS মোডে একটি চেইন শুরু করার পর, স্টেকিং স্মার্ট চুক্তি রেপোতে নিম্নলিখিত কমান্ড ব্যবহার করে +আনস্টেক করা যেতে পারে: + +```bash +npm run unstake +``` + +### স্টেকারদের তালিকা পাওয়া {#fetching-the-list-of-stakers} + +স্টেক করা সকল ঠিকানাকে স্টেকিং স্মার্ট চুক্তিতে সংরক্ষণ করা হয়। + +`.env` ফাইলটি সেটআপের পরে +যা [পূর্ববর্তী বিভাগে](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) +উল্লেখ করা হয়েছিল এবং PoS মোডে একটি চেইন শুরু করার পরে, স্টেকিং স্মার্ট চুক্তি রেপোতে নিম্নলিখিত কমান্ড +ব্যবহার করে যাচাইকারীদের তালিকা পাওয়া যাবে: + +```bash +npm run info +``` diff --git a/archive/edge/bn-edge/faq/Contracts.md b/archive/edge/bn-edge/faq/Contracts.md new file mode 100644 index 0000000000..41179f9b59 --- /dev/null +++ b/archive/edge/bn-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: স্মার্ট চুক্তির FAQ +description: "Polygon Edge-এর স্মার্ট চুক্তির FAQ" +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## Polygon Edge কি স্মার্ট চুক্তি সমর্থন করে? {#does-polygon-edge-support-smart-contracts} + +হ্যাঁ। Polygon Edge নেটওয়ার্কগুলো Ethereum সমর্থিত ব্লকচেইন, তাই যেসব স্মার্ট চুক্তি Ethereum-এ ডিপ্লয় করা যায়, সেগুলো Polygon Edge-এও ডিপ্লয় করা যায়। + +## আপনি কি PoS ডিপ্লয় করার পরে স্ট্যাকিং চুক্তির লজিকটি আপডেট করতে পারেন? {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +আপাতত, আপনি PoS নেটওয়ার্ক শুরু করার পর স্টেকিং চুক্তির লজিক পরিবর্তন করতে পারবেন না, কারণ এটি জেনেসিস ফাইলের অংশ। তাই আপনি, উদাহরণস্বরূপ, যাচাইকারীর সর্বনিম্ন/সর্বোচ্চ সীমা পরিবর্তন করতে পারবেন না। আপনি যাচাইকারী যোগ বা বাদ, স্টেক বা আনস্টেক করতে পারবেন। + + + diff --git a/archive/edge/bn-edge/faq/Gas.md b/archive/edge/bn-edge/faq/Gas.md new file mode 100644 index 0000000000..c24e586d44 --- /dev/null +++ b/archive/edge/bn-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: গ্যাস FAQ +description: "Polygon Edge-এর গ্যাস FAQ" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## সর্বনিম্ন গ্যাস মূল্য কীভাবে জারি করবেন? {#how-to-enforce-a-minimum-gas-price} +আপনি সার্ভার কমান্ডে প্রদত্ত `--price-limit` ফ্ল্যাগ ব্যবহার করতে পারেন। এটি আপনার নোডকে শুধুমাত্র সেইসব লেনদেন গ্রহণ করতে বাধ্য করবে যেখানে গ্যাসের দাম আপনার সেট করা মূল্যসীমার বেশি বা সমান। এটি সম্পূর্ণ নেটওয়ার্কে প্রয়োগ করা হয়েছে তা নিশ্চিত করতে, আপনাকে নিশ্চিত করতে হবে যে সকল নোডের একই মূল্যসীমা রয়েছে। + + +## আপনি কি 0 গ্যাস ফি দিয়ে লেনদেন করতে পারবেন? {#can-you-have-transactions-with-0-gas-fees} +হ্যাঁ, আপনি পারবেন। নোডগুলো যেটিকে ডিফল্ট মূল্যসীমা হিসাবে প্রয়োগ করে তা হলো `0`, অর্থাৎ নোডগুলো সেসকল লেনদেন গ্রহণ করবে যার মূল্যসীমা `0`-তে সেট করা আছে। + +## গ্যাস (নেটিভ) টোকেনের টোটাল সাপ্লাই কীভাবে সেট করবেন? {#how-to-set-the-gas-native-token-total-supply} + +আপনি `--premine flag` ব্যবহার করে অ্যাকাউন্টগুলোতে (ঠিকানা) আগে থেকে মাইন করা একটি ব্যালেন্স সেট করতে পারেন। অনুগ্রহ করে মনে রাখবেন যে এই কনফিগারেশনটি জেনেসিস ফাইলের অন্তর্ভুক্ত এবং এটা পরে পরিবর্তন করা যাবে না। + +কিভাবে `--premine flag` ব্যবহার করতে হবে তার উদাহরণ : + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +এটি 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862 ঠিকানায় আগে থেকে মাইন করা 1000 ETH ব্যালেন্স সেট করে (এই আর্গুমেন্টের পরিমাণ wei-এ আছে)। + +গ্যাস টোকেনের আগে থেকে মাইন করা পরিমাণই হল টোটাল সাপ্লাই। পরবর্তী সময়ে নেটিভ কারেন্সির (গ্যাস টোকেন) অন্য কোন পরিমাণ মিন্ট করা যাবে না। + +## Edge কি গ্যাস টোকেন হিসাবে ERC-20 সমর্থন করে? {#does-edge-support-erc-20-as-a-gas-token} + +Edge গ্যাস টোকেন হিসাবে ERC-20 সমর্থন করে না। গ্যাসের জন্য শুধুমাত্র নেটিভ Edge কারেন্সি সমর্থন করে। + +## গ্যাস লিমিট কীভাবে বৃদ্ধি করবেন? {#how-to-increase-the-gas-limit} + +Polygon Edge-এ গ্যাস লিমিট বাড়ানোর জন্য দুটি অপশন রয়েছে: +1. চেইনটি মুছে ফেলা এবং জেনেসিস ফাইলে `block-gas-limit` uint64 মানের সর্বোচ্চতে বৃদ্ধি করা +2. সকল নোডের গ্যাস লিমিট বাড়ানোর জন্য একটি উচ্চ মানের `--block-gas-target` ফ্ল্যাগ ব্যবহার করুন। এতে নোড পুনরায় চালু করার প্রয়োজন হয়। বিস্তারিত ব্যাখ্যা [এখানে](/docs/edge/architecture/modules/txpool/#block-gas-target)। \ No newline at end of file diff --git a/archive/edge/bn-edge/faq/Tokens.md b/archive/edge/bn-edge/faq/Tokens.md new file mode 100644 index 0000000000..31e4e582e9 --- /dev/null +++ b/archive/edge/bn-edge/faq/Tokens.md @@ -0,0 +1,24 @@ +--- +id: tokens +title: টোকেন FAQ +description: "Polygon Edge-এর টোকেনগুলোর জন্য FAQ" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## Polygon Edge কি EIP-1559 সমর্থন করে? {#does-polygon-edge-support-eip-1559} +আপাতত, Polygon Edge EIP-1559 সমর্থন করেনা। + +## কারেন্সি (টোকেন) সিম্বল কীভাবে সেট করতে হয়? {#how-to-set-the-currency-token-symbol} + +টোকেন সিম্বল UI-এর একটি অংশ, তাই এটি নেটওয়ার্কের কোথাও কনফিগার করা বা হার্ডকোডে করা যাবে না। কিন্তু আপনি মেটামাস্কের মতো একটি ওয়ালেটে নেটওয়ার্ককে যুক্ত করার সময় এটি পরিবর্তন করতে পারবেন। + +## একটি চেইন থেমে গেলে লেনদেনগুলোর কী হবে? {#what-happens-to-transactions-when-a-chain-halts} + +যেসমস্ত লেনদেন প্রক্রিয়া করা হয়নি, সেগুলো TxPool(এনকিউড বা প্রোমোটেড কিউ) এর মধ্যে আছে। চেইনটি থেমে গেলে (সকল ব্লক উৎপাদন বন্ধ হয়ে গেলে), এই লেনদেনগুলো কখনোই ব্লকে যাবে না।
+এটিই চেইন থামার একমাত্র ফলাফল নয়। যদি নোডগুলো থামানো হয় বা পুনরায় চালু করা হয়, তাহলে যে সমস্ত লেনদেনগুলো এখনও এক্সিকিউট হয়নি এবং এখনও TxPool-এর মধ্যে আছে সেগুলো বিনা বার্তায় মুছে যাবে।
+ব্রেকিং চেঞ্জ নিয়ে আসার সময় সেসব লেনদেনেরও একই অবস্থা হবে, কারণ ব্রেকিং চেঞ্জে নোডগুলোকে পুনরায় চালু করতে হয়। diff --git a/archive/edge/bn-edge/faq/Validators.md b/archive/edge/bn-edge/faq/Validators.md new file mode 100644 index 0000000000..ae523e7f26 --- /dev/null +++ b/archive/edge/bn-edge/faq/Validators.md @@ -0,0 +1,85 @@ +--- +id: validators +title: যাচাইকারীর FAQ +description: "Polygon Edge-এর যাচাইকারীর FAQ" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## কিভাবে একজন যাচাইকারী যোগ/অপসারণ করবেন? {#how-to-add-remove-a-validator} + +### PoA {#poa} +যাচাইকারী যোগ/অপসারণ ভোটিং দ্বারা সম্পন্ন করা হয়। আপনি [এখানে](/docs/edge/consensus/poa) এই সম্পর্কে একটি সম্পূর্ণ নির্দেশিকা খুঁজে পেতে পারেন। + +### PoS {#pos} +আপনি [এখানে](/docs/edge/consensus/pos-stake-unstake) ফান্ড স্টেক করার নির্দেশিকা খুঁজে পেতে পারেন, যাতে একটি নোড একটি যাচাইকারী হতে পারে এবং আনস্টেক করার নির্দেশিকাও পাবেন (যাচাইকারী অপসারণ করার)। + +দয়া করে নোট করুন: +- আপনি `--max-validator-count` জেনেসিস ফ্ল্যাগ ব্যবহার করে যাচাইকারীর সেটে সর্বোচ্চ যত সংখ্যক স্ট্যাকার যোগ করতে পারেন তা সেট করতে পারেন। +- আপনি `--min-validator-count ` জেনেসিস ফ্ল্যাগ ব্যবহার করে যাচাইকারীর সেটে সর্বনিম্ন যত সংখ্যক স্ট্যাকার যোগ করতে পারেন তা সেট করতে পারেন (ডিফল্টরূপে `1`)। +- যখন সর্বোচ্চ যাচাইকারী সংখ্যা পূরণ করা হয়, আপনি অন্য যাচাইকারী যোগ করতে পারবেন না যতক্ষণ না আপনি সেট থেকে একটি বিদ্যমান একটি অপসারণ করেন (নতুন জনের স্ট্যাকের পরিমাণ বেশি হলেও সমস্যা নেই)। আপনি যদি কোন যাচাইকারী অপসারণ করেন, তবে কখনোই অবশিষ্ট যাচাইকারীর সংখ্যা `--min-validator-count` এর কম হতে পারবে না। +- যাচাইকারী হতে নেটিভ নেটওয়ার্ক (গ্যাস) মুদ্রার ডিফল্ট থ্রেশহোল্ড হচ্ছে `1` ইউনিট। + + + +## যাচাইকারীর জন্য ডিস্ক কতটা খালি রাখার বিষয়ে সুপারিশ করা হয়? {#how-much-disk-space-is-recommended-for-a-validator} + +আমরা একটি রক্ষণশীল আনুমানিক রানওয়ে হিসাবে 100G দিয়ে শুরু করার পরামর্শ দিচ্ছি এবং নিশ্চিত করি যেন ডিস্কটি পরে স্কেল করা যায়। + + +## যাচাইকারীর সংখ্যায় কি কোনো সীমা আছে? {#is-there-a-limit-to-the-number-of-validators} + +আমরা যদি প্রযুক্তিগত সীমাবদ্ধতার কথা বলি, তাহলে একটি নেটওয়ার্কে কতটি নোড থাকতে পারে সে ব্যাপারে Polygon Edge-এর কোনো প্রকাশ্য সীমাবদ্ধতা নেই। আপনি প্রতিটি নোডে আলাদাভাবে সংযোগের সীমাবদ্ধতা (ইনবাউন্ড / আউটবাউন্ড সংযোগের সংখ্যা) সেট করতে পারেন। + +আমরা যদি বাস্তব সীমাবদ্ধতা সম্পর্কে কথা বলি, তাহলে আপনি একটি 10 নোড ক্লাস্টারের তুলনায় একটি 100 নোড ক্লাস্টারে অনেক দূর্বল পারফর্ম্যান্স পাবেন। আপনার ক্লাস্টারে নোডের সংখ্যা বৃদ্ধি করার মাধ্যমে, আপনি যোগাযোগের জটিলতা এবং আরো স্পষ্টভাবে বললে পুরো নেটওয়ার্কে চাপ বাড়িয়ে দেন। এই সবকিছু আপনি কী ধরনের নেটওয়ার্ক রান করছেন এবং আপনার কী ধরনের নেটওয়ার্ক টপোলজি রয়েছে তার উপর নির্ভর করে। + +## PoA থেকে PoS-এ কিভাবে সুইচ করবেন? {#how-to-switch-from-poa-to-pos} + +PoA হচ্ছে ডিফল্ট কনসেনসাস মেকানিজম। একটি নতুন ক্লাস্টার PoS-এ সুইচ করতে, জেনেসিস ফাইল তৈরি করার সময় আপনাকে `--pos` ফ্ল্যাগ যোগ করতে হবে। আপনার যদি কোনো চলমান ক্লাস্টার থাকে, তাহলে আপনি সুইচ কিভাবে করতে হয় তা [এখানে](/docs/edge/consensus/migration-to-pos) পাবেন। আমাদের কনসেনসাস মেকানিজম এবং সেটআপ সম্পর্কে আপনার প্রয়োজনীয় সমস্ত তথ্য আমাদের [কনসেনসাস বিভাগে](/docs/edge/consensus/poa) পেতে পারেন। + +## কোনো ব্রেকিং পরিবর্তন থাকলে আমি কিভাবে আমার নোড আপডেট করব? {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +আপনি [এখানে](/docs/edge/validator-hosting#update) এই পদ্ধতি কিভাবে করতে হয় তার একটি বিস্তারিত নির্দেশিকা খুঁজে পাবেন। + +## PoS Edge-এর জন্য কি স্ট্যাকিং-এর সর্বনিম্ন পরিমাণ কনফিগার করা যাবে? {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +ডিফল্টরূপে স্ট্যাকিং-এর সর্বনিম্ন পরিমাণ হচ্ছে `1 ETH` এবং এটি কনফিগার করা যাবে না। + +## JSON RPC কমান্ড `eth_getBlockByNumber` এবং `eth_getBlockByHash` কেন মাইনারের ঠিকানা ফেরত দেয় না? {#not-return-the-miner-s-address} + +Polygon Edge-এ বর্তমানে ব্যবহৃত কনসেনসাস হচ্ছে IBFT 2.0, যা ভোটিং মেকানিজমের উপর ভিত্তি করে নির্মাণ করা হয়েছে, এটি Clique PoA-তে বিস্তারিত বর্ণনা করা হয়েছে: [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225) + +EIP-225 (Clique PoA) দেখে আমরা বলতে পারি, এটি একটি প্রাসঙ্গিক অংশ যা ব্যাখ্যা করে `miner` (`beneficiary` নামেও পরিচিত) কেন ব্যবহার করা হয়: + +
+আমরা নিম্নরূপে ethash হেডার ফিল্ডটি রিপারপোজ করেছি: +
    +
  • বেনিফিশিয়ারি / মাইনার: অনুমোদিত স্বাক্ষরকারীদের তালিকা সংশোধনের প্রস্তাব করার ঠিকানা।
  • +
      +
    • স্বাভাবিকভাবে শূন্য দিয়ে পূর্ণ থাকা উচিত, তবে শুধুমাত্র ভোটের সময় পরিবর্তন করা যায়।
    • +
    • ভোটিং পদ্ধতির বাস্তবায়নে অতিরিক্ত জটিলতা এড়াতে আর্বিট্রারি মানগুলি (এমনকি অ-স্বাক্ষরকারীদের ভোট দেওয়ার মতো অর্থহীনগুলোও) অনুমোদন করা হয়।
    • +
    • চেকপয়েন্ট (অর্থাৎ epoch ট্রানজিশনে) ব্লকে শূন্য দিয়ে পূর্ণ থাকা উচিত।
    • +
    + +
+ +
+ +সুতরাং, `miner` ক্ষেত্রটি ব্লকের প্রস্তাবক দেখানোর পরিবর্তে একটি নির্দিষ্ট ঠিকানার জন্য কোনো ভোট প্রস্তাব করতে ব্যবহার করা হয়। + +ব্লকের প্রস্তাবক সম্পর্কে তথ্য ব্লক হেডারের RLP এনকোডেড ইস্তাম্বুল অতিরিক্ত ডেটা ক্ষেত্রের সীল ক্ষেত্র থেকে pubkey পুনরুদ্ধার করে খুঁজে পাওয়া যেতে পারে। + +## জেনেসিস কোন অংশ এবং মানকে নিরাপদে পরিবর্তন করা যেতে পারে? {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +অনুগ্রহ করে এটি সম্পাদনা করার চেষ্টা করার আগে বিদ্যমান genesis.json ফাইলের একটি ম্যানুয়াল কপি তৈরি করতে ভুল. ে। এছাড়াও, genesis.json ফাইল সম্পাদনা করার আগে পুরো চেইনটি বন্ধ করতে হবে। জেনেসিস ফাইল পরিবর্তন করা হলে এর নতুন সংস্করণ সকল non-validator এবং valdiator nodes জুড়ে বিতরণ করতে হবে। + +::: + +**শুধুমাত্র জেনেসিস ফাইলের bootnodes বিভাগে নিরাপদে পরিবর্তন করা যেতে পারে**, যেখানে আপনি তালিকা থেকে bootnodes যোগ বা অপসারণ করতে পারেন। \ No newline at end of file diff --git a/archive/edge/bn-edge/get-started/cli-commands.md b/archive/edge/bn-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..9d64a1a091 --- /dev/null +++ b/archive/edge/bn-edge/get-started/cli-commands.md @@ -0,0 +1,2220 @@ +--- +id: cli-commands +title: CLI কমান্ড +description: "Polygon Edge-এর CLI কমান্ড এবং কমান্ড ফ্ল্যাগের তালিকা।" +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +এই বিভাগে Polygon Edge-এ্রর বর্তমান কমান্ড, কমান্ড ফ্ল্যাগ এবং কিভাবে তাদের ব্যবহার করা হয় তার বিস্তারিত বর্ণনা করা হয়েছিল। + +:::tip JSON আউটপুট সমর্থন + +কিছু কমান্ডে `--json` ফ্ল্যাগটি সমর্থিত। এই ফ্ল্যাগ JSON ফরম্যাটে আউটপুট প্রিন্ট করতে কমান্ডকে নির্দেশনা প্রদান করে + +::: + +## স্টার্টআপ কমান্ড {#startup-commands} + +| **কমান্ড** | **বিবরণ** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| সার্ভার | সকল মডিউলকে একসাথে বুটস্ট্র্যাপ করার ব্লকচেইন ক্লায়েন্ট চালু করার ডিফল্ট কমান্ড | +| জেনেসিস | একটি *genesis.json* ফাইল তৈরি করে, যা ক্লায়েন্ট শুরু করার আগে একটি পূর্বনির্ধারিত চেইন স্টেট সেট করতে ব্যবহার করা হয়। জেনেসিস ফাইলের গঠন নিচে বর্ণনা করা হয়েছে | +| জেনেসিস প্রি-ডিপ্লয় | নতুন নেটওয়ার্কের জন্য একটি স্মার্ট চুক্তি প্রি-ডিপ্লয় করে | + +### সার্ভার ফ্ল্যাগ {#server-flags} + + +| **সকল সার্ভার ফ্ল্যাগ** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [prometheus](/docs/edge/get-started/cli-commands#prometheus) | [block-gas-target](/docs/edge/get-started/cli-commands#block-gas-target) | +| [max-peers](/docs/edge/get-started/cli-commands#max-peers) | [max-inbound-peers](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [max-outbound-peers](/docs/edge/get-started/cli-commands#max-outbound-peers) | [max-enqueued](/docs/edge/get-started/cli-commands#max-enqueued) | +| [log-level](/docs/edge/get-started/cli-commands#log-level) | [log-to](/docs/edge/get-started/cli-commands#log-to) | +| [চেইন](/docs/edge/get-started/cli-commands#chain) | [যোগদান](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [price-limit](/docs/edge/get-started/cli-commands#price-limit) | [max-slots](/docs/edge/get-started/cli-commands#max-slots) | +| [কনফিগ](/docs/edge/get-started/cli-commands#config) | [secrets-config](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-interval](/docs/edge/get-started/cli-commands#dev-interval) | +| [no-discover](/docs/edge/get-started/cli-commands#no-discover) | [পুনরুদ্ধার](/docs/edge/get-started/cli-commands#restore) | +| [block-time](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +Polygon Edge ক্লায়েন্ট ডেটা সংরক্ষণ করার জন্য ব্যবহৃত ডাটা ডিরেক্টরি নির্দিষ্ট করতে ব্যবহৃত হয়। ডিফল্ট: `./test-chain`। + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +JSON-RPC পরিষেবা `address:port`-এর জন্য ঠিকানা এবং পোর্ট সেট করে। +শুধুমাত্র একটি পোর্ট `:10001`-এ সংজ্ঞায়িত করা হয়, তাহলে এটি সমস্ত `0.0.0.0:10001` ইন্টারফেসে বাইন্ড করবে। +যদি বাদ দেওয়া হয়, তবে পরিষেবাটি ডিফল্ট মান `address:port` দিয়ে বাইন্ড করবে। +ডিফল্ট ঠিকানা: `0.0.0.0:8545`। + +--- + +####

json-rpc-block-range-limit + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +json-rpc অনুরোধ সম্পাদন করার সময় সর্বাধিক ব্লক পরিসীমা বিবেচনা করা হবে যা fromBlock/toBlock মান (e.g. eth_getLogs) অন্তর্ভুক্ত করে। ডিফল্ট:`1000`। + +--- + +####

json-rpc-batch-request-limit + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +json-rpc ব্যাচ অনুরোধ পরিচালনা করার সময় সর্বোচ্চ দৈর্ঘ্য বিবেচনা করা হবে। ডিফল্ট: `20`। + +--- + +####

grpc + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +gRPC পরিষেবাটির জন্য ঠিকানা এবং পোর্ট `address:port` সেট করে। ডিফল্ট ঠিকানা: `127.0.0.1:9632`। + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +libp2p পরিষেবাটির জন্য ঠিকানা এবং পোর্ট `address:port` সেট করে। ডিফল্ট ঠিকানা: `127.0.0.1:1478`। + +--- + +####

prometheus + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +Prometheus সার্ভার `address:port` এর জন্য ঠিকানা এবং পোর্ট সেট করে। +যদি শুধুমাত্র একটি পোর্ট `:5001` এ সংজ্ঞায়িত করা হয়, তাহলে সার্ভিসটি সব `0.0.0.0:5001` ইন্টারফেসকে বাইন্ড করবে। +যদি বাদ দেওয়া হয়, তবে পরিষেবাটি চালু হবে না। + +--- + +####

block-gas-target + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +চেইনের জন্য টার্গেট ব্লক গ্যাস সীমা সেট করে। ডিফল্ট (প্রয়োগ করা হয় না): `0`। + +ব্লক গ্যাস টার্গেটের উপর একটি আরো বিস্তারিত ব্যাখ্যা [TxPool বিভাগে](/docs/edge/architecture/modules/txpool#block-gas-target) পাওয়া যেতে পারে। + +--- + +####

max-peers + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +ক্লায়েন্টের সর্বোচ্চ পিয়ারের সংখ্যা সেট করে। ডিফল্ট: `40`। + +পিয়ার সীমা `max-inbound/outbound-peers` বা `max-peers` ফ্ল্যাগ ব্যবহার করে নির্দিষ্ট করা উচিত। + +--- + +####

max-inbound-peers + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +ক্লায়েন্টের সর্বোচ্চ ইনবাউন্ড পিয়ারের সংখ্যা সেট করে। যদি `max-peers` সেট করা হয়, তাহলে নিম্নলিখিত সূত্র ব্যবহার করে সর্বোচ্চ-ইনবাউন্ড-পিয়ার সীমা গণনা করা হয়। + +`max-inbound-peer = InboundRatio * max-peers` হচ্ছে `0.8` যেখানে `InboundRatio`। + +--- + +####

max-outbound-peers + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +ক্লায়েন্টের সর্বোচ্চ আউটবাউন্ড পিয়ারের সংখ্যা সেট করে। যদি `max-peers` সেট করা হয়, তাহলে নিম্নলিখিত সূত্র ব্যবহার করে সর্বোচ্চ-আউটবাউন্ড-পিয়ার গণনা করা হয়। + +`max-outbound-peer = OutboundRatio * max-peers` হচ্ছে `0.2` যেখানে `OutboundRatio`। + +--- + +####

max-enqueued + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +প্রতি অ্যাকাউন্টে এনকিউ করা লেনদেনের সর্বোচ্চ সংখ্যা সেট করে। ডিফল্ট:`128`। + +--- + +####

log-level + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +কনসোল আউটপুটের জন্য লগের লেভেল সেট করে। ডিফল্ট: `INFO`। + +--- + +####

log-to + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +সার্ভার কমান্ড থেকে সমস্ত লগ আউটপুট ধারণকারী লগ ফাইলের নামকে সংজ্ঞায়িত করে। +ডিফল্টরূপে, সমস্ত সার্ভার লগ কনসোলে (stdout) আউটপুট করা হবে, +তবে যদি ফ্ল্যাগ সেট করা হয়, তাহলে সার্ভার কমান্ড চালানোর সময় কনসোলে কোন আউটপুট হবে না। + +--- + +####

চেইন + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +চেইন শুরু করার জন্য ব্যবহৃত জেনেসিস ফাইল নির্দিষ্ট করে। ডিফল্ট: `./genesis.json`। + +--- + +####

যোগদান + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +পিয়ারের ঠিকানা নির্দিষ্ট করে যা যোগ করা উচিত। + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +পোর্ট ছাড়া বহিরাগত আইপি ঠিকানা সেট করে, কারণ এটি পিয়ার্স দ্বারা দেখা যেতে পারে। + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +হোস্ট DNS ঠিকানা সেট করে। এটি একটি বহিরাগত DNS বিজ্ঞাপন করার জন্য ব্যবহার করা যেতে পারে। `dns`,`dns4`,`dns6` সমর্থন করে। + +--- + +####

price-limit + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +পুলের মধ্যে স্বীকৃতির জন্য প্রয়োগ করার জন্য ন্যূনতম গ্যাসের মূল্যের সীমা সেট করে। ডিফল্ট: `1`। + +--- + +####

max-slots + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +পুলের মধ্যে সর্বোচ্চ স্লট সেট করে। ডিফল্ট: `4096`। + +--- + +####

কনফিগ + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +CLI কনফিগের পাথ নির্দিষ্ট করে। `.json` সমর্থন করে। + +--- + +####

secrets-config + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +SecretsManager কনফিগ ফাইলের পাথ সেট করে। Hashicorp Vault, AWS SSM এবং GCP সিক্রেট ম্যানেজারের জন্য ব্যবহৃত হয়। যদি বাদ দেওয়া হয়, তাহলে স্থানীয় FS সিক্রেট ম্যানেজার ব্যবহার করা হয়। + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +ক্লায়েন্ট dev মোডে সেট করে। ডিফল্ট: `false`। dev মোডে, ডিফল্টরূপে পিয়ারের আবিষ্কার নিষ্ক্রিয় করা হয়। + +--- + +####

dev-interval + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +সেকেন্ডে ক্লায়েন্টের dev নোটিফিকেশনের ইন্টারভেল সেট করে। ডিফল্ট: `0`। + +--- + +####

no-discover + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +অন্যান্য পিয়ার্স আবিষ্কার করতে ক্লায়েন্টকে বাধা দেয়। ডিফল্ট: `false`। + +--- + +####

পুনরুদ্ধার + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +নির্দিষ্ট আর্কাইভ ফাইল থেকে ব্লক পুনরুদ্ধার করুন + +--- + +####

block-time + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +সেকেন্ডে ব্লক উত্পাদনের সময় সেট করে। ডিফল্ট: `2` + +--- + +####

access-control-allow-origins + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +JSON-RPC অনুরোধ থেকে প্রতিক্রিয়া শেয়ার করতে অনুমোদিত ডোমেন সেট করে। +একাধিক ডোমেন অনুমোদন করতে একাধিক `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"` ফ্ল্যাগ যোগ করুন। +যদি বাদ দেওয়া Access-Control-Allow-Origins হেডার `*` এ সেট করা হলে সমস্ত ডোমেন অনুমোদন করা হবে। + +--- + +### জেনেসিস ফ্ল্যাগ {#genesis-flags} +| **সকল জেনেসিস ফ্ল্যাগ** | +|---------------------------------------|---------------------------------------------| +| [dir](/docs/edge/get-started/cli-commands#dir) | [নাম](/docs/edge/get-started/cli-commands#name) | +| [pos](/docs/edge/get-started/cli-commands#pos) | [epoch-size](/docs/edge/get-started/cli-commands#epoch-size) | +| [premine](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [ibft-validator-type](/docs/edge/get-started/cli-commands#ibft-validator-type) | [ibft-validators-prefix-path](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [ibft-validator](/docs/edge/get-started/cli-commands#ibft-validator) | [block-gas-limit](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [কনসেনসাস](/docs/edge/get-started/cli-commands#consensus) | [bootnode](/docs/edge/get-started/cli-commands#bootnode) | +| [max-validator-count](/docs/edge/get-started/cli-commands#max-validator-count) | [min-validator-count](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

dir + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +Polygon Edge জেনেসিস ডেটার জন্য ডিরেক্টরি সেট করে। ডিফল্ট: `./genesis.json`। + +--- + +####

নাম + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +চেইনের নাম সেট করে। ডিফল্ট: `polygon-edge`। + +--- + +####

pos + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +ফ্ল্যাগ সেট করে যা প্রুফ অফ স্ট্যাক IBFT ব্যবহার করতে হবে বলে ইঙ্গিত করে। +যদি ফ্ল্যাগ প্রদান করা না হয় বা `false` হয়, তাহলে ডিফল্ট প্রুফ অফ অথোরিটিতে ফিরে যায়। + +--- + +####

epoch-size + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +চেইনের জন্য epoch আকার সেট করে। ডিফল্ট `100000`। + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +`address:amount` ফরম্যাটে আগে থেকে মাইন করা অ্যাকাউন্ট এবং ব্যলেন্স সেট করে। +পরিমাণটি দশমিক বা হেক্সে প্রকাশ করা হবে। +ডিফল্ট প্রি-মাইন ব্যালেন্স: `0xD3C21BCECCEDA1000000`(1 মিলিয়ন নেটিভ মুদ্রার টোকেন)। + +--- + +####

chainid + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +চেইনের আইডি সেট করে। ডিফল্ট: `100`। + +--- + +####

ibft-validator-type + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +ব্লক হেডারের বৈধতা মোড নির্দিষ্ট করে। সম্ভাব্য মান: `[ecdsa, bls]`। ডিফল্ট: `bls`। + +--- + +####

ibft-validators-prefix-path + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +যাচাইকারী ফোল্ডার ডিরেক্টরির আগে থেকে নির্ধারিত পাথ। `ibft-validator` ফ্ল্যাগ বাদ দেওয়া হলে উপস্থিত থাকতে হবে। + +--- + +####

ibft-validator + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +IBFT যাচাইকারী হিসাবে ঠিকানা পাস করে। `ibft-validators-prefix-path` ফ্ল্যাগ বাদ দেওয়া হলে উপস্থিত থাকতে হবে। +1. যদি নেটওয়ার্ক ECDSA দিয়ে চলমান হয়, তাহলে ফরম্যাটটি হবে `--ibft-validator [ADDRESS]`। +2. যদি নেটওয়ার্ক BLS দিয়ে চলমান হয়, তাহলে ফরম্যাটটি হবে `--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]`। + +--- + +####

block-gas-limit + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +একটি ব্লকে সমস্ত অপারেশন দ্বারা ব্যবহৃত সর্বোচ্চ পরিমাণ গ্যাস দেখুন। ডিফল্ট: `5242880`। + +--- + +####

কনসেনসাস + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +কনসেনসাস প্রোটোকল সেট করে। ডিফল্ট: `pow`। + +--- + +####

bootnode + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +p2p ডিসকভারি বুটস্ট্র্যাপের জন্য Multiaddr URL। এই ফ্ল্যাগটি একাধিক বার ব্যবহার করা যেতে পারে। +একটি আইপি ঠিকানার পরিবর্তে, bootnode DNS ঠিকানা প্রদান করা যেতে পারে। + +--- + +####

max-validator-count + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +একটি PoS কনসেনসাসের যাচাইকারীর সেটে যোগ করতে সক্ষম সর্বোচ্চ স্ট্যাকারের সংখ্যা। +এই সংখ্যা MAX_SAFE_INTEGER (2^53 - 2) মান অতিক্রম করতে পারবে না। + +--- + +####

min-validator-count + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +একটি PoS কনসেনসাসের যাচাইকারী সেটে যোগ করতে সক্ষম সর্বনিম্ন স্ট্যাকারের সংখ্যা। +এই সংখ্যা max-validator-count মান অতিক্রম করতে পারবে না। +1-এ ডিফল্ট হবে। + +--- + +### জেনেসিস প্রি-ডিপ্লয় ফ্ল্যাগ {#genesis-predeploy-flags} + +

artifacts-path

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +চুক্তি artifacts JSON পথ সেট করে যাতে `abi`, `bytecode` এবং `deployedBytecode` থাকে। + +--- + +

চেইন

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +`genesis.json` ফাইলের পাথ সেট করে যা আপডেট করা উচিত। ডিফল্ট `./genesis.json`। + +--- + +

constructor-args

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +যদি থাকে তবে স্মার্ট চুক্তি কনস্ট্রাক্টর আর্গুমেন্ট সেট করে। এই আর্গুমেন্ট কীরকম দেখতে উচিত তার উপর একটি বিস্তারিত নির্দেশিকার জন্য, [প্রিডিপ্লয়মেন্ট নিবন্ধটি](/docs/edge/additional-features/predeployment) দেখুন। + +--- + +

predeploy-address

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +এতে প্রিডিপ্লয়ের ঠিকানা সেট করে। ডিফল্ট `0x0000000000000000000000000000000000001100`। + +--- + + +## অপারেটর কমান্ড {#operator-commands} + +### পিয়ার কমান্ড {#peer-commands} + +| **কমান্ড** | **বিবরণ** | +|------------------------|-------------------------------------------------------------------------------------| +| পিয়ার যোগ | পিয়ারদের libp2p ঠিকানা ব্যবহার করে একটি নতুন পিয়ার যোগ করে | +| পিয়ারের তালিকা | ক্লায়েন্ট libp2p দ্বারা সংযুক্ত থাকা সকল পিয়ারে তালিকা করে | +| পিয়ারের স্ট্যাটাস | libp2p ঠিকানা ব্যবহার করে পিয়ার তালিকা থেকে একটি নির্দিষ্ট পিয়ারের স্ট্যাটাস ফেরত পাঠায় | + +

পিয়াররা ফ্ল্যাগ যোগ করেন

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +পিয়ারের libp2p ঠিকানা multiaddr ফরম্যাটে আছে। + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +gRPC API-এর ঠিকানা। ডিফল্ট: `127.0.0.1:9632`। + +

পিয়ারের তালিকার ফ্ল্যাগ

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +gRPC API-এর ঠিকানা। ডিফল্ট: `127.0.0.1:9632`। + +

পিয়ার স্ট্যাটাসের ফ্ল্যাগ

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +p2p নেটওয়ার্কের মধ্যে একটি নির্দিষ্ট পিয়ারের Libp2p নোড আইডি। + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +gRPC API-এর ঠিকানা। ডিফল্ট: `127.0.0.1:9632`। + +### IBFT কমান্ড {#ibft-commands} + +| **কমান্ড** | **বিবরণ** | +|------------------------|-------------------------------------------------------------------------------------| +| ibft স্ন্যাপশট | IBFT স্ন্যাপশট ফেরত পাঠায় | +| ibft ক্যান্ডিডেট | এই কমান্ডটি প্রস্তাবিত ক্যান্ডিডেটের পাশাপাশি এখনও অন্তর্ভুক্ত না হওয়া ক্যান্ডিডেটদের বর্তমান সেটকে কুয়েরি করে থাকে | +| ibft প্রস্তাব | যাচাইকারীর সেট থেকে একটি নতুন ক্যান্ডিডেট যোগ/অপসারণের প্রস্তাব করে | +| ibft স্ট্যাটাস | IBFT ক্লায়েন্টের সামগ্রিক স্ট্যাটাস ফেরত পাঠায় | +| ibft সুইচ | IBFT টাইপ সুইচ করতে genesis.json ফাইলে ফর্ক কনফিগারেশন যোগ করুন | +| ibft কোরাম | ব্লক নাম্বার নির্দিষ্ট করে, যার মধ্যে সবচেয়ে উপযুক্ত কোরাম সাইজ পদ্ধতি ব্যবহৃত হবে কনসেনসাসে পৌঁছানোর জন্য | + + +

ibft স্ন্যাপশট ফ্ল্যাগ

+ +

সংখ্যা

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +স্ন্যাপশটের জন্য ব্লকের উচ্চতা (সংখ্যা) + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +gRPC API-এর ঠিকানা। ডিফল্ট: `127.0.0.1:9632`। + +

ibft ক্যান্ডিডেটদের ফ্ল্যাগ

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +gRPC API-এর ঠিকানা। ডিফল্ট: `127.0.0.1:9632`। + +

ibft প্রস্তাবের ফ্ল্যাগ

+ +

ভোট

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +যাচাইকারীর সেটে একটি পরিবর্তনের প্রস্তাব করে। সম্ভাব্য মান: `[auth, drop]`। + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +যে অ্যাকাউন্টের ঠিকানার জন্য ভোট করা হবে। + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +যে অ্যাকাউন্টের BLS পাবলিক কী'র জন্য ভোট করা হবে, শুধুমাত্র BLS মোডে প্রয়োজনীয়। + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +gRPC API-এর ঠিকানা। ডিফল্ট: `127.0.0.1:9632`। + +

ibft স্ট্যাটাসের ফ্ল্যাগ

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +gRPC API-এর ঠিকানা। ডিফল্ট: `127.0.0.1:9632`। + +

ibft সুইচ ফ্ল্যাগ

+ +

চেইন

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +আপডেট করার জন্য জেনেসিস ফাইল নির্দিষ্ট করে। ডিফল্ট: `./genesis.json`। + +--- + +

প্রকার

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +সুইচ করার জন্য IBFT টাইপ নির্দিষ্ট করে। সম্ভাব্য মান: `[PoA, PoS]`। + +--- + +

ডিপ্লয়মেন্ট

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +চুক্তি ডিপ্লয়মেন্টের উচ্চতা নির্দিষ্ট করে। শুধুমাত্র PoS-এ পাওয়া যাচ্ছে। + +--- + +

প্রেরক

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +ব্লক হেডারের বৈধতা মোড নির্দিষ্ট করে। সম্ভাব্য মান: `[ecdsa, bls]`। ডিফল্ট: `bls`। + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +নতুন যাচাইকারীদের ডিরেক্টরি জন্য পথ প্রিফিক্স করে। `ibft-validator` ফ্ল্যাগ বাদ দেওয়া হলে উপস্থিত থাকতে হবে। শুধুমাত্র IBFT মোড PoA হলেই পাওয়া যায় (`--pos` ফ্ল্যাগ বাদ দেওয়া হয়)। + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +ঠিকানাগুলোতে পাস সেট করে কারণ ফর্কের পরে IBFT যাচাইকারী ব্যবহৃত হয়। `ibft-validators-prefix-path` ফ্ল্যাগ বাদ দেওয়া হলে উপস্থিত থাকতে হবে। শুধুমাত্র PoA মোডে পাওয়া যাচ্ছে। +1. যদি নেটওয়ার্ক ECDSA দিয়ে চলমান হয়, তাহলে ফরম্যাটটি হবে `--ibft-validator [ADDRESS]`। +2. যদি নেটওয়ার্ক BLS দিয়ে চলমান হয়, তাহলে ফরম্যাটটি হবে `--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]`। + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +একটি PoS কনসেনসাসের যাচাইকারীর সেটে যোগ করতে সক্ষম সর্বোচ্চ স্ট্যাকারের সংখ্যা। +এই সংখ্যা MAX_SAFE_INTEGER (2^53 - 2) মান অতিক্রম করতে পারবে না। + +--- + +

min-validator-count

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +একটি PoS কনসেনসাসের যাচাইকারী সেটে যোগ করতে সক্ষম সর্বনিম্ন স্ট্যাকারের সংখ্যা। +এই সংখ্যা max-validator-count মান অতিক্রম করতে পারবে না। +1-এ ডিফল্ট হবে। + +ফর্কের শুরুর উচ্চতা নির্দিষ্ট করে। + +--- + +

ibft কোরাম পতাকা

+ +

প্রেরক

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +কোরাম গণনা থেকে QuorumOptimal এ সুইচ করার উচ্চতা, যা `(2/3 * N)` সূত্র ব্যবহার করে, এখানে `N` হচ্ছে যাচাইকারী নোডের সংখ্যা। অনুগ্রহ করে মনে রাখবেন যে এটি পূর্ববর্তী সংস্করণ সমর্থন করে না, অর্থাৎ শুধুমাত্র একটি নির্দিষ্ট ব্লক উচ্চতা পর্যন্ত একটি কোরাম লিগেসি গণনা ব্যবহার করা চেইনেই এটি সমর্থন করে। + +--- + +

চেইন

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +আপডেট করার জন্য জেনেসিস ফাইল নির্দিষ্ট করে। ডিফল্ট: `./genesis.json`। + +### লেনদেন পুলের কমান্ড {#transaction-pool-commands} + +| **কমান্ড** | **বিবরণ** | +|------------------------|--------------------------------------------------------------------------------------| +| txpool স্ট্যাটাস | পুলে লেনদেনের সংখ্যা ফেরত পাঠায় | +| txpool সাবস্ক্রাইব | লেনদেনের পুলে ইভেন্টগুলির জন্য সাবস্ক্রাইব করে | + +

txpool স্ট্যাটাসের পতাকা

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +gRPC API-এর ঠিকানা। ডিফল্ট: `127.0.0.1:9632`। + +

txpool সাবস্ক্রাইব ফ্ল্যাগ

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +gRPC API-এর ঠিকানা। ডিফল্ট: `127.0.0.1:9632`। + +--- + +

প্রোমোট

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +TxPool-এ প্রোমোট করা tx ইভেন্টের জন্য সাবস্ক্রাইব করে। + +--- + +

ড্রপ

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +TxPool-এ ড্রপ করা tx ইভেন্টগুলোর জন্য সাবস্ক্রাইব করে। + +--- + +

ডিমোট

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +TxPool-এ ডিমোট করা tx ইভেন্টগুলোর জন্য সাবস্ক্রাইব করে। + +--- + +

যোগ

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +TxPool-এ যোগ করা tx ইভেন্টগুলোর জন্য সাবস্ক্রাইব করে। + +--- + +

এনকিউ

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +অ্যাকাউন্ট কিউতে এনকিউ করা tx ইভেন্টগুলোর জন্য সাবস্ক্রাইব করে। + +--- + +### ব্লকচেইন কমান্ড {#blockchain-commands} + +| **কমান্ড** | **বিবরণ** | +|------------------------|-------------------------------------------------------------------------------------| +| স্ট্যাটাস | ক্লায়েন্টের স্ট্যাটাস ফেরত পাঠায়। বিস্তারিত প্রতিক্রিয়া নিচে পাবেন | +| মনিটর | একটি blockchain ইভেন্ট স্ট্রিমে সাবস্ক্রাইব করে। বিস্তারিত প্রতিক্রিয়া নিচে পাবেন | +| সংস্করণ | ক্লায়েন্টের বর্তমান সংস্করণ ফেরত পাঠায় | + +

স্ট্যাটাসের ফ্ল্যাগ

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +gRPC API-এর ঠিকানা। ডিফল্ট: `127.0.0.1:9632`। + +

মনিটর ফ্ল্যাগ

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +gRPC API-এর ঠিকানা। ডিফল্ট: `127.0.0.1:9632`। + +--- +

সংস্করণ কমান্ড

+ + + + + + version + + + + +রিলিজ সংস্করণ, git branch, commit hash এবং বিল্ড টাইম প্রদর্শন করে। + +## সিক্রেট কমান্ড {#secrets-commands} + +| **কমান্ড** | **বিবরণ** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| সিক্রেট init | সংশ্লিষ্ট সিক্রেট ম্যানেজারে প্রাইভেট কী চালু করে | +| সিক্রেট তৈরি | একটি সিক্রেট ম্যানেজার কনফিগারেশন ফাইল তৈরি করে যা Polygon Edge দ্বারা পার্স করা যেতে পারে | +| সিক্রেট আউটপুট | রেফারেন্স জন্য BLS পাবলিক কী ঠিকানা, যাচাইকারী পাবলিক কী ঠিকানা এবং নোড আইডি প্রিন্ট করে | + +### সিক্রেট init ফ্ল্যাগ {#secrets-init-flags} + +

কনফিগ

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +SecretsManager কনফিগ ফাইলের পাথ সেট করে। Hashicorp ভল্টের জন্য ব্যবহৃত হয়। যদি বাদ দেওয়া হয়, তাহলে স্থানীয় FS সিক্রেট ম্যানেজার ব্যবহার করা হয়। + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +স্থানীয় FS ব্যবহার করা হলে Polygon Edge তথ্যের জন্য ডিরেক্টরি সেট করে। + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +একটি ECDSA কী তৈরি করতে হবে কিনা তা নির্দেশ করার জন্য ফ্ল্যাগ সেট করে। ডিফল্ট: `true`। + +--- + +

নেটওয়ার্ক

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +একটি Libp2p নেটওয়ার্ক কী তৈরি করতে হবে কিনা তা নির্দেশ করে ফ্ল্যাগ সেট করে। ডিফল্ট: `true`। + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +একটি BLS কী তৈরি করতে হবে কিনা তা নির্দেশ করে ফ্ল্যাগ সেট করে। ডিফল্ট: `true`। + +### সিক্রেট তৈরির ফ্ল্যাগ {#secrets-generate-flags} + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +সিক্রেট ম্যানেজার কনফিগারেশন ফাইলের ডিরেক্টরি সেট করে। ডিফল্ট: `./secretsManagerConfig.json` + +--- + +

প্রকার

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +সিক্রেট ম্যানেজারের ধরন নির্দিষ্ট করে [`hashicorp-vault`]। ডিফল্ট: `hashicorp-vault` + +--- + +

টোকেন

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +সার্ভিসের জন্য অ্যাক্সেস টোকেন নির্দিষ্ট করে + +--- + +

server-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +সার্ভিসের জন্য সার্ভার URL নির্দিষ্ট করে + +--- + +

নাম

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +সার্ভিসে-থাকা রেকর্ড কিপিংয়ের জন্য নোডের নাম নির্দিষ্ট করে। ডিফল্ট: `polygon-edge-node` + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Hashicorp ভল্ট সিক্রেট ম্যানেজারের জন্য ব্যবহৃত namespace নির্দিষ্ট করে। ডিফল্ট: `admin` + +### সিক্রেট আউটপুট ফ্ল্যাগ {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +শুধুমাত্র BLS পাবলিক কী আউটপুট করতে হবে কিনা তা নির্দেশ করে ফ্ল্যাগ সেট করে। ডিফল্ট: `true` + +--- + +

কনফিগ

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +SecretsManager কনফিগ ফাইলের পাথ সেট করে। যদি বাদ দেওয়া হয়, তাহলে স্থানীয় FS সিক্রেট ম্যানেজার ব্যবহার করা হয়। + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +স্থানীয় FS ব্যবহার করা হলে Polygon Edge তথ্যের জন্য ডিরেক্টরি সেট করে। + +--- + +

node-id

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +শুধুমাত্র নেটওয়ার্ক নোড আইডি আউটপুট করতে হবে কিনা তা নির্দেশ করে ফ্ল্যাগ সেট করে। ডিফল্ট: `true` + +--- + +

যাচাইকারী

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +শুধুমাত্র যাচাইকারী ঠিকানা আউটপুট করতে হবে কিনা তা নির্দেশ করে ফ্ল্যাগ সেট করে। ডিফল্ট: `true` + +--- + +## প্রতিক্রিয়া {#responses} + +### স্টাটাসের প্রতিক্রিয়া {#status-response} + +প্রতিক্রিয়া অবজেক্টটি প্রোটোকল বাফার ব্যবহার করে সংজ্ঞায়িত করা হয়। +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### প্রতিক্রিয়া মনিটর করুন {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## ইউটিলিটি {#utilities} + +### কমান্ড হোয়াইটলিস্ট করুন {#whitelist-commands} + +| **কমান্ড** | **বিবরণ** | +|------------------------|-------------------------------------------------------------------------------------| +| হোয়াইটলিস্ট দেখান | হোয়াইলিস্টের তথ্য প্রদর্শন করে | +| হোয়াইটলিস্ট ডিপ্লয়মেন্ট | স্মার্ট চুক্তি ডিপ্লয়মেন্ট হোয়াইটলিস্ট আপডেট করে | + +

হোয়াইটলিস্ট দেখান

+ + + + + whitelist show + + + + +হোয়াইটলিস্টের তথ্য প্রদর্শন করে। + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +আপডেট করার জন্য জেনেসিস ফাইল নির্দিষ্ট করে। ডিফল্ট: `./genesis.json`। + +--- + +

হোয়াইটলিস্ট ডিপ্লয়মেন্ট

+ +

চেইন

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +আপডেট করার জন্য জেনেসিস ফাইল নির্দিষ্ট করে। ডিফল্ট: `./genesis.json`। + +--- + +

যোগ

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +চুক্তি ডিপ্লয়মেন্ট হোয়াইটলিস্টে একটি নতুন ঠিকানা যোগ করে। শুধুমাত্র চুক্তি ডিপ্লয়মেন্ট হোয়াইটলিস্টে থাকা ঠিকানাগুলো চুক্তি ডিপ্লয় করতে পারে। যদি খালি থাক, তাহলে যেকোনো ঠিকানা চুক্তি ডিপ্লয়মেন্ট এক্সিকিউট করতে পারে + +--- + +

অপসারণ

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +চুক্তি ডিপ্লয়মেন্ট হোয়াইটলিস্ট থেকে একটি ঠিকানা অপসারণ করে। শুধুমাত্র চুক্তি ডিপ্লয়মেন্ট হোয়াইটলিস্টে থাকা ঠিকানাগুলো চুক্তি ডিপ্লয় করতে পারে। যদি খালি থাক, তাহলে যেকোনো ঠিকানা চুক্তি ডিপ্লয়মেন্ট এক্সিকিউট করতে পারে + +--- + +### ব্যাকআপ ফ্ল্যাগ {#backup-flags} + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +gRPC API-এর ঠিকানা। ডিফল্ট: `127.0.0.1:9632`। + +--- + +

আউট

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +সংরক্ষণ করতে হবে এমন আর্কাইভের ফাইলের পাথ। + +--- + +

প্রেরক

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +আর্কাইভে ব্লকের শুরু উচ্চতা। ডিফল্ট: 0। + +--- + +

প্রাপক

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +আর্কাইভে ব্লকের শেষ উচ্চতা। + +--- + +## জেনেসিস টেমপ্লেট {#genesis-template} +জেনেসিস ফাইল ব্লকচেইনের প্রাথমিক অবস্থা সেট করতে ব্যবহার করা উচিত (যেমন, কিছু অ্যাকাউন্টের একটি প্রারম্ভিক ব্যালেন্স থাকবে কিনা)। + +নিম্নলিখিত *./genesis.json* ফাইল তৈরি হয়: +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### তথ্য ডিরেক্টরি {#data-directory} + +*data-dir* ফ্ল্যাগ এক্সিকিউট করার সময়, একটি **test-chain** ফোল্ডার তৈরি হয়। +ফোল্ডারের স্ট্রাকচারটিতে নিম্নলিখিত সাব-ফোল্ডার রয়েছে: +* **ব্লকচেইন** - ব্লকচেইন অবজেক্টের LevelDB সংরক্ষণ করে +* **ট্রি** - Merkle ট্রি'র জন্য LevelDB সংরক্ষণ করে +* **keystore** - ক্লায়েন্টের জন্য প্রাইভেট কী সংরক্ষণ করে। এতে libp2p প্রাইভেট কী এবং সিলিং/যাচাইকারী প্রাইভেট কী অন্তর্ভুক্ত রয়েছে +* **কনসেনসাস** - কাজের সময় ক্লায়েন্টের প্রয়োজন হতে পারে এমন সকল কনসেনসাস তথ্য সংরক্ষণ করে + +## রিসোর্স {#resources} +* **[প্রোটোকল বাফার](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/bn-edge/get-started/installation.md b/archive/edge/bn-edge/get-started/installation.md new file mode 100644 index 0000000000..5877cf0ef4 --- /dev/null +++ b/archive/edge/bn-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: ইনস্টলেশন +description: "কীভাবে Polygon Edge ইনস্টল করবেন।" +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +অনুগ্রহ করে আপনার জন্য আরও বেশি প্রযোজ্য ইনস্টলেশন পদ্ধতিটি পড়ুন। + +আমাদের সুপারিশ হচ্ছে প্রি-বিল্ট রিলিজ ব্যবহার করুন এবং প্রদত্ত চেকসামটি যাচাই করুন। + +## প্রি-বিল্ট রিলিজ {#pre-built-releases} + +রিলিজগুলোর একটি তালিকার জন্য, অনুগ্রহ করে [GitHub রিলিজ](https://github.com/0xPolygon/polygon-edge/releases) পৃষ্ঠাটি দেখুন। + +Polygon Edge-এ Darwin এবং Linux-এর জন্য ক্রস-কম্পাইলড AMD64/ARM64 বাইনারির সুবিধা পাওয়া যায়। + +--- + +## ডকার ইমেজ {#docker-image} + +অফিসিয়াল ডকার ইমেজ [hub.docker.com রেজিস্ট্রিতে](https://hub.docker.com/r/0xpolygon/polygon-edge) হোস্ট করা আছে। + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## উৎস থেকে নির্মাণ {#building-from-source} + +`go install` ব্যবহার করার আগে নিশ্চিত হয়ে নিন যে আপনি Go `>=1.18` ইনস্টল করেছেন এবং সেটি সঠিকভাবে কনফিগার করেছেন। + +স্থিতিশীল ব্রাঞ্চটি হচ্ছে সর্বশেষ রিলিজের ব্রাঞ্চ। + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## `go install` ব্যবহার করা + +`go install` ব্যবহার করার আগে নিশ্চিত হয়ে নিন যে আপনি Go `>=1.17` ইনস্টল করেছেন এবং সেটি সঠিকভাবে কনফিগার করেছেন। + +`go install github.com/0xPolygon/polygon-edge@release/` + +বাইনারি আপনার `GOBIN`এনভায়রনমেন্ট variable, পাওয়া যাবে, এবং সর্বশেষ রিলিজের পরিবর্তনগুলো অন্তর্ভুক্ত থাকবে। আপনি কোনটি সর্বশেষ which া তা খুঁজে বের করতে [GitHub রিলিজ](https://github.com/0xPolygon/polygon-edge/releases) আউট চেকআউট করতে পারেন। diff --git a/archive/edge/bn-edge/get-started/set-up-ibft-locally.md b/archive/edge/bn-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..f5e4da92d8 --- /dev/null +++ b/archive/edge/bn-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,390 @@ +--- +id: set-up-ibft-locally +title: লোকাল সেটআপ +description: "স্টেপ-বাই-স্টেপ লোকাল সেটআপ গাইড।" +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution এই গাইডটি শুধুমাত্র পরীক্ষার উদ্দেশ্যে তৈরি + +নীচের নির্দেশিকা আপনাকে পরীক্ষা এবং উন্নয়নের উদ্দেশ্যে আপনার লোকাল মেশিনে একটি Polygon Edge নেটওয়ার্ক কীভাবে সেট আপ করতে হয় সে সম্পর্কে নির্দেশ দেবে। + +বাস্তব ব্যবহারের দৃশ্যের জন্য আপনি যেভাবে Polygon Edge নেটওয়ার্ক সেট আপ করতে চান তার থেকে পদ্ধতিটি অনেকটাই আলাদা একটি ক্লাউড প্রোভাইডার থেকে: ** [ক্লাউড সেটআপ](/docs/edge/get-started/set-up-ibft-on-the-cloud)** + +::: + + +## প্রয়োজনীয়তা {#requirements} + +Polygon Edge ইনস্টল করার জন্য [ইনস্টলেশন](/docs/edge/get-started/installation) পড়ুন। + +## সংক্ষিপ্ত বিবরণ {#overview} + +![লোকাল সেটআপ](/img/edge/ibft-setup/local.svg) + +এই গাইডে আমাদের লক্ষ্য হল [IBFT এর consensus প্রোটোকল](https://github.com/ethereum/EIPs/issues/650) এর সাথে কাজ করে একটি কার্যক্ষম `polygon-edge`ব্লকচেইন নেটওয়ার্ক স্থাপন করা। ব্লকচেইন নেটওয়ার্কের মধ্যে 4টি নোড রয়েছে যার মধ্যে সবগুলোই ভ্যালিডেটর নোড, এবং তাই তারা ব্লক প্রপোজ করা এবং অন্যান্য প্রোপোজার থেকে যে ব্লক নেয়া হয়েছে তা যাচাই করা, উভয়ের ক্ষেত্রেই যোগ্য হবে। 4টি নোড একই মেশিনে চালানো হবে, কারণ এই গাইডের কাজ আপনাকে ন্যুনতম সময়ের মধ্যে একটি সম্পূর্ণ ফাংশনাল IBFT ক্লাস্টার প্রদান করা। + +এটি অর্জন করার জন্য, আমরা আপনাকে 4টি সহজ স্টেপের মাধ্যমে গাইড করব: + +1. ডাটা ডিরেক্টরি চালু করা হলে প্রতি 4টি নোডের জন্য উভয় ভ্যালিডেটর কী তৈরি হবে, এবং একটি খালি ব্লকচেইন ডাটা ডিরেক্টরি চালু হবে। ভ্যালিডেটর কীগুলো গুরুত্বপূর্ণ কারণ এই কীগুলো ব্যবহার করে ভ্যালিডেটরদের প্রাথমিক সেটের সাথে আমাদের জেনেসিস ব্লক বুটস্ট্র্যাপ করতে হবে। +2. বুট নোডের জন্য সংযোগ স্ট্রিং প্রস্তুত করা প্রতিটি নোডের জন্য গুরুত্বপূর্ণ তথ্য হবে কারণ আমরা জানতে পারবো যে প্রথমবার শুরু করতে কোন নোডের সাথে সংযোগ করা প্রয়োজন। +3. `genesis.json` ফাইল তৈরি করার জন্য জেনিসিস ব্লকে নেটওয়ার্কের প্রারম্ভিক ভ্যালিডেটর সেট করার জন্য ব্যবহৃত **ধাপ 1-এ** জেনারেট করা উভয় ভ্যালিডেটর কী এবং **ধাপ 2** থেকে বুট নোড সংযোগ স্ট্রিং উভয়ই ইনপুট হিসাবে প্রয়োজন হবে। +4. সমস্ত নোড চালানো এই গাইডের শেষ লক্ষ্য এবং এটি হবে আমাদের শেষ ধাপ, আমরা নোডকে নির্দেশ দিব কোন ডাটা ডিরেক্টরি ব্যবহার করতে হবে এবং কোথায় `genesis.json` খুঁজে বের করতে হবে যা প্রাথমিক নেটওয়ার্ক স্টেটকে বুটস্ট্র্যাপ করে। + +সেটআপ প্রক্রিয়ার সময় চারটি নোডই লোকালহোস্টে চলমান থাকবে, তাই আশা করা যায় যে সকল ডাটা ডিরেক্টরি প্রতিটি নোডের জন্য একই প্যারেন্ট ডিরেক্টরিতে রয়েছে। + +:::info ভ্যালিডেটরের সংখ্যা + +একটি ক্লাস্টারে নোডের সংখ্যার কোন ন্যূনতম মান নেই, অর্থাৎ শুধুমাত্র 1টি ভ্যালিডেটর নোড দিয়ে ক্লাস্টার সম্ভব। মনে রাখবেন যে _একটি একক_ নোড ক্লাস্টারের কোন **ক্র্যাশ সহনশীলতা** নেই **এবং কোন BFT গ্যারান্টি** নেই। + +একটি BFT গ্যারান্টি অর্জনের জন্য নোডের ন্যূনতম প্রস্তাবিত সংখ্যা 4 - যেহেতু একটি 4 নোড ক্লাস্টারে 1টি নোডের ব্যর্থতা সহনীয়, বাকি 3টি স্বাভাবিকভাবেই কাজ করবে। + +::: + +## স্টেপ 1: IBFT এর জন্য ডাটা ফোল্ডার চালু করুন এবং ভ্যালিডেটর কী তৈরি করুন {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +IBFT ভালোভাবে চালু করতে, আপনাকে ডাটা ফোল্ডার চালু করতে হবে, প্রতিটি নোডের জন্যঃ + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +এই কমান্ডগুলোর প্রতিটি ভ্যালিডেটর কী, bls পাবলিক কী এবং [নোড আইডি](https://docs.libp2p.io/concepts/peer-id/) প্রিন্ট করবে। পরবর্তী স্টেপের জন্য আপনার প্রথম নোডের নোড আইডি প্রয়োজন হবে। + +### সিক্রেট আউটপুট করা {#outputting-secrets} +যদি প্রয়োজন হয় তবে সিক্রেট আউটপুট আবার পুনরুদ্ধার করা যাবে। + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## স্টেপ 2: বুটনোডের জন্য multiaddr কানেকশন স্ট্রিং প্রস্তুত করুন {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +একটি নোডের সফলভাবে সংযোগ স্থাপন করার জন্য, তাকে অবশ্যই জানতে হবে যে কোন `bootnode`সার্ভারের সাথে সংযোগ করতে হবে নেটওয়ার্কের অবশিষ্ট সকল নোডের তথ্য পেতে। `bootnode` কে কখনও কখনও p2p জার্গনে `rendezvous` সার্ভারও বলা হয়। + +`bootnode`polygon-edge নোডের কোন বিশেষ উদাহরণ নয়। প্রতিটি polygon-edge নোড একটি `bootnode` হিসাবে কাজ করতে পারে, কিন্তু প্রতিটি polygon-edge নোডের একটি নির্দিষ্ট বুটনোডের সেট থাকতে হবে যা তথ্য প্রদান করবে কীভাবে সংযোগ করতে হয় নেটওয়ার্কের অবশিষ্ট সকল নোডের সাথে। + +বুটনোড নির্দিষ্ট করে সংযোগ স্ট্রিং তৈরি করার জন্য, আমাদের মানিয়ে চলতে হবে [multiaddr ফর্ম্যাট এর সাথে](https://docs.libp2p.io/concepts/addressing/)ঃ +``` +/ip4//tcp//p2p/ +``` + +এই গাইডে আমরা প্রথম এবং দ্বিতীয় নোডকে অন্য সকল নোডের জন্য বুটনোড হিসেবে ব্যবহার করব। এই পরিস্থিতিতে যা ঘটবে তা হল বা এর সাথে যে নোডগুল সংযোগ করে তারা একে অপরের সাথে পারস্পরিকভাবে সংযোজিত বুটনোড দি`node 2`য়ে `node 1`কীভাবে সংযোগ করবে তার তথ্য পাবে। + +:::info একটি নোড শুরু করতে আপনাকে অন্তত একটি বুটনোড নির্দিষ্ট করতে হবে + +অন্তত একটি বুটনোড প্রয়োজনীয়, যাতে নেটওয়ার্কের অন্যান্য নো**ডগ**ুলো একে অপরকে আবিষ্কার করতে পারে। অতিরিক্ত বুটনোডের পরামর্শ দেওয়া হয়, কারণ বিদ্যুৎ চলে যাওয়ার ক্ষেত্রে তারা নেটওয়ার্ককে সহনশীলতা প্রদান করে। এই গাইডে আমরা দুটি নোডের তালিকা দিব, কিন্তু এটি যেকোনো সময়ে পরিবর্তন করা যাবে, এবং এতে `genesis.json` ফাইলের বৈধতার উপর কোন প্রভাব পড়ে না। +::: + +যেহেতু আমরা লোকাল হোস্টে চলছি, তাই এটা অনুমান করা নিরাপদ যে `` হল `127.0.0.1`। + +`` এর জন্য আমরা `10001` ব্যবহার করব যেহেতু আমরা X-এর এই পোর্টে `node 1` শোনার জন্য libp2p সার্ভার কনফিগার করব। + +এবং অবশেষে, আমাদের `` প্রয়োজন যা আমরা পূর্বে রান করা কমান্ডের`polygon-edge secrets init --data-dir test-chain-1` আউটপুট থেকে পাবো (যা `node1`এর জন্য কী জেনারেট করতে এবং ডাটা ডিরেক্টরি তৈরি করতে ব্যবহৃত হয়েছিলও) + +অ্যাসেম্বলির পর, `node 1` এর সাথে multiaddr কানেকশন স্ট্রিং যা আমরা বুটনোড হিসেবে ব্যবহার করব, তা দেখতে কিছুটা এরকম হবে (শুধুমাত্র ``যেটি শেষে আছে, সেটি দেখতে কিছুটা আলাদা হবে): +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +একইভাবে, আমরা দ্বিতীয় বুটনোডের জন্য multiaddr তৈরি করি +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info ips এর পরিবর্তে DNS হোস্টনেম + +Polygon Edge নোড কনফিগারেশনের জন্য DNS হোস্টনেমের ব্যবহার সাপোর্ট করে। এটি ক্লাউড ভিত্তিক ডিপ্লয়মেন্টের জন্য অনেক সহায়ক বৈশিষ্ট্য, কারণ নোডের আইপি বিভিন্ন কারনে পরিবর্তিত হতে পারে। + +DNS হোস্টনেম ব্যবহার করার সময় কানেকশন স্ট্রিংয়ের জন্য multiaddr ফর্ম্যাটটি নিম্নলিখিতঃ`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## স্টেপ 3: 4টি নোডকে ভ্যালিডেটর হিসানে নিয়ে জেনেসিস ফাইল তৈরি করুন {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +এই কমান্ডটি যা করে: + +* X `--ibft-validators-prefix-path`প্রিফিক্স ফোল্ডার পাথকে নির্দিষ্ট করে দেয় যা IBFT ের মধ্যে Polygon Edge ব্যবহার করতে পারে। এই ডিরেক্টরিটি ফোল্ডারটি রাখার জন্য ব্যবহৃত `consensus/`হয়, যেখানে ভ্যালিডেটরের প্রাইভেট কী টি রাখা হয়। দ্যা জেনেসিস ফাইল তৈরি করার জন্য যাচাইকারীর পাবলিক কী প্রয়োজন - bootstrap nodes এর প্রাথমিক তালিকা। এই পতাকাটি শুধুমাত্র লোকালহোস্টে নেটওয়ার্ক সেট করার সময় কাজ করে, কারণ বাস্তবে আমরা কখনোই আশা করতে পারি না যে নোডগুলোর ডাটা ডিরেক্টরি একই ফাইলসিস্টেমে হবে যেখান থেকে আমরা সহজেই তাদের পাবলিক কী গুলো রিড করতে পারবো। +* বুটনোডের অ্যাড্রেস সেট করে `--bootnode`যা নোডগুলোকে একে অপরকে খুঁজে পেতে সাহায্য করবে। আমরা **স্টেপ 2** এর অনুযায়ী, `node 1` এর multiaddr স্ট্রিংটি ব্যবহার করব। + +এই কমান্ডের ফলাফল হলো `genesis.json`ফাইলটি, যা আমাদের নতুন ব্লকচেইনের জেনেসিস ব্লক ধারণ করে, যাতে প্রথমে কোন নোডের সাথে যোগাযোগ করতে হবে তার জন্য পূর্বনির্ধারিত ভ্যালিডেটর সেট এবং কনফিগারেশন থাকে। + +:::info ECDSA তে সুইচ করুন + +BLS ব্লক হেডারদের জন্য ডিফল্ট ভ্যালিডেশন মোড। আপনি যদি আপনার চেইনটিকে ECDSA মোডে রান করাতে চান তবে আপনি ফ্ল্যাগটি ব্যবহার করতে পারে`—ibft-validator-type`ন, এই আর্গুমেন্ট `ecdsa`সহ: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info অ্যাকাউন্টের প্রিমাইনিং ব্যালেন্স + +আপনি হয়তোবা কিছু "প্রিমাইন্ড" ব্যালেন্স সহ অ্যাড্রেস আপনার ব্লকচেইন নেটওয়ার্কে সেট আপ করতে চাইবেন। + +এটি অর্জন করতে, আপনি একটি নির্দিষ্ট ব্যালেন্সের সাথে শুরু করতে চান এমন সবগুলো অ্যাড্রেসকে যতবার ইচ্ছা ফ্ল্যা`--premine`গে পাস করুন ব্লকচেইনে। + +উদাহরণস্বরূপ, আমরা যদি আমাদের জেনেসিস ব্লকের অ্যাড্রেসে 1000 ETH `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862`প্রিমাইন করতে চাই, তবে আমাদের নিম্নলিখিত আর্গুমেন্ট সরবরাহ করতে হবে: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**মনে রাখবেন, প্রিমাইন করা পরিমাণ ETH এ নয়, WEI তে থাকবে।** + +::: + +:::info ব্লক গ্যাস সীমা সেট করুন + +প্রতিটি ব্লকের জন্য ডিফল্ট গ্যাস সীমা হলো`5242880`। এই মানটি জেনেসিস ফাইলে লেখা হয়, কিন্তু আপনি চাইতে পারেন এটি বৃদ্ধি / হ্রাস করতে। + +সেটি করতে, আপনি নীচের হিসাবে পছন্দসই মানের ফ্ল্যা`--block-gas-limit`গ ব্যবহার করতে পারেন: + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info সিস্টেম ফাইল ডেস্ক্রিপ্টর সীমা সেট করুন + +ডিফল্ট ফাইল ডেস্ক্রিপ্টর সীমা (সর্বাধিক সংখ্যক ওপেন ফাইল) কিছু অপারেটিং সিস্টেমে বেশ ছোট। নোডগুলোর থেকে যদি উচ্চ থ্রুপুটের আশা করা হয়, তবে আপনি অপারেটিং সিস্টেমে এই সীমা বৃদ্ধি করার কথা বিবেচনা করতে পারেন। + +উবুন্টু ডিস্ট্রোর জন্য পদ্ধতিটি নিম্নরূপ (আপনি যদি উবুন্টু / ডেবিয়ান ডিস্ট্র ব্যবহার না করেন, তবে আপনার OS এর জন্য অফিসিয়াল নিয়মাবলী দেখুন): +- বর্তমান OS সীমা চেক করুন (ওপেন ফাইল) +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- ওপেন ফাইল সীমা বৃদ্ধি করুন + - Localy - শুধুমাত্র বর্তমান সেশনকে প্রভাবিত করে: + ```shell + ulimit -u 65535 + ``` + - Globaly বা প্রতি ব্যবহারকারীর জন্য (/etc/security/limits.conf এর শেষে সীমা যোগ করুন): + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +ঐচ্ছিকভাবে, অতিরিক্ত প্যারামিটার মডিফাই করুন, ফাইলটি সংরক্ষণ করুন এবং সিস্টেমটি পুনরায় চালু করুন। পুনরায় চালু করার পরে ফাইল ডেস্ক্রিপ্টর সীমা আবার চেক করুন। আপনি limits.conf ফাইলে যে মান নির্ধারণ করেছিলেন, তাই হওয়া উচিৎ। +::: + + +## স্টেপ 4: সকল ক্লায়েন্ট রান করুন {#step-4-run-all-the-clients} + +আমরা যেহেতু একটি Polygon Edge নেটওয়ার্ক রান করার করছি যেখানে একই মেশিনে 4টি নোড থাকবে, তাই আমাদের অবশ্যই খেয়াল রাখতে হবে যাতে আমরা পোর্ট কনফ্লিক্ট এড়াতে পারি। এই কারণেই আমরা একটি নোডের প্রতিটি সার্ভারের লিসেনিং পোর্ট নির্ধারণ করার জন্য নিম্নলিখিত যুক্তিগুলো ব্যবহার করব: + +- `10000`gRPC সার্ভারের জন্য`node 1`, `20000`gRPC সার্ভারের জন্য`node 2`, ইত্যাদি। +- `10001`libp2p সার্ভারের `node 1`, `20001`libp2p সার্ভারের জন্য`node 2`, ইত্যাদি। +- `10002`JSON-RPC সার্ভারের`node 1`, `20002`JSON-RPC সার্ভারের জন্য`node 2`, ইত্যাদি। + +**প্রথম** ক্লায়েন্ট রান করতে (পোর্টটি নোট করুন `10001`যেহেতু এটি libp2p multiaddr এর একটি অংশ হিসাবে **স্টেপ 2** এর নোড 1 এর নোড আইডির সাথে ব্যবহার করা হয়েছে): + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +**দ্বিতীয়** ক্লায়েন্ট রান করতে: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +তৃতীয় ক্লায়েন্ট রান **করতে**: + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +**চতুর্থ** ক্লায়েন্ট রান করতে: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +এতদূর পর্যন্ত যা করা হয়েছে তা সংক্ষিপ্তভাবে বলতে গেলেঃ + +* ক্লায়েন্ট ডেটার জন্য ডিরেক্টরি হিসাবে.**/test-chain-\* **নির্ধারিত হয়েছে +* GRPC সার্ভারগুলো যথাক্রমে **10000**, **20000**, **30000** এবং **40000** এ পোর্ট চালু করেছে, প্রতিটি নোডের জন্য +* libp2p সার্ভারগুলো যথাক্রমে **10001**, **20001**, **30001** এবং **40001** এ পোর্ট চালু করেছে, প্রতিটি নোডের জন্য +* JSON-RPC সার্ভারগুলো যথাক্রমে **10002**, **20002**, **30002** এবং **40002** এ পোর্ট চালু করেছে, প্রতিটি নোডের জন্য +* *সীল* ফ্ল্যাগের অর্থ হল, যে নোডটি শুরু করা হচ্ছে তা ব্লক সিলিংয়ে অংশগ্রহণ করবে +* *চেইন* ফ্ল্যাগ এটি নির্দিষ্ট করে যে চেইন কনফিগারেশনের জন্য কোন জেনেসিস ফাইল ব্যবহার করা উচিত + +জেনেসিস ফাইলের গঠন নিয়ে [CLI Commands](/docs/edge/get-started/cli-commands) সেকশনে ব্যাখ্যা করা হয়েছে। + +পূর্ববর্তী কমান্ডগুলো রান করার পরে, আপনি একটি 4 নোডের Polygon Edge নেটওয়ার্ক সেট আপ করেছেন, যা ব্লক সিল করতে এবং ফিরে আসতে সক্ষম নোড ফেইলিওর থেকে। + +:::info কনফিগ ফাইল ব্যবহার করে ক্লায়েন্ট শুরু করুন + +সমস্ত কনফিগারেশন প্যারামিটার CLI আর্গুমেন্ট হিসাবে নির্দিষ্ট করার পরিবর্তে, ক্লায়েন্টটি নিম্নলিখিত কমান্ড সম্পাদন করে একটি কনফিগ ফাইল ব্যবহার করে শুরু করা যাবে: + +````bash +polygon-edge server --config +```` +উদাহরণ: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +বর্তমানে, আমরা `yaml` এবং `json` ভিত্তিক কনফিগারেশন ফাইলগুলো সাপোর্ট করি, নমুনা কনফিগ ফাইল **[এখানে](/docs/edge/configuration/sample-config)** পাওয়া যাবে + +::: + +:::info একটি নন-ভ্যালিডেটর নোড রান করার স্টেপসমূহ + +একটি নন-ভ্যালিডেটর সর্বদা ভ্যালিডেটর নোডের থেকে পাওয়া সর্বশেষ ব্লক সিঙ্ক করবে, আপনি নিম্নলিখিত কমান্ডটি রান করে একটি নন-ভ্যালিডেটর নোড শুরু করতে পারেন। + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +উদাহরণস্বরূপ, আপনি নিম্নলিখিত কমান্ডটি সম্পাদন করে পঞ্**চম নন**-ভ্যালিডেটর ক্লায়েন্ট যোগ করতে পারেন: + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info মূল্য সীমা নির্দিষ্ট করুন +একটি Polygon Edge নোড আসন্ন লেনদেনের জন্য একটি নির্ধারিত **প্রাইস লিমিট** দিয়ে শুরু করা যাবে। + +মূল্য সীমা জন্য ইউনিট হল `wei`। + +একটি মূল্য সীমা সেট করার অর্থ হল, বর্তমান নোডের দ্বারা যেসব লেনদেন প্রক্রিয়া করা হবে তার জন্য গ্যাস মূল্য **বেশি** হবে সেট মূল্য সীমা থেকে, অন্যথায় এটি একটি ব্লকে অন্তর্ভুক্ত করা হবে না। + +নোডের সংখ্যাগরিষ্ঠতা একটি নির্দিষ্ট মূল্য সীমাকে সম্মান করলে নেটওয়ার্কে লেনদেন একটি নির্দিষ্ট মূল্যের থ্রেশহোল্ডের নিচে হতে পারে না এরকম একটি নিয়ম তৈরি হয়। + +প্রাইস লিমিটের `0`জন্য ডিফল্ট মান হল , যার অর্থ এটি ডিফল্টরূপে কখনোই প্রয়োগ করা হয় না। + + ফ্ল্যাগ `--price-limit`ব্যবহার করার উদাহরণ: +````bash +polygon-edge server --price-limit 100000 ... +```` + +এটি মনে রাখা ভালো **যে শুধুমাত্র নন-লোকাল লেনদেনগুলিতে প্রাইস লিমিট প্রয়োগ করা হয়**, যার অর্থ হল যে নোডে স্থানীয়ভাবে যোগ করা লেনদেনগুলিতে প্রাইস লিমিট প্রযোজ্য নয়। +::: + +:::info WebSocket URL +ডিফল্টভাবে, যখন আপনি Polygon Edge রান করেন, তখন এটি চেইন লোকেশন এর উপর ভিত্তি করে একটি WebSocket URL তৈরি করে। URL স্কিম HTTPS লিঙ্কের জন্য এবং HTTP `ws://`এর জন্য ব্যবহার করা `wss://`হয়। + +Localhost WebSocket URL: +````bash +ws://localhost:10002/ws +```` +অনুগ্রহ করে মনে রাখবেন যে পোর্ট নম্বর নোডের জন্য নির্বাচিত JSON-RPC পোর্টের উপর নির্ভর করে। + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## স্টেপ 5: Polygon-edge নেটওয়ার্কের সাথে ইন্টারঅ্যাক্ট করুন {#step-5-interact-with-the-polygon-edge-network} + +এখন যেহেতু আপনি কমপক্ষে 1টি চলমান ক্লায়েন্ট সেট আপ করেছেন, আপনি এখন আপনার দেওয়া প্রিমাইন্ড অ্যাকাউন্টটি ব্যবহার করে ইন্টারঅ্যাক্ট করতে পারেন এবং 4টি নোডের যেকোনো একটিতে JSON-RPC URL উল্লেখ করে আপনিঃ +- নোড 1: `http://localhost:10002` +- নোড 2: `http://localhost:20002` +- নোড 3: `http://localhost:30002` +- নোড 4: `http://localhost:40002` + +নতুন নির্মিত ক্লাস্টারে অপারেটর কমান্ড ইস্যু করতে এই গাইডটি অনুসরণ করুন: [অপারেটর তথ্য কীভাবে কুয়েরি করবেন ](/docs/edge/working-with-node/query-operator-info) (আমরা যে ক্লাস্টার তৈরি করেছি তার জন্য GRPC পোর্টগুলি হল প্রতিটি নোডের জন্য যথাক্রমে `10000`/`20000`/`30000`/`40000`) diff --git a/archive/edge/bn-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/bn-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..0ccb942c16 --- /dev/null +++ b/archive/edge/bn-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,412 @@ +--- +id: set-up-ibft-on-the-cloud +title: ক্লাউড সেটআপ +description: "ধাপে ধাপে ক্লাউড সেটআপ গাইড" +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info এই গাইড মেইননেট বা testnet সেটআপ জন্য + +নীচের গাইড আপনাকে আপনার testnet বা মেইননেট একটি উত্পাদন সেটআপ জন্য একটি ক্লাউড প্রদানকারী একটি Polygon এজ নেটওয়ার্ক সেট আপ করার জন্য কিভাবে আপনাকে নির্দেশ করবে। + +আপনি একটি উত্পাদন মত সেটআপ করার আগে দ্রুত `polygon-edge`পরীক্ষা করার জন্য স্থানীয়ভাবে একটি Polygon এজ নেটওয়ার্ক সেটআপ করতে চান, দয়া করে **[লোকাল সেটআপ](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## প্রয়োজনীয়তা {#requirements} + +Polygon [Edge](/docs/edge/get-started/installation) ইনস্টল করার জন্য ইনস্টলেশন পড়ুন। + +### VM সংযোগ স্থাপন করা {#setting-up-the-vm-connectivity} + +ক্লাউড প্রদানকারী আপনার পছন্দ উপর নির্ভর করে, আপনি একটি ফায়ারওয়াল ব্যবহার করে VMs মধ্যে সংযোগ এবং নিয়ম সেট আপ করতে পারেন, নিরাপত্তা গ্রুপ, বা অ্যাক্সেস নিয়ন্ত্রণ তালিকা + +অন্যান্য VMs উন্মুক্ত করা প্রয়োজন যে একমাত্র অংশ হিসাবে `polygon-edge`libp2p সার্ভার ডিফল্ট `1478`libp2p পোর্ট VMs মধ্যে সমস্ত যোগাযোগ যথেষ্ট + +## সংক্ষিপ্ত বিবরণ {#overview} + +![ক্লাউড সেটআপ](/img/edge/ibft-setup/cloud.svg) + +এই গাইডে আমাদের লক্ষ্য হল [IBFT এর consensus](https://github.com/ethereum/EIPs/issues/650) প্রোটোকল এর সাথে কাজ করে একটি কার্যক্ষম `polygon-edge`ব্লকচেইন নেটওয়ার্ক স্থাপন করা। ব্লকচেইন নেটওয়ার্কের মধ্যে 4টি নোড রয়েছে যার মধ্যে সবগুলোই ভ্যালিডেটর নোড, এবং তাই তারা ব্লক প্রপোজ করা এবং অন্যান্য প্রোপোজার থেকে যে ব্লক নেয়া হয়েছে তা যাচাই করা, উভয়ের ক্ষেত্রেই যোগ্য হবে। 4 নোড প্রতিটি তাদের নিজস্ব VM এ চালানো হবে, কারণ এই গাইড ধারণা আপনাকে একটি সম্পূর্ণরূপে কার্যকরী Polygon এজ নেটওয়ার্ক প্রদান করা যখন একটি বিশ্বাসযোগ্য নেটওয়ার্ক সেটআপ নিশ্চিত করার জন্য যাচাইকারী কী প্রাইভেট করা হয়। + +এটি অর্জন করার জন্য, আমরা আপনাকে 4টি সহজ স্টেপের মাধ্যমে গাইড করব: + +0. উপরে প্রয়োজনীয়তা তালিকা **দেখুন** +1. ভ্যালিডেটরের প্রতিটি জন্য প্রাইভেট কী তৈরি করুন এবং ডেটা ডিরেক্টরি +2. বুটনোড ভাগ করা ইন করা জন্য সংযোগ স্ট্রিং তৈরি করুন`genesis.json` +3. `genesis.json`আপনার স্থানীয় মেশিনে তৈরি করুন এবং এটি নোড প্রতিটি +4. সমস্ত নোড শুরু করুন + +:::info ভ্যালিডেটরের সংখ্যা + +একটি ক্লাস্টারে নোডের সংখ্যার কোন ন্যূনতম মান নেই, অর্থাৎ শুধুমাত্র 1টি ভ্যালিডেটর নোড দিয়ে ক্লাস্টার সম্ভব। মনে রাখবেন যে _একটি একক_ নোড ক্লাস্টারের কোন **ক্র্যাশ সহনশীলতা** নেই **এবং কোন BFT গ্যারান্টি** নেই। + +একটি BFT গ্যারান্টি অর্জনের জন্য নোডের ন্যূনতম প্রস্তাবিত সংখ্যা 4 - যেহেতু একটি 4 নোড ক্লাস্টারে 1টি নোডের ব্যর্থতা সহনীয়, বাকি 3টি স্বাভাবিকভাবেই কাজ করবে। + +::: + +## ধাপ 1: ডেটা ফোল্ডার শুরু করুন এবং ভ্যালিডেটর কী তৈরি করুন {#step-1-initialize-data-folders-and-generate-validator-keys} + +Polygon Edge এর সাথে আপ এবং চলমান করার জন্য, আপনাকে প্রতিটি নোডে ডেটা ফোল্ডার শুরু করতে হবে: + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +এই কমান্ডগুলোর প্রতিটি ভ্যালিডেটর কী, bls পাবলিক কী এবং [নোড আইডি প্রিন্ট](https://docs.libp2p.io/concepts/peer-id/) করবে। পরবর্তী স্টেপের জন্য আপনার প্রথম নোডের নোড আইডি প্রয়োজন হবে। + +### সিক্রেট আউটপুট করা {#outputting-secrets} +যদি প্রয়োজন হয় তবে সিক্রেট আউটপুট আবার পুনরুদ্ধার করা যাবে। + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning আপনার ডেটা ডিরেক্টরি নিজের জন্য রাখুন! + +ব্লকচেইন স্টেট ধরে রাখার জন্য ডিরেক্টরি শুরু করার পাশাপাশি উপরে তৈরি ডেটা ডিরেক্টরি তৈরি করা হবে, এছাড়াও আপনার ভ্যালিডেটরের প্রাইভেট কী তৈরি করবে। **এই কীটি একটি গোপন হিসাবে রাখা উচিত, কারণ এটি চুরি করা এটি আপনাকে নেটওয়ার্কে ভ্যালিডেটর হিসাবে অনুকরণ করতে সক্ষম কাউকে রেন্ডার করবে!** +::: + +## স্টেপ 2: বুটনোডের জন্য multiaddr কানেকশন স্ট্রিং প্রস্তুত করুন {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +একটি নোডের সফলভাবে সংযোগ স্থাপন করার জন্য, তাকে অবশ্যই জানতে হবে যে কোন `bootnode`সার্ভারের সাথে সংযোগ করতে হবে নেটওয়ার্কের অবশিষ্ট সকল নোডের তথ্য পেতে। `bootnode`কে কখনও কখনও p2p জার্গনে `rendezvous`সার্ভারও বলা হয়। + +`bootnode`একটি Polygon Edge নোডের একটি বিশেষ উদাহরণ নয়। প্রতিটি Polygon এজ নোড একটি এবং `bootnode`হিসাবে পরিবেশন করতে পারে প্রতিটি Polygon Edge নোডের বুটনোডের একটি সেট নির্দিষ্ট করতে হবে যা কীভাবে সাথে সংযোগ করতে হবে সে সম্পর্কে তথ্য প্রদান করতে হবে নেটওয়ার্কের অবশিষ্ট সকল নোডের সাথে। + +বুটনোড নির্দিষ্ট করে সংযোগ স্ট্রিং তৈরি করার জন্য, আমাদের মানিয়ে চলতে হবে [multiaddr ফর্ম্যাট এর সাথে](https://docs.libp2p.io/concepts/addressing/)ঃ +``` +/ip4//tcp//p2p/ +``` + +এই গাইডে আমরা প্রথম এবং দ্বিতীয় নোডকে অন্য সকল নোডের জন্য বুটনোড হিসেবে ব্যবহার করব। এই পরিস্থিতিতে যা ঘটবে তা হল বা এর সাথে যে নোডগুল সংযোগ করে তারা একে অপরের সাথে পারস্পরিকভাবে সংযোজিত বুটনোড দি`node 2`য়ে `node 1`কীভাবে সংযোগ করবে তার তথ্য পাবে। + +:::info একটি নোড শুরু করতে আপনাকে অন্তত একটি বুটনোড নির্দিষ্ট করতে হবে + +অন্তত একটি বুটনোড প্রয়োজনীয়, যাতে নেটওয়ার্কের অন্যান্য নো**ডগ**ুলো একে অপরকে আবিষ্কার করতে পারে। অতিরিক্ত বুটনোডের পরামর্শ দেওয়া হয়, কারণ বিদ্যুৎ চলে যাওয়ার ক্ষেত্রে তারা নেটওয়ার্ককে সহনশীলতা প্রদান করে। এই গাইডে আমরা দুটি নোডের তালিকা দিব, কিন্তু এটি যেকোনো সময়ে পরিবর্তন করা যাবে, এবং এতে ফাইলের বৈধতার উপর কোন প্রভাব পড়ে `genesis.json`না। +::: + +multiaddr সংযোগ ``স্ট্রিংয়ের প্রথম অংশ হিসাবে এটি , এখানে আপনাকে আপনার সেটআপের উপর নির্ভর করে অন্যান্য নোডের দ্বারা রিচেবল হিসাবে আইপি ঠিকানা প্রবেশ করতে হবে, এটি একটি প্রাইভেট বা একটি পাবলিক আইপি ঠিকানা হতে পারে, না`127.0.0.1`। + +``আমরা ব্যবহার `1478`করব, কারণ এটি ডিফল্ট libp2p পোর্ট + +এবং অবশেষে, আমাদের প্রয়োজন ``যা আমরা পূর্বে রান করা কমান্ডের আউটপুট থেকে পাবো `polygon-edge secrets init --data-dir data-dir`(যা এর জন্য কী জেনারেট করতে এবং ডাটা ডিরেক্টরি তৈরি করতে ব্যবহৃত হয়েছি`node 1`লও) + +অ্যাসেম্বলির পর, এর সাথে multiaddr কানেকশন স্ট্রিং `node 1`যা আমরা বুটনোড হিসেবে ব্যবহার করব, তা দেখতে কিছুটা এরকম হবে (শুধুমাত্র ``যেটি শেষে আছে, সেটি দেখতে কিছুটা আলাদা হবে): +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +একইভাবে, আমরা দ্বিতীয় বুটনোডের জন্য multiaddr তৈরি করি +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info ips এর পরিবর্তে DNS হোস্টনেম + +Polygon Edge নোড কনফিগারেশনের জন্য DNS হোস্টনেমের ব্যবহার সাপোর্ট করে। এটি ক্লাউড ভিত্তিক ডিপ্লয়মেন্টের জন্য অনেক সহায়ক বৈশিষ্ট্য, কারণ নোডের আইপি বিভিন্ন কারনে পরিবর্তিত হতে পারে। + +DNS হোস্টনেম ব্যবহার করার সময় কানেকশন স্ট্রিংয়ের জন্য multiaddr ফর্ম্যাটটি নিম্নলিখিতঃ`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## স্টেপ 3: 4টি নোডকে ভ্যালিডেটর হিসানে নিয়ে জেনেসিস ফাইল তৈরি করুন {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +এই পদক্ষেপটি আপনার স্থানীয় মেশিনে চালানো যেতে পারে, কিন্তু আপনাকে 4 ভ্যালিডেটরের প্রতিটি জন্য পাবলিক ভ্যালিডেটর কী দরকার। + +ভ্যালিডেটর তাদের `secrets init`কমান্ডে আউটপুট নীচের প্রদর্শিত হিসাবে নিরাপদে ভাগ `Public key (address)`করতে পারে, যাতে আপনি তাদের পাবলিক কী দ্বারা চিহ্নিত প্রাথমিক ভ্যালিডেটর in সেই ভ্যালিডেটরের সাথে genesis.json নিরাপদে তৈরি করতে পারেন: + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +আপনি ভ্যালিডেটরের পাবলিক কী সব 4 পেয়েছি তা দেওয়া, আপনি জেনারেট করতে নিম্নলিখিত কমান্ডটি চালাতে পারেন`genesis.json` + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +এই কমান্ডটি যা করে: + +* ভ্যালিডেটরের পাবলিক কী সেট করে `--ibft-validator`যা জেনেসিস ব্লকে প্রাথমিক ভ্যালিডেটরের মধ্যে অন্তর্ভুক্ত করা উচিত। অনেক প্রাথমিক ভ্যালিডেটর হতে পারে। +* বুটনোডের অ্যাড্রেস সেট করে `--bootnode`যা নোডগুলোকে একে অপরকে খুঁজে পেতে সাহায্য করবে। আমরা স্টেপ **2**-এ উল্লিখিত হিসাবে multiaddr স্ট্রিং`node 1`টি ব্যবহার করব, যদিও আপনি উপরে প্রদর্শিত হিসাবে আপনি চান হিসাবে অনেক বুটনোড যোগ করতে পারেন। + +:::info ECDSA তে সুইচ করুন + +BLS ব্লক হেডারদের জন্য ডিফল্ট ভ্যালিডেশন মোড। আপনি যদি আপনার চেইনটিকে ECDSA মোডে রান করাতে চান তবে আপনি ফ্ল্যাগটি ব্যবহার করতে পারে`—ibft-validator-type`ন, এই আর্গুমেন্ট `ecdsa`সহ: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info অ্যাকাউন্টের প্রিমাইনিং ব্যালেন্স + +আপনি হয়তোবা কিছু "প্রিমাইন্ড" ব্যালেন্স সহ অ্যাড্রেস আপনার ব্লকচেইন নেটওয়ার্কে সেট আপ করতে চাইবেন। + +এটি অর্জন করতে, আপনি একটি নির্দিষ্ট ব্যালেন্সের সাথে শুরু করতে চান এমন সবগুলো অ্যাড্রেসকে যতবার ইচ্ছা ফ্ল্যা`--premine`গে পাস করুন ব্লকচেইনে। + +উদাহরণস্বরূপ, আমরা যদি আমাদের জেনেসিস ব্লকের অ্যাড্রেসে 1000 ETH `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862`প্রিমাইন করতে চাই, তবে আমাদের নিম্নলিখিত আর্গুমেন্ট সরবরাহ করতে হবে: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**মনে রাখবেন, প্রিমাইন করা পরিমাণ ETH এ নয়, WEI তে থাকবে।** + +::: + +:::info ব্লক গ্যাস সীমা সেট করুন + +প্রতিটি ব্লকের জন্য ডিফল্ট গ্যাস সীমা হলো`5242880`। এই মানটি জেনেসিস ফাইলে লেখা হয়, কিন্তু আপনি চাইতে পারেন এটি বৃদ্ধি / হ্রাস করতে। + +সেটি করতে, আপনি নীচের হিসাবে পছন্দসই মানের ফ্ল্যা`--block-gas-limit`গ ব্যবহার করতে পারেন: + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info সিস্টেম ফাইল ডেস্ক্রিপ্টর সীমা সেট করুন + +ডিফল্ট ফাইল ডেস্ক্রিপ্টর সীমা (সর্বাধিক সংখ্যক ওপেন ফাইল) কিছু অপারেটিং সিস্টেমে বেশ ছোট। নোডগুলোর থেকে যদি উচ্চ থ্রুপুটের আশা করা হয়, তবে আপনি অপারেটিং সিস্টেমে এই সীমা বৃদ্ধি করার কথা বিবেচনা করতে পারেন। + +উবুন্টু ডিস্ট্রোর জন্য পদ্ধতিটি নিম্নরূপ (আপনি যদি উবুন্টু / ডেবিয়ান ডিস্ট্র ব্যবহার না করেন, তবে আপনার OS এর জন্য অফিসিয়াল নিয়মাবলী দেখুন): +- বর্তমান OS সীমা চেক করুন (ওপেন ফাইল) +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- ওপেন ফাইল সীমা বৃদ্ধি করুন + - Localy - শুধুমাত্র বর্তমান সেশনকে প্রভাবিত করে: + ```shell + ulimit -u 65535 + ``` + - Globaly বা প্রতি ব্যবহারকারীর জন্য (/etc/security/limits.conf এর শেষে সীমা যোগ করুন): + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +ঐচ্ছিকভাবে, অতিরিক্ত প্যারামিটার মডিফাই করুন, ফাইলটি সংরক্ষণ করুন এবং সিস্টেমটি পুনরায় চালু করুন। পুনরায় চালু করার পরে ফাইল ডেস্ক্রিপ্টর সীমা আবার চেক করুন। আপনি limits.conf ফাইলে যে মান নির্ধারণ করেছিলেন, তাই হওয়া উচিৎ। +::: + +এটি নির্দিষ্ট করার পরে: +1. ভ্যালিডেটর সেট হিসাবে জেনেসিস ব্লকে ভ্যালিডেটরের পাবলিক কী অন্তর্ভুক্ত করা হবে +2. বুটনোড multiaddr সংযোগ strings +3. জেনেসিস ব্লকে প্রিমিয়াম অ্যাকাউন্ট এবং ব্যালেন্স অন্তর্ভুক্ত করা হবে + +এবং এটি তৈরি করা`genesis.json`, আপনাকে নেটওয়ার্কে সমস্ত VMs এ এটি কপি করতে হবে। আপনার সেটআপের উপর নির্ভর করে আপনি হতে পারেন এটি কপি / পেস্ট করুন, এটি নোড অপারেটরের কাছে প্রেরণ করুন, বা এটি কেবল SCP/FTP / SCP/FTP ওভার। + +জেনেসিস ফাইলের গঠন নিয়ে [CLI Commands](/docs/edge/get-started/cli-commands) সেকশনে ব্যাখ্যা করা হয়েছে। + +## স্টেপ 4: সকল ক্লায়েন্ট রান করুন {#step-4-run-all-the-clients} + +:::note ক্লাউড প্রদানকারীর নেটওয়ার্কিং + +বেশিরভাগ ক্লাউড প্রোভাইডার আপনার VM এ একটি সরাসরি নেটওয়ার্ক ইন্টারফেস হিসাবে আইপি ঠিকানা (বিশেষত পাবলিক বেশী) প্রকাশ করে না, বরং একটি অদৃশ্য don't প্রক্সি সেটআপ করুন। + + +এই ক্ষেত্রে নোডগুলিকে একে অপরকে সংযোগ করতে অনুমতি দেওয়ার জন্য আপনাকে সমস্ত ইন্টারফেসে বাঁধতে `0.0.0.0`IP ঠিকানা শোনার জন্য প্রয়োজন হবে, কিন্তু আপনাকে এখনও আইপি ঠিকানা বা DNS ঠিকানা নির্দিষ্ট করতে হবে যা অন্যান্য নোডগুলি আপনার ইনস্ট্যান্সের সাথে সংযোগ করতে ব্যবহার করতে পারে। এটি যথাক্রমে আপনার বহিরাগত আইপি বা DNS ঠিকানা নির্দিষ্ট করতে পারেন যেখানে `--nat`বা আর্`--dns`গুমেন্ট ব্যবহার করে হয় অর্জন করা হয়। + +#### উদাহরণ {#example} + +আপনি যা শুনতে `192.0.2.1`চান তা সংশ্লিষ্ট আইপি ঠিকানা হল , কিন্তু এটি আপনার কোনও নেটওয়ার্ক ইন্টারফেসের সাথে সরাসরি আবদ্ধ নয়। + +আপনি নিম্নলিখিত প্যারামিটারগুলি পাস করতে নোডগুলি সংযোগ করতে অনুমতি দিতে: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +Or, আপনি যদি একটি DNS `dns/example.io`ঠিকানা নির্দিষ্ট করতে চান তবে নিম্নলিখিত প্যারামিটার পাস করুন: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +এটি আপনার নোড সমস্ত ইন্টারফেসে শুনতে পাবে, কিন্তু এটি নিশ্চিত করা যে ক্লায়েন্ট নির্দিষ্ট বা `--dns`ঠিকানা মাধ্যমে এটি সংযোগ `--nat`করছে। + +::: + +চতুর্থ ক্লায়েন্ট রান **করতে**: + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +দ্বিতীয় ক্লায়েন্ট রান **করতে**: + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +তৃতীয় ক্লায়েন্ট রান **করতে**: + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +চতুর্থ ক্লায়েন্ট রান **করতে**: + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +পূর্ববর্তী কমান্ডগুলো রান করার পরে, আপনি একটি 4 নোডের Polygon Edge নেটওয়ার্ক সেট আপ করেছেন, যা ব্লক সিল করতে এবং ফিরে আসতে সক্ষম নোড ফেইলিওর থেকে। + +:::info কনফিগ ফাইল ব্যবহার করে ক্লায়েন্ট শুরু করুন + +সমস্ত কনফিগারেশন প্যারামিটার CLI আর্গুমেন্ট হিসাবে নির্দিষ্ট করার পরিবর্তে, ক্লায়েন্টটি নিম্নলিখিত কমান্ড সম্পাদন করে একটি কনফিগ ফাইল ব্যবহার করে শুরু করা যাবে: + +````bash +polygon-edge server --config +```` +উদাহরণ: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +বর্তমানে, আমরা শুধুমাত্র `json`ভিত্তিক কনফিগারেশন ফাইল সমর্থন করি, নমুনা কনফি**[গ](/docs/edge/configuration/sample-config)** ফাইল এখানে পাওয়া যাবে + +::: + +:::info একটি নন-ভ্যালিডেটর নোড রান করার স্টেপসমূহ + +একটি নন-ভ্যালিডেটর সর্বদা ভ্যালিডেটর নোডের থেকে পাওয়া সর্বশেষ ব্লক সিঙ্ক করবে, আপনি নিম্নলিখিত কমান্ডটি রান করে একটি নন-ভ্যালিডেটর নোড শুরু করতে পারেন। + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +উদাহরণস্বরূপ, আপনি নিম্নলিখিত কমান্ডটি সম্পাদন করে পঞ্**চম নন**-ভ্যালিডেটর ক্লায়েন্ট যোগ করতে পারেন: + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info মূল্য সীমা নির্দিষ্ট করুন +একটি Polygon Edge নোড আসন্ন লেনদেনের জন্য একটি নির্ধারিত **প্রাইস লিমিট** দিয়ে শুরু করা যাবে। + +মূল্য সীমা জন্য ইউনিট হল `wei`। + +একটি মূল্য সীমা সেট করার অর্থ হল, বর্তমান নোডের দ্বারা যেসব লেনদেন প্রক্রিয়া করা হবে তার জন্য গ্যাস মূল্য **বেশি হবে** সেট মূল্য সীমা থেকে, অন্যথায় এটি একটি ব্লকে অন্তর্ভুক্ত করা হবে না। + +নোডের সংখ্যাগরিষ্ঠতা একটি নির্দিষ্ট মূল্য সীমাকে সম্মান করলে নেটওয়ার্কে লেনদেন একটি নির্দিষ্ট মূল্যের থ্রেশহোল্ডের নিচে হতে পারে না এরকম একটি নিয়ম তৈরি হয়। + +প্রাইস লিমিটের `0`জন্য ডিফল্ট মান হল , যার অর্থ এটি ডিফল্টরূপে কখনোই প্রয়োগ করা হয় না। + + ফ্ল্যাগ `--price-limit`ব্যবহার করার উদাহরণ: +````bash +polygon-edge server --price-limit 100000 ... +```` + +এটি মনে রাখা ভালো **যে শুধুমাত্র নন-লোকাল লেনদেনগুলিতে প্রাইস লিমিট প্রয়োগ করা হয়**, যার অর্থ হল যে নোডে স্থানীয়ভাবে যোগ করা লেনদেনগুলিতে প্রাইস লিমিট প্রযোজ্য নয়। +::: + +:::info WebSocket URL +ডিফল্টভাবে, যখন আপনি Polygon Edge রান করেন, তখন এটি চেইন লোকেশন এর উপর ভিত্তি করে একটি WebSocket URL তৈরি করে। URL স্কিম HTTPS লিঙ্কের জন্য এবং HTTP `ws://`এর জন্য ব্যবহার করা `wss://`হয়। + +Localhost WebSocket URL: +````bash +ws://localhost:10002/ws +```` +অনুগ্রহ করে মনে রাখবেন যে পোর্ট নম্বর নোডের জন্য নির্বাচিত JSON-RPC পোর্টের উপর নির্ভর করে। + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/bn-edge/get-started/terraform-aws-deployment.md b/archive/edge/bn-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..ae432d0a8f --- /dev/null +++ b/archive/edge/bn-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,150 @@ +--- +id: terraform-aws-deployment +title: Terraform AWS স্থাপনা +description: "Terraform ব্যবহার করে AWS ক্লাউড প্রদানকারীর Polygon Edge নেটওয়ার্ক" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info উৎপাদন স্থাপনা গাইড +এটি অফিস, উত্পাদন প্রস্তুত, সম্পূর্ণরূপে অটোমেটেড, AWS স্থাপনা গাইড। + +***[ক্লাউড](set-up-ibft-locally)*** ***[বা স্থানীয়](set-up-ibft-on-the-cloud)*** আপনার ক্লাউড প্রদানকারী AWS না থাকলে পরীক্ষার জন্য সুপারিশ করা হয়। +::: + +:::info + এই স্থাপনা শুধুমাত্র PoA যদি PoS প্রক্রিয়া প্রয়োজন হয়, তাহলে এখন এই ***[গাইড](/docs/edge/consensus/migration-to-pos)*** PoA থেকে PoS একটি সুইচ করতে +::: + +এই গাইড বিস্তারিত, AWS ক্লাউড প্রদানকারীর একটি Polygon Edge blockchain নেটওয়ার্ক স্থাপনা প্রক্রিয়া বর্ণনা যে উত্পাদন প্রস্তুত হিসাবে যাচাইকারী নোড একাধিক প্রাপ্যতা জোন জুড়ে spanned করা হয়। + +## পূর্বশর্ত {#prerequisites} + +### সিস্টেম সরঞ্জাম {#system-tools} +* [terraform](https://www.terraform.io/) +* [aws cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [aws অ্যাক্সেস কী আইডি এবং গোপন অ্যাক্সেস কী](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Terraform ভেরিয়েবল {#terraform-variables} +deployment: চালানোর আগে দুটি ভেরিয়েবল প্রদান করা আবশ্যক: + +* `alb_ssl_certificate`- AWS সার্টিফিকেট ম্যানেজার থেকে সার্টিফিকেট ARN HTTPS প্রোটোকল জন্য ALB দ্বারা ব্যবহার করা হবে । সার্টিফিকেট স্থাপনা শুরু করার আগে তৈরি করা আবশ্যক, এবং এটি **জারি** অবস্থা +* `premine`- অ্যাকাউন্ট যে প্রাক mined নেটিভ মুদ্রা মান অফিসিয়াল [CLI](/docs/edge/get-started/cli-commands#genesis-flags) পতাকা স্পেসিফিকেশন + +## স্থাপনা তথ্য {#deployment-information} +### ডিপ্লয়েড সম্পদ {#deployed-resources} +সম্পদ যে স্থাপনা করা হবে: + +* উত্সর্গীকৃত VPC +* 4 যাচাইকারী নোড (যা বুট নোড +* 4 NAT গেটওয়ে নোড outbound ইন্টারনেট ট্রাফিক +* Lambda ফাংশন প্রথম (জেনেসিস) ব্লক তৈরি এবং চেইন +* উত্সর্গীকৃত নিরাপত্তা গ্রুপ এবং IAM ভূমিকা +* S3 বালতি genesis.json ফাইল +* অ্যাপ্লিকেশন লোড Balancer JSON-RPC এন্ডপয়েন্ট এক্সপোজ জন্য + +### ফল্ট সহনশীলতা {#fault-tolerance} + +শুধুমাত্র অঞ্চলে যে 4 প্রাপ্যতা অঞ্চল আছে এই স্থাপনা প্রতিটি নোড একটি এককে স্থাপন করা হয়। + +একটি এককে প্রতিটি নোড স্থাপন করে, পুরো ব্লকচেইন ক্লাস্টার একটি একক নোড (AZ) ব্যর্থতা জন্য fault-tolerant ঐক্যমত্য যা একটি একক নোড একটি 4 যাচাইকারী নোড ক্লাস্টার ব্যর্থ করতে + +### কমান্ড লাইন অ্যাক্সেস {#command-line-access} + +ভ্যালিডেটর নোড পাবলিক ইন্টারনেট যে কোন ভাবেই উন্মুক্ত করা হয় না এবং তারা তাদের সাথে সংযুক্ত পাবলিক আইপি ঠিকানা নেই। নোড কমান্ড লাইন অ্যাক্সেস শুধুমাত্র [AWS সিস্টেম ম্যানেজার মাধ্যমে সম্ভব](https://aws.amazon.com/systems-manager/features/) + +### বেস AMI আপগ্রেড {#base-ami-upgrade} + +এই স্থাপনা `ubuntu-focal-20.04-amd64-server`AWS AMI AWS AMI আপডেট করা হলে এটি EC2 **not** ট্রিগার *করবে* + +যদি, কিছু কারণে, বেস AMI আপডেট পেতে প্রয়োজন এটি প্রতিটি উদাহরণ `terraform apply` জন্য `terraform taint`কমান্ড চলমান দ্বারা অর্জন করা যেতে ইন্সট্যান্স চলমান দ্বারা টেইন্টেড`terraform taint module.instances[].aws_instance.polygon_edge_instance` কমান্ড। + +উদাহরণ: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info +একটি উত্পাদন পরিবেশে `terraform taint`ব্লকচেইন নেটওয়ার্ক কার্যকরী +::: + +## স্থাপনা পদ্ধতি {#deployment-procedure} + +### প্রাক স্থাপনা পদক্ষেপ {#pre-deployment-steps} +* [Polygon-technology](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)-edge terraform রেজিস্ট্রি readme +* মডিউল modules' পৃষ্ঠায় বিধান নির্দেশাবলী *ব্যবহার* `polygon-technology-edge``main.tf`করে +* `terraform init`সমস্ত প্রয়োজনীয় Terraform নির্ভরতা +* AWS সার্টিফিকেট [ম্যানেজার](https://aws.amazon.com/certificate-manager/) +* নিশ্চিত করুন যে **প্রদত্ত** সার্টিফিকেট **জারি** অবস্থায় +* cli মডিউল 'আউটপুট পেতে + +#### `main.tf`উদাহরণ {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### `terraform.tfvars`উদাহরণ {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### স্থাপনা পদক্ষেপ {#deployment-steps} +* `terraform.tfvars`ফাইল +* এই ফাইলের প্রয়োজনীয় terraform ভেরিয়েবল সেট করুন:::info +অন্যান্য অ বাধ্যতামূলক ভেরিয়েবল যে সম্পূর্ণরূপে এই স্থাপনা কাস্টমাইজ করতে আপনি আপনার নিজের ফাইল `terraform.tfvars`যোগ করে ডিফল্ট মান + +সমস্ত উপলব্ধ ভেরিয়েবল স্পেসিফিকেশন মডিউল 'Terraform ***[রেজিস্ট্রি](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)*** +::: +* নিশ্চিত করুন যে আপনি একটি aws `aws s3 ls`cli +* পরিকাঠামো`terraform apply` + +### পোস্ট স্থাপনা পদক্ষেপ {#post-deployment-steps} +* একবার স্থাপনা সমাপ্ত হয়, cli `json_rpc_dns_name`মুদ্রিত +* একটি পাবলিক dns cname রেকর্ড উপলব্ধ `json_rpc_dns_name`মান আপনার ডোমেন নাম উদাহরণস্বরূপ: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* একবার cname রেকর্ড প্রচার করে, চেক করুন যে চেইন আপনার JSON-PRC এন্ডপয়েন্ট কল করে সঠিকভাবে কাজ করছে । উপরে উদাহরণ + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## ধ্বংস পদ্ধতি {#destroy-procedure} +:::warning +নিম্নলিখিত পদ্ধতি স্থায়ীভাবে এই terraform স্ক্রিপ্ট সঙ্গে আপনার সম্পূর্ণ পরিকাঠামো স্থাপনা মুছে ফেলবে। নিশ্চিত [করুন যে আপনার সঠিক ব্লকচেইন ডেটা ব্যাকআপ](docs/edge/working-with-node/backup-restore) এবং / বা আপনি একটি টেস্টিং পরিবেশ সঙ্গে কাজ করছেন। +::: + +আপনি যদি পুরো পরিকাঠামো অপসারণ করতে হবে`terraform destroy` , নিম্নলিখিত কমান্ড উপরন্তু, আপনি নিজে AWS [পরামিতি দোকান সংরক্ষণ](https://aws.amazon.com/systems-manager/features/) গোপন অপসারণ অঞ্চলের জন্য স্থাপনা স্থান diff --git a/archive/edge/bn-edge/overview.md b/archive/edge/bn-edge/overview.md new file mode 100644 index 0000000000..2884256301 --- /dev/null +++ b/archive/edge/bn-edge/overview.md @@ -0,0 +1,35 @@ +--- +id: overview +title: Polygon Edge +sidebar_label: What is Edge +description: "Polygon Edge-এর পরিচিতি।" +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +Polygon Edge Ethereum-সামঞ্জস্যপূর্ণ ব্লকচেইন নেটওয়ার্ক, সাইডচেইন এবং সাধারণ স্কেলিং সমাধান তৈরির জন্য একটি মডুলার এবং এক্সটেনসিবল ফ্রেমওয়ার্ক। + +এর প্রাথমিক ব্যবহার হল, Ethereum স্মার্ট কন্ট্র্যাক্ট এবং লেনদেনের সাথে সম্পূর্ণ সামঞ্জস্য প্রদান করে একটি নতুন ব্লকচেইন নেটওয়ার্ক বুটস্ট্র্যাপ করা। এটি IBFT (ইস্তাম্বুল বাইজেন্টাইন ফল্ট Tolerant) Consensus প্রক্রিয়া ব্যবহার করে, যা [PoA (প্রুফ অব অথরিটি)](/docs/edge/consensus/poa) এবং [PoS (প্রুফ অব স্টেক)](/docs/edge/consensus/pos-stake-unstake) হিসাবে দুই প্রকারে সাপোর্টেড। + +Polygon Edge অন্য একাধিক ব্লকচেইনের সাথে যোগাযোগ এনাবল করে, [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) এবং [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) টোকেন ট্রান্সফার এনাবেল করে, একটি [সেন্ট্রালাইজড ব্রিজ সলিউশিন](/docs/edge/additional-features/chainbridge/overview) ব্যবহার করে। + +ইন্ডাস্ট্রি স্ট্যান্ডার্ড ওয়ালেটগুলো [JSON-RPC](/docs/edge/working-with-node/query-json-rpc) এন্ডপয়েন্টগুলির মাধ্যমে Polygon Edge-এর সাথে যোগাযোগ করতে ব্যবহার করা যেতে পারে এবং নোড অপারেটররা [gRPC](/docs/edge/working-with-node/query-operator-info) প্রোটোকলের মাধ্যমে নোডগুলোতে বিভিন্ন ক্রিয়া সম্পাদন করতে পারে। + +Polygon সম্পর্কে আরো জানতে [অফিসিয়াল ওয়েবসাইট](https://polygon.technology) ভিজিট করুন। + +**[GitHub রিপোজিটরি](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +এর উপরে এখনও কাজ চলছে তাই ভবিষ্যতে আর্কিটেকচারাল পরিবর্তন ঘটতে পারে। কোড এখনও অডিট করা হয়নি তাই আপনি এটা প্রোডাকশনে ব্যবহার করতে চাইলে Polygon টিমের সাথে যোগাযোগ করুন। + +::: + + + +একটি `polygon-edge`লোকাল নেটওয়ার্ক চালানো শুরু করতে, অনুগ্রহ করে পড়ুনঃ [ইন্সটলেশন](/docs/edge/get-started/installation) এবং [লোকাল সেটআপ](/docs/edge/get-started/set-up-ibft-locally)। diff --git a/archive/edge/bn-edge/performance-reports/overview.md b/archive/edge/bn-edge/performance-reports/overview.md new file mode 100644 index 0000000000..3ac4260a94 --- /dev/null +++ b/archive/edge/bn-edge/performance-reports/overview.md @@ -0,0 +1,29 @@ +--- +id: overview +title: সংক্ষিপ্ত বিবরণ +description: "Polygon Edge পরীক্ষার ভূমিকা।" +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +দয়া করে মনে রাখবেন যে আমাদের এই পরীক্ষার জন্য ব্যবহার করা `loadbot`হ, া এখন অবচিত হয়েছে। +::: + +| প্রকার | মান | পরীক্ষার লিঙ্ক | +| ---- | ----- | ------------ | +| নিয়মিত স্থানান্তর | 1428 tps | [জুলাই 4th 2022](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| ERC-20 স্থানান্তর | 1111 tps | [জুলাই 4th 2022](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| NFT Minting | 714 tps | [জুলাই 4th 2022](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +আমাদের লক্ষ্য একটি উচ্চ performant, বৈশিষ্ট্য সমৃদ্ধ এবং সেটআপ সহজ এবং ব্লকচেইন ক্লায়েন্ট সফ্টওয়্যার বজায় রাখা। সমস্ত পরীক্ষা Polygon Edge Loadbot ব্যবহার করে সম্পন্ন করা হয়। এই বিভাগে আপনি পাবেন প্রতিটি কর্মক্ষমতা রিপোর্ট সঠিকভাবে dated, পরিবেশ পরিষ্কারভাবে বর্ণনা এবং টেস্টিং পদ্ধতি পরিষ্কারভাবে ব্যাখ্যা। + +এই কর্মক্ষমতা পরীক্ষা লক্ষ্য Polygon Edge ব্লকচেইন নেটওয়ার্ক একটি বাস্তব বিশ্ব কর্মক্ষমতা প্রদর্শন করা। যে কেউ এখানে পোস্ট হিসাবে একই ফলাফল পেতে সক্ষম হতে হবে, একই পরিবেশ, আমাদের loadbot ব্যবহার করে। + +EC2 উদাহরণ নোড গঠিত একটি চেইন AWS প্ল্যাটফর্ম সমস্ত কর্মক্ষমতা পরীক্ষা পরিচালিত হয়। \ No newline at end of file diff --git a/archive/edge/bn-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/bn-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..92c67ab5be --- /dev/null +++ b/archive/edge/bn-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,130 @@ +--- +id: test-2022-01-21 +title: 21 জানুয়ারী 2022 +description: "জানুয়ারী 21 থেকে পারফরমেন্স টেস্ট" +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## 21 জানুয়ারী 2022 {#january-21st-2022} + +### সারাংশ {#summary} + +:::caution +দয়া করে মনে রাখবেন যে আমাদের এই পরীক্ষার জন্য ব্যবহার করা `loadbot`হ, া এখন অবচিত হয়েছে। +::: + +এই পরীক্ষাটি TxPool রিফ্যাক্টরের পরে করা হয়েছিল যা উল্লেখযোগ্যভাবে পার্ফরমেন্স উন্নত করেছে ([v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0) তে মুক্তি পায়)। + +যেহেতু সকল লেনদেন একটি একক নোড JSON-RPC-তে পাঠানো হয়েছিল, তাই লক্ষ্য ছিল 30 জন সক্রিয় অংশগ্রহণকারী ভ্যালিডেটরের, যাতে Consensus এবং TxPool কে ভালোভাবে স্ট্রেস টেস্ট করা যায়। + +আমাদের লক্ষ্য ছিল সর্বাধিক সম্ভাব্য TPS এ না পৌঁছানোর, কারণ নেটওয়ার্ক সাইজ পারফরম্যান্সের উপর নেতিবাচক প্রভাব ফেলে, ও যেহেতু ব্লক গ্যাস লিমিট এবং ব্লক টাইম সেন ভ্যালুগুলোতে সেট করা হয়েছে যা বেশি সিস্টেম রিসোর্স ব্যবহার করে না, এবং যা কমোডিটি হার্ডওয়্যারে চালানোর যাবে। + +### ফলাফল {#results} + +| মেট্রিক | মান | +| ------ | ----- | +| প্রতি সেকেন্ডে লেনদেন | 344 | +| লেনদেন ব্যর্থ | 0 | +| লেনদেন সফল হয়েছে | 10000 | +| মোট রান টাইম | 30s | + +### এনভায়রনমেন্ট {#environment} + +
+ হোস্ট কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ক্লাউড প্রোভাইডারAWS
ইন্সট্যান্স সাইজt2.xlarge
নেটওয়ার্কিংপ্রাইভেট সাবনেট
অপারেটিং সিস্টেমলিনাক্স উবুন্টু 20.04 LTS - Focal Fossa
ফাইল ডেস্ক্রিপ্টর লিমিট65535
ব্যবহারকারী সর্বোচ্চ প্রসেস করতে পারেন65535
+
+
+
+
+ +
+ ব্লকচেইন কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge সংস্করণডেভেলপ ব্রাঞ্চে 8377162281d1a2e4342ae27cd4e5367c4364aee2 কমিট করুন
ভ্যালিডেটর নোড30
নন-ভ্যালিডেটর নোড0
কনসেনসাসIBFT PoA
ব্লক টাইম2000ms
ব্লক গ্যাস সীমা5242880
+
+
+
+
+ +
+ Loadbot কনফিগারেশন +
+
+ + + + + + + + + + + + + +
মোট লেনদেন10000
প্রতি সেকেন্ডে পাঠানো লেনদেন400
লেনদেনের প্রকারEOA থেকে EOA ট্রান্সফার
+
+
+
+
diff --git a/archive/edge/bn-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/bn-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..57356a31dc --- /dev/null +++ b/archive/edge/bn-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,389 @@ +--- +id: test-2022-03-02 +title: 2 মার্চ 2022 +description: "2 মার্চের পারফরমেন্স টেস্ট।" +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### সারাংশ {#summary} + +:::caution +দয়া করে মনে রাখবেন যে আমাদের এই পরীক্ষার জন্য ব্যবহার করা `loadbot`হ, া এখন অবচিত হয়েছে। +::: + +SC ERC20 টোকেন ট্রান্সফার এবং হেভি লোডের সাথে SC ERC721 টোকেন মিন্টিং এর কার্যকারিতা ও লেনদেনের গতি পরিমাপ করতে এই পরীক্ষাটি করা হয়েছিল। + +হেভি লোডের সময় সবকিছু আশানুরূপ কাজ করছে কিনা তা পরীক্ষা করাটাই ছিল এর উদ্দেশ্য। লোডবট আউটপুটে গ্যাসের মেট্রিক্স চালু করার কারণও এটিই ছিল, যা আমাদেরকে দেখাচ্ছে যে ব্লকগুলোতে সঠিকভাবে লেনদেন চলছে কিনা। + +সমস্ত লেনদেন GRPC API এর মাধ্যমে একক নোডে পাঠানো হয়েছিল, এবং JSON-RPC API এর মাধ্যমে রিসিপ্ট গ্রহণ করা হয়েছিল। সকল লেনদেন সম্পন্ন হওয়ার পরে, প্রতিটি ব্লক থেকে গ্যাস তথ্য পড়তে eth_getBlockByNumber JSON-RPC পদ্ধতি ব্যবহার করা হয়েছিল। + +আমাদের লক্ষ্য সর্বাধিক সম্ভাব্য TPS এ পৌঁছানোর ছিল না, যেহেতু ব্লক গ্যাস লিমিট এবং ব্লক টাইম সেন ভ্যালুগুলোতে সেট করা হয়েছে যা বেশি সিস্টেম রিসোর্স ব্যবহার করে না, এবং যা কমোডিটি হার্ডওয়্যারে চালানোর যাবে। + +### ERC20 ফলাফল {#results-erc20} + +| মেট্রিক | মান | +| ------ | ----- | +| লেনদেনের প্রকার | ERC20 | +| প্রতি সেকেন্ডে লেনদেন | 65 | +| লেনদেন ব্যর্থ | 0 | +| লেনদেন সফল হয়েছে | 5000 | +| ERC20 লেনদেনের রান টাইম | 76.681690s | +| SC ডিপ্লয় টাইম | 4.048250s | + +### ERC721 ফলাফল {#results-erc721} + +| মেট্রিক | মান | +| ------ | ----- | +| লেনদেনের প্রকার | ERC721 | +| প্রতি সেকেন্ডে লেনদেন | 20 | +| লেনদেন ব্যর্থ | 0 | +| লেনদেন সফল হয়েছে | 2000 | +| ERC721 লেনদেনের রান টাইম | 97.239920s | +| SC ডিপ্লয় টাইম | 3.048970s | + +### এনভায়রনমেন্ট ERC20 {#environment-erc20} + +
+ হোস্ট কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ক্লাউড প্রোভাইডারAWS
ইন্সট্যান্স সাইজt2.micro
নেটওয়ার্কিংপ্রাইভেট সাবনেট
অপারেটিং সিস্টেমলিনাক্স উবুন্টু 20.04 LTS - Focal Fossa
ফাইল ডেস্ক্রিপ্টর লিমিট65535
ব্যবহারকারী সর্বোচ্চ প্রসেস করতে পারেন65535
+
+
+
+
+ +
+ ব্লকচেইন কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge সংস্করণডেভেলপ ব্রাঞ্চে 8a033aa1afb191abdac04636d318f83f32511f3c কমিট করা
ভ্যালিডেটর নোড6
নন-ভ্যালিডেটর নোড0
কনসেনসাসIBFT PoA
ব্লক টাইম2s
ব্লক গ্যাস সীমা5242880
গড়ে ব্লকের ব্যবহার95%
+
+
+
+
+ +
+ Loadbot কনফিগারেশন +
+
+ + + + + + + + + + + + + +
মোট লেনদেন5000
প্রতি সেকেন্ডে পাঠানো লেনদেন200
লেনদেনের প্রকারERC20 থেকে ERC20 ট্রান্সফার
+
+
+
+
+ +
+ লোডবট লগ + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### এনভায়রনমেন্ট ERC721 {#environment-erc721} + +
+ হোস্ট কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ক্লাউড প্রোভাইডারAWS
ইন্সট্যান্স সাইজt2.micro
নেটওয়ার্কিংপ্রাইভেট সাবনেট
অপারেটিং সিস্টেমলিনাক্স উবুন্টু 20.04 LTS - Focal Fossa
ফাইল ডেস্ক্রিপ্টর লিমিট65535
ব্যবহারকারী সর্বোচ্চ প্রসেস করতে পারেন65535
+
+
+
+
+ +
+ ব্লকচেইন কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge সংস্করণডেভেলপ ব্রাঞ্চে 8a033aa1afb191abdac04636d318f83f32511f3c কমিট করা
ভ্যালিডেটর নোড6
নন-ভ্যালিডেটর নোড0
কনসেনসাসIBFT PoA
ব্লক টাইম2s
ব্লক গ্যাস সীমা5242880
গড়ে ব্লকের ব্যবহার94%
+
+
+
+
+ +
+ Loadbot কনফিগারেশন +
+
+ + + + + + + + + + + + + +
মোট লেনদেন2000
প্রতি সেকেন্ডে পাঠানো লেনদেন200
লেনদেনের প্রকারERC721 টোকেন মিন্ট
+
+
+
+
+ +
+ লোডবট লগ + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/bn-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/bn-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..52bcc8a776 --- /dev/null +++ b/archive/edge/bn-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,956 @@ +--- +id: test-2022-03-23 +title: 23শে মার্চ 2022 +description: "23শে মার্চের পারফরম্যান্স টেস্ট।" +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### সারাংশ {#summary} + +:::caution +দয়া করে মনে রাখবেন যে আমাদের এই পরীক্ষার জন্য ব্যবহার করা `loadbot`হ, া এখন অবচিত হয়েছে। +::: + +SC ERC20 টোকেন ট্রান্সফার, SC ERC721 টোকেন মিন্টিং এবং উচ্চ-চাপে EOA থেকে EOA লেনদেনের কার্যকারিতা এবং উচ্চ হার্ডওয়্যার রিসোর্স থাকা নোডগুলির লেনদেনের গতি পরিমাপের জন্য এই পরীক্ষাটি করা হয়েছিল। + +উচ্চ-চাপে সবকিছু আশানুরূপ কাজ করছে কিনা তা পরীক্ষা করাই এর উদ্দেশ্য ছিল। লোডবট আউটপুটে গ্যাসের মেট্রিক্স চালু করার এটিও একটি কারণ ছিল, যা আমাদেরকে দেখাচ্ছে যে ব্লকগুলোতে সঠিকভাবে লেনদেন চলছে কিনা। + +সমস্ত লেনদেন GRPC API-এর মাধ্যমে একক নোডে পাঠানো হয়েছিল এবং JSON-RPC API দ্বারা রশিদ গ্রহণ করা হয়েছিল। সকল লেনদেন সম্পন্ন হওয়ার পরে eth_getBlockByNumber JSON-RPC পদ্ধতি ব্যবহার করে প্রতিটি ব্লক থেকে গ্যাসের তথ্য রিড করা হয়েছিল। + +বিদ্যমান হার্ডওয়্যারের রিসোর্সে সর্বাধিক সম্ভাব্য টিপিএস-এ পৌঁছানোই ছিল আমাদের লক্ষ্য। এটি অর্জন করার জন্য, আমরা ব্লক গ্যাস সীমা এবং ব্লক টাইম প্যারামিটারকে পরিবর্তন করেছি, যাতে আমরা আমাদের সেরা সম্ভাব্য টিপিএস ফলাফল পেতে পারি এবং সিস্টেমের ইন্টেগ্রিটি ও স্টেবিলিটি বজায় রাখতে পারি। + +:::info ব্লক গ্যাস সীমা + +লেনদেন কার্যকর করার জন্য অনেক গ্যাস ব্যবহার করা হলে ব্লক গ্যাস সীমাও তার সাথে তাল মিলিয়ে বৃদ্ধি করা যাবে। +নিম্নের লিখা উদাহরণটিতে, ব্লক গ্যাস লিমিট 80 000 000 (20 মিলিয়নের পরিবর্তে) সেট করলে ERC721 টোকেন মিন্টিং খুব দ্রুত কাজ করে, কিন্তু ERC20 টোকেন ট্রান্সফারে ব্লক গ্যাস লিমিট 80 মিলিয়ন হওয়ায় সার্ভার ক্র্যাশ করে। +::: + +:::info প্রোডাকশনের এনভায়রনমেন্ট + +একটি প্রোডাকশন এনভায়রনমেন্ট কনফিগার করার সময়, আপনি চেইনের উচ্চ কার্যকারিতা অর্জন করার চেষ্টা করলে আপনাকে সাবধান হতে হবে। +ব্লক গ্যাস লিমিট প্যারামিটার একটি উচ্চ মানে সেট করা থাকলে, ব্লক টাইম 1s এ সেট করা থাকে, এবং একটি একক নোডের উপর বেশি লেনদেনের চাপ থাকে, সেই নোডটি অনেক বেশি (অথবা পুরো) RAM ব্যবহার করবে এবং তা সার্ভার ক্র্যাশের কারণ হতে পারে। সবকিছু ভালোভাবে পরীক্ষা করতে লোডবট ব্যবহার করুন, সিস্টেম রিসোর্স ইউটিলাইজেশন পর্যবেক্ষণ করুন এবং সেই অনুযায়ী আপনার কনফিগারেশন প্যারামিটার সেট করুন। +::: + +:::info মেমোরি অপর্যাপ্ত ত্রুটি + +সিস্টেম স্থিতিশীলতা বজায় রাখতে কিছু Linux ডিস্ট্রো খুব বেশি RAM ব্যবহার করা (OOM ত্রুটি) প্রক্রিয়াকে বন্ধ করে দিবে। +এই OOM ত্রুটির লগ আউটপুট দেখতে নিচের মত হবে। +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### EOA থেকে EOA-তে ট্রান্সফারের ফলাফল {#results-of-eoa-to-eoa-transfers} +| মেট্রিক | মান | +| ------ | ----- | +| লেনদেনের প্রকার | EOA থেকে EOA | +| প্রতি সেকেন্ডের লেনদেন | 689 | +| লেনদেন ব্যর্থ | 0 | +| লেনদেন সফল হয়েছে | 20000 | +| মোট ব্যবহৃত ব্লক | 25 | +| মোট রান টাইম | 29.921110s | + +### ERC20 টোকেন ট্রান্সফারের ফলাফল {#results-of-erc20-token-transfers} + +| মেট্রিক | মান | +| ------ | ----- | +| লেনদেনের প্রকার | ERC20 | +| প্রতি সেকেন্ডের লেনদেন | 500 | +| লেনদেন ব্যর্থ | 0 | +| লেনদেন সফল হয়েছে | 20000 | +| মোট ব্যবহৃত ব্লক | 33 | +| ERC20 লেনদেনের রান টাইম | 40.402900s | +| SC ডিপ্লয় টাইম | 2.004140s | + +### ERC721 টোকেন মিন্টিং-এর ফলাফল {#results-of-erc721-token-minting} + +| মেট্রিক | মান | +| ------ | ----- | +| লেনদেনের প্রকার | ERC721 | +| প্রতি সেকেন্ডের লেনদেন | 157 | +| লেনদেন ব্যর্থ | 0 | +| লেনদেন সফল হয়েছে | 20000 | +| মোট ব্যবহৃত ব্লক | 124 | +| ERC721 লেনদেনের রান টাইম | 127.537340s | +| SC ডিপ্লয় টাইম | 2.004420s | + + +### খুব উচ্চ ব্লক গ্যাস সীমা (80 মিলি.) দিয়ে ERC721 টোকেন মিন্টিং এর ফলাফল {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| মেট্রিক | মান | +| ------ | ----- | +| লেনদেনের প্রকার | ERC721 | +| প্রতি সেকেন্ডের লেনদেন | 487 | +| লেনদেন ব্যর্থ | 0 | +| লেনদেন সফল হয়েছে | 20000 | +| মোট ব্যবহৃত ব্লক | 34 | +| ERC721 লেনদেনের রান টাইম | 41.098410s | +| SC ডিপ্লয় টাইম | 2.004300s | + + +### EOA থেকে EOA এর এনভায়রনমেন্ট {#environment-eoa-to-eoa} +
+ হোস্ট কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ক্লাউড প্রোভাইডারAWS
ইনস্ট্যান্সের আকারc5.2xlarge
নেটওয়ার্কিংপ্রাইভেট সাবনেট
অপারেটিং সিস্টেমAmazon Linux 2 AMI (HVM) - Kernel 5.10
ফাইল ডেস্ক্রিপ্টর লিমিট65535
ব্যবহারকারী সর্বোচ্চ প্রসেস করতে পারেন65535
+
+
+
+
+ +
+ ব্লকচেইন কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge সংস্করণডেভেলপ ব্রাঞ্চে 06e11eac8da98c79c938fc53ddda2da3318cfbe04 কমিট করুন
যাচাইকারীর নোড4
অ-যাচাইকারী নোড0
কনসেনসাসIBFT PoA
ব্লক টাইম1s
ব্লক গ্যাস সীমা20000000
সর্বোচ্চ স্লট1000000
ব্লকের গড় ব্যবহার84.00%
+
+
+
+
+ +
+ লোডবট কনফিগারেশন +
+
+ + + + + + + + + + + + + +
মোট লেনদেন20000
প্রতি সেকেন্ডে পাঠানো লেনদেন689
লেনদেনের প্রকারEOA থেকে EOA ট্রান্সফার
+
+
+
+
+ +
+ লোডবট লগ + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### এনভায়রনমেন্ট ERC20 {#environment-erc20} +
+ হোস্ট কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ক্লাউড প্রোভাইডারAWS
ইনস্ট্যান্সের আকারc5.2xlarge
নেটওয়ার্কিংপ্রাইভেট সাবনেট
অপারেটিং সিস্টেমAmazon Linux 2 AMI (HVM) - Kernel 5.10
ফাইল ডেস্ক্রিপ্টর লিমিট65535
ব্যবহারকারী সর্বোচ্চ প্রসেস করতে পারেন65535
+
+
+
+
+ +
+ ব্লকচেইন কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge সংস্করণডেভেলপ ব্রাঞ্চে 06e11eac8da98c79c938fc53ddda2da3318cfbe04 কমিট করুন
যাচাইকারীর নোড4
অ-যাচাইকারী নোড0
কনসেনসাসIBFT PoA
ব্লক টাইম1s
ব্লক গ্যাস সীমা20000000
সর্বোচ্চ স্লট1000000
ব্লকের গড় ব্যবহার88.38%
+
+
+
+
+ +
+ লোডবট কনফিগারেশন +
+
+ + + + + + + + + + + + + +
মোট লেনদেন20000
প্রতি সেকেন্ডে পাঠানো লেনদেন500
লেনদেনের প্রকারERC20 থেকে ERC20 ট্রান্সফার
+
+
+
+
+ +
+ লোডবট লগ + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### এনভায়রনমেন্ট ERC721 {#environment-erc721} +
+ হোস্ট কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ক্লাউড প্রোভাইডারAWS
ইনস্ট্যান্সের আকারc5.2xlarge
নেটওয়ার্কিংপ্রাইভেট সাবনেট
অপারেটিং সিস্টেমAmazon Linux 2 AMI (HVM) - Kernel 5.10
ফাইল ডেস্ক্রিপ্টর লিমিট65535
ব্যবহারকারী সর্বোচ্চ প্রসেস করতে পারেন65535
+
+
+
+
+ +
+ ব্লকচেইন কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge সংস্করণডেভেলপ ব্রাঞ্চে 06e11eac8da98c79c938fc53ddda2da3318cfbe04 কমিট করুন
যাচাইকারীর নোড4
অ-যাচাইকারী নোড0
কনসেনসাসIBFT PoA
ব্লক টাইম1s
ব্লক গ্যাস সীমা20000000
সর্বোচ্চ স্লট1000000
ব্লকের গড় ব্যবহার92.90%
+
+
+
+
+ +
+ লোডবট কনফিগারেশন +
+
+ + + + + + + + + + + + + +
মোট লেনদেন20000
প্রতি সেকেন্ডে পাঠানো লেনদেন157
লেনদেনের প্রকারERC721 টোকেন মিন্ট
+
+
+
+
+ +
+ লোডবট লগ + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### এনভায়রনমেন্ট ERC20 - খুব উচ্চ ব্লক গ্যাস সীমা {#environment-erc20-very-high-block-gas-limit} +
+ হোস্ট কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ক্লাউড প্রোভাইডারAWS
ইনস্ট্যান্সের আকারc5.2xlarge
নেটওয়ার্কিংপ্রাইভেট সাবনেট
অপারেটিং সিস্টেমAmazon Linux 2 AMI (HVM) - Kernel 5.10
ফাইল ডেস্ক্রিপ্টর লিমিট65535
ব্যবহারকারী সর্বোচ্চ প্রসেস করতে পারেন65535
+
+
+
+
+ +
+ ব্লকচেইন কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge সংস্করণডেভেলপ ব্রাঞ্চে 06e11eac8da98c79c938fc53ddda2da3318cfbe04 কমিট করুন
যাচাইকারীর নোড4
অ-যাচাইকারী নোড0
কনসেনসাসIBFT PoA
ব্লক টাইম1s
ব্লক গ্যাস সীমা80000000
সর্বোচ্চ স্লট1000000
ব্লকের গড় ব্যবহার---
+
+
+
+
+ +
+ লোডবট কনফিগারেশন +
+
+ + + + + + + + + + + + + +
মোট লেনদেন20000
প্রতি সেকেন্ডে পাঠানো লেনদেন---
লেনদেনের প্রকারERC20 থেকে ERC20-তে ট্রান্সফার
+
+
+
+
+ +
+ OOM ত্রুটির লগ + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### এনভায়রনমেন্ট ERC721 - খুব উচ্চ ব্লক গ্যাস সীমা {#environment-erc721-very-high-block-gas-limit} +
+ হোস্ট কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ক্লাউড প্রোভাইডারAWS
ইনস্ট্যান্সের আকারc5.2xlarge
নেটওয়ার্কিংপ্রাইভেট সাবনেট
অপারেটিং সিস্টেমAmazon Linux 2 AMI (HVM) - Kernel 5.10
ফাইল ডেস্ক্রিপ্টর লিমিট65535
ব্যবহারকারী সর্বোচ্চ প্রসেস করতে পারেন65535
+
+
+
+
+ +
+ ব্লকচেইন কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge সংস্করণডেভেলপ ব্রাঞ্চে 06e11eac8da98c79c938fc53ddda2da3318cfbe04 কমিট করুন
যাচাইকারীর নোড4
অ-যাচাইকারী নোড0
কনসেনসাসIBFT PoA
ব্লক টাইম1s
ব্লক গ্যাস সীমা80000000
সর্বোচ্চ স্লট1000000
ব্লকের গড় ব্যবহার84.68%
+
+
+
+
+ +
+ লোডবট কনফিগারেশন +
+
+ + + + + + + + + + + + + +
মোট লেনদেন20000
প্রতি সেকেন্ডে পাঠানো লেনদেন487
লেনদেনের প্রকারERC721 টোকেন মিন্ট
+
+
+
+
+ +
+ লোডবট লগ + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/bn-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/bn-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..ba47e8a021 --- /dev/null +++ b/archive/edge/bn-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,565 @@ +--- +id: test-2022-07-04 +title: জুলাই 4th 2022 +description: "4 জুলাই থেকে পারফরম্যান্স টেস্ট" +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### সারাংশ {#summary} + +:::caution +দয়া করে মনে রাখবেন যে আমাদের এই পরীক্ষার জন্য ব্যবহার করা `loadbot`হ, া এখন অবচিত হয়েছে। +::: + +SC ERC20 টোকেন ট্রান্সফার, SC ERC721 টোকেন মিন্টিং এবং উচ্চ-চাপে EOA থেকে EOA লেনদেনের কার্যকারিতা এবং উচ্চ হার্ডওয়্যার রিসোর্স থাকা নোডগুলির লেনদেনের গতি পরিমাপের জন্য এই পরীক্ষাটি করা হয়েছিল। + +উচ্চ-চাপে সবকিছু আশানুরূপ কাজ করছে কিনা তা পরীক্ষা করাই এর উদ্দেশ্য ছিল। লোডবট আউটপুটে গ্যাসের মেট্রিক্স চালু করার এটিও একটি কারণ ছিল, যা আমাদেরকে দেখাচ্ছে যে ব্লকগুলোতে সঠিকভাবে লেনদেন চলছে কিনা। + +সমস্ত লেনদেন GRPC API-এর মাধ্যমে একক নোডে পাঠানো হয়েছিল এবং JSON-RPC API দ্বারা রশিদ গ্রহণ করা হয়েছিল। সকল লেনদেন সম্পন্ন হওয়ার পরে eth_getBlockByNumber JSON-RPC পদ্ধতি ব্যবহার করে প্রতিটি ব্লক থেকে গ্যাসের তথ্য রিড করা হয়েছিল। + +বিদ্যমান হার্ডওয়্যারের রিসোর্সে সর্বাধিক সম্ভাব্য টিপিএস-এ পৌঁছানোই ছিল আমাদের লক্ষ্য। এটি অর্জন করার জন্য, আমরা ব্লক গ্যাস সীমা এবং ব্লক টাইম প্যারামিটারকে পরিবর্তন করেছি, যাতে আমরা আমাদের সেরা সম্ভাব্য টিপিএস ফলাফল পেতে পারি এবং সিস্টেমের ইন্টেগ্রিটি ও স্টেবিলিটি বজায় রাখতে পারি। + + +:::info প্রোডাকশনের এনভায়রনমেন্ট + +একটি প্রোডাকশন এনভায়রনমেন্ট কনফিগার করার সময়, আপনি চেইনের উচ্চ কার্যকারিতা অর্জন করার চেষ্টা করলে আপনাকে সাবধান হতে হবে। +ব্লক গ্যাস লিমিট প্যারামিটার একটি উচ্চ মানে সেট করা থাকলে, ব্লক টাইম 1s এ সেট করা থাকে, এবং একটি একক নোডের উপর বেশি লেনদেনের চাপ থাকে, সেই নোডটি অনেক বেশি (অথবা পুরো) RAM ব্যবহার করবে এবং তা সার্ভার ক্র্যাশের কারণ হতে পারে। সবকিছু ভালোভাবে পরীক্ষা করতে লোডবট ব্যবহার করুন, সিস্টেম রিসোর্স ইউটিলাইজেশন পর্যবেক্ষণ করুন এবং সেই অনুযায়ী আপনার কনফিগারেশন প্যারামিটার সেট করুন। +::: + + + +### EOA থেকে EOA-তে ট্রান্সফারের ফলাফল {#results-of-eoa-to-eoa-transfers} +| মেট্রিক | মান | +| ------ | ----- | +| লেনদেনের প্রকার | EOA থেকে EOA | +| প্রতি সেকেন্ডের লেনদেন | 1428 | +| লেনদেন ব্যর্থ | 0 | +| লেনদেন সফল হয়েছে | 30000 | +| মোট ব্যবহৃত ব্লক | 15 | +| মোট রান টাইম | 21.374620s | + +### ERC20 টোকেন ট্রান্সফারের ফলাফল {#results-of-erc20-token-transfers} + +| মেট্রিক | মান | +| ------ | ----- | +| লেনদেনের প্রকার | ERC20 | +| প্রতি সেকেন্ডের লেনদেন | 1111 | +| লেনদেন ব্যর্থ | 0 | +| লেনদেন সফল হয়েছে | 50000 | +| মোট ব্যবহৃত ব্লক | 38 | +| ERC20 লেনদেনের রান টাইম | 45.906450s | +| SC ডিপ্লয় টাইম | 2.006580s | + +### ERC721 টোকেন মিন্টিং-এর ফলাফল {#results-of-erc721-token-minting} + +| মেট্রিক | মান | +| ------ | ----- | +| লেনদেনের প্রকার | ERC721 | +| প্রতি সেকেন্ডের লেনদেন | 714 | +| লেনদেন ব্যর্থ | 0 | +| লেনদেন সফল হয়েছে | 30000 | +| মোট ব্যবহৃত ব্লক | 39 | +| ERC721 লেনদেনের রান টাইম | 42.864140s | +| SC ডিপ্লয় টাইম | 2.005500s | + + + + +### EOA থেকে EOA এর এনভায়রনমেন্ট {#environment-eoa-to-eoa} +
+ হোস্ট কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ক্লাউড প্রোভাইডারAWS EC2
ইনস্ট্যান্সের আকারc6a.48xlarge
নেটওয়ার্কিংপ্রাইভেট সাবনেট
অপারেটিং সিস্টেমলিনাক্স উবুন্টু 20.04 LTS - Focal Fossa
ফাইল ডেস্ক্রিপ্টর লিমিট65535
ব্যবহারকারী সর্বোচ্চ প্রসেস করতে পারেন65535
+
+
+
+
+ +
+ ব্লকচেইন কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge সংস্করণরিলিজ v0.4.1
যাচাইকারীর নোড4
অ-যাচাইকারী নোড0
কনসেনসাসIBFT PoA
ব্লক টাইম1s
ব্লক গ্যাস সীমা70778880
সর্বোচ্চ স্লট276480
ব্লকের গড় ব্যবহার59.34%
+
+
+
+
+ +
+ লোডবট কনফিগারেশন +
+
+ + + + + + + + + + + + + +
মোট লেনদেন30000
প্রতি সেকেন্ডে পাঠানো লেনদেন1428
লেনদেনের প্রকারEOA থেকে EOA ট্রান্সফার
+
+
+
+
+ +
+ লোডবট লগ + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### এনভায়রনমেন্ট ERC20 {#environment-erc20} +
+ হোস্ট কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ক্লাউড প্রোভাইডারAWS EC2
ইনস্ট্যান্সের আকারc6a.48xlarge
নেটওয়ার্কিংপ্রাইভেট সাবনেট
অপারেটিং সিস্টেমলিনাক্স উবুন্টু 20.04 LTS - Focal Fossa
ফাইল ডেস্ক্রিপ্টর লিমিট65535
ব্যবহারকারী সর্বোচ্চ প্রসেস করতে পারেন65535
+
+
+
+
+ +
+ ব্লকচেইন কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge সংস্করণরিলিজ v0.4.1
যাচাইকারীর নোড4
অ-যাচাইকারী নোড0
কনসেনসাসIBFT PoA
ব্লক টাইম1s
ব্লক গ্যাস সীমা47185920
সর্বোচ্চ স্লট184320
ব্লকের গড় ব্যবহার81.29%
+
+
+
+
+ +
+ লোডবট কনফিগারেশন +
+
+ + + + + + + + + + + + + +
মোট লেনদেন50000
প্রতি সেকেন্ডে পাঠানো লেনদেন1111
লেনদেনের প্রকারERC20 থেকে ERC20 ট্রান্সফার
+
+
+
+
+ +
+ লোডবট লগ + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### এনভায়রনমেন্ট ERC721 {#environment-erc721} +
+ হোস্ট কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ক্লাউড প্রোভাইডারAWS EC2
ইনস্ট্যান্সের আকারc6a.48xlarge
নেটওয়ার্কিংপ্রাইভেট সাবনেট
অপারেটিং সিস্টেমলিনাক্স উবুন্টু 20.04 LTS - Focal Fossa
ফাইল ডেস্ক্রিপ্টর লিমিট65535
ব্যবহারকারী সর্বোচ্চ প্রসেস করতে পারেন65535
+
+
+
+
+ +
+ ব্লকচেইন কনফিগারেশন +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge সংস্করণরিলিজ v0.4.1
যাচাইকারীর নোড4
অ-যাচাইকারী নোড0
কনসেনসাসIBFT PoA
ব্লক টাইম1s
ব্লক গ্যাস সীমা94371840
সর্বোচ্চ স্লট1000000
ব্লকের গড় ব্যবহার93.88%
+
+
+
+
+ +
+ লোডবট কনফিগারেশন +
+
+ + + + + + + + + + + + + +
মোট লেনদেন30000
প্রতি সেকেন্ডে পাঠানো লেনদেন714
লেনদেনের প্রকারERC721 টোকেন মিন্ট
+
+
+
+
+ +
+ লোডবট লগ + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/bn-edge/troubleshooting.md b/archive/edge/bn-edge/troubleshooting.md new file mode 100644 index 0000000000..41db8e09ee --- /dev/null +++ b/archive/edge/bn-edge/troubleshooting.md @@ -0,0 +1,66 @@ +--- +id: troubleshooting +title: সমস্যার সমাধান +description: "Polygon Edge-এর জন্য সমস্যা সমাধান বিভাগ" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# সমস্যার সমাধান {#troubleshooting} + +## `method=eth_call err="invalid signature"`ত্রুটি {#error} + +আপনি Polygon Edge সঙ্গে একটি লেনদেন করতে একটি মানিব্যাগ ব্যবহার করা হয়, দয়া করে আপনার মানিব্যাগ স্থানীয় নেটওয়ার্ক সেটআপ + +1. `chainID`ডান এক। `chainID`Edge জন্য ডিফল্ট , `100`কিন্তু এটি জেনেসিস পতাকা ব্যবহার করে কাস্টমাইজ করা যেতে পারে`--chain-id`। + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. নিশ্চিত করুন, "RPC URL" এ, ক্ষেত্র আপনি নোড আপনি সংযুক্ত করা হয় JSON RPC পোর্ট + + +## একটি WebSocket URL {#how-to-get-a-websocket-url} + +ডিফল্টভাবে, যখন আপনি Polygon Edge রান করেন, তখন এটি চেইন লোকেশন এর উপর ভিত্তি করে একটি WebSocket URL তৈরি করে। URL স্কিম HTTPS লিঙ্কের জন্য এবং HTTP `ws://`এর জন্য ব্যবহার করা `wss://`হয়। + +Localhost WebSocket URL: +````bash +ws://:/ws +```` +অনুগ্রহ করে মনে রাখবেন যে পোর্ট নম্বর নোডের জন্য নির্বাচিত JSON-RPC পোর্টের উপর নির্ভর করে। + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## `insufficient funds`একটি চুক্তি {#error-when-trying-to-deploy-a-contract} + +আপনি এই ত্রুটি পেতে, দয়া করে নিশ্চিত করুন যে আপনি পছন্দসই ঠিকানা যথেষ্ট তহবিল আছে, এবং ঠিকানা ব্যবহৃত সঠিক
এক। premined ভারসাম্য সেট করতে, আপনি জেনেসিস ফাইল তৈরি করার `genesis [--premine ADDRESS:VALUE]`সময় জেনেসিস পতাকা এই পতাকা +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +এই 1000 WEI 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862। + + +## CHainbridge ব্যবহার করার সময় ERC20 টোকেন রিলিজ করা হয় না {#erc20-tokens-not-released-while-using-chainbridge} + +আপনি Polygon PoS এবং একটি স্থানীয় Edge নেটওয়ার্ক মধ্যে ERC20 টোকেন স্থানান্তর করার চেষ্টা করেন, এবং আপনার ERC20 টোকেন আমানত করা হয়, এছাড়াও প্রস্তাব relayer মৃত্যুদন্ড করা হয়, কিন্তু আপনার Edge নেটওয়ার্ক টোকেন মুক্তি করা হয় না, দয়া করে নিশ্চিত করুন Polygon Edge চেইন ERC20 হ্যান্ডলার মুক্তি
যথেষ্ট টোকেন গন্তব্য চেইন হ্যান্ডলার চুক্তি lock-release মোড জন্য মুক্তি জন্য যথেষ্ট টোকেন থাকতে হবে। আপনার স্থানীয় Edge নেটওয়ার্ক ERC20 হ্যান্ডলার মধ্যে কোন ERC20 টোকেন না থাকে, তাহলে নতুন টোকেন mint এবং ERC20 হ্যান্ডলার + +## `Incorrect fee supplied`Chainbridge ব্যবহার করার সময় {#error-when-using-chainbridge} + +মুম্বাই Polygon PoS চেইন এবং একটি স্থানীয় Polygon Edge সেটআপের মধ্যে ERC20 টোকেন স্থানান্তর করার চেষ্টা করার সময় আপনি এই ত্রুটি পেতে পারে। আপনি পতাকা ব্যবহার করে স্থা`--fee`পনা ফি সেট করার সময় এই ত্রুটি প্রদর্শিত হয়, কিন্তু আপনি আমানত লেনদেন আপনি ফি পরিবর্তন করতে নীচের কমান্ড +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +আপনি [এখানে](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md) এই ফ্ল্যাগ সম্পর্কে আরও তথ্য পাবেন। + + + + + diff --git a/archive/edge/bn-edge/validator-hosting.md b/archive/edge/bn-edge/validator-hosting.md new file mode 100644 index 0000000000..70043e54b4 --- /dev/null +++ b/archive/edge/bn-edge/validator-hosting.md @@ -0,0 +1,226 @@ +--- +id: validator-hosting +title: ভ্যালিডেটর হোস্টিং +description: "Polygon Edge জন্য হোস্টিং প্রয়োজনীয়তা" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +নিচে একটি Polygon Edge নেটওয়ার্কে একটি যাচাইকারী নোড সঠিকভাবে হোস্টিং করার পরামর্শ দেওয়া হয়। দয়া করে নিশ্চিত করতে নীচের তালিকাভুক্ত সবগুলোতে সাবধানে মনোযোগ দিতে যে আপনার যাচাইকারী সেটআপ নিরাপদ, স্থিতিশীল এবং performant হতে সঠিকভাবে কনফিগার করা হয়। + +## জ্ঞান বেস {#knowledge-base} + +যাচাইকারী নোড চালানোর চেষ্টা করার আগে, দয়া করে এই ডকুমেন্টে পুঙ্খানুপুঙ্খভাবে পড়ু ন। অতিরিক্ত ডক্স যা সহায়ক হতে পারে: + +- [ইনস্টলেশন](get-started/installation) +- [ক্লাউড সেটআপ](get-started/set-up-ibft-on-the-cloud) +- [CLI কমান্ড](get-started/cli-commands) +- [সার্ভার কনফিগ ফাইল](configuration/sample-config) +- [প্রাইভেট কী](configuration/manage-private-keys) +- [Prometheus মেট্রিক্স](configuration/prometheus-metrics) +- [গোপন ম্যানেজার](/docs/category/secret-managers) +- [ব্যাকআপ / রিস্টোর](working-with-node/backup-restore) + +## ন্যূনতম সিস্টেমের প্রয়োজনীয়তা {#minimum-system-requirements} + +| প্রকার | মান | দ্বারা প্রভাবিত | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 2 কোর |
  • JSON-RPC প্রশ্নের সংখ্যা
  • ব্লকচেইন স্টেট আকার
  • ব্লক গ্যাস সীমা
  • সময় ব্লক করুন
| +| RAM | 2 জিবি |
  • JSON-RPC প্রশ্নের সংখ্যা
  • ব্লকচেইন স্টেট আকার
  • ব্লক গ্যাস সীমা
| +| ডিস্ক |
  • 10 গিগাবাইট রুট প্যাটিশন
  • ডিস্ক এক্সটেনশন জন্য LVM সঙ্গে 30 গিগাবাইট রুট পার্টিশন
|
  • ব্লকচেইন স্টেট আকার
| + + +## সার্ভিস কনফিগারেশন {#service-configuration} + +`polygon-edge`বাইনারি প্রতিষ্ঠিত নেটওয়ার্ক সংযোগে স্বয়ংক্রিয়ভাবে একটি সিস্টেম সার্ভিস হিসাবে চালানোর প্রয়োজন এবং শুরু / স্টপ / রিস্টার্ট কার্যকারিতা। আমরা একটি সার্ভিস ম্যানেজার ব্যবহার করে সুপারিশ`systemd.` + +`systemd`উদাহরণ সিস্টেম কনফিগারেশন ফাইল: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### বাইনারি {#binary} + +উত্পাদন ইন বা`polygon-edge`ইনারি শুধুমাত্র pre-built GitHub রিলিজ বাইনারি থেকে নিয়োজিত করা উচিত - ম্যানুয়ালি কম্পাইলিং দ্বারা:::info +নিজে থেকে `develop`GitHub শাখা কম্পাইলিং করে, আপনি আপনার পরিবেশে ব্রেকিং পরিবর্তন পরিচয় করিয়ে দিতে পারেন। সেই কারণেই এটি বহুভুজ এজ বাইনারি বিশেষভাবে রিলিজ থেকে ডিপ্লয় করার সুপারিশ করা হয় ভেঙ্গে পরিবর্তন সম্পর্কে তথ্য এবং কীভাবে তাদের কাটিয়ে উঠতে। +::: + +দয়া করে ইনস্টলেশন পদ্ধতি একটি সম্পূর্ণ ওভারভিউ [জন্য ইনস্টলেশন পড়ুন](/docs/edge/get-started/installation)। + +### ডেটা স্টোরেজ {#data-storage} + +পুরো ব্লকচেইন স্টেট ধা`data/`রণকারী ফোল্ডার একটি ডেডিকেটেড ডিস্ক / ভলিউম জন্য অনুমতি দেওয়া স্বয়ংক্রিয় ডিস্ক ব্যাকআপ, ভলিউম এক্সটেনশন এবং অপশনাল ব্যর্থতার ক্ষেত্রে ডিস্ক / ভলিউম মাউন্ট করা। + + +### লগ ফাইল {#log-files} + +লগ ফাইল একটি দৈনিক ভিত্তিতে ঘোরা করা প্রয়োজন (একটি টুল মত )`logrotate`।:::warning +লগ ঘূর্ণমান ছাড়াই কনফিগার করা হলে, লগ ফাইল সমস্ত উপলব্ধ ডিস্ক স্পেস ব্যবহার করতে পারে যা যাচাইকারী আপটাইমে বাধা দিতে পারে। +::: + +উদাহরণ `logrotate`কনফিগারেশন: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +লগ স্টোরেজ সুপারি[শগ](#logging)ুলির জন্য নীচে লগিং বিভাগে পড়ুন। + +### অতিরিক্ত নির্ভরতা {#additional-dependencies} + +`polygon-edge`স্ট্যাটিকভাবে কম্পাইল করা হয়, কোনও অতিরিক্ত হোস্ট OS ডিপ্রেসেন্ট প্রয়োজন। + +## রক্ষণাবেক্ষণ {#maintenance} + +একটি Polygon Edge নেটওয়ার্কের একটি চলমান যাচাইকারী নোড বজায় রাখার জন্য সেরা অনুশীলন + +### ব্যাকআপ {#backup} + +Polygon Edge নোড জন্য দুটি ধরনের ব্যাকআপ পদ্ধতি + +পরামর্শ উভয় ব্যবহার করা হয়, যখনই সম্ভব, Polygon এজ ব্যাকআপ একটি সবসময় উপলব্ধ বিকল্প + +* ***ভলিউম*** ব্যা কআপ: Polygon Edge নোডের ভলিউম `data/`বা সম্পূর্ণ VM এর দৈনিক ইনক্রিমেন্ট ব্যাকআপ + + +* ***Polygon এজ ব্যাকআপ*** : দৈনিক CRON কাজ যা Polygon Edge এর নিয়মিত ব্যাকআপ করে এবং একটি অফসাইট লোকেশন `.dat`বা একটি নিরাপদ ক্লাউড অবজেক্ট স্টোরেজ এ সরানো হয়। + +Polygon এজ ব্যাকআপ উপরে বর্ণিত ভলিউম ব্যাকআপ সঙ্গে আদর্শভাবে ওভারল্যাপ করা উচিত। + +Polygon Edge ব্যাকআপ সঞ্চালন কিভাবে নির্দেশাবলী জন্য ব্যাকআপ [/ রিস্টোর নোড ইনস্ট্যান্স](working-with-node/backup-restore) পড়ুন। + +### লগিং {#logging} + +Polygon এজ নোড দ্বারা আউটপুট লগ উচিত: +- ইনডেক্সিং এবং অনুসন্ধানের ক্ষমতা সহ একটি বহিরাগত ডেটা স্টোরে +- 30 দিনের একটি লগ ধারণ সময় + +যদি এটি একটি Polygon এজ যাচাইকারী সেট আপ আপনার প্রথম, আমরা নোড শুরু করতে আপনি যে কোনও সমস্যা মুখোমুখি হতে দ্রুত ডিবাগ করতে সক্ষম হওয়ার `--log-level=DEBUG`বিকল্প + +:::info +নো`--log-level=DEBUG`ডের লগ আউটপুট যতটা সম্ভব ক্রিয়ামূলক হতে হবে। ডিবাগ লগ লগ ফাইল আকার ব্যাপকভাবে বৃদ্ধি করা হবে লগ ঘূর্ণন সমাধান। +::: +### OS নিরাপত্তা প্যাচ {#os-security-patches} + +অ্যাডমিনিস্ট্রেটরদের নিশ্চিত করতে হবে যে যাচাইকারী ইনস্ট্যান্স OS সর্বদা প্রতি মাসে অন্তত একবার সর্বশেষ প্যাচ সঙ্গে আপডেট করা হয়। + +## মেট্রিক্স {#metrics} + +### সিস্টেম মেট্রিক্স {#system-metrics} + +প্রশাসকদের কিছু ধরণের সিস্টেম মেট্রিক্স মনিটর সেটআপ করতে হবে, (যেমন টেলিগ্রাফ + InfluxDB + Grafana বা একটি 3rd পার্টি SaaS)। + +মেট্রিক্স যা পর্যবেক্ষণ করা প্রয়োজন এবং যে এলার্ম বিজ্ঞপ্তি সেটআপ করতে হবে: + +| মেট্রিক নাম | এলার্ম থ্রেশহোল্ড | +|-----------------------|-------------------------------| +| CPU ব্যবহার (%) | > 5 মিনিটের বেশি 90% | +| RAM ব্যবহার (%) | > 5 মিনিটের বেশি 90% | +| রুট ডিস্ক ব্যবহার | > 90% | +| ডেটা ডিস্ক ব্যবহার | > 90% | + +### ভ্যালিডেটর মেট্রিক্স {#validator-metrics} + +অ্যাডমিনিস্ট্রেটরদের Polygon Edge এর Prometheus API থেকে মেট্রিক্স সেটআপ সংগ্রহ করতে ব্লকচেইন কর্মক্ষমতা নিরীক্ষণ। + +[কোন মেট্রিক্স উন্মুক্ত](configuration/prometheus-metrics) করা হচ্ছে এবং কিভাবে Prometheus মেট্রিক সংগ্রহ সেট আপ করা বুঝতে Prometheus মেট্রিক্স + + +নিম্নলিখিত মেট্রিক্স অতিরিক্ত মনোযোগ দেওয়া প্রয়োজন: +- ***ব্লক উত্পাদন সময়*** - ব্লক উত্পাদন সময় স্বাভাবিক তুলনায় বেশি হলে, নেটওয়ার্কের সাথে একটি সম্ভাব্য সমস্যা +- ***ঐক্যমত্য চক্রের*** সংখ্যা - যদি 1 চক্রের বেশি হয়, নেটওয়ার্কে যাচাইকারী সেট সঙ্গে একটি সম্ভাব্য সমস্যা +- ***পিয়ারের সংখ্যা -*** যদি পিয়ারের সংখ্যা ড্রপ হয়, নেটওয়ার্কে একটি সংযোগ সমস্যা + +## নিরাপত্তা {#security} + +একটি Polygon এজ নেটওয়ার্কের একটি চলমান যাচাইকারী নোড সুরক্ষিত করার জন্য সেরা অনুশীলন + +### API সেবা {#api-services} + +- ***JSON-RPC*** - শুধুমাত্র API সেবা যা জনসাধারণের উন্মুক্ত করা প্রয়োজন (লোড balancer বা সরাসরি মাধ্যমে ) এই API সমস্ত ইন্টারফেস বা একটি নির্দিষ্ট আইপি ঠিকানা (উদাহরণ: বা )তে `--json-rpc 0.0.0.0:8545``--json-prc 192.168.1.1:8545`চালানো উচিত।:::info +এটি প্রকাশ্যে API সম্মুখীন করা হয় হিসাবে এটি নিরাপত্তা এবং হার সীমাবদ্ধতা প্রদান করার সামনে একটি লোড balancer / বিপরীত প্রক্সি +::: + + +- ***LibP2P*** - এটি পিয়ার যোগাযোগের জন্য নোড দ্বারা ব্যবহৃত নেটওয়ার্কিং API এটি সমস্ত ইন্টারফেস বা একটি নির্দিষ্ট আইপি ঠিকানা উপর চালানো `--libp2p 0.0.0.0:1478`(বা বা )`--libp2p 192.168.1.1:1478`। এই API প্রকাশ্যে উন্মুক্ত করা উচিত নয়, কিন্তু এটি অন্যান্য সব নোড থেকে reachable করা:::info +যদি লোকালহোস্ট () এ `--libp2p 127.0.0.1:1478`রান করা হয় অন্য নোড সংযোগ করতে সক্ষম হবে +::: + + +- ***GRPC*** - এই API শুধুমাত্র অপারেটর কমান্ড চলমান এবং অন্য উল্লেখ জন্য ব্যবহার করা যেমন এটি লোকালহোস্ট (`--grpc-address 127.0.0.1:9632`) এ একচেটিয়াভাবে চালানো উচিত। + +### Polygon এজ গোপন {#polygon-edge-secrets} + +Polygon এজ গোপন (`ibft`এবং `libp2p`কী) একটি স্থানীয় ফাইল সিস্টেমে সংরক্ষণ করা উচিত পরিবর্তে[, একটি সমর্থিত গোপন ম্যানেজার](configuration/secret-managers/set-up-aws-ssm) ব্যবহার করা উচি ত। স্থানীয় ফাইল সিস্টেমে গোপন সংরক্ষণ করা শুধুমাত্র অ উত্পাদন পরিবেশে ব্যবহার করা উচিত। + +## আপডেট {#update} + +নিম্নলিখিত যাচাইকারী নোড জন্য পছন্দসই আপডেট পদ্ধতি + +### আপডেট পদ্ধতি {#update-procedure} + +- অফিসিয়াল GitHub রিলিজ থেকে সর্বশেষ Polygon এজ বা[ইনারি](https://github.com/0xPolygon/polygon-edge/releases) +- Polygon এজ সেবা বন্ধ করুন (উদা`sudo systemctl stop polygon-edge.service`হরণ: +- ডাউনলোড করা একটি `polygon-edge`(উদা`sudo mv polygon-edge /usr/local/bin/`হরণ: +- চেক করুন সঠিক `polygon-edge`সংস্করণ চলমান করে জায়গায় হয় `polygon-edge version`- এটি রিলিজ সংস্করণ সাথে মিলা +- শুরু করার আগে কোনও ব্যাকওয়ার্ড সামঞ্জস্য `polygon-edge`পদক্ষেপ প্রয়োজন কিনা রিলিজ ডকুমেন্টেশন +- `polygon-edge`শুরু সেবা (উদাহরণ: `sudo systemctl start polygon-edge.service`) +- অবশেষে, `polygon-edge`লগ আউটপুট চেক করুন এবং নিশ্চিত করুন যে কোনও লগ `[ERROR]`ছাড়াই + +:::warning +যখন একটি বিরতি রিলিজ হয়, এই আপডেট পদ্ধতি সব নোড উপর সঞ্চালিত বর্তমানে চলমান বাইনারি নতুন রিলিজ সঙ্গে সামঞ্জস্যপূর্ণ নয়। + +এর মানে বাইনারি `polygon-edge`বদলানো এবং সার্ভিস আবার শুরু না হওয়া পর্যন্ত সংক্ষিপ্ত সময়সীমার জন্য এই চেইনকে অবশ্যই থামাতে হবে। তাই সেই অনুযায়ী পরিকল্পনা করুন। + +আপনি **[Ansible](https://www.ansible.com/)** বা কিছু কাস্টম স্ক্রিপ্টের মতো টুল ব্যবহার করে ভালোভাবে আপডেট সম্পন্ন করতে পারেন এবং চেইন ডাউনটাইম কমাতে পারেন। +::: + +## স্টার্টআপ পদ্ধতি {#startup-procedure} + +নিম্নলিখিত Polygon এজ যাচাইকারী জন্য প্রারম্ভ পদ্ধতি পছন্দসই প্রবাহ + +- নোলেজ বেস [বিভাগে](#knowledge-base) তালিকাভুক্ত ডক্স মাধ্যমে পড়ুন +- যাচাইকারী নোড সর্বশেষ OS প্যাচ প্রয়োগ করুন +- অফিসিয়াল GitHub রিলিজ থেকে সর্বশেষ বাইনারি ডাউনলোড করুন `polygon-edge`এবং [স্থানীয়](https://github.com/0xPolygon/polygon-edge/releases) উদাহরণে এটি`PATH` +- CLI কমান্ড ব্যবহার করে সমর্থিত [গোপন পরিচালকদের](/docs/category/secret-managers) একটি `polygon-edge secrets generate`শুরু করুন +- [CLI কমান্ড ব্যবহার](/docs/edge/get-started/cli-commands#secrets-init-flags)`polygon-edge secrets init` করে তৈরি এবং গোপন সংরক্ষণ করুন +- এবং মান `Public key (address)`নোট `NodeID`নিন +- [CLI কমান্ড ব্যবহার](/docs/edge/get-started/cli-commands#genesis-flags)`polygon-edge genesis` করে ক্লাউড সে[টআপ](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators) বর্ণিত হিসাবে `genesis.json`ফাইল +- [CLI কমান্ড](/docs/edge/configuration/sample-config)`polygon-edge server export` ব্যবহার করে ডিফল্ট কনফিগ ফাইল তৈরি করুন +- স্থানীয় যাচাইকারী নোড পরিবেশ (ফাইল পাথ, ইত্যাদি) মিটমাট করতে `default-config.yaml`ফাইল সম্পাদনা করুন +- একটি Polygon এজ সেবা (`systemd`বা অনুরূপ) তৈরি করুন যেখানে `polygon-edge`বাইনারি একটি ফাইল `default-config.yaml`থেকে সার্ভার চালানো হবে +- পরিষেবা শুরু করে Polygon এজ সার্ভার শুরু করুন (উদা`systemctl start polygon-edge`হরণ: +- লগ আউটপুট চেক করুন এবং ব্লক তৈরি করা হচ্ছে এবং কোন লগ আছে `[ERROR]`নিশ্চিত `polygon-edge`করুন +- একটি JSON-RPC পদ্ধতি যেমন কল করে চেইন কার্যকারিতা[`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid) diff --git a/archive/edge/bn-edge/working-with-node/backup-restore.md b/archive/edge/bn-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..8eac2e2787 --- /dev/null +++ b/archive/edge/bn-edge/working-with-node/backup-restore.md @@ -0,0 +1,83 @@ +--- +id: backup-restore +title: ব্যাকআপ / পুনরুদ্ধার নোড উদাহরণ +description: "একটি Polygon Edge নোড উদাহরণ ব্যাক আপ এবং পুনরুদ্ধার কিভাবে।" +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +এই গাইড একটি Polygon Edge নোড উদাহরণ ব্যাক আপ এবং পুনরুদ্ধার কিভাবে উপর বিস্তারিত যায়। এটি বেস ফোল্ডার এবং তারা যা ধারণ করে, সেইসাথে একটি সফল ব্যাকআপ এবং পুনরুদ্ধার সম্পাদন জন্য ফাইল সমালোচক + +## বেস ফোল্ডার {#base-folders} + +Polygon Edge তার স্টোরেজ ইঞ্জিন হিসাবে লেভারেজ করে। একটি Polygon Edge নোড শুরু করার সময়, নিম্নলিখিত সাব-ফোল্ডার নির্দিষ্ট কাজ ডিরেক্টরি তৈরি করা হয়: +* **ব্লকচেইন** - ব্লকচেইন তথ্য +* চেষ্টা - **Merkle** চেষ্টা সংরক্ষণ (বিশ্ব রাষ্ট্র তথ্য) +* **keystore** - ক্লায়েন্ট জন্য ব্যক্তিগত কী এটি libp2p ব্যক্তিগত কী এবং sealing/validator ব্যক্তিগত কী +* **ঐক্যমত**্য - ক্লায়েন্ট কাজ করার সময় প্রয়োজন হতে পারে যে কোন ঐক্যমত্য তথ্য এখন, এটি নোডের *ব্যক্তিগত যাচাইকারী কী* + +Polygon Edge উদাহরণ জন্য মসৃণ চালানোর জন্য এই ফোল্ডার সংরক্ষণ করা সমালোচক + +## একটি চলমান নোড থেকে ব্যাকআপ তৈরি করুন এবং নতুন নোড জন্য পুনরুদ্ধার {#create-backup-from-a-running-node-and-restore-for-new-node} + +এই বিভাগ একটি চলমান নোড ব্লকচেইন আর্কাইভ তথ্য তৈরি করে এবং অন্য উদাহরণ এটি পুনরুদ্ধার করার মাধ্যমে আপনাকে গাইড করে। + +### ব্যাকআপ {#backup} + +`backup`gRPC দ্বারা একটি চলমান নোড থেকে কমান্ড fetches ব্লক এবং একটি আর্কাইভ ফাইল কমান্ড `--from``--to`এবং না দেওয়া হয়, এই কমান্ড জেনেসিস থেকে সর্বশেষ ব্লক আনতে হবে। + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### পুনরুদ্ধার {#restore} + +পতাকা সঙ্গে শুরু করার সময় শুরু একটি আর্কাইভ থেকে একটি সার্ভার আমদানি ব্`--restore`লক। দয়া করে নিশ্চিত করুন যে নতুন নোড জন্য একটি কী আমদানি বা কী তৈরি সম্পর্কে আরও জানতে সি[ক্রেট ম্যানেজার অধ্যায়](/docs/edge/configuration/secret-managers/set-up-aws-ssm) + +```bash +$ polygon-edge server --restore archive.dat +``` + +## ব্যাক আপ / পুরো তথ্য {#back-up-restore-whole-data} + +এই বিভাগ রাষ্ট্র তথ্য এবং কী এবং নতুন উদাহরণ পুনরুদ্ধার সহ ডেটা ব্যাকআপ মাধ্যমে আপনাকে গাইড করে + +### ধাপ 1: চলমান ক্লায়েন্ট {#step-1-stop-the-running-client} + +যেহেতু Polygon Edge ডেটা স্টোরেজ জন্য **LevelDB** ব্যবহার করে, নোড ব্যাকআপ সময়কাল জন্য বন্ধ করা প্রয়োজন, **LevelDB** তার ডাটাবেস ফাইল সমতুল্য অ্যাক্সেস জন্য অনুমতি দেয় না। + +উপরন্তু, Polygon Edge এছাড়াও বন্ধ তথ্য flushing করে। + +প্রথম পদক্ষেপ চলমান ক্লায়েন্ট বন্ধ করা জড়িত (একটি সেবা ম্যানেজার বা প্রক্রিয়া একটি SIGINT সংকেত পাঠায় যে কিছু অন্যান্য প্রক্রিয়া মাধ্যমে), তাই এটি 2 ঘটনা ট্রিগার করতে পারে যখন gracefully নিচে শাট: +* ডিস্ক ডেটা ফ্লাশ +* LevelDB দ্বারা DB ফাইল লক + +### ধাপ 2: ডিরেক্টরি {#step-2-backup-the-directory} + +এখন ক্লায়েন্ট চলমান না হয়, তথ্য ডিরেক্টরি অন্য মাঝারি ব্যাক আপ করা যেতে পারে। একটি এক্সটেনশন সঙ্গে ফাইল `.key`ব্যক্তিগত কী তথ্য ধারণ করে এবং তারা একটি তৃতীয় / অজানা পার্টি সঙ্গে ভাগ করা + +:::info +দয়া করে ব্যাকআপ `genesis`এবং ম্যানুয়ালি তৈরি ফাইল পুনরুদ্ধার করুন, তাই পুনরুদ্ধার নোড সম্পূর্ণরূপে অপারেশন +::: + +## পুনরুদ্ধার {#restore-1} + +### ধাপ 1: চলমান ক্লায়েন্ট {#step-1-stop-the-running-client-1} + +Polygon Edge কোনো উদাহরণ চলমান হয়, এটি ধাপ 2 সফল হতে অর্ডার বন্ধ করা প্রয়োজন। + +### ধাপ 2: পছন্দসই ফোল্ডার {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +ক্লায়েন্ট চলমান না হলে, পূর্বে ব্যাক আপ ডেটা ডিরেক্টরি পছন্দসই ফোল্ডার কপি করা যেতে পারে। উপরন্তু, পূর্বে কপি `genesis`ফাইল + +### ধাপ 3: সঠিক তথ্য ডিরেক্টরি নির্দিষ্ট করার সময় Polygon Edge ক্লায়েন্ট {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +Polygon Edge পুনরুদ্ধার তথ্য ডিরেক্টরি ব্যবহার করার জন্য, আরম্ভ করতে, ব্যবহারকারী পথ নির্দিষ্ট করতে তথ্য ডিরেক্টরি। অনুগ্রহ করে [পতাকা সংক্রান্ত তথ্য CLI কমান্ড](/docs/edge/get-started/cli-commands) `data-dir`অধ্যায় diff --git a/archive/edge/bn-edge/working-with-node/query-json-rpc.md b/archive/edge/bn-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..16be084094 --- /dev/null +++ b/archive/edge/bn-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,85 @@ +--- +id: query-json-rpc +title: প্রশ্ন JSON RPC এন্ডপয়েন্ট +description: "Query ডেটা এবং একটি premined অ্যাকাউন্ট সঙ্গে চেইন শুরু করুন।" +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## সংক্ষিপ্ত বিবরণ {#overview} + +Polygon Edge JSON-RPC স্তর ডেভেলপারদের ব্লকচেইনে সহজেই ইন্টারঅ্যাক্ট করার কার্যকারিতা provides ে প্রদান করে, HTTP অনুরোধ মাধ্যমে। + +এই উদাহরণ তথ্য প্রশ্নের জন্য **curl** মত সরঞ্জাম ব্যবহার করে কভার করে, পাশাপাশি একটি premined অ্যাকাউন্ট সঙ্গে চেইন শুরু করে, এবং একটি লেনদেন পাঠান। + +## ধাপ 1: একটি premined অ্যাকাউন্ট সঙ্গে একটি জেনেসিস ফাইল তৈরি করুন {#step-1-create-a-genesis-file-with-a-premined-account} + +একটি জেনেসিস ফাইল তৈরি করতে, নিম্নলিখিত কমান্ড চালান: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +**premine** পতাকা সেই ঠিকানা সেট করে যা জেনে**সিস**
ফাইলের একটি প্রারম্ভিক ভারসাম্য সঙ্গে অন্তর্ভুক্ত করা উচিত এই ক্ষেত্রে, ঠিকানা `0x1010101010101010101010101010101010101010`একটি প্রারম্**ভিক ডিফল্ট ভারসাম্য** থাকবে`0xD3C21BCECCEDA1000000` (1 মিলিয়ন নেটিভ মুদ্রা টোকেন)। + +যদি আমরা একটি ভারসাম্য নির্দিষ্ট করতে চেয়েছি, আমরা ভারসাম্য এবং ঠিকানা একটি সঙ্গে পৃথক করতে পারে`:`ন, যেমন: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +ভারসাম্য একটি বা মান `hex``uint256`হতে পারে। + +:::warning শুধুমাত্র আপনার জন্য একটি প্রাইভেট কী অ্যাকাউন্ট premine করুন! +আপনি অ্যাকাউন্ট premine এবং তাদের অ্যাক্সেস করার জন্য একটি প্রাইভেট কী নেই তবে আপনি premined ভারসাম্য ব্যবহারযোগ্য হবে না +::: + +## ধাপ 2: dev মোডে Polygon Edge শুরু করুন {#step-2-start-the-polygon-edge-in-dev-mode} + +উন্নয়ন মোডে Polygon Edge শুরু করতে, যা [CLI কমান্ড](/docs/edge/get-started/cli-commands) সেকশনে ব্যাখ্যা করা হয়, নিম্নলিখিত +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## ধাপ 3: অ্যাকাউন্ট ভারসাম্য {#step-3-query-the-account-balance} + +এখন যে ক্লায়েন্ট ধাপ **1**-এ তৈরি জেনেসিস ফাইল ব্যবহার করে dev মোডে আপ এবং চলমান হয়, আমরা একটি টুল মত ব্যবহার করতে অ্যাকাউন্ট ভারসাম্য প্রশ্নের জন্য কার্**ল:** +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +কমান্ড নিম্নলিখিত আউটপুট +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## ধাপ 4: একটি স্থানান্তর লেনদেন {#step-4-send-a-transfer-transaction} + +এখন যে আমরা premined হিসাবে সেট আপ অ্যাকাউন্ট সঠিক ভারসাম্য + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/bn-edge/working-with-node/query-operator-info.md b/archive/edge/bn-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..89bc0b69b8 --- /dev/null +++ b/archive/edge/bn-edge/working-with-node/query-operator-info.md @@ -0,0 +1,85 @@ +--- +id: query-operator-info +title: কুয়েরি অপারেটরের তথ্য +description: "অপারেটরের তথ্য কীভাবে কুয়েরি করবেন।" +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## পূর্বশর্ত {#prerequisites} + +এই নির্দেশিকাটি ধরে নিচ্ছে যে আপনি [লোকাল সেটআপ](/docs/edge/get-started/set-up-ibft-locally) অথবা [ক্লাউডে IBTF ক্লাস্টার কীভাবে সেটআপ করতে হয় তার নির্দেশিকা](/docs/edge/get-started/set-up-ibft-on-the-cloud) পড়েছেন। + +যে কোনও ধরণের অপারেটর তথ্য অনুসন্ধান করতে একটি কার্যকরী নোড প্রয়োজন। + +Polygon Edge দিয়ে নোড অপারেটররা যে নোড অপারেট করছেন তার নিয়ন্ত্রণে থাকেন এবং সেটি কী করছে তা সম্পর্কে অবগত থাকতে পারেন।
+যেকোনও সময়ে তারা, কোন লগ সিফটিং এর প্রয়োজনীয়তা ছাড়াই gRPC এর উপর তৈরি করা ইনফরমেশন লেয়ার ব্যবহার করতে পারেন এবং অর্থপূর্ণ তথ্য পেতে পারেন। + +:::note + +যদি আপনার নোড `127.0.0.1:8545`-তে রান না করে, তাহলে আপনার এই ডকুমেন্টে তালিকাভুক্ত কমান্ডগুলোতে একটি ফ্ল্যাগ `--grpc-address ` যোগ করা উচিত। + +::: + +## পিয়ার ইনফরমেশন {#peer-information} + +### পিয়ার লিস্ট {#peers-list} + +সংযুক্ত পিয়ারের সম্পূর্ণ তালিকা পেতে (চলমান নোডটি সহ) নিম্নলিখিত কমান্ডটি রান করুন: +````bash +polygon-edge peers list +```` + +এটি libp2p অ্যাড্রেসগুলোর একটি তালিকা প্রদান করবে যা বর্তমানে চলমান ক্লায়েন্টের পিয়ার। + +### পিয়ার স্ট্যাটাস {#peer-status} + +একটি নির্দিষ্ট পিয়ারের স্ট্যাটাসের জন্য, রান করুন: +````bash +polygon-edge peers status --peer-id
+```` +*অ্যাড্রেস* প্যারামিটারটিই পিয়ারের libp2p অ্যাড্রেস। + +## IBFT তথ্য {#ibft-info} + +অনেক সময়ে, একজন অপারেটর, IBFT কনসেনসাসের অপারেটিং নোডের বিষয়ে জানতে চাইতে পারেন। + +সৌভাগ্যবশত, Polygon Edge এই তথ্যগুলো খুঁজে বের করার একটি সহজ উপায় প্রদান করে। + +### স্ন্যাপশট {#snapshots} + +নিম্নলিখিত কমান্ডটি রান করলে সবথেকে সাম্প্রতিক স্ন্যাপশটটি ফেরত পাওয়া যায়। +````bash +polygon-edge ibft snapshot +```` +একটি নির্দিষ্ট উচ্চতায় স্ন্যাপশটটি কুয়েরি করতে, অপারেটর এটা রান করতে পারেন: +````bash +polygon-edge ibft snapshot --num +```` + +### ক্যান্ডিডেট {#candidates} + +ক্যান্ডিডেটদের সর্বশেষ তথ্য পেতে, অপারেটর এটা রান করতে পারেন: +````bash +polygon-edge ibft candidates +```` +এই কমান্ডটি প্রস্তাবিত ক্যান্ডিডেটের পাশাপাশি এখনও অন্তর্ভুক্ত না হওয়া ক্যান্ডিডেটদের বর্তমান সেটকে কুয়েরি করে থাকে + +### স্ট্যাটাস {#status} + +নিম্নলিখিত কমান্ডটি চলমান IBFT ক্লায়েন্টের বর্তমান যাচাইকারীর কী রিটার্ন করে: +````bash +polygon-edge ibft status +```` + +## লেনদেন পুল {#transaction-pool} + +লেনদেন পুলে বর্তমান লেনদেনের সংখ্যা খুঁজে পেতে, অপারেটর রান করতে পারেন: +````bash +polygon-edge txpool status +```` diff --git a/archive/edge/de-edge/additional-features/blockscout.md b/archive/edge/de-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..1af73c8dda --- /dev/null +++ b/archive/edge/de-edge/additional-features/blockscout.md @@ -0,0 +1,376 @@ +--- +id: blockscout +title: Blockscout +description: Wie man eine Blockscout Instance einrichtet, um mit Polygon Edge zu arbeiten. +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## Übersicht {#overview} +Dieser Leitfaden geht in Details darüber, wie man Blockscout zusammenstellen und implementieren kann, um mit Polygon-Edge zusammenzuarbeiten. Blockscout hat seine eigene [Dokumentation](https://docs.blockscout.com/for-developers/manual-deployment), aber dieser Leitfaden konzentriert sich auf einfache aber detaillierte Schritt-für-Schritt-Anleitungen darüber, wie man step-by-step einrichtet. + +## Umgebung {#environment} +* Betriebssystem: Ubuntu Server 20.04 LTS [Download-Link](https://releases.ubuntu.com/20.04/) mit Sudo-Genehmigungen +* Server-Hardware: 8CPU / 16 GB RAM / 50 GB HDD (LVM) +* Datenbankserver: Dedizierter Server mit 2 CPU / 4 GB RAM / 100 GB SSD / PostgreSQL 13.4 + +### DB-Server {#db-server} +Die Voraussetzung für die Befolgung dieses Leitfadens ist, dass ein Datenbankserver bereit ist, Datenbank und db-Benutzer konfiguriert sind. Dieser Leitfaden wird nicht in Details darüber gehen, wie man den PostgreSQL-Server einsetzen und konfigurieren kann. Es gibt zu diesem Thema viele Leitfäden, wie beispielsweise [DigitalOcean Guide](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart) + +:::info HAFTUNGSAUSSCHLUSS +Dieser Leitfaden soll nur helfen, Blockscout auf einer einzigen Instance zu starten und zu laufen, was kein ideales Produktions- Setup ist. Für die Produktion möchten Sie wahrscheinlich Reverse-Proxy, Load-Balancer, scalability usw. in die Architektur einführen. +::: + +# Blockscout Bereitstellungsverfahren {#blockscout-deployment-procedure} + +## Teil 1 - Abhängigkeiten installieren {#part-1-install-dependencies} +Bevor wir beginnen, müssen wir sicherstellen, dass alle Binaries installiert sind, von denen der Blockscout abhängig ist. + +### System aktualisieren {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### Erlang repos hinzufügen {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### NodeJS repo hinzufügen {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### Rust installieren {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### Erforderliche Version von Erlang installieren {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### Erforderliche Version von Elixir installieren {#install-required-version-of-elixir} +Die Version von Elixir muss `1.13`sein. Wenn wir versuchen, diese Version aus dem offiziellen Repo zu installieren, `erlang`wird auf aktualisiert werden `Erlang/OTP 25`und das wollen wir nicht. Aus diesem Grund müssen wir die spezifische vorkompilierte `elixir`Version von GitHub Releases installieren. + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +`exlixir`Jetzt müssen wir System Binaries ordnungsgemäß einrichten. +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +Überprüfen, ob `elixir`und 2 ordnungsgemäß installiert sind. Dazu wird `erlang``elixir -v`ausgeführt. Dies sollte die Ausgabe sein: +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning +`Erlang/OTP`muss Version sein `24`und `Elixir`muss Version sein.`1.13.*` Wenn das nicht der Fall ist, werden Sie Probleme mit der Erstellung von Blockscout und/oder Ausführung haben. +::: +:::info +Schaue die offizielle ***[Seite von Blockscout Anforderungen an](https://docs.blockscout.com/for-developers/information-and-settings/requirements)*** +::: + +### NodeJS installieren {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### Cargo installieren {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### Andere Abhängigkeiten installieren {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### Installieren Sie optional postgresql Client, um Ihre db-Verbindung zu überprüfen {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## Teil 2 - Umgebungsvariablen setzen {#part-2-set-environment-variables} +Wir müssen die Umgebungsvariablen setzen, bevor wir Blockscout Compilation beginnen. In diesem Leitfaden werden wir nur das grundlegende Minimum festlegen, damit es funktioniert. Die vollständige Liste [der](https://docs.blockscout.com/for-developers/information-and-settings/env-variables) Variablen, die eingestellt werden können, finden Sie hier + +### Datenbankverbindung als Umgebungsvariable einstellen {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +Testen Sie jetzt ihre DB-Verbindung mit den angegebenen Parametern. Da Sie PG env vars zur Verfügung gestellt haben, sollten Sie sich mit der Datenbank nur durch Ausführen von verbinden können: +```bash +psql +``` + +Wenn die Datenbank korrekt konfiguriert ist, sollten Sie eine psql sehen: +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +Andernfalls wird ein Fehler wie folgt angezeigt: +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +Wenn dies der Fall ist, könnten [diese Dokumente](https://ubuntu.com/server/docs/databases-postgresql) Ihnen helfen. + +:::info DB-Verbindung +Stelle sicher, dass du alle db-Verbindungsprobleme aussortiert hast, bevor du zum nächsten fortfährst. Du musst Superuser-Rechte für den blockscout-Benutzer bereitstellen. +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## Teil 3 - klonen und kompilieren von Blockscout {#part-3-clone-and-compile-blockscout} +Jetzt bekommen wir endlich Blockscout Installation zu starten. + +### Blockscout repo klonen {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### Geheime Schlüsselbasis generieren, um den Produktions-Build zu schützen {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +In der letzten Zeile sollten Sie eine lange Reihe von zufälligen Zeichen sehen. Dies sollte als `SECRET_KEY_BASE`Umgebungsvariable festgelegt werden, vor dem nächsten Schritt. Zum Beispiel: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### Produktionsmodus einstellen {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### Kompilieren {#compile} +Cd in das Klonverzeichnis und mit dem Kompilieren beginnen + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info +Wenn Sie bereits eine Installation durchgeführt haben, entfernen Sie die statischen Elemente aus dem vorherigen Build ***mix phx.digestclean.*** +::: + +### Datenbanken migrieren {#migrate-databases} +:::info +Dieser Teil wird misslingen, wenn Sie Ihre DB-Verbindung nicht richtig eingerichtet haben, sie nicht zur Verfügung gestellt haben, oder in der DATABASE_URL-Umgebung festgelegt wurden. Der Datenbankbenutzer muss Superuser-Rechte haben. +::: +```bash +mix do ecto.create, ecto.migrate +``` + +Muss die Datenbank zuerst abgelegt werden, +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### zuerst Npm-Abhängigkeiten installieren ausführen und Frontend Assets kompilieren {#install-npm-dependencies-and-compile-frontend-assets} +Sie müssen das Verzeichnis im Ordner mit den Frontend Assets ändern. + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info Sei geduldig +Das Kompilieren dieser Assets kann ein paar Minuten dauern, und es wird keine Ausgabe anzeigen. Es kann aussehen, als wäre der Prozess eingefroren, aber Abwarten und Tee trinken. Wenn der Kompiliervorgang abgeschlossen ist, sollte etwas ausgegeben werden, `webpack 5.69.1 compiled with 3 warnings in 104942 ms`wie: +::: + +### Statische Assets erstellen {#build-static-assets} +Für diesen Schritt müssen Sie zur Root Ihres Blockscout clone zurückkehren. +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### Selbstsignierte Zertifikate generieren {#generate-self-signed-certificates} +:::info +Du kannst diesen Schritt überspringen, wenn du `https`nicht verwendest. +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## Teil 4 - Blockscout Service erstellen und ausführen {#part-4-create-and-run-blockscout-service} +In diesem Teil müssen wir einen Systemdienst einrichten, da Blockscout im Hintergrund läuft und nach dem System-Neustart fortbesteht. + +### Service file erstellen {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### Servicedatei bearbeiten {#edit-service-file} +Verwende den bevorzugten Linux Texteditor, um diese Datei zu bearbeiten und den Service zu konfigurieren. +```bash +sudo vi /etc/systemd/system/explorer.service +``` +Der Inhalt der explorer.service-Datei sollte wie folgt aussehen: +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### Start service auf Systemstart aktivieren {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### Verschieben des Blockscout clone an systemweiten Standort {#move-your-blockscout-clone-folder-to-system-wide-location} +Blockscout-Service muss Zugriff auf den Ordner haben, den du von Blockscout repo geklont hast und alle Assets kompiliert hast. +```bash +sudo mv ~/blockscout /usr/local +``` + +### env vars Datei erstellen, die von Blockscout-Service verwendet werden {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info +Verwende den `SECRET_KEY_BASE`du in Teil 3 generiert hast. +:::Speichern der Datei und beenden. + +### Starten Sie Blockscout-Service {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## Teil 5 - teste die Funktionalität deiner Blockscout-Instance {#part-5-test-out-the-functionality-of-your-blockscout-instance} +Alles was jetzt noch zu tun ist, ist zu überprüfen, ob der Blockscout-Service läuft. Service-Status prüfen mit: +```bash +sudo systemctl status explorer.service +``` + +Um die Service-Ausgabe zu überprüfen: +```bash +sudo journalctl -u explorer.service -f +``` + +Sie können überprüfen, ob es neue Listening Ports gibt: +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +Du solltest eine Liste der listening Ports erhalten, und auf der Liste sollte so etwas sein: +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +Blockscout führt den in env-Datei definierten Port und das Protokoll aus. In diesem Beispiel läuft es auf `4000`(http) . `http://:4000`Wenn alles in Ordnung ist, sollte man auf das Blockscout-Web-Portal mit zugreifen können. + +## Überlegungen {#considerations} +Für die beste Leistung ist es ratsam, einen dedizierten/lokalen `polygon-edge`vollständigen full -archive nicht validator-Knoten zu haben der ausschließlich für Blockscout-Abfragen verwendet wird. Die `json-rpc`API dieses Knotens müssen nicht öffentlich exponiert werden, da Blockscout alle Abfragen vom Backend ausführt. + + +## Schlussgedanken {#final-thoughts} +Wir haben gerade eine einzige Blockscout-Instance bereitgestellt, die in Ordnung ist, aber für die Produktion sollte erwogen werden, diese Instanz hinter einem Reverse-Proxy wie Nginx einzustellen. Du solltest auch über die Skalierbarkeit von Datenbanken und Instances nachdenken, abhängig von deinem Anwendungsfall. + +Sie sollten auf jeden Fall die offizielle [Blockscout-Dokumentation](https://docs.blockscout.com/) ansehen, da viele Anpassungsmöglichkeiten vorhanden sind. \ No newline at end of file diff --git a/archive/edge/de-edge/additional-features/chainbridge/definitions.md b/archive/edge/de-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..dfc2aa1d92 --- /dev/null +++ b/archive/edge/de-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,220 @@ +--- +id: definitions +title: Allgemeine Definitionen +description: Allgemeine Definitionen für in ChainBridge verwendete Begriffe +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## Relayer {#relayer} +ChainBridge ist eine Bridge vom Typ Relayer. Die Rolle eines Relayers besteht darin, für die Ausführung einer Anfrage zu stimmen (z.B. wie viele Token gebrannt/freigegeben werden sollen). +Er überwacht Ereignisse aus jeder Chain und stimmt für einen Vorschlag im Bridge-Contract der Destination-Chain, wenn er ein `Deposit`Event von einer Chain erhält. Ein Relayer ruft eine Methode im Bridge-Contract auf, um den Vorschlag auszuführen, nachdem die erforderliche Anzahl an Stimmen abgegeben wurde. Die Bridge delegiert die Ausführung an den Handler-Contract. + + +## Contract-Arten {#types-of-contracts} +In ChainBridge gibt es in jeder Chain drei Arten von Contracts, Bridge/Handler/Target genannt. + +| **Art** | **Beschreibung** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Bridge-Contract | In jeder Chain muss ein Bridge-Contract implementiert werden, der Anfragen, Abstimmungen und Ausführungen verwaltet. Benutzer rufen `deposit`in Bridge auf, um eine Übertragung zu starten, und Bridge delegiert den Vorgang an den Handler-Contract, der dem Target-Contract entspricht. Sobald der Handler-Contract den Target-Contract erfolgreich aufgerufen hat, sendet der Bridge-Contract ein `Deposit`Event, um die Relayers zu informieren. | +| Handler-Contract | Dieser Contract interagiert mit dem Target-Contract, um eine Einzahlung oder einen Vorschlag auszuführen. Er validiert die Anfrage des Benutzers, ruft den Target-Contract auf und unterstützt bei einigen Einstellungen im Target-Contract. Es gibt gewisse Handler-Contracts, die jeden Target-Contract aufrufen, der über eine andere Schnittstelle verfügt. Durch die indirekten Aufrufe des Handler-Vertrags ermöglicht die Bridge die Übertragung von Assets oder Daten jeglicher Art. Derzeit gibt es drei Arten von Handler-Contracts, die von ChainBridge implementiert werden: ERC20Handler, ERC721Handler und GenericHandler. | +| Target-Contract | Ein Contract, der die auszutauschenden Assets oder die Nachrichten, die zwischen den Chains übertragen werden, verwaltet. Die Interaktion mit diesem Contract wird von jeder Seite der Bridge aus durchgeführt. | + +
+ +![ChainBridge Architektur](/img/edge/chainbridge/architecture.svg) +*ChainBridge Architektur* + +
+ +
+ +![Workflow der ERC20-Token-Übertragung](/img/edge/chainbridge/erc20-workflow.svg) +*z. B. Workflow einer ERC20-Token-Übertragun*g + +
+ +## Kontotypen {#types-of-accounts} + +Sicherstellen, dass die Konten genügend native Token haben, um Transaktionen zu erstellen, bevor Sie loslegen. In Polygon Edge können Sie bei der Erstellung des Genesis-Blocks den Konten vorab ermittelte Salden zuweisen. + +| **Art** | **Beschreibung** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Admin | Diesem Konto wird standardmäßig die Rolle des Administrators zugewiesen. | +| Benutzer | Das Sender-/Empfängerkonto, das Assets sendet/empfängt. Das Senderkonto zahlt die Gebühren (Gas) bei der Genehmigung von Token-Transfers und ruft die Einzahlung im Bridge-Contract auf, um eine Übertragung zu beginnen. | + +:::info Die Administratorrolle + +Bestimmte Aktionen können nur von einem Konto mit Administratorrolle durchgeführt werden. Standardmäßig hat derjenige, der den Bridge-Contract bereitstellt, die Administratorrolle. Im Folgenden erfahren Sie, wie Sie die Administratorrolle einem anderen Konto zuweisen oder sie entfernen können. + +### Administratorrolle hinzufügen {#add-admin-role} + +Fügt einen Administrator hinzu + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### Administratorrolle widerrufen {#revoke-admin-role} + +Entfernt einen Administrator + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## Die mit dem `admin`Konto möglichen Operationen sind die Folgenden. {#account-are-as-below} + +### Ressource einstellen {#set-resource} + +Registrierung einer Ressourcen-ID mit einer Vertragsadresse für einen Handler. + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Einen Contract erstellen, mit dem Coins ausgeschieden/förderbar gemacht werden können {#make-contract-burnable-mintable} + +Einen Token-Contract in einem Handler als förderbar/ausscheidbar festlegen. + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Vorschlag abbrechen {#cancel-proposal} + +Vorschlag für die Ausführung abbrechen + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### Pause/Unterbrechung {#pause-unpause} + +Einzahlungen, Vorschlagserstellung, Abstimmungen und Einzahlungsausführungen zeitlich unterbrechen. + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### Gebühr ändern {#change-fee} + +Ändern Sie die Gebühr, die an den Bridge-Contract entrichtet wird + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### Einen Relayer hinzufügen/entfernen {#add-remove-a-relayer} + +Konto als neuen Relayer hinzufügen oder ein Relayer-Konto entfernen + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### Schwellenwert für Relayer ändern {#change-relayer-threshold} + +Ändern Sie die Anzahl der erforderlichen Stimmen für die Ausführung eines Vorschlags + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## Chain-ID {#chain-id} + +Die ChainBridge `chainId`ist ein beliebiger Wert, der in der Bridge zur Unterscheidung zwischen den Blockchain-Netzwerken verwendet wird und im Bereich von uint8 liegen muss. Nicht zu verwechseln mit der Chain-ID des Netzwerks, das ist nicht das gleich. Dieser Wert muss zwar eindeutig sein, aber er muss nicht mit der ID des Netzwerks übereinstimmen. + +In diesem Beispiel setzen wir i`99`n, w`chainId`eil die Chain-ID des Mumbai-Testnets ist`80001`, was nicht mit einem uint8 dargestellt werden kann. + +## Ressourcen-ID {#resource-id} + +Eine Ressourcen-ID ist ein eindeutiger 32-Byte-Wert in einer Cross-Chain-Umgebung, der mit einem bestimmten Asset (Ressource) verbunden ist, das zwischen Netzwerken übertragen wird. + +Die Ressourcen-ID ist frei wählbar. In der Regel enthält das letzte Byte jedoch die Chain-ID der Source-Chain (das Netzwerk, aus dem dieses Asset stammt). + +## JSON-RPC URL für Polygon PoS {#json-rpc-url-for-polygon-pos} + +Für diese Anleitung verwenden wir https://rpc-mumbai.matic.today, eine öffentliche JSON-RPC-URL, die von Polygon zur Verfügung gestellt wird und möglicherweise Datenübertragungs- oder Leistungsbeschränkungen hat. Dies dient nur zur Verbindung mit dem Polygon Mumbai Testnet. Wir empfehlen Ihnen, Ihre JSON-RPC-URL über einen externen Dienst wie Infura zu beziehen, da bei der Einrichtung von Verträgen viele Abfragen an den JSON-RPC gesendet werden. + +## Möglichkeiten zur Übertragung von Token {#ways-of-processing-the-transfer-of-tokens} +Bei der Übertragung von ERC20-Tokens zwischen Chains können diese in zwei verschiedenen Modi verarbeitet werden: + +### Sperren/Freigeben Modus {#lock-release-mode} +Source-Chain: Die versendeten Token werden im Handler-Contract gesperrt. +D
estination-Chain: Die gleiche Menge an in der Source-Chain gesendeten Token, wird freigeschaltet und vom Handler-Contract auf das Empfängerkonto in der Destination-Chain übertragen. + +### Ausscheiden/Fördern-Modus {#burn-mint-mode} +Source-Chain: Die versendeten Token werden ausgeschieden. De
stination-Chain: Die gleiche Menge an Token, die Sie in der Source-Chain gesendet und ausgeschieden haben, wird auf der Destination-Chain ausgestellt und an das Empfängerkonto gesendet. + +Für jede Chain können Sie verschiedene Modi nutzen. Das bedeutet, dass ein Token in der Mainchain sperrbar ist, während ein Token in der Subchain für die Übertragung ausgegeben wird. So kann es zum Beispiel sinnvoll sein, Token zu sperren/freizugeben, wenn der Gesamtvorrat oder der Ausstellungszeitplan kontrolliert wird. Token würden ausgestellt/ausgeschieden, wenn der Contract in der Subchain dem Angebot in der Haupt-Chain folgen muss. + +Der Standardmodus ist der Sperren/Freigeben Modus. Möchten Sie die Token ausstellbar/ausscheidbar machen, müssen Sie die `adminSetBurnable`Methode wählen. Wenn Sie die Token bei der Ausführung ausstellen möchten, müssen Sie dem ERC20 Handler-Contract die Rolle `minter`zuweisen. + + diff --git a/archive/edge/de-edge/additional-features/chainbridge/overview.md b/archive/edge/de-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..1e3be5dec5 --- /dev/null +++ b/archive/edge/de-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Übersicht +description: ChainBridge Übersicht +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Was ist ChainBridge? {#what-is-chainbridge} + +ChainBridge ist eine modulare, multidirektionale Blockchain Bridge, die EVM- und Substrat-kompatible Chains unterstützt und von ChainSafe entwickelt wurde. Sie ermöglicht es Benutzern, alle Arten von Assets oder Nachrichten zwischen zwei verschiedenen Chains zu übertragen. + +Um mehr über ChainBridge zu erfahren, besuche bitte zuerst die [offizielle Dokumentation](https://chainbridge.chainsafe.io/), die von den Entwicklern bereitgestellt wird. + +Dieser Leitfaden soll Ihnen bei der Integration von ChainBridge in Polygon Edge helfen. Er führt durch die Einrichtung einer Bridge zwischen einem laufenden Polygon PoS (Mumbai Testnet) und einem lokalen Polygon Edge-Netzwerk. + +## Voraussetzungen {#requirements} + +In diesem Leitfaden werden Polygon Edge-Knoten, ein ChainBridge-Relayer (mehr dazu [hier](/docs/edge/additional-features/chainbridge/definitions)) und das Tool cb-sol-cli, ein CLI-Tool zur Bereitstellung von lokalen Contracts ausgeführt, Ressourcen registriert und Einstellungen für die Bridge geändert ([das](https://chainbridge.chainsafe.io/cli-options/#cli-options) ist nachprüfbar). Vor der Einrichtung müssen die folgenden Voraussetzungen erfüllt sein: + +* Go: >= 1.17 +* Node.js >= 16.13.0 +* Git + + +Außerdem müssen die folgenden Repositories mit den Versionen geklont werden, um bestimmte Anwendungen auszuführen. + +* [Polygon Edge](https://github.com/0xPolygon/polygon-edge): auf dem `develop`Branch +* [ChainBridge](https://github.com/ChainSafe/ChainBridge): v1.1.5 +* [ChainBridge Bereitstellungstools](https://github.com/ChainSafe/chainbridge-deploy): `f2aa093`auf B`main`ranch + + +Sie müssen ein Polygon-Edge-Netzwerk einrichten, bevor Sie mit dem nächsten Abschnitt fortfahren. Weitere Informationen finden Sie unter [Lokale Einrichtung](/docs/edge/get-started/set-up-ibft-locally) oder [Cloud Einrichtung](/docs/edge/get-started/set-up-ibft-on-the-cloud). \ No newline at end of file diff --git a/archive/edge/de-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/de-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..91535ba0a1 --- /dev/null +++ b/archive/edge/de-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,142 @@ +--- +id: setup-erc20-transfer +title: ERC20 Token-Transfer +description: ERC-20-Transfer in ChainBridge einrichten +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Bisher haben wir eine Bridge eingerichtet, um Assets/Daten zwischen der Polygon PoS und der Polygon Edge-Chain auszutauschen. In diesem Abschnitt erfahren Sie, wie eine ERC20 Bridge eingerichtet und Token zwischen verschiedenen Blockchains gesendet werden. + +## Schritt 1: Ressourcen-ID registrieren {#step-1-register-resource-id} + +Zunächst registrieren Sie eine Ressourcen-ID, die Ressourcen in einer Cross-Chain-Umgebung zuordnet. Eine Ressourcen-ID ist ein 32-Byte-Wert, der für die Ressource, die wir zwischen diesen Blockchains übertragen, einmalig sein muss. Die Ressourcen-IDs sind frei wählbar, können aber als Konvention die Chain-ID der Home-Chain im letzten Byte enthalten (die Home-Chain bezieht sich auf das Netzwerk, aus dem diese Ressourcen stammen). + +Um die Ressourcen-ID zu registrieren, können Sie den Befehl `cb-sol-cli bridge register-resource`verwenden. Der Private Key des `admin`Kontos muss angegeben werden. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (Optional) Contracts sind ausstellbar/ausscheidbar anzulegen {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## Schritt 2: ERC20-Token übertragen {#step-2-transfer-erc20-token} + +Wir senden ERC20 Token von der Polygon PoS-Chain an die Polygon Edge-Chain. + +Zunächst erhalten Sie Token, in dem Sie sie ausstellen. Ein Konto mit der `minter`Rolle kann neue Token ausgeben. Das Konto, das den ERC20-Contract bereitgestellt hat, hat standardmäßig die `minter`Rolle. Um andere Konten als Mitglieder der `minter`Rolle anzugeben, muss der Befehl a`cb-sol-cli erc20 add-minter`usgeführt werden. + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +Um den aktuellen Saldo zu überprüfen, kann der Befehl `cb-sol-cli erc20 balance`verwendet werden. + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +Als Nächstes muss der Transfer von ERC20-Token vom Konto durch den ERC20 Handler genehmigt werden + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +Um Token auf Polygon Edge-Chains zu übertragen, `deposit`aufrufen. + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Nachdem erfolgreicher Einzahlung, erhält der Relayer das Event und stimmt für den Vorschlag. Er führt eine Transaktion aus, um Token an das Empfängerkonto in der Polygon Edge-Chain zu senden, nachdem die erforderliche Anzahl von Stimmen abgegeben wurde. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Sobald die Transaktion erfolgreich durchgeführt wurde, erhalten Sie Token in der Polygon Edge-Chain. + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/de-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/de-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..bcec2d99d3 --- /dev/null +++ b/archive/edge/de-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,134 @@ +--- +id: setup-erc721-transfer +title: ERC721 NFT Transfer +description: ERC721-Transfer in ChainBridge einrichten +keywords: + - docs + - polygon + - edge + - Bridge +--- + +In diesem Abschnitt erfahren Sie, wie eine ERC721 Bridge eingerichtet und NFTs zwischen Blockchain-Netzwerken gesendet werden. + +## Schritt 1: Ressourcen-ID registrieren {#step-1-register-resource-id} + +Zunächst muss die Ressourcen-ID für den ERC721-Token in den Bridge-Contracts auf beiden Chains registriert werden. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (Optional) Ausstellbare/ausschéidbare contracts anlegen {#optional-make-contracts-mintable-burnable} + +Um Token ausstellbar/ausscheidbar zu machen, müssen Sie die folgenden Befehle aufrufen: + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## Schritt 2: NFT übertragen {#step-2-transfer-nft} + +Zunächst werden Sie eine NFT einführen, wenn Sie sie benötigen. + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Um den NFT-Besitzer zu überprüfen, kann `cb-sol-cli erc721 owner`verwendet werden. + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Dann ist ein Transfer der NFT durch ERC721 Handler freizugeben + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Der Transfer startet + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +Der Relayer erhält das Event und stimmt für den Vorschlag. Er führt eine Transaktion aus, um NFTs an das Empfängerkonto in der Polygon Edge-Chain zu senden, nachdem die erforderliche Anzahl von Stimmen abgegeben wurde. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Sie können den NFT-Besitzer im Polygon Edge-Netzwerk überprüfen, nachdem die Ausführung abgeschlossen ist. + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/de-edge/additional-features/chainbridge/setup.md b/archive/edge/de-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..14a9b1a0bd --- /dev/null +++ b/archive/edge/de-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,197 @@ +--- +id: setup +title: Einrichtung +description: Wie man chainBridge einrichtet +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Bereitstellung von Verträgen {#contracts-deployment} + +In diesem Abschnitt werden Sie die erforderlichen Verträge für die Polygon PoS- und Polygon Edge-ChainIn mit `cb-sol-cli`bereitstellen. + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +Zunächst werden wir mit dem Befehl `cb-sol-cli deploy`Verträge in der Polygon PoS-Chain bereitstellen. M`--all`it Flagwerden alle Verträge bereitgestellt, einschließlich Bridge, ERC20 Handler, ERC721 Handler, Generic Handler, ERC20 und ERC721 Vertrag. Ferner werden die Standardadresse des Relayerkontos und der Schwellenwert festgelegt + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +Mehr über chainID und JSON-RPC URL [hier](/docs/edge/additional-features/chainbridge/definitions) erfahren + +:::caution + +Der vorgegebene Gaspreis in i`cb-sol-cli`st ()`20000000`.`0.02 Gwei` `--gasPrice`Um den geeigneten Gaspreis in einer Transaktion einzurichten, setze den Wert mit dem Argument fest. + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +Der Bridge-Vertrag kostet ungefähr 0x3f97b8 (4167608) Gas zur Bereitstellung Vergewissern, dass die erzeugten Blöcke über ein ausreichendes Blockgaslimit verfügen, damit die Transaktion zur Vertragserstellung durchgeführt werden kann. Um mehr über die Änderung des Blockgaslimits in Polygon Edge zu erfahren, siehe die [lokale Einrichtung](/docs/edge/get-started/set-up-ibft-locally) + +::: + +Sobald die Verträge bereitgestellt wurden, erhalten Sie das folgende Ergebnis: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +Jetzt können wir die Verträge in der Polygon Edge Chain bereitstellen. + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Speichern Sie die Terminalausgaben mit den Adressen der eingesetzten Smart Contracts, da wir sie für den nächsten Schritt benötigen. + +## Relayer-Einrichtung {#relayer-setup} + +In diesem Abschnitt werden Sie einen Relayer starten, um Daten zwischen 2 Chains auszutauschen. + +Zunächst müssen wir das ChainBridge Repository klonen und bauen. + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +Als Nächstes müssen Sie `config.json`erstellen und die JSON-RPC URLs einstellen, die Relay-Adresse und Vertragsadresse für jede Chain festlegen. + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +Um einen Relayer zu starten, müssen Sie den privaten Schlüssel importieren, der der Relayer-Kontoadresse entspricht. Sie müssen das Passwort eingeben, wenn Sie den privaten Schlüssel importieren. Sobald der Import erfolgreich war, wird der Schlüssel unter `keys/
.key`gespeichert. + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +Jetzt kann der Relayer gestartet werden. Sie müssen das gleiche Passwort eingeben, das Sie zu Beginn für die Speicherung des Schlüssels gewählt haben. + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +Mit dem Start des Relayer beginnt er mit der Beobachtung neuer Blöcke in jeder Chain. diff --git a/archive/edge/de-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/de-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..2ba7b4cab8 --- /dev/null +++ b/archive/edge/de-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,255 @@ +--- +id: use-case-erc20-bridge +title: Anwendungsfall – ERC20 Bridge +description: Beispiel für die Überbrückung des ERC20-Vertrags +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +Dieser Abschnitt soll Ihnen einen Überblick über die Einrichtung der ERC20 Bridge für einen praktischen Anwendungsfall geben. + +In diesem Leitfaden werden Sie das Mumbai Polygon PoS Testnet und die lokale Polygon Edge Chain verwenden. Vergewissern, dass JSON-RPC Endpoint für Mumbai und Polygon Edge in der lokalen Umgebung eingerichtet ist. Weitere Details unter [Lokale Einrichtung](/docs/edge/get-started/set-up-ibft-locally) oder [Cloud-Einrichtung](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +## Szenario {#scenario} + +In diesem Szenario soll eine Bridge für den ERC20-Token eingerichtet werden, der bereits in der öffentlichen Chain (Polygon PoS) eingesetzt wurde, um den Nutzern im Normalfall einen kostengünstigen Transfer in eine private Chain (Polygon Edge) zu ermöglichen. In einem solchen Fall wurde die Gesamtversorgung des Tokens in der öffentlichen Chain definiert und nur die Menge der Token, die von der öffentlichen Chain in die private übertragen wurde, muss in der privaten Chain existieren. Daher müssen Sie den Sperr-/Freigabemodus in der öffentlichen Chain und den Ausscheide/Ausgabemodus in der privaten Chain verwenden. + +Wenn Token von der öffentlichen Chain in die private Chain gesendet werden, wird das Token im ERC20 Handler-Vertrag der öffentlichen Chain gesperrt und die gleiche Menge an Token wird in der privaten Chain ausgestellt, Andererseits wird das Token in der privaten Chain verbrannt und die gleiche Menge an Token wird vom ERC20-Handler-Vertrag in der öffentlichen Chain, im Falle der Übertragung von der privaten Chain in die öffentliche Chain, freigegeben. + +## Contracts {#contracts} + +Erklärungen mit einem einfachen ERC20-Vertrag anstelle des von ChainBridge entwickelten Vertrags. Für den Ausscheide/Ausgabemodus muss der ERC20-Vertrag zusätzlich zu den Methoden für ERC20 über`burnFrom` und`mint`Methoden verfügen: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +Alle Codes und Skripte befinden sich im Beispiel Github Repo [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Schritt1: Bereitstellen von Bridge und ERC20-Handler-Verträgen {#step1-deploy-bridge-and-erc20-handler-contracts} + +Zunächst werden Sie Bridge und ERC20Handler-Verträge mit `cb-sol-cli`in den beiden Chains bereitstellen. + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Sie erhalten Bridge und ERC20Handler-Vertragsadressen wie folgt: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Schritt2: Bereitstellen Ihres ERC20-Vertrags {#step2-deploy-your-erc20-contract} + +Bereitstellung Ihres ERC20-Vertrags. Dieses Beispiel führt Sie durch das Hardhat-Projekt[Trapesys/chainbridge-example.](https://github.com/Trapesys/chainbridge-example) + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Neue `.env`Datei erstellen und folgende Werte einstellen. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Als Nächstes wird der ERC20-Vertrag in den beiden Chains bereitgestellt. + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +Nach erfolgreicher Bereitstellung erhalten Sie eine Vertragsadresse wie diese: + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## Schritt3: Ressourcen-ID in Bridge registrieren {#step3-register-resource-id-in-bridge} + +Eine Ressourcen-ID anmelden, die Ressourcen in einer Cross-Chain-Umgebung zuordnet. In beiden Chains muss dieselbe Ressourcen-ID eingestellt werden. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## Schritt4: Ausscheide/Ausgabemodus in der ERC20-Bridge von Edge einstellen {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +Bridge erwartet, dass es in Polygon Edge im Ausscheide/Ausgabemodus arbeitet. Es wird also der Ausscheide/Ausgabemodus `cb-sol-cli`eingestellt. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +Der ERC20-Handler-Vertrag muss mit einer Ausgabe/Ausscheidefunktion ausgestattet werden. + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Schritt5: Tokenausgabe {#step5-mint-token} + +In Mumbai werden neue ERC20-Token ausgegeben. + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +Nachdem die Transaktion erfolgreich ist, gibt das Konto den Token aus. + +## Schritt6: ERC20-Transfer starten {#step6-start-erc20-transfer} + +Vor diesem Schritt vergewissern, dass ein Relayer gestartet wurde. Überprüfen Sie [Setup](/docs/edge/additional-features/chainbridge/setup) für weitere Details. + +Während der Token-Übertragung von Mumbai zu Edge, hebt der ERC20-Handler-Vertrag in Mumbai Token von Ihrem Konto ab. Vor der Übertragung freigeben. + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +`cb-sol-cli`Schließlich beginnen Sie den Token-Transfer von Mumbai nach Edge mit + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Nach erfolgreicher Einzahlung erhält der Relayer das Event und stimmt für den Vorschlag. Er führt eine Transaktion aus, um Token an das Empfängerkonto in der Polygon Edge-Chain zu senden, nachdem die erforderliche Anzahl von Stimmen abgegeben wurde. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Sobald die Transaktion erfolgreich durchgeführt wurde, erhalten Sie Token in der Polygon Edge-Chain. diff --git a/archive/edge/de-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/de-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..14ec1a3fd3 --- /dev/null +++ b/archive/edge/de-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,308 @@ +--- +id: use-case-erc721-bridge +title: Anwendungsfall – ERC721 Bridge +description: Beispiel für einen Bridge ERC721 Contract +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +In diesem Abschnitt wird die Einrichtung der ERC721 Bridge für einen praktischen Anwendungsfall beschrieben. + +In diesem Leitfaden werden Sie das Mumbai Polygon PoS Testnet und die lokale Polygon Edge Chain verwenden. Vergewissern, dass JSON-RPC Endpoint für Mumbai und Polygon Edge in der lokalen Umgebung eingerichtet ist. Weitere Details unter [Lokale Einrichtung](/docs/edge/get-started/set-up-ibft-locally) oder [Cloud-Einrichtung](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +## Szenario {#scenario} + +In diesem Szenario geht es darum, eine Bridge für die ERC721 NFT einzurichten, die bereits in der öffentlichen Chain (Polygon PoS) eingesetzt wurde, um den Benutzern im Normalfall einen kostengünstigen Transfer in einer privaten Chain (Polygon Edge) zu ermöglichen. In einem solchen Fall wurden die ursprünglichen Metadaten in der öffentlichen Chain definiert und die einzigen NFTs, die von der öffentlichen Chain übertragen wurden, können in der privaten Chain existieren. Daher müssen Sie den Sperr-/Freigabemodus in der öffentlichen Chain und den Ausscheide/Ausgabemodus in der privaten Chain verwenden. + +Wenn NFTs von der öffentlichen Chain an die private Chain gesendet werden, wird die NFT in der öffentlichen Chain im ERC721 Handler-Contract gesperrt und dieselbe NFT wird in der privaten Chain ausgestellt. Bei einer Übertragung von der privaten Chain auf die öffentliche Chain wird die NFT in der privaten Chain verbrannt und dieselbe NFT wird aus dem ERC721 Handler-Contract in der öffentlichen Chain freigegeben. + +## Contracts {#contracts} + +Erläuterung mit einem einfachen ERC721-Contract anstelle des von ChainBridge entwickelten Contracts. Für den Ausscheide/Ausgabemodus muss der ERC721-Contract zusätzlich zu den in ERC721 definierten Methoden `mint`und f`burn`olgende Methoden haben: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +Alle Codes und Skripte befinden sich im Beispiel Github Repo [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Schritt 1: Bridge und ERC721 Handler-Contracts bereitstellen {#step1-deploy-bridge-and-erc721-handler-contracts} + +Zunächst werden Sie Bridge und ERC721Handler-Contracts mit `cb-sol-cli`in den beiden Chains bereitstellen. + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Sie erhalten Bridge- und ERC721Handler-Vertragsadressen wie diese: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Schritt 2: ERC721-Contracts bereitstellen {#step2-deploy-your-erc721-contract} + +Ihren ERC721-Contract bereitstellen. Dieses Beispiel führt Sie durch das Hardhat-Projekt[Trapesys/chainbridge-example.](https://github.com/Trapesys/chainbridge-example) + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Eine D`.env`atei erstellen und folgende Werte einstellen. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Als Nächstes werden Sie den ER721-Contract in den beiden Chains bereitstellen. + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +Nach erfolgreicher Bereitstellung erhalten Sie eine Contractadresse wie diese: + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## Schritt 3: Ressourcen-ID in Bridge anmelden {#step3-register-resource-id-in-bridge} + +Sie melden eine Ressourcen-ID an, die Ressourcen in einer Cross-Chain-Umgebung zuordnet. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## Schritt4: Ausgabe/Ausscheidemodus in der ERC721-Bridge von Edge einstellen {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +Bridge erwartet, dass sie in Edge als Ausscheide/Ausgabefunktion arbeitet. Ausscheide/Ausgabemodus einstellen. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +Dem ERC721-Handler-Contract muss eine Ausgabe/Ausscheidefunktion eingeräumt werden. + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Schritt5: NFT ausgeben {#step5-mint-nft} + +In der Mumbai Chain wird eine ERC721 NFT ausgegeben. + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +Nach erfolgreichen Abwicklung gibt das Konto den NFT aus. + +## Schritt6: ERC721-Transfer starten {#step6-start-erc721-transfer} + +Vor diesem Schritt vergewissern, dass der Relayer gestartet wurde. [Setup](/docs/edge/additional-features/chainbridge/setup) für weitere Details prüfen. + +Während des NFT-Transfers von Mumbai nach Edge zieht der ERC721-Handler-Contract in Mumbai NFT von deinem Konto ab. Vor der Übertragung freigeben. + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +Schließlich beginnst du den NFT-Transfer von Mumbai nach Edge. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +Nach erfolgreicher Einzahlung erhält der Relayer das Event und stimmt für den Vorschlag. +Er führt eine Transaktion aus, um NFT an das Empfängerkonto in der Polygon Edge Chain zu senden, nachdem die erforderliche Anzahl von Stimmen abgegeben wurde. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Sobald die Transaktion erfolgreich ausgeführt wurde, erhalten Sie NFT in der Polygon Edge Chain. diff --git a/archive/edge/de-edge/additional-features/permission-contract-deployment.md b/archive/edge/de-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..e519167411 --- /dev/null +++ b/archive/edge/de-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,86 @@ +--- +id: permission-contract-deployment +title: Berechtigung zur Bereitstellung von Smart-Contract +description: So fügen Sie die Berechtigung zur Bereitstellung von Smart-Contracts hinzu. +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## Übersicht {#overview} + +In diesem Leitfaden wird detailliert beschrieben, wie Sie Adressen, die Smart-Contracts einsetzen können, auf die Whitelist setzt. +Manchmal möchten die Betreiber eines Netzwerks verhindern, dass Benutzer Smart-Contracts einsetzen, die nichts mit dem Zweck des Netzwerks zu tun haben. Netzwerkbetreiber können: + +1. Adressen zur Whitelist für die Bereitstellung von Smart-Contract hinzufügen +2. Adressen von der Whitelist für die Bereitstellung von Smart-Contract entfernen + +## Video-Präsentation {#video-presentation} + +[![permission Contract-Bereitstellung - Video](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## Wie verwendet man sie? {#how-to-use-it} + + +Alle CLI-Befehle, die mit der Bereitstellung der Whitelist zusammenhängen, finden Sie auf der Seite [CLI-Befehle](/docs/edge/get-started/cli-commands#whitelist-commands). + +* `whitelist show`: Zeigt Informationen zur Whitelist +* `whitelist deployment --add`: Fügt eine neue Adresse zur Whitelist für die Bereitstellung von Contracts hinzu +* `whitelist deployment --remove`: Entfernt eine neue Adresse von der Whitelist für die Bereitstellung von Contracts + +#### Alle Adressen in der Bereitstellungs-Whitelist anzeigen {#show-all-addresses-in-the-deployment-whitelist} + +Es gibt 2 Möglichkeiten, Adressen von der Whitelist für die Bereitstellung zu finden. +1. Sehen Sie sich `genesis.json`an, wo Whitelists gespeichert werden +2. Ausführen von,`whitelist show` das Informationen für alle von Polygon Edge unterstützten Whitelists druckt + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### Hinzufügen einer neuen Adresse zur Whitelist {#add-an-address-to-the-deployment-whitelist} + +Um eine neue Adresse zur Bereitstellungs-Whitelist hinzuzufügen, den CLI-Befehl `whitelist deployment --add [ADDRESS]`ausführen. Es gibt kein Limit für die Anzahl der Adressen in der Whitelist. Nur Adressen, die auf der Whitelist für die Bereitstellung von Contracts stehen, können diese bereitstellen. Wenn die Whitelist leer ist, kann jede Adresse die Bereitstellung durchführen + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### Entfernen einer Adresse von der Whitelist {#remove-an-address-from-the-deployment-whitelist} + +Um eine Adresse aus der Bereitstellungs-Whitelist zu entfernen, führe den CLI-Befehl `whitelist deployment --remove [ADDRESS]`aus. Nur Adressen, die auf der Whitelist für die Bereitstellung von Contracts stehen, können diese bereitstellen. Wenn die Whitelist leer ist, kann jede Adresse die Bereitstellung durchführen + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/de-edge/architecture/modules/blockchain.md b/archive/edge/de-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..b29a5080e7 --- /dev/null +++ b/archive/edge/de-edge/architecture/modules/blockchain.md @@ -0,0 +1,156 @@ +--- +id: blockchain +title: Blockchain +description: Erläuterung für die Blockchain- und State Modules von Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## Übersicht {#overview} + +Eines der Hauptmodule des Polygon Edge sind **Blockchain** und** State**.
+ +**Blockchain** ist das Powerhouse, das sich mit Block-Neuorganisationen beschäftigt. Dies bedeutet, dass es mit all der Logik handelt, die passiert, wenn ein neuer Block in der Blockchain enthalten ist. + +**State** repräsentiert das *State transition* Objekt. Es behandelt, wie sich der Zustand ändert, wenn ein neuer Block enthalten ist.
**State** behandelt unter anderem: +* Transaktionen ausführen +* Ausführen des EVM +* Merkleversuche ändern +* Viel mehr, was in dem entsprechenden **State** Abschnitt abgedeckt ist 🙂 + +Das Wichtigste ist, dass diese 2 Teile sehr miteinander verbunden sind, und sie arbeiten eng zusammen, damit der Client funktioniert.
Wenn beispielsweise die **Blockchain** einen neuen Block erhält (und keine Reorganisation stattgefunden hat), ruft es den **State** dazu auf, eine State-Übertragung durchzuführen. + +**Blockchain** behandelt auch einige Dinge im Zusammenhang mit Konsens (Bsp. *ist dieses ethHash korrekt?* i*st dieser PoW korrekt?)*.
In einem Satz **ist es der Hauptkern von Logik, durch den alle Blöcke enthalten sind**. + +## *WriteBlocks* + +Eines der wichtigsten Teile im Zusammenhang mit der **Blockchain** Ebene ist die *WriteBlocks* Methode: + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +Die *WriteBlocks* Methode ist der Einstiegspunkt, um Blöcke in die Blockchain zu schreiben. Als Parameter nimmt es eine Reihe von Blöcken
auf. Zunächst werden die Blöcke validiert. Danach werden sie in die Chain geschrieben. + +Die tatsächliche *State-Transition* wird durchgeführt, indem die *processBlock* Methode innerhalb von *WriteBlocks* aufgerufen wird. + +Es ist erwähnenswert, dass, weil es der Einstiegspunkt für das Schreiben von Blöcken auf die Blockchain ist, andere Module (wie der **Sealer**) diese Methode verwenden. + +## Blockchain-Subscriptions {#blockchain-subscriptions} + +Es muss eine Möglichkeit geben, blockchain-bezogene Änderungen zu überwachen.
Hier kommen **Subscriptions** ins Spiel. + +Subscriptions sind eine Möglichkeit, Blockchain-Event-Streams zu erschließen und sofort aussagekräftige Daten zu erhalten. + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +Die **Blockchain-Events** enthalten Informationen über alle Änderungen an der tatsächlichen Chain. Dazu gehören Reorganisationen, sowie neue Blöcke: + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip Refresher +Erinnern Sie sich, als wir den ***monitor*** in den [CLI Commands](/docs/edge/get-started/cli-commands) erwähnt haben? + +Die Blockchain Events sind die ursprünglichen Ereignisse, die in Polygon Edge passieren, und sie werden später für eine einfache Übertragung einem Nachrichtenformat im Protokollspeicher zugeordnet. +::: \ No newline at end of file diff --git a/archive/edge/de-edge/architecture/modules/consensus.md b/archive/edge/de-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..3e479c81c5 --- /dev/null +++ b/archive/edge/de-edge/architecture/modules/consensus.md @@ -0,0 +1,493 @@ +--- +id: consensus +title: Konsens +description: Erläuterung für das Konsensmodul von Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## Übersicht {#overview} + +Das **Konsens** Modul bietet eine Schnittstelle für Konsensmechanismen. + +Derzeit stehen folgende Konsensmaschinen zur Verfügung: +* **IBFT PoA** +* **IBFT PoS** + +Polygon Edge möchte einen Zustand der Modularität und der Steckbarkeit beibehalten.
Deshalb wurde die Kernkonsenslogik wegabstrahiert, sodass neue Konsensmechanismen darauf aufgebaut werden können, ohne Kompromittierung von Usability und Benutzerfreundlichkeit. + +## Konsens-Schnittstelle {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + +Die ***Konsens*** Schnittstelle ist der Kern der erwähnten Abstraktion.
+* Die **VerifyHeader** Methode stellt eine Helper-Funktion dar, die die Konsensebene der **Blockchain** Ebene aussetzt Es besteht, um Header-Verifizierung zu verarbeiten +* Die **Start**-Methode startet einfach den Konsensprozess und alles, was damit verbunden ist. Dazu gehört die Synchronisierung, Versieglung, alles, was getan werden muss +* Die **Close** Methode schließt die Konsensverbindung + +## Konsens-Konfiguration {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +Es kann vorkommen, dass Sie einen benutzerdefinierten Speicherort für das Konsensprotokoll angeben möchten, um Daten zu speichern, oder vielleicht eine benutzerdefinierte Key-Value Karte, bei der Sie möchten, dass der Konsensmechanismus verwendet wird. Dies kann durch die ***Config*** struct erreicht werden, die gelesen wird, wenn eine neue Konsens-Instance erstellt wird. + +## IBFT {#ibft} + +### ExtraData {#extradata} + +Das Blockchain-Header-Objekt hat unter anderem ein Feld mit dem Namen **ExtraData**. + +IBFT verwendet dieses zusätzliche Feld, um operative Informationen über den Block zu speichern, und beantwortet Fragen wie: +* "Wer hat diesen Block unterzeichnet?" +* "Wer sind die Validatoren für diesen Block?" + +Diese zusätzlichen Felder für IBFT sind wie folgt definiert: +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### Signieren von Daten {#signing-data} + +Damit der Knoten Informationen in IBFT unterzeichnet, nutzt er die *signHash* Methode: +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +Eine weitere bemerkenswerte Methode ist die *VerifyCommittedFields* Methode, die überprüft, dass die eingesetzten Siegel von gültigen Validatoren stammen: +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### Snapshots {#snapshots} + +Snapshots, wie der Name schon sagt, gibt es, um einen *Snapshot* oder den *Zustand* eines Systems in jeder Blockhöhe (Nummer) bereitzustellen. + +Snapshots enthalten eine Reihe von Knoten, die Validatoren sind, sowie Abstimminformationen (Validatoren können für andere Validatoren stimmen). Validators enthalten Abstimminformationen im **Miner** Header und ändern den Wert der **nonce**: +* Nonce ist **alle 1s**, wenn der Knoten einen Validator entfernen möchte +* Nonce ist **alle 0s**, wenn der Knoten einen Validator hinzufügen möchte + +Snapshots werden mit der ***processHeaders** *Methode berechnet: + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +Diese Methode wird normalerweise mit 1 Header aufgerufen, aber der Flow ist auch mit mehreren Headern gleich.
Für jeden passed-in Header muss IBFT überprüfen, ob der proposer des Headers der Validator ist. Dies kann leicht gemacht werden durch Erfassung des neuesten Snapshots, und prüfen, ob Knoten im Validator eingerichtet ist, + +Als Nächstes wird die Nonce geprüft. Das Votum wird aufgenommen und ausgewertet – und wenn es genügend Stimmen gibt, wird ein Knoten aus dem Validierungssatz hinzugefügt/entfernt, woraufhin der neue Schnappschuss gespeichert wird. + +#### Snapshot-Store {#snapshot-store} + +Der Snapshot Service verwaltet und aktualisiert ein Objekt namens **snapshotStore**, die die Liste aller verfügbaren Snapshots speichert. Mit ihm kann der Dienst schnell herausfinden, welcher Snapshot mit welcher Blockhöhe verknüpft ist. +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### IBFT-Startup {#ibft-startup} + +Um IBFT zu starten, muss der Polygon Edge zuerst den IBFT Transport einrichten: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +Es erstellt im Wesentlichen ein neues Thema mit IBFT Proto, mit einer neuen Proto buff Nachricht.
Die Nachrichten sollen von Validatoren verwendet werden. Polygon Edge meldet sich dann für das Thema und behandelt Nachrichten entsprechend. + +#### MessageReq {#messagereq} + +Die Nachricht wurde von Validatoren ausgetauscht: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +Das Feld **Ansicht** im **MessageReq** repräsentiert die aktuelle Knotenposition innerhalb der Chain. Es hat ein *round* und ein *sequence* Attribut. +* **round** steht für die Proposerrunde für die Höhe +* **sequence** repräsentiert die Höhe der Blockchain + +Die *msgQueue* in der IBFT Implementierung hat den Zweck, message-Anforderungen zu speichern. Es ordnet Nachrichten durch die *Ansicht* (zuerst nach der sequence, dann nach der round). Die IBFT Implementierung besitzt auch verschiedene Warteschlangen für verschiedene Systemzustände. + +### IBFT-States {#ibft-states} + +Nachdem der Konsensmechanismus mit der **Start**-Methode gestartet wird, läuft er in eine unendliche Schleife, die eine State Machine simuliert: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### SyncState {#syncstate} + +Alle Knoten beginnen zunächst im **Sync** State. + +Dies liegt daran, dass frische Daten aus der Blockchain abgerufen werden müssen. Der Client muss herausfinden, ob es der Validator ist, den aktuellen snapshot finden. Dieser State löst alle ausstehenden Blöcke auf. + +Nachdem der Sync beendet wurde und der Client bestimmt, dass er ein Validator ist, muss er an **AcceptState** übertragen. Wenn der Client **kein** Validator ist, wird er weiterhin synchronisiert und bleibt in **SyncState** + +#### AcceptState {#acceptstate} + +Der **Accept** State überprüfe immer den snapshot und den Validatorsatz. Wenn der aktuelle Knoten nicht im Validatorsatz ist, bewegt es sich zurück in den **Sync** State. + +Andererseits, wenn der Knoten ein Validator **ist**, berechnet er den Proposer. Wenn es sich herausstellt, dass der aktuelle Knoten der proposer ist, baut es einen Block und sendet preprepare und bereitet dann Nachrichten vor. + +* Preprepare von Nachrichten – Nachrichten, die von Proposers an Validatoren gesendet werden, um sie über das proposal zu informieren +* Prepare von Nachrichten – Nachrichten, in denen Validatoren auf einen proposal übereinstimmen. Alle Knoten empfangen alle prepare Nachrichten +* Commit Nachrichten – Nachrichten, die Commit Informationen für das proposal enthalten + +Wenn der aktuelle Knoten **kein** Validator ist, verwendet er die *getNextMessage* Methode, um eine Nachricht aus der zuvor gezeigten Warteschlange zu
lesen. Er wartet auf die preprepare Nachrichten. Sobald es bestätigt wird, dass alles korrekt ist, verschiebt sich der Knoten in den **Validate** State. + +#### ValidateState {#validatestate} + +Der **Validate** State ist eher einfach - alle Knoten in diesem State lesen Nachrichten und fügen sie zu ihrem lokalen Snapshot State hinzu. diff --git a/archive/edge/de-edge/architecture/modules/json-rpc.md b/archive/edge/de-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..e1a8b43490 --- /dev/null +++ b/archive/edge/de-edge/architecture/modules/json-rpc.md @@ -0,0 +1,175 @@ +--- +id: json-rpc +title: JSON RPC +description: Erläuterung für das JSON-RPC-Modul von Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## Übersicht {#overview} + +Das **JSON RPC** Modul implementiert die **JSON RPC API-Ebene**, was dApp Entwickler verwenden, um mit der Blockchain zu interagieren. + +Es enthält Unterstützung für normale **[json-rpc Endpoints](https://eth.wiki/json-rpc/API)**, sowie für Websocket Endpoints. + +## Blockchain-Schnittstelle {#blockchain-interface} + +Das Polygon Edge verwendet die ***Blockchain Schnittstelle***, um alle Methoden zu definieren, die das JSON-RPC-Modul verwenden muss, um seine Endpoints bereitzustellen. + +Die Blockchain-Schnittstelle wird vom **[Minimal](/docs/edge/architecture/modules/minimal)** Server implementiert. Es ist die Basisimplementierung die in die JSON-RPC-Ebene übergeben wird. + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## ETH Endpoints {#eth-endpoints} + +Alle Standard JSON-RPC-Endpoints sind implementiert in: + +````bash +jsonrpc/eth_endpoint.go +```` + +## Filter-Manager {#filter-manager} + +Der **Filter Manager** ist ein Service, der neben dem JSON-RPC-Server läuft. + +Es bietet Unterstützung für das Filtern von Blöcken auf der
Blockchain. Insbesondere enthält er sowohl ein **Protokoll** als auch einen **Block** Level Filter. + +Der Filter Manager stützt sich stark auf Subscription Events, die im [Blockchain](blockchain#blockchain-subscriptions) Abschnitt + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +Filter Manager Events in der *Run* Methode ausgeliefert werden: + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## 📜 Ressourcen {#resources} +* **[Ethereum JSON-RPC](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/de-edge/architecture/modules/minimal.md b/archive/edge/de-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..4146a8b4be --- /dev/null +++ b/archive/edge/de-edge/architecture/modules/minimal.md @@ -0,0 +1,119 @@ +--- +id: minimal +title: Minimal +description: Erläuterung für das Minimalmodul von Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## Übersicht {#overview} + +Wie bereits erwähnt, besteht Polygon Edge aus einer Reihe verschiedener Module, die alle miteinander verbunden sind.
+Die **Blockchain** ist mit dem **State** verbunden, oder zum Beispiel mit der **Synchronisation**, die neue Blöcke in die **Blockchain** leitet. + +**Minimal** ist der Grundstein für diese miteinander verbundenen Module.
+Es fungiert als zentraler Knotenpunkt für alle Dienste, die auf der Polygon Edge ausgeführt werden. + +## Start-up Magic {#startup-magic} + +Minimal ist unter anderem verantwortlich für: +* Datenverzeichnisse einrichten +* Erstellen eines Keystore für die libp2p-Kommunikation +* Speicherplatz erstellen +* Konsens einrichten +* Einrichten des Blockchain-Objekts mit GRPC, JSON RPC und Synchronisierung + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/de-edge/architecture/modules/networking.md b/archive/edge/de-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..52ca68467e --- /dev/null +++ b/archive/edge/de-edge/architecture/modules/networking.md @@ -0,0 +1,80 @@ +--- +id: networking +title: Vernetzung +description: Erläuterung für das Vernetzungsmodul von Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## Übersicht {#overview} + +Ein Knotenpunkt muss mit anderen Knotenpunkten im Netzwerk kommunizieren, um nützliche Informationen
auszutauschen. +Um diese Aufgabe zu erfüllen, nutzt der Polygon Edge das bewährte **libp2p**-Framework. + +Die Entscheidung für **libp2p** fällt in erster Linie aus folgenden Gründen: +* **Geschwindigkeit**- libp2p bietet eine deutliche Leistungsverbesserung gegenüber devp2p (verwendet in GETH und anderen Clients) +* **Erweiterungsfähigkeit** – es dient als hervorragende Grundlage für andere Funktionen des Systems +* **Modularität** – libp2p ist von Natur aus modular, genau wie Polygon Edge. Dies bietet mehr Flexibilität, vor allem wenn Teile des Polygon Edge austauschbar sein müssen + +## GRPC {#grpc} + +Zusätzlich zu **libp2p** verwendet Polygon Edge das **GRPC**-Protokoll.
+Technisch gesehen verwendet Polygon Edge mehrere GRPC-Protokolle. Darauf werden wir später noch eingehen. + +Die GRPC-Schicht hilft bei der Abstraktion aller Anfrage/Antwort-Protokolle und vereinfacht die Streaming-Protokolle, die für das Funktionieren des Polygon Edge erforderlich sind. + +GRPC stützt sich auf **Protokollpuffer** zur Definition von *Services* und *Nachrichtenstrukturen*.
+Die Dienste und Strukturen sind in.*proto-*Dateien definiert, die kompiliert werden und sprachunabhängig sind. + +Wir haben bereits erwähnt, dass Polygon Edge mehrere GRPC-Protokolle nutzt.
+Damit soll die Benutzerfreundlichkeit für den Betreiber des Knotens verbessert werden, was bei Clients wie GETH und Parität oft der Fall ist. + +Der Knotenbetreiber hat einen besseren Überblick über die Vorgänge im System, wenn er den GRPC-Service aufruft, anstatt die Protokolle zu durchsuchen, um die gesuchten Informationen zu finden. + +### GRPC für Knotenbetreiber {#grpc-for-node-operators} + +Der folgende Abschnitt kommt Ihnen vielleicht bekannt vor, weil er bereits im Abschnitt [CLI-Befehle](/docs/edge/get-started/cli-commands) kurz behandelt wurde. + +Der GRPC-Service, der von **Knotenbetreibern** genutzt werden soll, ist wie folgt definiert: +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip + +Die CLI-Befehle rufen die Implementierungen dieser Servicemethoden auf. + +Diese Methoden werden in ***minimal/system_service.go***. implementiert. + +::: + +### GRPC für andere Knoten {#grpc-for-other-nodes} + +Polygon Edge implementiert auch mehrere Service-Methoden, die von anderen Knotenpunkten im Netzwerk genutzt werden.
+Der genannte Service wird im Abschnitt **[Protokoll](docs/edge/architecture/modules/consensus)** beschrieben. + +## 📜 Ressourcen {#resources} +* **[Protokollpuffer](https://developers.google.com/protocol-buffers)** +* **[libp2p](https://libp2p.io/)** +* **[gRPC](https://grpc.io/)** diff --git a/archive/edge/de-edge/architecture/modules/other-modules.md b/archive/edge/de-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..ba0788f178 --- /dev/null +++ b/archive/edge/de-edge/architecture/modules/other-modules.md @@ -0,0 +1,36 @@ +--- +id: other-modules +title: Andere Module +description: Erläuterung einiger Module von Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## Krypto {#crypto} + +Das Modul **Krypto** enthält Hilfsfunktionen für Krypto. + +## Chain {#chain} + +Das Modul **Chain** enthält Chain-Parameter (aktive Abspaltungen (Forks), Konsens-Engine usw.) + +* **Chains** – Vordefinierte Chain-Konfigurationen (mainnet, goerli, ibft) + +## Helfer {#helper} + +Das Modul **Helfer** enthält Hilfspakete. + +* **dao** – Dao utils +* **enode** – Kodier-/Dekodierfunktion aktivieren +* **hex** – Hex-Codierung/Decodierung Funktionen +* **ipc** – IPC Verbindungsfunktionen +* **keccak** – Keccak Funktionen +* **rlputil** – Rlp Kodierungs-/Dekodierungs-Hilfsfunktion + +## Befehl {#command} + +Das Modul **Befehl** enthält Schnittstellen für CLI-Befehle. \ No newline at end of file diff --git a/archive/edge/de-edge/architecture/modules/sealer.md b/archive/edge/de-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..d450e1f9cf --- /dev/null +++ b/archive/edge/de-edge/architecture/modules/sealer.md @@ -0,0 +1,71 @@ +--- +id: sealer +title: Sealer +description: Erläuterung für das Sealermodul von Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## Übersicht {#overview} + +Der **Sealer** ist eine Einheit, die die Transaktionen sammelt und einen neuen Block erstellt.
+Dann wird dieser Block an das **Consensus** Modul gesendet, um ihn zu versiegeln. + +Die endgültige Sealing-Logik befindet sich im **Consensus** Modul. + +## Ausführen der Methode {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution Laufende Arbeiten +Der **Sealer** und die **Consensus** Module werden in naher Zukunft zu einer einzigen Einheit zusammengeführt. + +Das neue Modul enthält modulare Logik für verschiedene Arten von Konsensmechanismen, die unterschiedliche Sealingmaßnahmen erfordern: +* **PoS** (Proof of Stake) +* **PoA** (Proof of Authority) + +Derzeit arbeiten die **Sealer** und die **Consensus** Module mit PoW (Proof of Work). +::: \ No newline at end of file diff --git a/archive/edge/de-edge/architecture/modules/state.md b/archive/edge/de-edge/architecture/modules/state.md new file mode 100644 index 0000000000..ba06bcf9bb --- /dev/null +++ b/archive/edge/de-edge/architecture/modules/state.md @@ -0,0 +1,247 @@ +--- +id: state +title: State +description: Erläuterung für das Zustandsmodul von Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +Um wirklich zu verstehen, wie **State** funktioniert, sollten Sie einige grundlegende Ethereum-Konzepte verstehen.
+ +Wir empfehlen, den **[Leitfaden zu State in Ethereum](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)** zu lesen. + +## Übersicht {#overview} + +Nachdem wir uns nun mit den grundlegenden Ethereum-Konzepten vertraut gemacht haben, sollte der nächste Überblick einfach sein. + +Wir haben erwähnt, dass der **World State Trie** alle Ethereum-Konten hat, die es
gibt. Diese Konten sind die Blätter des Merkle Tries (Datenstruktur). Jedes Blatt enthält kodierte **Informationen zum Kontostatus**. + +So kann der Polygon Edge einen bestimmten Merkle Trie für einen bestimmten Zeitpunkt erhalten.
+Wir können zum Beispiel den Hash des State in Block 10 erhalten. + +Der Merkle Trie wird zu jedem Zeitpunkt als ***Snapshot*** bezeichnet. + +Wir können ***Snapshots*** für die **State-Trie** (Kerndatenbank) oder für die **Storage-Trie** (Datenstruktur zum Speichern) haben – sie sind im Grunde das Gleiche.
+Der einzige Unterschied besteht darin, was die Blätter darstellen: + +* Im Fall des Storage-Tries enthalten die Blätter einen beliebigen Zustand, den wir nicht verarbeiten können und von dem wir nicht wissen, was er enthält +* Im Fall des State-Tries stehen die Blätter für Konten + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + +Die Schnittstelle **Snapshot** ist als solche definiert: + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +Die Informationen, die übertragen werden können, werden in der *Objekt-Struktur* definiert: + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +Die Implementierung für den Merkle-Trie befindet sich im *Ordner State/Immutable-Trie*.
+*state/immutable-trie/state.go* implementiert die **State** Schnittstelle. + +*state/immutable-trie/trie.go* ist das wichtigste Merkle-Trie-Objekt. Es stellt eine optimierte Version des Merkle-Tries dar, +die so viel Speicher wie möglich wiederverwendet. + +## Executor {#executor} + +*state/executor.go* enthält alle Informationen, die Polygon Edge braucht, um zu entscheiden, wie ein Block den aktuellen Zustand +verändert. Die Implementierung von *ProcessBlock* befindet sich hier. + +Die *Apply* Methode führt den eigentlichen Zustandsübergang durch. Der Executor ruft die EVM (Ethereum Virtual Machine) auf. + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## Laufzeit {#runtime} + +Wenn ein Zustandsübergang ausgeführt wird, ist das Hauptmodul, das den Zustandsübergang ausführt, die EVM (befindet sich in +state/runtime/evm). + +Die **Dispatch-Tabelle** führt einen Abgleich zwischen dem **Opcode** und der Anweisung durch. + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +Die Hauptlogik, die die EVM antreibt, ist die *Run*-Schleife.
+ +Dies ist der Haupteinstiegspunkt für die EVM. Er macht eine Schleife und prüft den aktuellen Opcode, holt die Anweisung, prüft, +ob sie ausgeführt werden kann, verbraucht Gas und führt die Anweisung aus, bis sie entweder fehlschlägt oder stoppt. + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/de-edge/architecture/modules/storage.md b/archive/edge/de-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..b900852454 --- /dev/null +++ b/archive/edge/de-edge/architecture/modules/storage.md @@ -0,0 +1,116 @@ +--- +id: storage +title: Speicher +description: Erläuterung für das Speichermodul von Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## Übersicht {#overview} + +Der Polygon Edge verwendet derzeit **LevelDB** für die Datenspeicherung sowie einen **in-memory** Datenspeicher. + +Im gesamten Polygon Edge, wenn Module mit dem zugrundeliegenden Datenspeicher interagieren müssen, müssen sie nicht wissen, mit welcher DB-Engine oder -Dienstleistung, sie kommunizieren. + +Die DB-Ebene wird zwischen einem Modul namens **Speicher** abstrahiert, das Schnittstellen exportiert, die Module abfragen. + +Jede **DB-Ebene**implementiert diese Methoden separat und stellt sicher, dass sie in ihre Implementierung passen. + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### Prefixes {#prefixes} + +Um den LevelDB-Speicher abzufragen und um das Zusammenstecken von Schlüsselspeichern zu vermeiden, nutzt Polygon Edge Prefixes und Sub-prefixes beim Speichern von Daten + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## Zukünftige Pläne {#future-plans} + +Die Pläne für die nahe Zukunft umfassen das Hinzufügen einiger der beliebtesten DB-Lösungen, wie z.B.: +* PostgreSQL +* MySQL + + +## 📜 Ressourcen {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/de-edge/architecture/modules/syncer.md b/archive/edge/de-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..0f422bd2f9 --- /dev/null +++ b/archive/edge/de-edge/architecture/modules/syncer.md @@ -0,0 +1,64 @@ +--- +id: syncer +title: Syncer +description: Erläuterung für das Syncermodul von Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## Übersicht {#overview} + +Dieses Modul enthält die Logik für das Synchronisationsprotokoll. Es wird verwendet, um einen neuen Knoten mit dem laufenden Netzwerk zu synchronisieren oder neue Blöcke für die Knoten zu validieren, die nicht am Konsens teilnehmen (non-validators). + +Der Polygon Edge verwendet **libp2p** als Netzwerkebene und läuft darüber hinaus mit **gRPC**. + +Es gibt im Wesentlichen 2 sync in Polygon Edge: +* Bulk Sync – synchronisieren eine große Reihe von Blöcken gleichzeitig +* Watch Sync – Sync auf einer per-block-Basis synchronisieren + +### Bulk Sync {#bulk-sync} + +Die Schritte für die Massensynchronisierung sind ziemlich einfach, um dem Ziel der Massensynchronisierung gerecht zu werden – so viele Blöcke wie möglich (verfügbar) vom anderen Peer zu synchronisieren, um schnellstmöglich aufzuschließen. + +Der Ablauf Massensynchronisierung: + +1. ** Feststellen, ob der Knoten Massensynchronisierung durchführen muss ** – In diesem Schritt überprüft der Knoten die Peer um zu sehen, ob es jemand gibt, der eine größere Blocknummer hat als das, was der Knoten lokal hat +2. ** Suche nach dem besten Peer (unter Verwendung der Sync-Peer-Map) ** – In diesem Schritt findet der Knoten den besten Peer für die Synchronisierung auf der Grundlage der im obigen Beispiel genannten Kriterien. +3. ** Öffnen eines Bulk-Sync-Streams ** – In diesem Schritt öffnet der Knoten einen gRPC-Stream für den besten Peer, um Blöcke aus der gemeinsamen Blocknummer zu synchronisieren +4. ** Der beste Peer schließt den Stream, wenn er alle Blöcke gesendet hat ** – In diesem Schritt schließt der beste Peer, mit dem der Knoten synchronisiert, den Stream, sobald er alle verfügbaren Blöcke gesendet hat. +5. ** Nach der Massensynchronisierung prüfen, ob der Knoten ein Validierer ist ** – In diesem Schritt wird der Stream vom besten Peer geschlossen, und der Knoten muss prüfen, ob er nach der Massensynchronisierung ein Validierer ist. + * Wenn das der Fall ist, verlassen sie den Synchronisationszustand und beginnen, sich am Konsens zu beteiligen. + * Ist das nicht der Fall, beobachten sie weiterhin die ** Synchronisierung ** + +### Watch Sync {#watch-sync} + +:::info +Der Schritt für Watch Syncing wird nur ausgeführt, wenn der Knoten kein Validator ist, sondern ein normaler Nicht-Validator-Knoten im Netzwerk, der nur auf ankommende Blöcke wartet. +::: + +Das Verhalten von Watch Sync ist ziemlich einfach, der Knoten ist bereits mit dem Rest des Netzwerks synchronisiert und muss nur neue Blöcke analysieren, die hereinkommen. + +So funktioniert die Synchronisierung: + +1. ** Hinzufügen eines neuen Blocks, wenn der Status eines Peers aktualisiert wird ** – In diesem Schritt warten die Knoten auf die neuen Block-Ereignisse. Wenn ein neuer Block vorliegt, wird ein gRPC-Funktionsaufruf ausgeführt, der Block abgerufen und der lokale Status aktualisiert. +2. ** Prüfen, ob der Knoten ein Validator ist, nachdem der letzte Block synchronisiert wurde ** + * Falls ja, den Sync State verlassen + * Wenn es nicht so ist, weiter auf neue Blockevents warten + +## Leistungsbericht {#perfomance-report} + +:::info +Leistung wurde auf einer lokalen Maschine durch die Syncing von ** Millionen Blöcke ** gemessen. +::: + +| Name | Ergebnis | +|----------------------|----------------| +| Syncing von 1M Blöcken | ~ 25 min | +| Transfer von 1M Blöcke | ~ 1 min | +| Anzahl der GRPC-Aufrufe | 2 | +| Testabdeckung | ~ 93 % | \ No newline at end of file diff --git a/archive/edge/de-edge/architecture/modules/txpool.md b/archive/edge/de-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..747623c29b --- /dev/null +++ b/archive/edge/de-edge/architecture/modules/txpool.md @@ -0,0 +1,230 @@ +--- +id: txpool +title: TxPool +description: Erläuterung für das TxPool-Modul von Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## Übersicht {#overview} + +Das TxPool-Modul stellt die Implementierung des Transaktionspools dar, in dem Transaktionen aus verschiedenen Teilen +des Systems hinzugefügt werden. Das Modul bietet auch einige nützliche Funktionen für Knotenbetreiber, die im Folgenden beschrieben werden. + +## Bedienerbefehle {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +Die Knotenbetreiber können diese GRPC-Endpunkte abfragen, wie im Abschnitt **[CLI-Befehle](/docs/edge/get-started/cli-commands#transaction-pool-commands)** beschrieben. + +## Verarbeitung von Transaktionen {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +Die ***addImpl*** Methode ist das A und O des **TxPool**-Moduls. Es ist der zentrale Ort, an dem Transaktionen im System hinzugefügt werden. Er wird vom GRPC-Service, von JSON-RPC-Endpunkten, +und immer dann aufgerufen, wenn der Client eine Transaktion über das **Gossip**-Protokoll erhält. + +Als Argument wird **ctx** verwendet, das den Kontext angibt, aus dem die Transaktionen hinzugefügt werden (GRPC, JSON RPC...).
+Der andere Parameter sind die Liste der Transaktionen, die dem Pool hinzugefügt werden sollen. + +Der hier zu beachtende Key ist die Prüfung des **Von** Feldes innerhalb der Transaktion: +* Wenn das **Von** Feld **leer** ist, wird es als unverschlüsselte/unsignierte Transaktion betrachtet. Diese Arten von Transaktionen werden nur +im Entwicklungsmodus akzeptiert +* Wenn das **Von** Feld **nicht leer** ist, bedeutet das, dass es sich um eine signierte Transaktion handelt, also findet eine Signaturprüfung statt + +Nach all diesen Prüfungen gelten die Transaktionen als gültig. + +## Datenstrukturen {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +Die Felder im TxPool-Objekt, die für Verwirrung sorgen können, sind **Warteschlange** und **sortierte** Listen. +* **Warteschlange** – Heap-Implementierung einer sortierten Liste von Kontobewegungen (nach Nonce) +* **sortiert** – Sortierte Liste für alle aktuell beförderten Vorgänge (alle ausführbaren Vorgänge). Sortiert nach Gaspreis + +## Gaslimit-Fehlermanagement {#gas-limit-error-management} + +Wenn Sie eine Transaktion einreichen, gibt es drei Möglichkeiten, wie sie vom TxPool verarbeitet werden kann. + +1. Alle anstehenden Transaktionen können in einen Block passen +2. Eine oder mehrere anstehende Transaktionen können nicht in einen Block passen +3. Eine oder mehrere anstehende Transaktionen werden niemals in einen Block passen + +Hier bedeutet das Wort **_passen_**, dass die Transaktion ein Gaslimit hat, das niedriger ist als das verbleibende Gas im TxPool. + +Das erste Szenario verursacht keinen Fehler. + +### Zweites Szenario {#second-scenario} + +- Das verbleibende Gas im TxPool wird auf das Gaslimit des letzten Blocks gesetzt, z.B. **5000** +- Eine erste Transaktion verarbeitet und verbraucht **3000** Gas aus dem TxPool + - Das restliche Gas des TxPool beträgt jetzt **2000** +- Eine zweite Transaktion, die dieselbe ist wie die erste – beide verbrauchen 3000 Einheiten Gas – wird eingereicht +- Da das verbleibende Gas des TxPools **niedriger** ist als das Transaktionsgas, kann es im aktuellen +Block nicht verarbeitet werden + - Es wird in eine Warteschlange für ausstehende Transaktionen zurückgestellt, damit es im nächsten Block bearbeitet werden kann +- Der erste Block ist fertig – nennen wir ihn **Block #1** +- Das verbleibende TxPool-Gas wird auf das Gaslimit des übergeordneten Blocks gesetzt – **Block #1** +- Die Transaktion, die in die TxPool-Warteschlange für ausstehende Transaktionen zurückgestellt wurde, wird nun verarbeitet und in den Block geschrieben + - Das verbleibende TxPool Gas beträgt jetzt **2000** +- Der zweite Block ist geschrieben +- ... + +![TxPool Fehler-Szenario #1](/img/edge/txpool-error-1.png) + +### Drittes Szenario {#third-scenario} +- Das verbleibende Gas im TxPool wird auf das Gaslimit des letzten Blocks gesetzt, z.B. **5000** +- Eine erste Transaktion verarbeitet und verbraucht **3000** Gas aus dem TxPool + - Das restliche Gas des TxPool beträgt jetzt **2000** +- Eine zweite Transaktion mit einem Gasfeld auf **6000** wird eingereicht +- Da das Blockgaslimit **niedriger** ist als das Transaktionsgas, wird diese Transaktion verworfen + - Es wird niemals in einen Block passen +- Der erste Block ist geschrieben +- ... + + +![TxPool Fehler-Szenario #2](/img/edge/txpool-error-2.png) + +> Folgendes kann passieren, wenn der nachfolgenden Fehler auftritt: +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## Blockgas-Ziel {#block-gas-target} + +Es gibt Situationen, in denen die Knoten das Blockgaslimit in einer laufenden Chain unter oder bei einem bestimmten Zielwert halten wollen. + +Der Knotenbetreiber kann das Zielgaslimit für einen bestimmten Knoten festlegen, der dann versucht, dieses Limit auf neu erstellte Blöcke anzuwenden. +Wenn die Mehrheit der anderen Knoten ein ähnliches (oder gleiches) Zielgaslimit festgelegt hat, wird sich das Blockgaslimit immer um dieses Blockgas-Ziel +herum bewegen und sich langsam darauf zubewegen (bei maximal)`1/1024 * parent block gas limit`, wenn neue Blöcke erstellt werden. + +### Beispiel-Szenario {#example-scenario} + +* Der Knotenbetreiber legt das Blockgaslimit für einen einzelnen Knoten auf den Wert `5000`fest +* Andere Knoten sind ebenfalls als `5000`konfiguriert, mit Ausnahme eines einzelnen Knotens, der als k`7000`onfiguriert ist. +* Wenn die Knoten, die ihr Gasziel auf `5000`gesetzt haben, Antragsteller werden, prüfen sie, ob das Gaslimit bereits das Ziel erreicht hat +* Wenn das Gaslimit nicht auf dem Zielwert liegt (es ist größer/kleiner), setzt der Antragsknoten das Blockgas-Ziel auf höchstens (1/1024 * übergeordnetes Gaslimit) in Richtung des Ziels + 1. z. B.:`parentGasLimit = 4500` und `blockGasTarget = 5000` berechnet der Antragsteller das Gaslimit für den neuen Block wie folgt (`4504.39453125`)`4500/1024 + 4500` + 2. z. B.:`parentGasLimit = 5500` und `blockGasTarget = 5000` berechnet der Antragsteller das Gaslimit für den neuen Block wie folgt (`5494.62890625`)`5500 - 5500/1024` +* Dies stellt sicher, dass das Blockgaslimit in der Chain auf dem Zielwert gehalten wird, da der einzelne Antragsteller, der den Zielwert auf `7000`konfiguriert hat, den Grenzwert nicht wesentlich erhöhen kann, und die Mehrheit +der Knoten, die den Wert auf `5000`eingestellt haben, immer versuchen wird, ihn auf diesem Wert zu halten \ No newline at end of file diff --git a/archive/edge/de-edge/architecture/modules/types.md b/archive/edge/de-edge/architecture/modules/types.md new file mode 100644 index 0000000000..17953be8ab --- /dev/null +++ b/archive/edge/de-edge/architecture/modules/types.md @@ -0,0 +1,39 @@ +--- +id: types +title: Arten +description: Erläuterung für das Types Modul von Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## Übersicht {#overview} + +Das **Types** Modul implementiert core Objektarten, wie z. B.: + +* **Adresse** +* **Hash** +* **Header** +* viele Helferfunktionen + +## RLP Encoding / Decoding {#rlp-encoding-decoding} + +Anders als Clients wie GETH verwendet der Polygon Edge keine Reflexion für die Codierung.
Die Präferenz war, die Reflexion nicht zu verwenden, da sie neue Probleme, wie z. B. die Leistung, Abbau, und härtere Skalierung mit sich bringt. + +Das **Types** Modul bietet eine einfach zu bedienende Schnittstelle für RLP Marshaling und Unmarshalling, mit dem FastRLP Paket. + +Marshaling wird durch die *MarshalRLPWith* und *MarshalRLPTo* durchgeführt. Die analogen Methoden existieren für Unmarshalling. + +Indem er diese Methoden manuell definiert, muss Polygon Edge keine Reflexion verwenden. In *rlp_marshal.go* können Sie Methoden für Marshaling finden: + +* **Bodies** +* **Blöcke** +* **Headers** +* **Receipts** +* **Logs** +* **Transactions** \ No newline at end of file diff --git a/archive/edge/de-edge/architecture/overview.md b/archive/edge/de-edge/architecture/overview.md new file mode 100644 index 0000000000..51b114ea61 --- /dev/null +++ b/archive/edge/de-edge/architecture/overview.md @@ -0,0 +1,60 @@ +--- +id: overview +title: Übersicht über die Architektur +sidebar_label: Overview +description: Einführung in die Architektur von Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +Wir begannen mit der Erstellung einer *modularen* Software. + +Dies ist etwas, was in fast allen Teilen des Polygon Edge vorhanden ist. Nachstehend eine Kurzübersicht über die integrierte Architektur und das Layering. + +## Polygon Edge Layering {#polygon-edge-layering} + +![Polygon Edge Architektur](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +Alles beginnt mit der grundlegenden Netzwerkschicht, die **libp2p** verwendet. Wir haben uns für diese Technologie entschieden, weil sie in die Designphilosophie von Polygon Edge passt. Libp2p ist: + +- Modular +- Erweiterbar +- Schnell + +Am wichtigsten ist, es bietet eine großartige Grundlage für mehr fortgeschrittene Funktionen, die wir später abdecken werden. + + +## Synchronisation & Konsens {#synchronization-consensus} +Die Trennung der Synchronisation und des Consensus Protokolls ermöglicht die Modularität und Implementierung von **benutzerdefinierten** Sync und Konsensmechanismen – je nachdem, wie der Client ausgeführt wird. + +Polygon Edge ist so konzipiert, dass es standardmäßig einsteckbare Konsensalgorithmen bietet. + +Die aktuelle Liste der unterstützten Konsens-Algorithmen: + +* IBFT PoA +* IBFT PoS + +## Blockchain {#blockchain} +Die Blockchain Layer ist die zentrale Ebene, die alles im Polygon Edge koordiniert. Es wird ausführlich im entsprechenden *Modul*abschnitt behandelt. + +## State {#state} +Die Innenschicht State enthält die Statusübergangslogik. +Es geht darum, wie sich der Zustand ändert, wenn ein neuer Block aufgenommen wird. Es wird ausführlich im entsprechenden *Modul*abschnitt behandelt. + +## JSON RPC {#json-rpc} +Die JSON RPC ist eine API-Ebene, die dApp Entwickler verwenden, um mit der Blockchain zu interagieren. Es wird ausführlich im entsprechenden *Modul*abschnitt behandelt. + +## TxPool {#txpool} +Die TxPool Layer repräsentiert den Transaktionspool, und es ist eng mit anderen Modulen im System verknüpft, da Transaktionen von mehreren Einstiegspunkten hinzugefügt werden können. + +## GRPC {#grpc} +gRPC oder Google Remote Procedure Call ist ein robustes gRPC, das ursprünglich erstellt wurde, um skalierbare und schnelle APIs zu erstellen. Die GRPC-Schicht ist für die Interaktion mit dem Operator unerlässlich. Durch sie können Knoten unkompliziert mit dem Client interagieren, was eine angenehme UX bietet. diff --git a/archive/edge/de-edge/community/propose-new-feature.md b/archive/edge/de-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..81ac4a9b39 --- /dev/null +++ b/archive/edge/de-edge/community/propose-new-feature.md @@ -0,0 +1,60 @@ +--- +id: propose-new-feature +title: Ein neues Feature vorschlagen +description: "PR-Vorlage und Anleitung für den Vorschlag eines neuen Features." +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## Übersicht {#overview} + +Wenn du einen Fehler beheben oder einfach etwas zum Code beitragen möchtest, sollten Sie sich zuerst mit dem Team in Verbindung setzen.
+Polygon Edge verwendet eine relativ einfache Vorlage für Feature-Vorschläge, die präzise und treffend sind. + +## PR-Vorlage {#pr-template} + +### Beschreibung {#description} + +Beschreiben Sie ausführlich, was in dieser PR gemacht wurde + +### Änderungen beinhalten {#changes-include} + +- [ ] Bugfix (nicht unterbrochene Änderung, die ein Problem behebt) +- [ ] Hotfix (Änderung, die ein dringendes Problem löst und sofortige Aufmerksamkeit erfordert) +- [ ] Neues Feature (nicht unterbrochene Änderung, die die Funktion erweitert) +- [ ] Breaking Change (Änderung, die nicht abwärtskompatibel ist und/oder die aktuelle Funktionalität verändert) + +### Breaking Changes {#breaking-changes} + +Bitte füllen Sie diesen Abschnitt aus, wenn Sie Breaking Changes vorgenommen haben, andernfalls löschen. + +### Checkliste {#checklist} + +- [ ] Ich habe mir diese PR zugewiesen +- [ ] Ich habe mindestens 1 Überprüfer hinzugefügt +- [ ] Ich habe die relevanten Labels hinzugefügt +- [ ] Ich habe die offizielle Dokumentation aktualisiert +- [ ] Ich habe eine ausreichende Dokumentation im Code hinzugefügt + +### Testen {#testing} + +- [ ] Ich habe diesen Code mit der offiziellen Test-Suite getestet +- [ ] Ich habe diesen Code manuell getestet + +## Manuelle Tests {#manual-tests} + +Bitte füllen Sie diesen Abschnitt aus, wenn Sie manuelle Tests für diese Funktion durchgeführt haben, andernfalls löschen + +### Dokumentations-Update {#documentation-update} + +Bitte verlinken Sie die Dokumentations-Update-PR in diesem Abschnitt, wenn er vorhanden ist, andernfalls löschen + +### Zusätzliche Kommentare {#additional-comments} + +Wenn Sie zusätzliche Kommentare haben, in diesem Abschnitt veröffentlichen, andernfalls löschen \ No newline at end of file diff --git a/archive/edge/de-edge/community/report-bug.md b/archive/edge/de-edge/community/report-bug.md new file mode 100644 index 0000000000..341ce39afa --- /dev/null +++ b/archive/edge/de-edge/community/report-bug.md @@ -0,0 +1,53 @@ +--- +id: report-bug +title: Melde ein Problem +description: Vorlage und Anweisungen für die Problemmeldung bei Polygon Edge +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## Übersicht {#overview} + +Manchmal geht etwas
schief. Es ist immer besser, das Team über alle Probleme zu informieren, die auftreten
können. Auf der Polygon Edge GitHub können Sie ein neues Problem einreichen und es mit dem Team besprechen. + +## Vorlage für ein Problem {#issue-template} + +## [Gegenstand des Problems] + +### Beschreibung {#description} + +Beschreiben Sie ihr Problem so ausführlich wie möglich + +### Ihre Umgebung {#your-environment} + +* OS und Version +* Version des Polygon Edge +* Bereich, die dieses Problem verursacht + +### Schritte zur Reproduktion {#steps-to-reproduce} + +* Informieren Sie uns, wie
man dieses Problem reproduzieren kann +* Wo das Problem besteht, sofern bekannt
+* Welche Befehle ggfs. das Problem ausgelöst haben + +### Erwartetes Verhalten {#expected-behaviour} + +Teilen Sie uns mit, was passieren sollte + +### Tatsächliches Verhalten {#actual-behaviour} + +Teilen Sie uns mit, was stattdessen geschieht + +### Protokolle {#logs} + +Bitte fügen Sie hier alle Protokolle ein, die das Problem aufzeigen, sofern sie vorhanden sind + +### Vorgeschlagene Lösung {#proposed-solution} + +Wenn Sie eine Lösung für dieses Problem haben, schreiben Sie sie bitte hier auf, damit wir darüber diskutieren können \ No newline at end of file diff --git a/archive/edge/de-edge/configuration/manage-private-keys.md b/archive/edge/de-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..ea132db181 --- /dev/null +++ b/archive/edge/de-edge/configuration/manage-private-keys.md @@ -0,0 +1,79 @@ +--- +id: manage-private-keys +title: Private Keys verwalten +description: "Wie man Private Keys verwaltet und welche Arten von Keys es gibt." +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## Übersicht {#overview} + +Der Polygon Edge hat zwei Arten von private Keys, die direkt verwaltet werden: + +* **Private Key, der für den Konsensmechanismus verwendet wird** +* **Private Key für die Vernetzung von libp2p** +* **(Optional) BLS Private Key, der für den Konsensmechanismus verwendet wird, um die Signaturen der Prüfer zusammenzufassen** + +Derzeit bietet der Polygon Edge keine Unterstützung für die direkte Kontoführung. + +Basierend auf der im [Leitfaden Backup & Restore](/docs/edge/working-with-node/backup-restore) beschriebenen Verzeichnisstruktur speichert der Polygon Edge +die erwähnten Schlüsseldateien in zwei verschiedenen Verzeichnissen – **Konsens** und **Keystore**. + +## Key-Format {#key-format} + +Die Private Keys werden im einfachen **Base64-Format** gespeichert, damit sie für Menschen lesbar und übertragbar sind. + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info Schlüsseltyp + +Alle Private Key-Dateien, die innerhalb von Polygon Edge erzeugt und verwendet werden, basieren auf ECDSA mit der Kurve [secp256k1](https://en.bitcoin.it/wiki/Secp256k1). + +Da die Kurve nicht standardisiert ist, kann sie nicht in einem standardisierten PEM-Format kodiert und gespeichert werden. +Der Import von Keys, die nicht mit diesem Key-Typ übereinstimmen, wird nicht unterstützt. + +::: +## Konsens Private Key {#consensus-private-key} + +Die Private Key-Datei, die als *Konsens Private Key* bezeichnet wird, wird auch als **Validator Private Key** bezeichnet. +Dieser Private Key wird verwendet, wenn der Knoten als Validator im Netzwerk fungiert und neue Daten signieren muss. + +Die Private Key-Datei befindet sich in `consensus/validator.key`und entspricht dem erwähnten [Key-Format.](/docs/edge/configuration/manage-private-keys#key-format) + +:::warning + +Der Private Key der Prüfer ist für jeden Prüferknoten einmalig. Der gleiche Key darf nicht für alle Validatoren verwendet werden, da dies die Sicherheit Ihrer Chain gefährden könnte. + +::: + +## Private Key vernetzen {#networking-private-key} + +Die für die Vernetzung erwähnte Private Key-Datei wird von libp2p verwendet, um die entsprechende PeerID zu generieren und dem Knoten die Teilnahme am Netzwerk zu ermöglichen. + +Sie befindet sich in `keystore/libp2p.key`und hält sich an das erwähnte K[ey-Format.](/docs/edge/configuration/manage-private-keys#key-format) + +## BLS Secret Key {#bls-secret-key} + +Die geheime BLS Key-Datei wird verwendet, um die zugesagten Siegel in der Konsensschicht zusammenzufassen. Die Größe der aggregierten BLS-Siegel ist geringer als die der seriellen ECDSA-Signaturen. + +Die BLS-Funktion ist optional und Sie können wählen, ob Sie BLS verwenden möchten oder nicht. Mehr Details unter [BLS](/docs/edge/consensus/bls). + +## Import / Export {#import-export} + +Da die Key-Dateien im einfachen Base64-Format auf der Festplatte gespeichert werden, können sie leicht gesichert oder importiert werden. + +:::caution Ändern der Key-Dateien + +Jede Änderung der Key-Dateien in einem bereits eingerichteten/laufenden Netzwerk kann zu ernsthaften Netzwerk-/Konsensstörungen führen, +da die Konsens- und Peer-Discovery-Mechanismen die von diesen Keys abgeleiteten Daten in einem knotenspezifischen Speicher ablegen und sich auf diese Daten verlassen, +um Verbindungen zu initiieren und die Konsenslogik auszuführen + +::: \ No newline at end of file diff --git a/archive/edge/de-edge/configuration/prometheus-metrics.md b/archive/edge/de-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..ef789e0c9b --- /dev/null +++ b/archive/edge/de-edge/configuration/prometheus-metrics.md @@ -0,0 +1,35 @@ +--- +id: prometheus-metrics +title: Prometheus-Metriken +description: "Wie Sie Prometheus-Metriken für Polygon Edge aktivieren." +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## Übersicht {#overview} + +Polygon Edge kann die Prometheus-Metriken melden und bereitstellen, die wiederum mit Prometheus-Collector(s) verwendet werden können. + +Prometheus-Metriken sind standardmäßig deaktiviert. Es kann aktiviert werden, indem die Listener-Adresse über eine `--prometheus`Flagge oder einem `Telemetry.prometheus`Feld in der Konfigurationsdatei angegeben wird. +Metriken werden unter `/metrics`auf die angegebene Adresse zugestellt. + +## Verfügbare Metriken {#available-metrics} + +Folgende Metriken sind verfügbar: + +| **Name** | **Art** | **Beschreibung** | +|-----------------------------------------------|---------------|-------------------------------------------------| +| txpool_pending_transactions | Messgerät | Anzahl ausstehender Transaktionen in TxPool | +| consensus_validators | Messgerät | Anzahl der Validatoren | +| consensus_rounds | Messgerät | Anzahl der Runden | +| consensus_num_txs | Messgerät | Anzahl der Transaktionen im neuesten Block | +| consensus_block_interval | Messgerät | Zeit zwischen diesem und dem letzten Block in Sekunden | +| network_peers | Messgerät | Anzahl verbundener Peers | +| network_outbound_connections_count | Messgerät | Anzahl ausgehender Verbindungen | +| network_inbound_connections_count | Messgerät | Anzahl eingehender Verbindungen | +| network_pending_outbound_connections_count | Messgerät | Anzahl ausstehender ausgehender Verbindungen | +| network_pending_inbound_connections_count | Messgerät | Anzahl ausstehender eingehender Verbindungen | \ No newline at end of file diff --git a/archive/edge/de-edge/configuration/sample-config.md b/archive/edge/de-edge/configuration/sample-config.md new file mode 100644 index 0000000000..f5cd3fbf6b --- /dev/null +++ b/archive/edge/de-edge/configuration/sample-config.md @@ -0,0 +1,151 @@ +--- +id: sample-config +title: Server-Konfigurationsdatei +description: "Starte den Polygon Edge-Server mithilfe einer Konfigurationsdatei." +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# Server-Konfigurationsdatei {#server-configuration-file} +Das Starten des Servers mit verschiedenen Konfigurationsoptionen kann über eine Konfigurationsdatei erfolgen, anstatt nur über Flags. +Der Befehl, mit dem der Server mit einer Konfigurationsdatei gestartet wird: `polygon-edge server --config ` + +## Konfigurationsdatei mit Standardkonfiguration exportieren {#export-config-file-with-default-configuration} +Die Konfiguration mit den Standardeinstellungen für den Polygon Edge-Server kann in eine Konfigurationsdatei im `yaml`oder `json`Dateiformat exportiert werden. +Diese Datei kann als Vorlage für den Betrieb des Servers mit einer Konfigurationsdatei verwendet werden. + +### YAML {#yaml} +Erstellen der Konfigurationsdatei im `yaml`-Format: +```bash +polygon-edge server export --type yaml +``` +oder nur +```bash +polygon-edge server export +``` +die Konfigurationsdatei mit dem Namen `default-config.yaml`wird in demselben Verzeichnis erstellt, von dem dieser Befehl ausgeführt wurde. + +Dateibeispiel: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +Erstellen der Konfigurationsdatei im `json`-Format: +```bash +polygon-edge server export --type json +``` +die Konfigurationsdatei mit dem Namen `default-config.json`wird in demselben Verzeichnis erstellt, von dem dieser Befehl ausgeführt wurde. + +Dateibeispiel: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +Im Abschnitt [CLI-Befehle](/docs/edge/get-started/cli-commands) erfahren Sie, wie Sie diese Parameter verwenden können. + +### Typoscript-Schema {#typescript-schema} + +Im Folgenden finden Sie ein Beispiel für das Format der Konfigurationsdatei. Es ist in TypeScript geschrieben, um die Eigenschaftstypen (`string`, `number`,)`boolean` auszudrücken, von denen Sie ihre Konfiguration ableiten können. Erwähnenswert ist, dass der `PartialDeep`Typ von v`type-fest`erwendet wird, um auszudrücken, dass alle Eigenschaften optional sind. + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/de-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/de-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..1055c5daac --- /dev/null +++ b/archive/edge/de-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,119 @@ +--- +id: set-up-aws-ssm +title: Richte AWS SSM (Systems Manager) ein +description: "Richte AWS SSM (Systems Manager) für Polygon Edge ein." +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## Übersicht {#overview} + +Derzeit ist der Polygon Edge damit beschäftigt, 2 wichtige Laufzeitgeheimnisse zu bewahren: +* Der vom Knoten benutzte **Validator Private Key**, wenn der Knoten ein Validator ist +* Der **Networking Private Key** verwendet von libp2p, für die Teilnahme und die Kommunikation mit anderen Peers + +Für weitere Informationen siehe Leitfaden zur [Verwaltung von Private Keys](/docs/edge/configuration/manage-private-keys) + +Die Module des Polygon Edge **sollten nicht wissen müssen, wie Geheimhaltung funktioniert**. Letztlich sollte sich ein Modul nicht kümmern, wenn ein Geheimnis auf einem fernen Server oder lokal auf der Festplatte des Knoten gespeichert wird. + +Alles, was ein Modul über Geheimhaltung wissen muss, ist, **das Geheimnis zu verwenden**, **zu wissen, welche Geheimnisse beizubehalten oder zu speichern sind**. Die feineren Implementierungsdetails dieser Operationen werden zu `SecretsManager`delegiert, was natürlich eine Abstraktion ist. + +Der Knotenbetreiber, der den Polygon Edge startet, kann jetzt angeben, welche Secrets Manager sie verwenden möchten, da der richtige Secrets Manager instantiiert wird, behandeln die Module die Geheimnisse über die erwähnte Schnittstelle ohne sich zu kümmern, ob die Geheimnisse auf einer Festplatte oder auf einem Server gespeichert werden. + +Dieser Artikel beschreibt die notwendigen Schritte, um Polygon Edge mit dem [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) in Betrieb zu nehmen. + +:::info Bisherige Anleitungen +Es wird **dringend empfohlen**, ehe Sie diesen Artikel durchgehen, Artikel auf [**Local Setup**](/docs/edge/get-started/set-up-ibft-locally), sowie [**Cloud Setup**](/docs/edge/get-started/set-up-ibft-on-the-cloud) zu lesen. +::: + + +## Voraussetzungen {#prerequisites} +### IAM Richtlinie {#iam-policy} +Der Benutzer muss eine IAM-Richtlinie erstellen, die Lese- und Schreibvorgänge für den AWS Systems Manager Parameter Store zulässt. Nachdem die IAM-Richtlinie erfolgreich erstellt wurde, muss der Benutzer sie an die EC2-Instanz anhängen, auf der der Polygon Edge-Server läuft. Die IAM-Richtlinie sollte etwa so aussehen: +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +Weitere Informationen zu AWS SSM IAM Rollen unter[AWS Docs](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html). + +Erforderliche Informationen ehe Sie fortfahren: +* **Region** (die Region, in der sich Systems Manager und Knoten befinden) +* **Parameterpfad** (beliebiger Pfad, in dem das Geheimnis platziert wird, zum Beispiel`/polygon-edge/nodes`) + +## Schritt 1 - Generiere die Secrets Manager Konfiguration {#step-1-generate-the-secrets-manager-configuration} + +Damit der Polygon Edge nahtlos mit dem AWS SSM kommunizieren kann, muss er eine bereits generierte config Datei analysieren, die alle notwendigen Informationen für die geheime Speicherung auf AWS SSM enthält. + +Um die Konfiguration zu generieren, führen Sie den folgenden Befehl aus: + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +Vorhandene Parameter: +* `PATH`ist der Pfad, in den die Konfigurationsdatei exportiert werden sollte. Standard`./secretsManagerConfig.json` +* `NODE_NAME`ist der Name des aktuellen Knotens, für den die AWS SSM Konfiguration eingerichtet wird. Es kann ein beliebiger Wert sein. Standard`polygon-edge-node` +* `REGION`ist die Region, in der sich der AWS SSM befindet. Dies muss die gleiche Region sein wie der Knoten mit AWS SSM. +* `SSM_PARAM_PATH`ist der Name des Pfads, in dem das Geheimnis gespeichert wird. Zum Beispiel, wenn u`--name node1``ssm-parameter-path=/polygon-edge/nodes`nd werden angegeben, wird das Geheimnis als`/polygon-edge/nodes/node1/` gespeichert + +:::caution Knoten-Namen +Vorsicht bei der Angabe von Knoten-Namen. + +Der Polygon Edge verwendet den angegebenen Knotennamen, um die Geheimnisse zu verfolgen, die er generiert, und die er auf dem AWS SSM verwendet. Die Angabe eines vorhandenen Knotennamens kann dazu führen, dass das Geheimnis nicht in AWS SSM geschrieben werden kann. + +Secrets werden auf dem folgenden Basispfad `SSM_PARAM_PATH/NODE_NAME`gespeichert: +::: + +## Schritt 2 - Initialisieren der Geheimschlüssel mit der Konfiguration {#step-2-initialize-secret-keys-using-the-configuration} + +Nun, da die Konfigurationsdatei vorhanden ist, können wir die erforderlichen Geheimschlüssel mit der Konfiguration initialisieren Datei eingerichtet in Schritt 1, mit der:`--config` + +```bash +polygon-edge secrets init --config +``` + +Der `PATH`Param ist der Ort des zuvor generierten Secrets Manager Param aus Schritt 1. + +:::info IAM-Richtlinie +Dieser Schritt schlägt fehl, wenn die IAM-Richtlinie, die Lese-/Schreibvorgänge zulässt, nicht korrekt konfiguriert und/oder nicht mit der EC2-Instanz verbunden ist, die diesen Befehl ausführt. +::: + +## Schritt 3 - Genesis-Datei erzeugen {#step-3-generate-the-genesis-file} + +Die Genesis-Datei sollte in einer ähnlichen Weise wie die [**Lokale Einrichtung**](/docs/edge/get-started/set-up-ibft-locally) und die Anleitungen für die [**Cloud-Einrichtung**](/docs/edge/get-started/set-up-ibft-on-the-cloud) erzeugt werden, aber mit geringfügigen Änderungen. + +Da AWS SSM anstelle des lokalen Dateisystems verwendet wird, sollten Validator Adressen über die `--ibft-validator`Flag hinzugefügt werden: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Schritt 4 - Starte den Polygon Edge Client {#step-4-start-the-polygon-edge-client} + +Nun, da die Schlüssel eingerichtet sind und die Genesis-Datei generiert wird, würde der letzte Schritt zu diesem Prozess Polygon Edge mit dem `server`Befehl sein. + +Der `server`Befehl wird in der gleichen Weise wie in den zuvor genannten Anleitungen eingesetzt, mit einem kleinen Zusatz – der `--secrets-config`Flagge: +```bash +polygon-edge server --secrets-config ... +``` + +Der `PATH`Param ist der Ort des zuvor generierten Secrets Manager Param aus Schritt 1. \ No newline at end of file diff --git a/archive/edge/de-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/de-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..04a572dcd4 --- /dev/null +++ b/archive/edge/de-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,108 @@ +--- +id: set-up-gcp-secrets-manager +title: Einrichtung des GCP Secrets Managers +description: "Einrichtung von GCP Secrets Manager für Polygon Edge." +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## Übersicht {#overview} + +Derzeit ist der Polygon Edge damit beschäftigt, 2 wichtige Laufzeitgeheimnisse zu bewahren: +* Der vom Knoten benutzte **Validator Private Key**, wenn der Knoten ein Validator ist +* Der **Networking Private Key** verwendet von libp2p, für die Teilnahme und die Kommunikation mit anderen Peers + +Für weitere Informationen siehe Leitfaden zur [Verwaltung von Private Keys](/docs/edge/configuration/manage-private-keys) + +Die Module des Polygon Edge **sollten nicht wissen müssen, wie Geheimhaltung funktioniert**. Letztlich sollte sich ein Modul nicht kümmern, wenn ein Geheimnis auf einem fernen Server oder lokal auf der Festplatte des Knoten gespeichert wird. + +Alles, was ein Modul über Geheimhaltung wissen muss, ist, **das Geheimnis zu verwenden**, **zu wissen, welche Geheimnisse beizubehalten oder zu speichern sind**. Die feineren Implementierungsdetails dieser Operationen werden zu `SecretsManager`delegiert, was natürlich eine Abstraktion ist. + +Der Knotenbetreiber, der den Polygon Edge startet, kann jetzt angeben, welche Secrets Manager sie verwenden möchten, da der richtige Secrets Manager instantiiert wird, behandeln die Module die Geheimnisse über die erwähnte Schnittstelle ohne sich zu kümmern, ob die Geheimnisse auf einer Festplatte oder auf einem Server gespeichert werden. + +Dieser Artikel beschreibt die notwendigen Schritte, um den Polygon Edge mit dem [GCP Secret Manager](https://cloud.google.com/secret-manager) in Betrieb zu nehmen. + +:::info Vorherige Anleitungen +Es wird **dringend empfohlen**, ehe Sie diesen Artikel durchgehen, Artikel auf [**Local Setup**](/docs/edge/get-started/set-up-ibft-locally), sowie [**Cloud Setup**](/docs/edge/get-started/set-up-ibft-on-the-cloud) zu lesen. +::: + + +## Voraussetzungen {#prerequisites} +### GCP-Rechnungskonto {#gcp-billing-account} +Um den GCP Secrets Manager nutzen zu können, muss der Benutzer das [Rechnungskonto](https://console.cloud.google.com/) im GCP-Portal aktiviert haben. +Neue Google-Konten auf der GCP-Plattform werden mit einigen Geldern ausgestattet, um den Start zu erleichtern, sozusagen als kostenlose Probe. +Mehr Informationen [unter GCP Doks](https://cloud.google.com/free) + +### Secrets Manager API {#secrets-manager-api} +Der Benutzer muss die GCP Secrets Manager API aktivieren, bevor er sie nutzen kann. +Dies kann über [das Secrets Manager API Portal](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com) erfolgen. +Weitere Informationen: [Konfigurieren von Secret Manger](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + +### GCP Anmeldeinformationen {#gcp-credentials} +Der Benutzer muss schließlich neue Anmeldedaten erstellen, die für die Authentifizierung verwendet werden. +Gehen Sie dazu anhand der Anweisungen, die [hier](https://cloud.google.com/secret-manager/docs/reference/libraries) veröffentlicht wurden, vor +Die erzeugte json-Datei mit den Anmeldeinformationen sollte an jeden Knoten, der den GCP Secrets Manager nutzen muss, übertragen werden. + +Erforderliche Informationen, ehe Sie fortfahren: +* **Projekt ID** (die auf der GCP-Plattform angegebene Projekt-ID) +* **Speicherort der Anmeldedatei** (der Pfad zur json-Datei, die die Anmeldedaten enthält) + +## Schritt 1 - Generieren der Secrets Manager Konfiguration {#step-1-generate-the-secrets-manager-configuration} + +Damit der Polygon Edge nahtlos mit dem GCP SM kommunizieren kann, muss er eine bereits erstellte Konfigurationsdatei parsen, die alle +notwendigen Informationen für die geheime Speicherung auf dem GCP SM enthält. + +Um die Konfiguration zu generieren, führe den folgenden Befehl aus: + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +Vorhandene Parameter: +* `PATH`ist der Pfad, in den die Konfigurationsdatei exportiert werden sollte. Standard`./secretsManagerConfig.json` +* `NODE_NAME` ist der Name des aktuellen Knotens, für den die GCP SM-Konfiguration eingerichtet werden soll. Es kann ein beliebiger Wert sein. Standard`polygon-edge-node` +* `PROJECT_ID` ist die Projekt-ID, die der Benutzer bei der Einrichtung des Kontos und der Aktivierung der Secrets Manager API in der GCP-Konsole definiert hat. +* `GCP_CREDS_FILE` ist der Pfad zu der json-Datei mit den Anmeldeinformationen, die den Lese- und Schreibzugriff auf den Secrets Manager ermöglichen. + +:::caution Knoten-Namen +Vorsicht bei der Angabe von Knoten-Namen. + +Der Polygon Edge verwendet den angegebenen Knotennamen, um die Geheimnisse zu verfolgen, die er generiert, und die er auf dem GCP SM verwendet. Wenn Sie einen bestehenden Knotennamen angeben, kann das dazu führen, dass das secret nicht an den GCP SM geschrieben wird. + +Secrets werden auf dem folgenden Basispfad `projects/PROJECT_ID/NODE_NAME`gespeichert: +::: + +## Schritt 2 - Initialisieren der Geheimschlüssel mit der Konfiguration {#step-2-initialize-secret-keys-using-the-configuration} + +Nun, da die Konfigurationsdatei vorhanden ist, können wir die erforderlichen Geheimschlüssel mit der Konfiguration initialisieren Datei eingerichtet in Schritt 1, mit der:`--config` + +```bash +polygon-edge secrets init --config +``` + +Der `PATH`Parameter ist der Ort des zuvor generierten Secrets Manager Parameters aus Schritt 1. + +## Schritt 3 - Genesis-Datei erzeugen {#step-3-generate-the-genesis-file} + +Die Genesis-Datei sollte in einer ähnlichen Weise wie die [**Lokale Einrichtung**](/docs/edge/get-started/set-up-ibft-locally) und die Anleitungen für die [**Cloud Einrichtungen**](/docs/edge/get-started/set-up-ibft-on-the-cloud) erzeugt werden, aber mit geringfügigen Änderungen. + +Da GCP SM anstelle des lokalen Dateisystems verwendet wird, sollten Prüfer-Adressen über die `--ibft-validator`Flagge hinzugefügt werden: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Schritt 4 - Starten des Polygon Edge Clients {#step-4-start-the-polygon-edge-client} + +Nun, da die Schlüssel eingerichtet sind und die Genesis-Datei generiert wird, würde der letzte Schritt zu diesem Prozess Polygon Edge mit dem `server`Befehl sein. + +Der `server`Befehl wird in der gleichen Weise wie in den zuvor genannten Anleitungen eingesetzt, mit einem kleinen Zusatz – der `--secrets-config`Flagge: +```bash +polygon-edge server --secrets-config ... +``` + +Der `PATH`Param ist der Ort des zuvor generierten Secrets Manager Param aus Schritt 1. \ No newline at end of file diff --git a/archive/edge/de-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/de-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..137d14a66e --- /dev/null +++ b/archive/edge/de-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,105 @@ +--- +id: set-up-hashicorp-vault +title: Einrichtung von Hashicorp Vault +description: "Hashicorp Vault für Polygon Edge einrichten." +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## Übersicht {#overview} + +Derzeit ist der Polygon Edge damit beschäftigt, 2 wichtige Laufzeitgeheimnisse zu bewahren: +* Der vom Knoten benutzte **Validator Private Key**, wenn der Knoten ein Validator ist +* Der **Networking Private Key** verwendet von libp2p, für die Teilnahme und die Kommunikation mit anderen Peers + +:::warning + +Der Private Key der Prüfer ist für jeden Prüferknoten einmalig. Der gleiche Key darf nicht für alle Validatoren verwendet werden, da dies die Sicherheit ihrer Chain gefährden könnte. + +::: + +Für weitere Informationen siehe [Leitfaden zur Verwaltung von Private Keys](/docs/edge/configuration/manage-private-keys) + +Die Module des Polygon Edge **sollten nicht wissen müssen, wie Geheimhaltung funktioniert**. Letztlich sollte sich ein Modul nicht kümmern, wenn ein Geheimnis auf einem fernen Server oder lokal auf der Festplatte des Knoten gespeichert wird. + +Alles, was ein Modul über Geheimhaltung wissen muss, ist, **das Geheimnis zu verwenden**, **zu wissen, welche Geheimnisse beizubehalten oder zu speichern sind**. Die feineren Implementierungsdetails dieser Operationen werden zu `SecretsManager`delegiert, was natürlich eine Abstraktion ist. + +Der Knotenbetreiber, der den Polygon Edge startet, kann jetzt angeben, welche Secrets Manager sie verwenden möchten, da der richtige Secrets Manager instantiiert wird, behandeln die Module die Geheimnisse über die erwähnte Schnittstelle ohne sich zu kümmern, ob die Geheimnisse auf einer Festplatte oder auf einem Server gespeichert werden. + +Dieser Artikel beschreibt die notwendigen Schritte, um den Polygon Edge mit dem [Hashicorp Vault](https://www.vaultproject.io/) Server in Betrieb zu nehmen. + +:::info Vorherige Anleitungen +Es wird **dringend empfohlen**, ehe Sie diesen Artikel durchgehen, Artikel auf [**Local Setup**](/docs/edge/get-started/set-up-ibft-locally), sowie [**Cloud Setup**](/docs/edge/get-started/set-up-ibft-on-the-cloud) zu lesen. +::: + + +## Voraussetzungen {#prerequisites} + +Dieser Artikel geht davon aus, dass bereits eine funktionierende Instanz des Hashicorp Vault Servers **eingerichtet ist**. + +Außerdem muss der Hashicorp Vault Server, der für den Polygon Edge verwendet wird, über **aktivierten KV-Speicher** verfügen. + +Erforderliche Informationen, ehe Sie fortfahren: +* **Die Server-URL** (die API-URL des Hashicorp Vault-Servers) +* **Token** (Zugriffstoken, der für den Zugriff auf die KV-Speicher-Engine verwendet wird) + +## Schritt 1 - Generieren Sie die secrets Manager Konfiguration {#step-1-generate-the-secrets-manager-configuration} + +Damit der Polygon Edge nahtlos mit dem Vault-Server kommunizieren kann, muss er eine bereits erstellte Konfigurationsdatei parsen, die alle +notwendigen Informationen für die Speicherung von Geheimnissen im Vault enthält. + +Um die Konfiguration zu generieren, führen Sie den folgenden Befehl aus: + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +Vorhandene Parameter: +* `PATH`ist der Pfad, in den die Konfigurationsdatei exportiert werden sollte. Standard`./secretsManagerConfig.json` +* `TOKEN` ist das Zugangs-Token, das im Abschnitt [Voraussetzungen](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) erwähnt wird +* `SERVER_URL` ist die API-URL für den Vault-Server, die auch im Abschnitt [Voraussetzungen](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) erwähnt wird +* `NODE_NAME` ist der Name des aktuellen Knotens, für den die Vault-Konfiguration eingerichtet werden soll. Es kann ein beliebiger Wert sein. Standard`polygon-edge-node` + +:::caution Knoten-Namen +Vorsicht bei der Angabe von Knoten-Namen. + +Polygon Edge verwendet den angegebenen Knotennamen, um die Geheimnisse zu verfolgen, die er erzeugt und auf der Vault-Instanz verwendet. Die Angabe eines bestehenden Knotennamens kann dazu führen, dass Daten auf dem Vault-Server überschrieben werden. + +Secrets werden auf dem folgenden Basispfad `secrets/node_name`gespeichert: +::: + +## Schritt 2 - Initialisieren der Geheimschlüssel mit der Konfiguration {#step-2-initialize-secret-keys-using-the-configuration} + +Nun, da die Konfigurationsdatei vorhanden ist, können wir die erforderlichen Geheimschlüssel mit der Konfiguration initialisieren Datei eingerichtet in Schritt 1, mit der:`--config` + +```bash +polygon-edge secrets init --config +``` + +Der `PATH`Parameter ist der Ort des zuvor generierten Secrets Manager Parameters aus Schritt 1. + +## Schritt 3 - Genesis-Datei erzeugen {#step-3-generate-the-genesis-file} + +Die Genesis-Datei sollte in einer ähnlichen Weise wie die [**Lokale Einrichtung**](/docs/edge/get-started/set-up-ibft-locally) und die Anleitungen für die [**Cloud Einrichtung**](/docs/edge/get-started/set-up-ibft-on-the-cloud) erzeugt werden, aber mit geringfügigen Änderungen. + +Da Hashicorp Vault anstelle des lokalen Dateisystems verwendet wird, sollten Prüfer-Adressen über die `--ibft-validator`Flagge hinzugefügt werden: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Schritt 4 - Starten des Polygon Edge Clients {#step-4-start-the-polygon-edge-client} + +Nun, da die Schlüssel eingerichtet sind und die Genesis-Datei generiert wird, würde der letzte Schritt zu diesem Prozess Polygon Edge mit dem `server`Befehl sein. + +Der `server`Befehl wird in der gleichen Weise wie in den zuvor genannten Anleitungen eingesetzt, mit einem kleinen Zusatz – der `--secrets-config`Flagge: +```bash +polygon-edge server --secrets-config ... +``` + +Der `PATH`Param ist der Ort des zuvor generierten Secrets Manager Param aus Schritt 1. \ No newline at end of file diff --git a/archive/edge/de-edge/consensus/bls.md b/archive/edge/de-edge/consensus/bls.md new file mode 100644 index 0000000000..ad1d7d25dc --- /dev/null +++ b/archive/edge/de-edge/consensus/bls.md @@ -0,0 +1,141 @@ +--- +id: bls +title: BLS +description: "Erläuterung und Anweisungen in Bezug auf den BLS" +keywords: + - docs + - polygon + - edge + - bls +--- + +## Übersicht {#overview} + +BLS auch bekannt als Boneh–Lynn–Shacham (BLS) ist ein kryptographisches Signaturschema, das es einem Benutzer ermöglicht, zu überprüfen, ob ein Signer authentisch ist. Es ist ein signature das mehrere Signaturen aggregieren kann. In Polygon Edge wird BLS standardmäßig verwendet, um eine bessere Sicherheit im IBFT Consensus Modus zu bieten. BLS kann Signaturen in ein einziges Byte Array aggregieren und die Block-Header Größe reduzieren. Jede Chain kann wählen, ob BLS verwendet werden soll Der ECDSA Key wird unabhängig davon, ob der BLS Modus aktiviert ist oder nicht. + +## Video-Präsentation {#video-presentation} + +[![bls - video](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## Wie man eine neue Kette mit BLS einrichtet {#how-to-setup-a-new-chain-using-bls} + +Bezüglich einer umfassenden Einrichtung siehe [Lokale Einrichtung](/docs/edge/get-started/set-up-ibft-locally) / [Cloud Einrichtung](/docs/edge/get-started/set-up-ibft-on-the-cloud) + +## Wie man aus einer bestehenden ECDSA PoA Chain zu BLS PoA Chain migriert {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +Dieser Abschnitt beschreibt, wie man den BLS Modus in einer vorhandenen PoA Chain verwendet. Die folgenden Schritte erforderlich sind, um BLS in einer PoA Chain zu aktivieren. + +1. Stoppen Sie alle Knoten +2. BLS Schlüssel für Validatoren erzeugen +3. Eine Fork in genesis.json hinzufügen +4. Starten Sie alle Knoten neu + +### 1. Stoppen Sie alle Knoten {#1-stop-all-nodes} + +Beenden Sie alle Prozesse der Validatoren durch Drücken von Ctrl + c (Control + c). Bitte merken Sie sich die letzte Blockhöhe (die höchste Sequenznummer im Block-Committed-Log). + +### 2. Generieren Sie den BLS Key {#2-generate-the-bls-key} + +`secrets init`mit der g`--bls`eneriert einen BLS Key. `--ecdsa`Um den vorhandenen ECDSA und Network Key zu behalten und einen neuen BLS Key hinzuzufügen, müssen `--network`deaktiviert werden. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Fork Einstellung hinzufügen {#3-add-fork-setting} + +`ibft switch`Befehl fügt eine Fork hinzu, die in der vorhandenen Chain BLS in... aktiviert`genesis.json`. + +Bei PoA-Netzen müssen die Validatoren im Befehl angegeben werden. Wie bei der Art von `genesis`Befehl o`--ibft-validators-prefix-path``--ibft-validator`der können Flags verwendet werden, um den Prüfer anzugeben. + +Legen Sie die Höhe fest, von der die Chain beginnt, BLS mit der `--from`Flag zu verwenden. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. Starten Sie alle Knoten neu {#4-restart-all-nodes} + +Starte Sie mit dem `server`Befehl alle Knoten neu. Nachdem der Block auf dem erstellt wurde, der im vorherigen Schritt `from`angegeben ist, aktiviert die Chain das BLS und zeigt Protokolle wie folgt an: + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +Außerdem zeigen die Protokolle, mit welchem Überprüfungsmodus jeder Block nach der Erstellung des Blocks generiert wird. + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## Wie man aus einer bestehenden ECDSA PoA Chain zu BLS PoS Chain migriert {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +Dieser Abschnitt beschreibt, wie man den BLS Modus in einer vorhandenen PoS Chain verwendet. Die folgenden Schritte sind erforderlich, um BLS in einer PoS Chain zu aktivieren. + +1. Stoppen Sie alle Knoten +2. BLS Schlüssel für Validatoren erzeugen +3. Eine Fork in genesis.json hinzufügen +4. Rufen Sie den Staking-Vertrag auf, um den öffentlichen BLS-Schlüssel zu registrieren. +5. Starten Sie alle Knoten neu + +### 1. Stoppen Sie alle Knoten {#1-stop-all-nodes-1} + +Beenden Sie alle Prozesse der Validatoren durch Drücken von Ctrl + c (Control + c). Bitte merken Sie sich die letzte Blockhöhe (die höchste Sequenznummer im Block-Committed-Log). + +### 2. Generieren Sie den BLS Key {#2-generate-the-bls-key-1} + +`secrets init`mit der `--bls`Flag generiert den BLS-Key. Um den vorhandenen ECDSA und Network Key zu behalten und einen neuen BLS Key hinzuzufügen, `--network`müssen `--ecdsa`deaktiviert werden. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Fork Einstellung hinzufügen {#3-add-fork-setting-1} + +`ibft switch`Befehl fügt eine Fork-Einstellung hinzu, die in der Mitte der Chain BLS in aktiviert`genesis.json`. + +Legen Sie die Höhe fest, von der aus die Chain den BLS-Modus mit der `from`Flag verwendet, und geben auch die Höhe an, in der der Vertrag mit der `development`Flag aktualisiert wird. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. Registrieren Sie den öffentlichen Schlüssel des BLS im Staking {#4-register-bls-public-key-in-staking-contract} + +Nachdem die Fork hinzugefügt ist und Validatoren neu gestartet werden, muss jeder Validator `registerBLSPublicKey`im Staking-Vertrag aufrufen, um den öffentlichen BLS registrieren. Dies muss nach der in angegebenen Höhe geschehen, und zwar `--deployment`vor der in 2 angegebenen Höhe`--from`. + +Das Skript zum Registrieren von BLS Public Key ist im [Staking Smart Contract repo definiert](https://github.com/0xPolygon/staking-contracts). + +`BLS_PUBLIC_KEY`einstellen, damit es in der `.env`-Datei registriert werden kann. Weitere Details zu anderen Parametern unter [pos-stake-unstake](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts). + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +`.env`Der folgende Befehl registriert den öffentlichen BLS Key in 1 zum Vertrag. + +```bash +npm run register-blskey +``` + +:::warning Prüfer müssen den Public BLS manuell registrieren +Im BLS-Modus müssen Prüfer ihre eigene Adresse und den öffentlichen Schlüssel des öffentlichen BLS haben. Die Konsensschicht ignoriert die Prüfer, die keinen öffentlichen BLS-Schlüssel im Vertrag registriert haben, wenn der Konsens die Prüferinformationen aus dem Vertrag abruft. + +::: + +### 4. Starten Sie alle Knoten neu {#5-restart-all-nodes} + +Starte Sie mit dem `server`Befehl alle Knoten neu. Die Chain ermöglicht das BLS, nachdem der Block bei 1 erstellt wird, die im vorherigen Schritt `from`angegeben wurde. diff --git a/archive/edge/de-edge/consensus/migration-to-pos.md b/archive/edge/de-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..2cb72d0f02 --- /dev/null +++ b/archive/edge/de-edge/consensus/migration-to-pos.md @@ -0,0 +1,39 @@ +--- +id: migration-to-pos +title: Migration von PoA zu PoS +description: "Wie du aus PoA in den PoS IBFT Modus migrierst und umgekehrt." +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## Übersicht {#overview} + +Dieser Abschnitt führt dich durch die Migration von PoA zu PoS IBFT Modi und umgekehrt für einen laufenden Cluster - ohne dass die Blockchain zurückgesetzt werden muss. + +## Wie man auf PoS migriert {#how-to-migrate-to-pos} + +Du musst alle Knoten beenden, fork in genesis.json durch `ibft switch`Befehl hinzufügen und die Knoten neu starten. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution Switching während der Verwendung von ECDSA +Wenn du ECDSA verwendest, muss die `--ibft-validator-type`Flagge dem Switch hinzugefügt werden, und zwar in der Erwähnung dass ECDSA verwendet wird. Wenn nicht enthalten ist, wird Edge automatisch zu BLS wechseln. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::Um auf PoS zu wechseln, musst du 2 Blockhöhen angeben: `deployment`und . `from`ist `deployment`die Höhe, um den staking bereitzustellen, und `from`die Höhe des Anfangs von PoS. `0x0000000000000000000000000000000000001001``deployment`Der staking wird an der Adresse in der , wie im Fall eines vorbereiteten Vertrags bereitgestellt. + +Bitte beziehe dich auf [Proof of Stake](/docs/edge/consensus/pos-concepts) für weitere Informationen über den Staking Vertrag. + +:::warning Validatoren müssen manuell einsetzen +Jeder Prüfer muss nach dem Einsatz von Vertrag `deployment`bei und vor `from`, um zu Beginn von PoS ein Prüfer zu sein. Jeder Prüfer aktualisiert einen eigenen Prüfer, der von dem Satz im staking zu Beginn von PoS festgelegt wird. + +Um mehr über Staking zu erfahren, besuche das **[Setup und verwende Proof of Stake](/docs/edge/consensus/pos-stake-unstake)**. +::: diff --git a/archive/edge/de-edge/consensus/poa.md b/archive/edge/de-edge/consensus/poa.md new file mode 100644 index 0000000000..d58c823477 --- /dev/null +++ b/archive/edge/de-edge/consensus/poa.md @@ -0,0 +1,103 @@ +--- +id: poa +title: Proof of Authority (PoA) +description: "Erläuterung und Anweisungen zu Beweis der Autorität." +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## Übersicht {#overview} + +Der IBFT PoA ist der Standard-Konsensmechanismus in der Polygon Edge In PoA sind Prüfer verantwortlich für die Erstellung der Blöcke und das Hinzufügen von Blöcken einer Serie. + +Alle Prüfer bilden ein dynamisches Prüfer-Set, in dem Prüfer durch Verwendung eines Abstimmmechanismus hinzugefügt oder aus dem Satz entfernt werden können. Dies bedeutet, dass Prüfer in dem Prüfer-Set gewählt werden können, wenn die Mehrheit (51 %) der Prüferknoten dazu abstimmen einen bestimmten Prüfer zu/vom Set zu hinzufügen bzw. zu fallen. Auf diese Weise können bösartige Prüfer erkannt und aus dem Netzwerk entfernt werden, während neue vertrauenswürdige Prüfer dem Netzwerk hinzugefügt werden können. + +Alle Prüfer werden in der Vorschläge des nächsten Blocks (Round-robin) und für den in die Blockchain zu validieren/eingefügten Block muss eine Supermehrheit (mehr als 2/3) der Prüfer den genannten Block genehmigen. + +Neben Prüfern gibt es Nicht-Prüfer, die nicht an der block creation teilnehmen, aber am block validation Prozess. + +## Hinzufügen eines Prüfers zum Prüfer-Set {#adding-a-validator-to-the-validator-set} + +Dieser Leitfaden beschreibt, wie du einem aktiven IBFT mit 4 Prüferknoten einen neuen Prüferknoten zu einem aktiven IBFT Netzwerk hinzufügst. Wenn du Hilfe beim Einrichten des Netzwerks benötigst, sieh in den Sektionen [Local Setup](/edge/get-started/set-up-ibft-locally.md) / [Cloud Setup](/edge/get-started/set-up-ibft-on-the-cloud.md) auf. + +### Schritt 1: Initialisiere Datenordner für IBFT und generiere validator keys für den neuen Knoten {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +Um mit IBFT auf dem neuen Knoten in Betrieb zu sein, musst du zuerst die Datenordner initialisieren und die Schlüssel generieren: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +Dieser Befehl wird den validator Key (Adresse) und die Knoten-ID drucken. Für den nächsten Schritt benötigst du den Prüfschlüssel (Adresse). + +### Schritt 2: Schlage einen neuen Kandidaten aus anderen Prüfknoten vor {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +Damit ein neuer Knoten ein Prüfer wird, müssen mindestens 51 % der Prüfer ihn vorschlagen. + +Beispiel für die Vorschlagsfunktion eines neuen Prüfers (`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`) aus dem vorhandenen Prüfknoten auf der grpc 127.0.0.1:100: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +Die Struktur der IBFT-Befehle ist im Abschnitt [CLI Befehle](/docs/edge/get-started/cli-commands) abgedeckt. + +:::info Öffentlicher Schlüssel BLS +Der öffentliche BLS ist nur dann notwendig, wenn das Netzwerk mit dem BLS läuft, für das Netzwerk das nicht im BLS-`--bls`Modus läuft. +::: + +### Schritt 3: Führe den Client-Knoten aus {#step-3-run-the-client-node} + +Da in diesem Beispiel das Netzwerk ausführen wird, in dem alle Knoten auf dem gleichen Rechner sind, müssen wir darauf achten, um nodes zu vermeiden. + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +Nach Abrufen aller Blöcke werden Sie in Ihrer Konsole feststellen, dass ein neuer Knoten an der Validierung beteiligt ist + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info Förderung eines non-validator für einen Prüfer +Natürlich kann ein Nicht-Prüfer durch den Abstimmungsprozess ein Prüfer werden, aber damit er nach dem Abstimmungsprozess erfolgreich in den validator-set aufgenommen wird, muss der Knoten mit der Flag neu `--seal`gestartet werden. +::: + +## Entfernen eines Prüfers aus dem Prüfer-Set {#removing-a-validator-from-the-validator-set} + +Diese Operation ist ziemlich einfach. Um einen Prüferknoten aus dem Prüfer-Set zu entfernen, muss dieser Befehl für die Mehrheit der Prüferknoten ausgeführt werden. + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info Öffentlicher Schlüssel BLS +Der öffentliche BLS ist nur dann notwendig, wenn das Netzwerk mit dem BLS läuft, für das Netzwerk das nicht im BLS-`--bls`Modus läuft. +::: + +Nachdem die Befehle ausgeführt werden, beachte bitte, dass die Anzahl der Prüfer gesunken ist (in diesem log von 4 auf + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/de-edge/consensus/pos-concepts.md b/archive/edge/de-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..7683d42efd --- /dev/null +++ b/archive/edge/de-edge/consensus/pos-concepts.md @@ -0,0 +1,99 @@ +--- +id: pos-concepts +title: Proof of Stake +description: "Erläuterung und Anweisungen zu Proof of Stake." +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## Übersicht {#overview} + +Dieser Abschnitt soll einen besseren Überblick über einige Konzepte geben, die derzeit im Proof of Stake (PoS) enthalten sind Implementierung der Polygon Edge. + +Die Implementierung von Polygon Edge Proof of Stake (PoS) soll eine Alternative zur bestehenden PoA IBFT Implementierung sein, geben Knotenbetreibern die Möglichkeit, leicht zwischen den beiden zu wählen, wenn eine Chain beginnt. + +## PoS Funktionen {#pos-features} + +Die Kernlogik hinter der Proof of Stake Implementierung befindet sich innerhalb der **[Staking Smart Contract](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)**. + +Dieser Vertrag wird pre-deployed wenn eine Polygon Edge Chain des PoS Mechanismus initialisiert wird und auf der Adresse verfügbar ist`0x0000000000000000000000000000000000001001` aus Block `0`. + +### Epochen {#epochs} + +Epochen sind ein Konzept, das mit dem Zusatz PoS zur Polygon Edge eingeführt wurde. + +Epochen gelten als ein spezieller Zeitrahmen (in Blöcken), in dem ein bestimmter Satz von Prüfern Blöcke erzeugen kann. Ihre Längen sind veränderbar, d.h. Knotenbetreiber können die Länge einer Epoche während der genesis konfigurieren. + +Am Ende jeder Epoche wird ein _epoch_ erstellt, und nach diesem Ereignis beginnt eine neue Epoche. Um mehr über die epoch Blöcke findest du im Abschnitt[ Epoch Blöcke](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Die Prüfungssätze werden am Ende jeder Epoche aktualisiert. Die Knoten fragen den validator aus dem Staking Smart Contract während der Erstellung des epoch und speichert die erhaltenen Daten auf dem lokalen Speicher. Diese Abfrage und save cycle ist wiederholt am Ende jeder Epoche. + +Im Wesentlichen stellt er sicher, dass der Staking Smart Contract die vollständige Kontrolle über die Adressen im validator hat und verlässt Knoten mit nur 1 Verantwortung - um den Vertrag während einer Epoche für den Abruf des neuesten Prüfers einmal abzufragen Informationen festlegen. Dies lindert die Verantwortung von einzelnen Knoten von der Betreuung von validator sets. + +### Staking {#staking} + +Adressen können Geld auf dem Staking Smart Contract einsetzen, indem du die `stake`Methode aufrufst und einen Wert für den staked Betrag in der Transaktion bestimmst: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +Durch das Staking auf dem Staking Smart Contract können Adressen den validator eingeben und somit in der Lage sein, an den Prozess der Produktion des Blocks teilzunehmen. + +:::info Schwelle zum Staking +`1 ETH`Derzeit ist die minimale Schwelle für die Eingabe in den validator +::: + +### Unstaking {#unstaking} + +Adressen, die über gestapelte Mittel verfügen, können nur **alle ihre gestapelten Mittel auf einmal auflösen**. + +Unstaking kann durch den Aufruf der `unstake`Methode im Staking Smart Contract: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +Nach dem Unstaking ihrer Mittel werden Adressen aus dem Prüfer, der auf dem Staking Smart Contract festgelegt ist, entfernt und werden nicht als Prüfer in der nächsten Epoche betrachtet. + +## Epoch Blöcke {#epoch-blocks} + +**Epoch Blocks** sind ein Konzept, das in der PoS Implementierung von IBFT in Polygon Edge eingeführt wurde. + +Im Wesentlichen sind epoch spezielle Blöcke, die **keine Transaktionen** enthalten und erst am **Ende einer Epoche** auftreten. Wenn die **epoch** beispielsweise `50`auf Blöcke gesetzt wird, werden epoch als Blöcke 10, `50`100 `100``150`und so weiter betrachtet. + +Sie werden verwendet, um zusätzliche Logik auszuführen, die während der regulären Blockproduktion nicht auftreten sollte. + +Am wichtigsten sind sie ein Hinweis für den Knoten, dass **er die neuesten Informationen zum validator abrufen muss** des Staking Smart Contract. + +Nach Aktualisierung des validator im epoch wird der validator (entweder geändert oder unverändert) wird für die nachfolgenden `epochSize - 1`Blöcke verwendet, bis es erneut aktualisiert wird, indem du die neuesten Informationen aus des Staking Smart Contract. + +Epoch (in Blöcken) bei der Generierung der Genesis-Datei mit einem speziellen Flag änderbar `--epoch-size`sind: + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +`100000`Die Standardgröße einer Epoche ist Blöcke in der Polygon Edge. + +## Contract Pre-Deployment {#contract-pre-deployment} + +Die Polygon Edge _Pre-Deploys_ des [Staking Smart Contract](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol). während der **genesis generation** an die Adresse `0x0000000000000000000000000000000000001001`. + +Es tut dies ohne einen laufenden EVM, indem es die Blockchain des Smart Contract direkt mit dem übergebenen modifiziert Konfigurationswerte für den genesis Befehl . diff --git a/archive/edge/de-edge/consensus/pos-stake-unstake.md b/archive/edge/de-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..87dc7c2383 --- /dev/null +++ b/archive/edge/de-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,149 @@ +--- +id: pos-stake-unstake +title: Einrichtung und Verwendung von Proof of Stake (PoS) +description: "Stake, Unstake und andere staking-related Anweisungen." +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## Übersicht {#overview} + +Dieser Leitfaden geht in Detail darüber, wie du ein Proof of Stake Netzwerk mit der Polygon Edge einrichtest, wie du Mittel für Knoten staken kannst um Prüfer zu werden und wie du Mittel freisetzen kannst. + +Es wird **sehr** ermutigt, zu lesen und durchzugehen die [lokale Einrichtung](/docs/edge/get-started/set-up-ibft-locally) / [Cloud Setup](/docs/edge/get-started/set-up-ibft-on-the-cloud) Abschnitte, bevor du diesem PoS Guide folgst. Diese Abschnitte beschreiben die Schritte, die für den Start eines Proof of Authority (PoA) Clusters mit dem Polygon Edge notwendig sind. + +Derzeit gibt es kein Limit für die Anzahl der Prüfer, die Mittel auf dem Staking Smart Contract einsetzen können. + +## Staking Smart Contract {#staking-smart-contract} + +Das Repo für den Staking Smart Contract befindet sich [hier](https://github.com/0xPolygon/staking-contracts). + +Es enthält die notwendigen Prüfskripte, ABI Dateien und vor allem den Staking Smart Contract selbst. + +## Einrichtung eines N node Clusters {#setting-up-an-n-node-cluster} + +Die Einrichtung eines Netzwerks mit dem Polygon Edge ist abgedeckt die [lokale Einrichtung](/docs/edge/get-started/set-up-ibft-locally) / [Cloud Setup](/docs/edge/get-started/set-up-ibft-on-the-cloud) Abschnitte. + +Der **einzige Unterschied** zwischen der Einrichtung eines PoS und PoA Clusters ist im genesis generation part. + +**Wenn die Genesis-Datei für einen PoS Cluster erstellt wird, wird ein zusätzliches Flag benötigt`--pos`**: + +```bash +polygon-edge genesis --pos ... +``` + +## Einstellung der Länge einer Epoche {#setting-the-length-of-an-epoch} + +Epochen sind im Abschnitt [Epoch Blocks](/docs/edge/consensus/pos-concepts#epoch-blocks) ausführlich behandelt. + +Um die Größe einer Epoche für einen Cluster (in Blöcken) festzulegen, ist ein zusätzliches Flag angegeben `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +Dieser in der Genesis-Datei angegebene Wert, dass die epoch Größe `50`Blöcke sein sollte. + +Der Standardwert für die Größe einer Epoche (in Blöcken) ist `100000`. + +:::info Senken der Epochenlänge +Wie im Abschnitt [Epoch Blocks](/docs/edge/consensus/pos-concepts#epoch-blocks) beschrieben, epoch Blöcke werden verwendet, um die validator sets für Knoten zu aktualisieren. + +Die default epoch Länge in Blöcken (`100000`) kann eine lange Zeit für validator sein. Berücksichtigung dieser neuen Blöcke werden ~2s hinzugefügt, es würde ~55.5h für den Prüfer dauern, um möglicherweise zu ändern. + +Wenn ein niedrigerer Wert für die Epochenlänge festgelegt wird, wird sichergestellt, dass der validator häufiger aktualisiert wird. +::: + +## Verwendung der Staking Smart Contract Skripte {#using-the-staking-smart-contract-scripts} + +### Voraussetzungen {#prerequisites} + +Das Staking Smart Contract repo ist ein Hardhat Projekt, das NPM erfordert. + +Um es richtig zu initialisieren, im Hauptverzeichnis ausführen: + +```bash +npm install +```` + +### Einrichtung der bereitgestellten Helfer-Skripte {#setting-up-the-provided-helper-scripts} + +Skripte für die Interaktion mit dem bereitgestellten Staking Smart Contract befinden sich auf dem [Staking Smart Contract](https://github.com/0xPolygon/staking-contracts). + +Erstellen Sie eine `.env`Datei mit den folgenden Parametern im Repo Smart Contracts location: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +Wo die Parameter sind: + +* **JSONRPC_URL** - der JSONRPC_URL Endpunkt für den laufenden Knoten +* **PRIVATE_KEYS** - Private Keys der staker Adresse. +* **STAKING_CONTRACT_ADDRESS** - die Adresse des staking Smart Contract ( `0x0000000000000000000000000000000000001001`default) +* **BLS_PUBLIC_KEY** - BLS öffentlicher Key des staker. Nur erforderlich, wenn das Netzwerk mit BLS läuft + +### Staking Fonds {#staking-funds} + +:::info Staking Adresse +Der Staking Smart Contract ist im Voraus bereitgestellt Adresse `0x0000000000000000000000000000000000001001`. + +Jede Art von Interaktion mit dem Staking wird über den Staking Smart Contract an der angegebenen Adresse durchgeführt. + +Um mehr über den Staking Smart Contract zu erfahren, besuche bitte der **[Staking Smart Contract](/docs/edge/consensus/pos-concepts#contract-pre-deployment)** Abschnitt. +::: + +Um Teil des validator zu werden, muss eine Adresse einen bestimmten Betrag an Mitteln über einer Schwelle einsetzen. + +`1 ETH`Derzeit ist die Standardschwelle für die Aufnahme eines Teils des validator . + +Staking kann initiiert werden, indem man die `stake`Methode des Staking Smart Contracts aufruft und einen Wert angibt.`>= 1 ETH` + +Nach der in erwähnten `.env`Datei der [vorherigen Abschnitt](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) eingerichtet wurde und eine Chain wurde im PoS Modus gestartet, kann Staking mit dem folgenden Befehl im Staking Smart Contract durchgeführt werden: + +```bash +npm run stake +``` + +Das `stake`Hardhat Skript setzt eine Standardmenge von `1 ETH`, die durch die Änderung `scripts/stake.ts`der Datei ein angepasst werden kann. + +Wenn die Mittel staked `>= 1 ETH`sind, wird der im Staking Smart Contract festgelegte Prüfer aktualisiert und die Adresse wird Teil des validator sein, beginnend mit der nächsten Epoche. + +:::info Registrierung der BLS Keys +Wenn das Netzwerk im BLS Modus läuft, um Prüfer zu werden, müssen sie nach dem Staking ihre öffentlichen BLS registrieren + +Dies kann mit dem folgenden Befehl erfolgen: + +```bash +npm run register-blskey +``` +::: + +### Unstaking Mittel {#unstaking-funds} + +Adressen, die einen Einsatz haben, können **nur alle ihre Mittel** auf einmal auflösen. + +Nach der in erwähnten `.env`Datei im [vorherigen Abschnitt](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) eingerichtet und eine Chain gestartet wurde, kann mit dem folgenden Befehl im PoS durchgeführt werden Staking Smart Contract repo: + +```bash +npm run unstake +``` + +### Suche die Liste der Stakers {#fetching-the-list-of-stakers} + +Alle Adressen, die Mittel einsetzen, werden im Staking Smart Contract gespeichert. + +Nach der in erwähnten `.env`Datei im [vorherigen Abschnitt](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) wurde eingerichtet und eine Chain im PoS gestartet wurde, kann die Liste der validatoren mit dem folgenden Befehl in der Staking Smart Contract repo gemacht werden: + +```bash +npm run info +``` diff --git a/archive/edge/de-edge/faq/Contracts.md b/archive/edge/de-edge/faq/Contracts.md new file mode 100644 index 0000000000..9139ca3a29 --- /dev/null +++ b/archive/edge/de-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: Smart Contracts FAQ +description: "FAQ für Polygon Edge Smart Contracts" +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## Unterstützt Polygon Edge Smart Contracts? {#does-polygon-edge-support-smart-contracts} + +Ja. Polygon Edge sind Ethereum kompatible Blockchains, so dass Smart Contracts, die auf Ethereum bereitgestellt werden können, auch auf Polygon Edge bereitgestellt werden können. + +## Kannst du die staking Contract Logik für PoS nach der Bereitstellung aktualisieren? {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +Nachdem du das PoS Netzwerk gestartet hast, kannst du den Staking Contract nicht ändern, da es Teil der genesis ist. So kannst du beispielsweise die minimal/maximale Anzahl an Prüfern nicht ändern. Was du tun kannst, ist das Stake oder das Unstake, um validatoren hinzuzufügen oder zu entfernen. + + + diff --git a/archive/edge/de-edge/faq/Gas.md b/archive/edge/de-edge/faq/Gas.md new file mode 100644 index 0000000000..56b6013199 --- /dev/null +++ b/archive/edge/de-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: Gas FAQ +description: "Gas FAQ für Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Wie kann ich einen minimalen Gaspreis durchsetzen? {#how-to-enforce-a-minimum-gas-price} +Du kannst die `--price-limit`Flag verwenden, die auf dem Server bereitgestellt wird. Dies wird deinen Knoten dazu zwingen, nur Transaktionen zu akzeptieren, die das Gas höher oder gleich dem von dir festgelegten Preislimit haben. Um sicherzustellen, dass es im gesamten Netzwerk durchgesetzt wird, musst du sicherstellen, dass alle Knoten das gleiche Preislimit haben. + + +## Können Sie Transaktionen mit 0 Gasgebühren haben? {#can-you-have-transactions-with-0-gas-fees} +Ja, das können Sie. Die default Preisgrenze, die Knoten durchsetzen, ist `0`, d.h. die Knoten akzeptieren Transaktionen mit einem Gaspreis auf`0` . + +## Wie stelle ich die gas(native) Token Total Supply ein? {#how-to-set-the-gas-native-token-total-supply} + +Du kannst einen vorgegebene Saldo auf die Konten (Adressen) einstellen, indem du die `--premine flag`verwendest. Bitte beachte, dass dies eine Konfiguration aus der genesis Datei ist und sie kann später nicht geändert werden. + +Beispiel für die Verwendung von `--premine flag`: + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +Dies stellt eine vorgegebene Balance von 1000 ETH auf 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862 dar (der Betrag aus dem Argument ist in wei). + +Die vorausschauende Menge des gas token wird die Gesamtversorgung sein. Kein anderer Betrag der of the native Währung (Gas Token) kann später angezeigt werden. + +## Unterstützt Edge ERC-20 als Gas-Token? {#does-edge-support-erc-20-as-a-gas-token} + +Edge unterstützt ERC-20 Token nicht als Gas-Token. Nur die native Edge Währung wird für Gas unterstützt. + +## Wie erhöht man die gas {#how-to-increase-the-gas-limit} + +Es gibt zwei Möglichkeiten, die gas in Polygon Edge zu erhöhen: +1. Wische die Chain und erhöht den maximalen uint64-Wert in der `block-gas-limit`Genesis-Datei. +2. Benutze die `--block-gas-target`Flagge mit einem hohen Wert, um die gas aller Knoten zu erhöhen. Dies erfordert den Neustart von Knoten. Detaillierte Erklärung [hier](/docs/edge/architecture/modules/txpool/#block-gas-target). \ No newline at end of file diff --git a/archive/edge/de-edge/faq/Tokens.md b/archive/edge/de-edge/faq/Tokens.md new file mode 100644 index 0000000000..3d47797ab7 --- /dev/null +++ b/archive/edge/de-edge/faq/Tokens.md @@ -0,0 +1,22 @@ +--- +id: tokens +title: Token FAQ +description: "FAQ für Polygon Edge Prüfer" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## Unterstützt Polygon Edge EIP-1559? {#does-polygon-edge-support-eip-1559} +Im Moment unterstützt Polygon Edge keine EIP-1559. + +## Wie setze das currency(token) Symbol ein? {#how-to-set-the-currency-token-symbol} + +Das Token-Symbol ist nur eine Benutzeroberfläche, sodass nicht irgendwo im Netzwerk konfiguriert oder hardcodiert werden kann. Aber du kannst es ändern, wenn du Netzwerk zu einer Wallet wie Metamask, zum Beispiel + +## Was passiert mit Transaktionen, wenn eine Chain eingehört? {#what-happens-to-transactions-when-a-chain-halts} + +Alle Transaktionen, die nicht verarbeitet wurden, befinden sich in der TxPool (anfrage oder beworbene Warteschlange). Wenn die Chain einstellt (alle Blockproduktion stoppt), werden diese Transaktionen niemals in Blöcke übergehen.
Dies ist nicht nur der Fall, wenn die Chain angehört. Wenn die Knoten gestoppt oder neu gestartet werden, werden alle Transaktionen entfernt, die noch nicht ausgeführt wurden und noch in TxPool sind, still entfernt.
Das gleiche wird bei Transaktionen passieren, wenn eine thing eingeführt wird, da es erforderlich ist, damit die Knoten neu gestartet werden. diff --git a/archive/edge/de-edge/faq/Validators.md b/archive/edge/de-edge/faq/Validators.md new file mode 100644 index 0000000000..823bc307ef --- /dev/null +++ b/archive/edge/de-edge/faq/Validators.md @@ -0,0 +1,85 @@ +--- +id: validators +title: Prüfer FAQ +description: "FAQ für Polygon Edge Prüfer" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Wie füge ich einen Prüfer hinzu/entferne ihn? {#how-to-add-remove-a-validator} + +### PoA {#poa} +Das Hinzufügen/Entfernen von Prüfern wird per Abstimmung durchgeführt. [Hier](/docs/edge/consensus/poa) findest du einen vollständigen Leitfaden dazu. + +### PoS {#pos} +[Hier](/docs/edge/consensus/pos-stake-unstake) findest du einen Leitfaden zum Staken von Geldern, damit ein Knoten zum Prüfer werden kann, und wie du das Staken aufheben (den Prüfer entfernen) kannst. + +Bitte beachte: +- Mit dem Genesis-Flag `--max-validator-count` kannst du eine maximale Anzahl von Stakern festlegen, die dem Prüfer-Set beitreten können. +- Mit dem Genesis-Flag `--min-validator-count ` kannst du die Mindestanzahl der Staker festlegen, die benötigt werden, um dem Prüfer-Set beizutreten (standardmäßig `1`). +- Wenn die maximale Anzahl an Prüfern erreicht ist, kannst du keinen weiteren Prüfer hinzufügen, bis du einen bestehenden Prüfer aus dem Set entfernst (egal, ob der Stake-Betrag des neuen Prüfers höher ist). Wenn du einen Prüfer entfernst, kann die Anzahl der verbleibenden Prüfer nicht kleiner als `--min-validator-count` sein. +- Um Prüfer zu werden, gibt es eine Standardschwelle von `1` Währungseinheit des nativen Netzwerks (Gas). + + + +## Wie viel Speicherplatz wird für einen Prüfer empfohlen? {#how-much-disk-space-is-recommended-for-a-validator} + +Wir empfehlen, mit 100 GB als konservativ geschätzter Startbahn zu beginnen und sicherzustellen, dass es möglich ist, den Speicherplatz anschließend zu skalieren. + + +## Gibt es eine Begrenzung für die Anzahl der Prüfer? {#is-there-a-limit-to-the-number-of-validators} + +Hinsichtlich technischer Einschränkungen gibt es bei Polygon Edge keine explizite Obergrenze für die Anzahl der Knoten, die du in einem Netzwerk einrichten kannst. Du kannst Verbindungsobergrenzen (Anzahl der eingehenden/ausgehenden Verbindungen) für jeden Knoten festlegen. + +Hinsichtlich praktischer Einschränkungen ist die Leistung bei einem 100-Knoten-Cluster geringer als bei einem 10-Knoten-Cluster. Wenn du die Anzahl der Knoten in deinem Cluster erhöhst, steigt die Komplexität der Kommunikation und der Netzwerk-Overhead im Allgemeinen. Das hängt davon ab, welche Art von Netzwerk du betreibst und welche Art von Netzwerktopologie du hast. + +## Wie wechsele ich von PoA zu PoS? {#how-to-switch-from-poa-to-pos} + +PoA ist der Standard-Konsensmechanismus. Wenn du einen neuen Cluster auf PoS umstellen willst, musst du bei der Erstellung der Genesis-Datei den Flag `--pos` hinzufügen. Wenn ein Cluster ausgeführt wird, kannst du [hier](/docs/edge/consensus/migration-to-pos) nachlesen, wie du die Umstellung vornehmen kannst. Alle Informationen, die du über unsere Konsensmechanismen und deren Einrichtung brauchst, findest du in unserem [Abschnitt zum Konsens](/docs/edge/consensus/poa). + +## Wie aktualisiere ich meine Knoten, wenn es einen Breaking Change gibt? {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +Einen ausführlichen Leitfaden zu diesem Verfahren findest du [hier](/docs/edge/validator-hosting#update). + +## Ist der Mindest-Stake-Betrag für PoS Edge konfigurierbar? {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +Der Mindest-Stake-Betrag beträgt standardmäßig `1 ETH` und ist nicht konfigurierbar. + +## Warum geben die JSON-RPC-Befehle `eth_getBlockByNumber` und `eth_getBlockByHash` nicht die Adresse des Miners zurück? {#not-return-the-miner-s-address} + +Der derzeit in Polygon Edge verwendete Konsens ist IBFT 2.0, der wiederum auf dem Abstimmungsmechanismus aufbaut, der im Clique PoA erklärt wird: [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225). + +Wenn du dir das EIP-225 (Clique PoA) ansiehst, ist das der relevante Teil, der erklärt, wofür `miner` (auch bekannt als `beneficiary`) verwendet wird: + +
+Wir setzen die ethash-Headerfelder wie folgt um: +
    +
  • beneficiary / miner: Adresse, mit der du die Änderung der Liste der Zeichnungsberechtigten vorschlägst.
  • +
      +
    • Sollte normalerweise mit Nullen ausgefüllt werden und nur während der Abstimmung geändert werden.
    • +
    • Beliebige Werte sind dennoch erlaubt (auch sinnlose wie die Abwahl von Nichtunterzeichnern), um zusätzliche Komplexität bei der Implementierung von Abstimmungsmechanismen zu vermeiden.
    • +
    • Muss bei Checkpoint-Blöcken (d. h. Epochenübergängen) mit Nullen ausgefüllt werden.
    • +
    + +
+ +
+ +Das `miner`-Feld wird also für den Vorschlag einer Abstimmung für eine bestimmte Adresse verwendet. Es dient nicht dazu, den Antragsteller des Blöcke anzuzeigen. + +Die Informationen über den Antragsteller des Blöcke können durch die Rückgewinnung des Pubkeys aus dem Siegelfeld des RLP-codierten Istanbul-Extra-Datenfelds im Block-Header ermittelt werden. + +## Welche Teile und Werte von Genesis können sicher geändert werden? {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +Bitte stelle sicher, eine manuelle Kopie der vorhandenen genesis.json-Datei zu erstellen, bevor du sie bearbeiten möchtest. Außerdem muss die gesamte Chain gestoppt werden, bevor du die genesis.json-Datei bearbeitest. Sobald die Genesis-Datei geändert wurde, muss die neuere Version davon auf allen non-validator und non-validator verteilt werden. + +::: + +**Nur der bootnodes Abschnitt der genesis-Datei kann sicher geändert werden**, wo du bootknoten aus der Liste hinzufügen oder entfernen kannst. \ No newline at end of file diff --git a/archive/edge/de-edge/get-started/cli-commands.md b/archive/edge/de-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..b0f7e8d21d --- /dev/null +++ b/archive/edge/de-edge/get-started/cli-commands.md @@ -0,0 +1,2200 @@ +--- +id: cli-commands +title: CLI Befehle +description: "Liste der CLI-Befehle und command flags für Polygon Edge." +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +Dieser Abschnitt enthält die aktuellen Befehle, die command flags in der Polygon Edge und wie sie verwendet werden. + +:::tip Unterstützung für die JSON Ausgabe + +Die `--json`Flag wird auf einigen Befehlen unterstützt. Diese Flag weist den Befehl an, die Ausgabe im JSON-Format zu drucken + +::: + +## Startup Befehle {#startup-commands} + +| **Befehl** | **Beschreibung** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Server | Der Standardbefehle, der den Blockchain Client startet, indem alle Module zusammenlädt | +| genesis | Generiert eine *genesis.json* Datei, die verwendet wird, um einen vorbestimmten Chain Status festzulegen, bevor du den Client startest. Die Struktur der genesis Datei ist unten beschrieben | +| genesis predeploy | Predeploys einen Smart Contract für frische Netzwerke | + +### Server Flags {#server-flags} + + +| **Alle server** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [GRPC](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [prometheus](/docs/edge/get-started/cli-commands#prometheus) | [block-gas-target](/docs/edge/get-started/cli-commands#block-gas-target) | +| [max-Peers](/docs/edge/get-started/cli-commands#max-peers) | [max-inbound-Peers](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [max-outbound-Peers](/docs/edge/get-started/cli-commands#max-outbound-peers) | [max-enqueued](/docs/edge/get-started/cli-commands#max-enqueued) | +| [log-Level](/docs/edge/get-started/cli-commands#log-level) | [log-to](/docs/edge/get-started/cli-commands#log-to) | +| [Chain](/docs/edge/get-started/cli-commands#chain) | [mitmachen](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [price-limit](/docs/edge/get-started/cli-commands#price-limit) | [max-Slots](/docs/edge/get-started/cli-commands#max-slots) | +| [config](/docs/edge/get-started/cli-commands#config) | [secrets-config](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-interval](/docs/edge/get-started/cli-commands#dev-interval) | +| [no-Discover](/docs/edge/get-started/cli-commands#no-discover) | [wiederherstellen](/docs/edge/get-started/cli-commands#restore) | +| [block-time](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +`./test-chain`Wird verwendet, um das Datenverzeichnis anzugeben, das für die Speicherung von Polygon Edge Clientdaten verwendet wird. + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +Setzt die Adresse und den Port für den JSON-RPC Service `address:port` . `0.0.0.0:10001` Wenn nur Port definiert ist wird `:10001`er an alle Schnittstellen gebunden Wenn der Dienst nicht mehr an den Standard `address:port` bindet. Standardadresse: `0.0.0.0:8545`. + +--- + +####

json-rpc-block-range-limit + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +Setzt den maximalen Blockbereich, der bei der Ausführung von json-rpc Requests berücksichtigt werden soll, die fromBlock/toBlock Werte enthalten (z.B. eth_getLogs). Default:`1000`. + +--- + +####

json-rpc-batch-request-limit + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +Setzt die maximale Länge, die bei der Bearbeitung von json-rpc berücksichtigt werden soll. `20`Standard: + +--- + +####

GRPC + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +Setzt die Adresse und den Port für den gRPC Service `address:port`. Standardadresse: `127.0.0.1:9632`. + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +Setzt die Adresse und den Port für den libp2p Service `address:port`. Standardadresse: `127.0.0.1:1478`. + +--- + +####

prometheus + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +Setzt die Adresse und den Port für prometheus Server `address:port` . Wenn nur Port definiert ist `0.0.0.0:5001` , wird `:5001`der Dienst an alle Schnittstellen gebunden Wenn der Dienst nicht ausgelassen wird, wird nicht gestartet. + +--- + +####

block-gas-target + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +Setzt das target block gas Limit für die Chain . Standard (nicht durchgesetzt): `0`. + +Eine ausführlichere Erklärung zum block findest du im [Abschnitt](/docs/edge/architecture/modules/txpool#block-gas-target) TxPool. + +--- + +####

max-Peers + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +Setzt die maximale Peer Count des Clients. `40`Standard: + +Peer limit sollte entweder mit Hilfe von `max-peers`oder `max-inbound/outbound-peers`Flag angegeben + +--- + +####

max-inbound-Peers + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +Setzt die maximale Inbound Peer Count des Clients. Wenn `max-peers` gesetzt wird, wird Max-inbound-Peer Grenze mit den folgenden Formeln berechnet. + +`max-inbound-peer = InboundRatio * max-peers`, wo `InboundRatio`ist `0.8`. + +--- + +####

max-outbound-Peers + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +Setzt die maximale Outbound Peer Count des Clients. Wenn gesetzt `max-peers`wird, wird max-outbound-Peer count mit den folgenden Formeln berechnet. + +`max-outbound-peer = OutboundRatio * max-peers`, wo `OutboundRatio`ist `0.2`. + +--- + +####

max-enqueued + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +Setzt die maximale Anzahl der angeforderten Transaktionen pro Konto. Default:`128`. + +--- + +####

log-Level + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +Setzt den Log-Level für die Ausgabe der Konsole. `INFO`Standard: + +--- + +####

log-to + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +Definiert den Protokolldateinamen, der alle Protokollausgabe aus dem server hält. Standardmäßig werden alle Server-Protokolle zur Konsole (stdout) ausgegeben, aber wenn das Flag gesetzt ist, wird es keine Ausgabe an der Konsole geben, wenn du den server ausführst. + +--- + +####

Chain + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +Gibt die Genesis-Datei an, die für den Start der Chain verwendet wird. `./genesis.json`Standard: + +--- + +####

mitmachen + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Gibt die Adresse des Peers an, die beigetreten werden sollte. + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +Setzt die externe IP-Adresse ohne den Port, wie sie von Peers zu sehen ist. + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +Setzt die host DNS Adresse. Dies kann verwendet werden, um einen externen DNS zu werben. Unterstützt `dns`,`dns4`,`dns6`. + +--- + +####

price-limit + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +Setzt das minimum für Gas Preislimit, um die Annahme in den Pool zu erzwingen. `1`Standard: + +--- + +####

max-Slots + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +Setzt maximale Slots im Pool. `4096`Standard: + +--- + +####

Config + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +Gibt den Pfad zur CLI Config an. Unterstützt `.json`. + +--- + +####

secrets-config + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +Setzt den Pfad zur SecretsManager Config Datei ein. Wird für Hashicorp Vault, AWS SSM und GCP Secrets Manager verwendet. Wenn weggelassen, wird der lokale FS secrets Manager verwendet. + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +Setzt den Client in den dev Modus. Standard: `false`. Im dev ist peer standardmäßig deaktiviert. + +--- + +####

dev-interval + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +Setzt das dev notification Intervall des Clients in Sekunden ein. `0`Standard: + +--- + +####

no-Discover + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +Hindert den Client daran, andere Peers zu entdecken. `false`Standard: + +--- + +####

wiederherstellen + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +Stellen Sie Blöcke aus der angegebenen Archivdatei wieder her + +--- + +####

block-time + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +Stellt die Block-Produktionszeit in Sekunden ein. Default:`2` + +--- + +####

access-control-allow-origins + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +Setzt die autorisierten Domains um Antworten von JSON-RPC Anfragen zu teilen. Füge mehrere Flags hinzu, `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"`um mehrere Domains zu autorisieren. Wenn der Access-Control-Allow-Origins Header auf eingestellt wird `*`und alle Domains autorisiert werden. + +--- + +### genesis flags {#genesis-flags} +| **Alle genesis Flags** | +|---------------------------------------|---------------------------------------------| +| [dir](/docs/edge/get-started/cli-commands#dir) | [Name](/docs/edge/get-started/cli-commands#name) | +| [PoS](/docs/edge/get-started/cli-commands#pos) | [epoch-size](/docs/edge/get-started/cli-commands#epoch-size) | +| [premine](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [ibft-validator-type](/docs/edge/get-started/cli-commands#ibft-validator-type) | [ibft-validators-prefix-path](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [ibft-validator](/docs/edge/get-started/cli-commands#ibft-validator) | [block-gas-limit](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [Konsens](/docs/edge/get-started/cli-commands#consensus) | [bootnode](/docs/edge/get-started/cli-commands#bootnode) | +| [max-validator-count](/docs/edge/get-started/cli-commands#max-validator-count) | [min-validator-count](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

dir + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +Setzt das Verzeichnis für Polygon Edge genesis Daten. Default: `./genesis.json`. + +--- + +####

Name + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +Setzt den Namen für die Chain. `polygon-edge`Standard: + +--- + +####

PoS + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +Setzt die Flag, die anzeigt, dass der Client Proof of Stake IBFT verwenden sollte. Defaults zu Proof of Authority wenn Flag nicht bereitgestellt wird oder `false`. + +--- + +####

epoch-size + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +Setzt die epoch für die Chain. `100000`Standard. + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +Setzt die vorab entwickelten Konten und Salden im Format `address:amount`. Die Menge kann entweder in Dezimal oder in Hex sein. Default Balance: `0xD3C21BCECCEDA1000000`(1 Million native currency + +--- + +####

chainid + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +Setzt die ID der Chain. `100`Standard: + +--- + +####

ibft-validator-type + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +Gibt den validation Modus von Block Header an. Mögliche Werte: `[ecdsa, bls]`. `bls`Standard: + +--- + +####

ibft-validators-prefix-path + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +Prefix Pfad für validator Ordner Directory. Muss vorhanden sein, wenn die Flag weggelassen `ibft-validator`wird. + +--- + +####

ibft-validator + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Setzt Adressen als IBFT validatoren. Muss vorhanden sein, wenn die Flag weggelassen `ibft-validators-prefix-path`wird. +1. Wenn das Netzwerk mit ECDSA läuft, ist das Format `--ibft-validator [ADDRESS]`. +2. Wenn das Netzwerk mit BLS läuft, ist das Format `--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]`. + +--- + +####

block-gas-limit + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +Bezieht sich auf die maximale Menge an Gas, das von allen Operationen in einem Block verwendet wird. `5242880`Standard: + +--- + +####

Konsens + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +Sets consensus protocol. `pow`Standard: + +--- + +####

bootnode + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Multiaddr URL für p2p discovery bootstrap. Diese Flag kann mehrmals verwendet werden. Anstelle einer IP-Adresse kann die DNS Adresse des bootnode bereitgestellt werden. + +--- + +####

max-validator-count + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +Die maximale Anzahl an Stakers, die in der Lage sind, dem validator in einem PoS Konsens beizutreten. Diese Zahl kann den Wert von MAX_SAFE_INTEGER (2^53 - 2) nicht überschreiten. + +--- + +####

min-validator-count + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +Die minimale Anzahl an Stakers benötigt, um dem validator in einem PoS Konsens beizutreten. Diese Zahl kann den Wert von max-validator-count nicht überschreiten. Standardmäßig auf 1. + +--- + +### genesis predeploy flags {#genesis-predeploy-flags} + +

artifacts-path

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +Setzt den Pfad zu den contract JSON, die die `abi`enthält, `bytecode`und .`deployedBytecode` + +--- + +

Chain

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +Setzt den Pfad zur `genesis.json`Datei, die aktualisiert werden soll. `./genesis.json`Standard. + +--- + +

constructor-args

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +Setzt die Argumente des Smart Contract Konstruktors fest, falls vorhanden. Für einen detaillierten Leitfaden darüber, wie diese Argumente aussehen sollen, referiere bitte [Predeployment Artikel](/docs/edge/additional-features/predeployment). + +--- + +

predeploy-address

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +Setzt die Adresse für die predeploy fest. `0x0000000000000000000000000000000000001100`Standard. + +--- + + +## Bedienerbefehle {#operator-commands} + +### Peer Befehle {#peer-commands} + +| **Befehl** | **Beschreibung** | +|------------------------|-------------------------------------------------------------------------------------| +| Peers hinzufügen | Fügt einen neuen Peer mit libp2p Adresse hinzu | +| Peers Liste | Listet alle Peers auf, mit denen der Client über libp2p verbunden ist | +| Peers Status | Gibt den Status eines bestimmten Peers aus der Peers Liste mit der libp2p Adresse zurück | + +

Peers fügen Flags hinzu

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Peers libp2p Adresse im Multiaddr Format. + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +Adresse der gRPC API. `127.0.0.1:9632`Standard: + +

Peers list Flags

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +Adresse der gRPC API. `127.0.0.1:9632`Standard: + +

Peers Status Flags

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Libp2p node ID eines bestimmten Peer innerhalb des p2p Netzwerks. + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +Adresse der gRPC API. `127.0.0.1:9632`Standard: + +### IBFT Befehle {#ibft-commands} + +| **Befehl** | **Beschreibung** | +|------------------------|-------------------------------------------------------------------------------------| +| ibft Snapshot | Gibt den IBFT Snapshot zurück | +| ibft Kandidaten | Dieser Befehl fragt die aktuelle Menge der vorgeschlagenen Kandidaten ab, sowie die Kandidaten, die noch nicht aufgenommen wurden | +| ibft Vorschlag | Schlägt einen neuen Kandidaten, der hinzugefügt oder aus dem validator entfernt werden soll | +| ibft Status | Gibt den Gesamtstatus des IBFT Clients zurück | +| ibft Switch | Füge Fork Konfigurationen in die genesis.json Datei hinzu um den IBFT Typ zu schalten | +| ibft quorum | Gibt die Blocknummer an, nach der die optimale quorum Methode für das Erreichen des Konsens verwendet wird | + + +

ibft Snapshot Flags

+ +

Nummer

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +Die Blockhöhe (Nummer) für den Snapshot. + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +Adresse der gRPC API. `127.0.0.1:9632`Standard: + +

ibft candidates flags

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Adresse der gRPC API. `127.0.0.1:9632`Standard: + +

ibft schlagen Flags vor

+ +

Abstimmung

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +Schlage eine Änderung des validator vor. Mögliche Werte:`[auth, drop]` + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +Adresse des Kontos, für das du stimmen sollst. + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +BLS Public Key des Kontos für das gewählt werden soll, nur im BLS Modus notwendig + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Adresse der gRPC API. `127.0.0.1:9632`Standard: + +

ibft status flags

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +Adresse der gRPC API. `127.0.0.1:9632`Standard: + +

ibft switch Flags

+ +

Chain

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +Gibt die genesis Datei an, die aktualisiert werden soll. `./genesis.json`Standard: + +--- + +

Art

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +Gibt den IBFT Typ an, den sie umschalten sollen. Mögliche Werte: `[PoA, PoS]`. + +--- + +

Bereitstellung

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +Gibt die Höhe der contract Bereitstellung an. Nur mit PoS verfügbar. + +--- + +

von

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +Gibt den validation Modus von Block Header an. Mögliche Werte: `[ecdsa, bls]`. `bls`Standard: + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +Prefix Pfad für die Verzeichnisse der neuen validatoren Muss vorhanden sein, wenn die Flag weggelassen `ibft-validator`wird. Verfügbar nur wenn der IBFT Modus PoA ist ( `--pos`Flag wird weggelassen). + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Sets wurden in Adressen als IBFT validators übergeben, die nach der Fork verwendet werden. Muss vorhanden sein, wenn die Flag weggelassen `ibft-validators-prefix-path`wird. Verfügbar nur im PoA Modus. +1. Wenn das Netzwerk mit ECDSA läuft, ist das Format `--ibft-validator [ADDRESS]`. +2. Wenn das Netzwerk mit BLS läuft, ist das Format `--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]`. + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +Die maximale Anzahl an Stakers, die in der Lage sind, dem validator in einem PoS Konsens beizutreten. Diese Zahl kann den Wert von MAX_SAFE_INTEGER (2^53 - 2) nicht überschreiten. + +--- + +

min-validator-count

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +Die minimale Anzahl an Stakers benötigt, um dem validator in einem PoS Konsens beizutreten. Diese Zahl kann den Wert von max-validator-count nicht überschreiten. Standardmäßig auf 1. + +Gibt die Anfangshöhe der Fork an. + +--- + +

ibft quorum flags

+ +

von

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +`(2/3 * N)``N`Die Höhe um die quorum Kalkulation auf QuorumOptimal zu wechseln, die die Formel verwendet, ist die Anzahl der validator Knoten. Bitte beachte, dass dies für die Abwärtskompatibilität bestimmt ist, dh nur für Chains, die eine Quorum Legacy Berechnung bis zu einer bestimmten Blockhöhe verwendet haben. + +--- + +

Chain

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +Gibt die genesis Datei an, die aktualisiert werden soll. `./genesis.json`Standard: + +### Transaction Pool Befehle {#transaction-pool-commands} + +| **Befehl** | **Beschreibung** | +|------------------------|--------------------------------------------------------------------------------------| +| txpool Status | Gibt die Anzahl der Transaktionen im Pool zurück | +| txpool subscribe | Abonniert für Events im Transaktionspool | + +

txpool status Flags

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +Adresse der gRPC API. `127.0.0.1:9632`Standard: + +

txpool subscribe Flags

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +Adresse der gRPC API. `127.0.0.1:9632`Standard: + +--- + +

gefördert

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +Abonniert für beworbene tx Events im TxPool. + +--- + +

gelöscht

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +Abonniert für dropped tx Events im TxPool. + +--- + +

demoted

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +Abonniert für demoted tx Events im TxPool. + +--- + +

hinzugefügt

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +Abonniert für zusätzliche tx Events zum TxPool. + +--- + +

enqueued

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +Abonniert für enqueued tx Events in den Konto Warteschlangen. + +--- + +### Blockchain Befehle {#blockchain-commands} + +| **Befehl** | **Beschreibung** | +|------------------------|-------------------------------------------------------------------------------------| +| Status | Gibt den Status des Clients zurück. Die detaillierte Antwort kann unten gefunden | +| Monitor | Abonniert einen Blockchain Event Stream. Die detaillierte Antwort kann unten gefunden | +| Version | Gibt die aktuelle Version des Clients zurück | + +

status-Flags

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +Adresse der gRPC API. `127.0.0.1:9632`Standard: + +

monitor flags

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +Adresse der gRPC API. `127.0.0.1:9632`Standard: + +--- +

Version-Befehl

+ + + + + + version + + + + +Zeigt Release-Version, git branch, bekomme Hash und Build-Zeit. + +## Secrets Befehle {#secrets-commands} + +| **Befehl** | **Beschreibung** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| secrets init | Initialisiert die privaten Keys zum entsprechenden Secrets Manager | +| secrets generieren | Generiert eine secrets manager Konfigurationsdatei, die von dem Polygon Edge analysiert werden kann | +| secrets Ausgabe | Druckt die öffentlichen key die öffentliche address, des Prüfers und den Knoten-ID für die Referenz | + +### secrets init Flag {#secrets-init-flags} + +

Config

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +Setzt den Pfad zur SecretsManager Config Datei ein. Wird für Hashicorp Vault verwendet. Wenn weggelassen, wird der lokale FS secrets Manager verwendet. + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +Setzt das Verzeichnis für die Polygon Edge Daten, wenn der lokale FS verwendet wird. + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +Setzt das Flag mit dem Hinweis, ob du einen ECDSA Key generieren soll. `true`Standard: + +--- + +

Netzwerk

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +Setzt die Flag mit der Anzeige, ob du ein Libp2p Network generieren soll. `true`Standard: + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +Setzt das Flag mit dem Hinweis, ob du einen BLS Key generieren sollst. `true`Standard: + +### secrets generieren Flags {#secrets-generate-flags} + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +Setzt das Verzeichnis für die secrets Manager Konfigurationsdatei Default:`./secretsManagerConfig.json` + +--- + +

Art

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +Gibt den Typ des secrets Manager [`hashicorp-vault`]an. Default:`hashicorp-vault` + +--- + +

Token

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +Gibt den Access Token für den Dienst an + +--- + +

server-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +Gibt die Server-URL für den Dienst an + +--- + +

Name

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +Gibt den Namen des Knotens für die on-Service Record keeping an. Default:`polygon-edge-node` + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Gibt den Namespace an, der für den Hashicorp Vault Secrets Manager verwendet wird. Default:`admin` + +### secrets output {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +Setzt die Flagge an, die anzeigt, ob nur den öffentlichen BLS Key ausgegeben werden soll. Default:`true` + +--- + +

Config

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +Setzt den Pfad zur SecretsManager Config Datei ein. Wenn weggelassen, wird der lokale FS secrets Manager verwendet. + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +Setzt das Verzeichnis für die Polygon Edge Daten, wenn der lokale FS verwendet wird. + +--- + +

node-id

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +Setzt die Flagge an, die anzeigt, ob nur die network ausgegeben werden soll. Default:`true` + +--- + +

Validator

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +Setzt die Flagge an, die angibt, ob nur die validator ausgegeben werden soll. Default:`true` + +--- + +## Antworten {#responses} + +### Status Antwort {#status-response} + +Das Antwort Objekt wird mit Protocol Buffers definiert. +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### Monitor Antwort {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## Utilities {#utilities} + +### whitelist Befehle {#whitelist-commands} + +| **Befehl** | **Beschreibung** | +|------------------------|-------------------------------------------------------------------------------------| +| whitelist Show | Zeigt Whitelist Informationen | +| whitelist Bereitstellung | Aktualisiert die Smart Contract Deployment Whitelist | + +

whitelist Show

+ + + + + whitelist show + + + + +Zeigt Whitelist Informationen an. + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +Gibt die genesis Datei an, die aktualisiert werden soll. `./genesis.json`Standard: + +--- + +

whitelist Bereitstellung

+ +

Chain

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +Gibt die genesis Datei an, die aktualisiert werden soll. `./genesis.json`Standard: + +--- + +

add

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Fügt eine neue Adresse zur Bereitstellung von Contracts hinzu Nur die Adressen in der Contract Deployment Whitelist können Verträge bereitstellen. Wenn leer, kann jede Adresse die contract Bereitstellung ausführen + +--- + +

entfernen

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Entfernt eine Adresse aus der Contract Deployment Whitelist. Nur die Adressen in der Contract Deployment Whitelist können Verträge bereitstellen. Wenn leer, kann jede Adresse die contract Bereitstellung ausführen + +--- + +### backup flags {#backup-flags} + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +Adresse der gRPC API. `127.0.0.1:9632`Standard: + +--- + +

out

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +Pfad, die Archivdatei zu speichern. + +--- + +

von

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +Die Anfangshöhe der Blöcke im Archiv. Standard: 0. + +--- + +

to

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +Die Endhöhe der Blöcke im Archiv. + +--- + +## Genesis Vorlage {#genesis-template} +Die genesis-Datei sollte verwendet werden, um den Anfangszustand der Blockchain zu setzen (z.B. wenn einige Konten ein Startguthaben haben). + +Die folgende *./genesis.json* Datei wird generiert: +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### Data Directory {#data-directory} + +Wenn du die *data-dir* Flagge ausführt, wird ein **Test-Chain** Ordner generiert. Die Ordnerstruktur besteht aus den folgenden Unterordnern: +* **blockchain** - Speichert die LevelDB für blockchain Objekte +* **trie** - Speichert die LevelDB für die Merkle Versuche +* **Keystore** - Speichert Private Keys für den Client. Dazu gehören der Private Key von libp2p und der Private Key des Sealers/Prüfers +* **Konsens** - Speichert alle Konsensinformationen, die der Client während der Arbeit benötigt. + +## Ressourcen {#resources} +* **[Protokollpuffer](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/de-edge/get-started/installation.md b/archive/edge/de-edge/get-started/installation.md new file mode 100644 index 0000000000..b27a082604 --- /dev/null +++ b/archive/edge/de-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: Installation +description: "Wie installiere ich Polygon Edge?" +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +Bitte wähle die für dich am besten geeignete Installationsmethode. + +Wir empfehlen, die vorgefertigten Releases zu verwenden und die angegebenen Prüfsummen zu verifizieren. + +## Vorgefertigte Releases {#pre-built-releases} + +Auf der Seite [GitHub Releases](https://github.com/0xPolygon/polygon-edge/releases) findest du eine Liste von Releases. + +Polygon Edge wird mit per Cross-Compiler erstellten AMD64/ARM64-Binärdateien für Darwin und Linux geliefert. + +--- + +## Docker Image {#docker-image} + +Offizielle Docker Images werden unter der [Registry hub.docker.com](https://hub.docker.com/r/0xpolygon/polygon-edge) gehostet. + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## Von der Quelle aus aufbauen {#building-from-source} + +Vergewissere dich vor der Verwendung von `go install`, dass du Go `>=1.18` installiert und richtig konfiguriert hast. + +Der stabile Zweig ist der Zweig der neuesten Release. + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## Verwenden von `go install` + +Vergewissere dich vor der Verwendung von `go install`, dass du Go `>=1.17` installiert und richtig konfiguriert hast. + +`go install github.com/0xPolygon/polygon-edge@release/` + +Die Binärdatei ist in deiner `GOBIN`Umgebungsvariable verfügbar und enthält die Änderungen von der neuesten Version. Du kannst [GitHub Releases](https://github.com/0xPolygon/polygon-edge/releases) ausprobieren, um herauszufinden, welche die neueste ist. diff --git a/archive/edge/de-edge/get-started/set-up-ibft-locally.md b/archive/edge/de-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..022b0c939c --- /dev/null +++ b/archive/edge/de-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,415 @@ +--- +id: set-up-ibft-locally +title: Lokale Einrichtung +description: "Schritt-für-Schritt lokaler Setup Guide." +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution Dieser Leitfaden dient nur zu Prüfungszwecken + +Der folgende Leitfaden wird dich anweisen, wie du ein Polygon Edge Netzwerk auf deinem lokalen Rechner für das Testen und die Entwicklung einrichtest Zwecke. + +Die Prozedur unterscheidet sich erheblich von der Art und Weise, wie du das Polygon Edge Netzwerk für ein echtes Anwendungsszenario einrichten möchtest. a Cloud Provider: **[Cloud Setup](/docs/edge/get-started/set-up-ibft-on-the-cloud)** + +::: + + +## Voraussetzungen {#requirements} + +Siehe [Installation](/docs/edge/get-started/installation) zur Installation von Polygon Edge. + +## Übersicht {#overview} + +![Lokale Einrichtung](/img/edge/ibft-setup/local.svg) + +In diesem Leitfaden geht es darum, ein funktionierendes `polygon-edge` Blockchain-Netzwerk aufzubauen, das mit dem [IBFT-Konsensprotokoll](https://github.com/ethereum/EIPs/issues/650) arbeitet. +Das Blockchain-Netzwerk wird aus 4 Knoten bestehen, von denen alle 4 Prüfknoten sind. Als solche sind sie berechtigt, sowohl Blöcke vorzuschlagen als auch Blöcke zu validieren, die von anderen Vorschlagenden stammen. +Alle 4 Knoten werden auf dem gleichen Rechner laufen, da die Idee dieses nodes ist, dir in der minimalen Menge an Zeit einen voll funktionsfähigen IBFT Cluster zu geben. + +Um das zu erreichen, führen wir dich durch 4 einfache Schritte: + +1. Initialisierung von Datenverzeichnissen generiert beide validator keys für jeden der 4 Knoten und initialisiert leere blockchain Verzeichnissen. Die Validator-Schlüssel sind wichtig, da wir den genesis Block mit dem ersten Satz von Validatoren bootstrap müssen, die diese Schlüssel verwenden. +2. Die Vorbereitung der Verbindungszeichenfolge für den bootnode wird die lebenswichtige Information für jeden Knoten sein, mit dem wir ausführen werden, wie welchem Knoten wir dich verbinden sollen, wenn du das erste Mal beginnst. +3. Die Generierung der `genesis.json`Datei erfordert als Eingabe beide die in **Schritt 1** **generierten** validator keys , die für die Einstellung der ursprünglichen validators des Netzwerks im genesis Block und die bootnode Connection String aus Schritt 2 verwendet werden. +4. Wenn wir alle Knoten ausführen möchten, ist das Endziel dieses Leitfadens und wird der letzte Schritt sein, den wir tun. Wir werden die anweisen, welches Datenverzeichnis zu verwenden ist und wo wir die finden die , `genesis.json`die den ursprünglichen Netzwerkzustand bootstraps + +Da alle vier Knoten auf localhost laufen, wird während des setup erwartet, dass alle Datenverzeichnisse +für jeden der Knoten im selben übergeordneten Verzeichnis sind. + +:::info Anzahl der Prüfer + +Es gibt keine Mindestanzahl von Knoten in einem Cluster, d. h. Cluster mit nur einem Prüfknoten sind möglich. +Bedenke, dass es bei einem _Einzelknotencluster_ **keine Absturztoleranz** und **keine BFT-Garantie** gibt. + +Die empfohlene Mindestanzahl von Knoten, um eine BFT-Garantie zu erreichen, ist 4, denn in einem Cluster mit 4 Knoten kann der Ausfall +eines Knotens toleriert werden, während die übrigen 3 normal funktionieren. + +::: + +## Schritt 1: Initialisiere Datenordner für IBFT und generiere validator {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +Um mit IBFT aufstehen und laufen zu können, musst du die Datenordner initialisieren. für jeden Knoten: + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +Jeder dieser Befehle gibt den Validator Key, den öffentlichen Key und die [Knoten-ID](https://docs.libp2p.io/concepts/peer-id/) aus. Für den nächsten Schritt benötigst du die Knoten-ID des ersten Knotens. + +### Ausgabe von Secrets {#outputting-secrets} +Die Ausgabe der Secrets kann bei Bedarf wieder abgerufen werden. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## Schritt 2: Bereite den Multiaddr-Verbindungsstring für den Bootknode vor {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Damit ein Knoten erfolgreich eine Verbindung herstellen kann, muss er wissen, mit welchem `bootnode`Server er sich verbinden muss, +um Informationen über alle anderen Knoten im Netzwerk zu erhalten. Der `bootnode` wird im P2P-Jargon manchmal auch als `rendezvous` Server bezeichnet. + +`bootnode`ist keine besondere Instanz des polygon edge Knoten. `bootnode`Jeder polygon-edge kann als ein , aber jeder polygon-edge muss einen Satz von Bootknoten angegeben haben, die kontaktiert werden können, um Informationen darüber zu liefern, man sich mit wie man sich mit allen übrigen Knoten im Netzwerk verbindet. + +Um den Verbindungsstring für die Angabe des Bootnodes zu erstellen, +müssen wir das [multiaddr-Format](https://docs.libp2p.io/concepts/addressing/) einhalten: +``` +/ip4//tcp//p2p/ +``` + +In diesem Leitfaden werden wir den ersten und zweiten Knoten als Bootnode für alle anderen Knoten behandeln. In diesem Szenario +werden die Knoten, die sich mit dem `node 1` oder `node 2` verbinden, Informationen darüber erhalten, wie sie sich über den gegenseitig kontaktierten Bootnode miteinander +verbinden können. + +:::info Du musst mindestens einen Bootnode angeben, um einen Knoten zu beginnen + +Mindestens **ein** Bootnode ist erforderlich, damit sich andere Knoten im Netzwerk finden können. Es werden mehrere Bootnodes empfohlen, da +sie das Netzwerk im Falle von Ausfällen schützen. +In diesem Leitfaden werden wir zwei Knoten auflisten (kann spontan geändert werden), ohne dass dies Auswirkungen auf die Gültigkeit der `genesis.json` Datei hat. +::: + +Da wir auf localhost laufen, ist es sicher, zu glauben, dass der ```127.0.0.1`ist. + +Für die werden ``wir verwenden, `10001`da wir den libp2p Server für konfigurieren, um diesen Port später `node 1`zu hören. + +Und schließlich brauchen wir die ``, die wir aus der Ausgabe des zuvor ausgeführten Befehls `polygon-edge secrets init --data-dir test-chain-1` (mit dem die Keys und Datenverzeichnisse für die `node1` erzeugt wurden) erhalten können + +Nach dem Assembly sieht der Multiaddr-Verbindungsstring zu der `node 1`, die wir als Bootnode verwenden werden, etwa so aus (nur die `` am Ende sollte anders sein): +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +In ähnlicher Weise konstruieren wir Multiaddr für den zweiten Bootnode wie unten gezeigt +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info DNS-Hostnamen anstelle von ips + +Polygon Edge unterstützt die Verwendung von DNS-Hostnamen für die Konfiguration der Knoten. Dies ist eine sehr hilfreiche Funktion für cloudbasierte Einsätze, da sich die IP des Knotens aus verschiedenen Gründen ändern kann. + +Das multiaddr-Format für den Verbindungsstring bei der Verwendung von DNS-Hostnamen lautet wie folgt: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## Schritt 3: Erstelle die Genesis-Datei mit den 4 Knoten als Prüfer {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +Was dieser Befehl tut: + +* Der `--ibft-validators-prefix-path`setzt den prefix auf den angegebenen Pfad, den IBFT in Polygon Edge bestimmt, der verwendet werden kann. Dieses Verzeichnis wird verwendet, um den `consensus/`Ordner zu unterhalten, in dem der private Schlüssel des Prüfers aufbewahrt wird. Der öffentliche Schlüssel des Prüfers wird benötigt, um die Genesis-Datei zu erstellen - die erste Liste der Bootstrap Knoten. Diese Flag macht nur Sinn, wenn das Netzwerk auf localhost eingerichtet ist, da wir in einem realen Szenario nicht alle erwarten können die Datenverzeichnisse der Knoten, um auf dem gleichen Dateisystem zu sein, von dem wir ihre öffentlichen Schlüssel leicht lesen können. +* Der `--bootnode` legt die Adresse des Bootnodes fest, über die sich die Knoten gegenseitig finden können. Wir werden den multiaddr des , wie in **Schritt 2** `node 1`erwähnt, verwenden. + +Das Ergebnis dieses Befehls ist die `genesis.json`Datei, die den Genesis-Block unserer neuen Blockchain enthält, mit dem vordefinierten validator und die Konfiguration, für die der Knoten zuerst kontaktiert werden soll, um die Konnektivität zu etablieren. + +:::info Wechseln zu ECDSA + +BLS ist der default von block Wenn du möchtest, dass deine Chain im ECDSA Modus läuft, kannst du die `—ibft-validator-type`Flagge verwenden, mit dem Argument `ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info Premining der Kontosalden + +Wahrscheinlich wirst du dein Blockchain-Netzwerk so einrichten wollen, dass einige Adressen bereits vorabgebaute (Pre-Mining) Salden haben. + +Um dies zu erreichen, übergibst du so viele `--premine` Flags wie du willst pro Adresse, die mit einem bestimmten Saldo +auf der Blockchain initialisiert werden soll. + +Wenn wir zum Beispiel 1000 ETH an die Adresse `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` in unserem Genesis-Block preminen möchten, müssen wir das folgende Argument angeben: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Beachte, dass der vorausbezahlte Betrag in WEI und nicht in ETH angegeben ist.** + +::: + +:::info Stelle das Blockgaslimit ein + +Der Standard-Gasgrenzwert für jeden Block ist `5242880`. Dieser Wert steht in der Genesis-Datei. Du kannst ihn aber auch +erhöhen oder verringern. + +Dazu kannst du das Flag `--block-gas-limit` verwenden, gefolgt von dem gewünschten Wert, wie unten gezeigt: + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Setze das Limit für Systemdateideskriptoren + +Die Standardgrenze für Dateideskriptoren (maximale Anzahl der geöffneten Dateien) ist auf einigen Betriebssystemen ziemlich niedrig. +Wenn von den Knoten ein hoher Durchsatz erwartet wird, kannst du in Erwägung ziehen, diese Grenze auf Betriebssystemebene zu erhöhen. + +Für die Ubuntu-Distribution ist die Vorgehensweise wie folgt (wenn du keine Ubuntu/Debian-Distribution verwendest, siehe die offiziellen Dokumenten für dein Betriebssystem): +- Überprüfe aktuelle Betriebssystemgrenzen (offene Dateien) +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- Erhöhe das Limit für offene Dateien + - Lokal - betrifft nur die aktuelle Sitzung: + ```shell + ulimit -u 65535 + ``` + - Global oder pro Benutzer (Grenzen am Ende der Datei /etc/security/limits.conf hinzufügen): + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +Optional kannst du weitere Parameter ändern, die Datei speichern und das System neu starten. Überprüfe nach dem Neustart erneut das Limit des Dateideskriptors. +Dieser sollte auf den Wert gesetzt werden, den du in der Datei limits.conf festgelegt hast. + +::: + + +## Schritt 4: Führe alle Clients aus {#step-4-run-all-the-clients} + +Da wir versuchen, ein Polygon Edge-Netzwerk zu betreiben, das aus 4 Knoten besteht, die alle auf demselben Rechner bestehen, müssen wir darauf achten, Konflikte zu vermeiden. Deshalb werden wir die folgende Argumentation verwenden, um die listening jedes Servers eines Knotens zu bestimmen: + +- `10000`für den gRPC von `node 1`, `20000`für den GRPC Server von `node 2`, etc. +- `10001``node 2`für den libp2p Server von `node 1`, `20001`für den Server , etc. +- `10002`für den JSON-RPC-Server von `node 1`, `20002`für den JSON-RPC-Server von `node 2`, etc. + +Um den **ersten** Client auszuführen (beachte den Port , `10001`da er in **Schritt 2** neben der Knoten-ID des Knoten 1 als Teil des libp2p Multiaddr verwendet wurde): + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +Um den **zweiten** Client auszuführen: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +Um den **dritten** Client auszuführen: + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +Um den **vierten** Client auszuführen: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +Um kurz darüber zu gehen, was bisher getan wurde: + +* Das Verzeichnis für die Clientdaten wurde als **./test-chain-\*** angegeben. +* Die GRPC wurden für jeden Knoten auf den Ports **10000**, **20000**, **30000** und **40000** gestartet +* Die libp2p Server wurden für jeden Knoten auf den Ports **10001**, **20001**, **30001** und **40001** gestartet +* Die **JSON-RPC**************-Server wurden für jeden Knoten auf den Ports 10002, 20002, 30002 und 40002 gestartet +* Der *seal* bedeutet, dass der Knoten, der gestartet wird, an der block sealing teilnimmt +* Der *chain* Flag gibt an, welche Genesis-Datei für die Kettenkonfiguration verwendet werden soll + +Die Struktur der Genesis-Datei wird im Abschnitt [CLI-Befehle](/docs/edge/get-started/cli-commands) behandelt. + +Nachdem du die vorherigen Befehle ausgeführt hast, hast du ein 4-Knoten-Polygon-Edge-Netzwerk eingerichtet, das in der Lage ist, Blöcke zu versiegeln und sich von +Knotenausfällen wieder zu erholen. + +:::info Starte den Client mit der Konfigurationsdatei + +Anstatt alle Konfigurationsparameter als CLI-Argumente anzugeben, kann der Client auch mit einer Konfigurationsdatei gestartet werden, indem du folgende Befehl ausführst: + +````bash +polygon-edge server --config +```` +Beispiel: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Derzeit unterstützen `yaml`und `json`basierende Konfigurationsdateien, Beispiel-Konfigurationsdateien finden Sie **[hier](/docs/edge/configuration/sample-config)** + +::: + +:::info Schritte zur Ausführung eines Nicht-Prüfer-Knotens + +Ein Nicht-Prüfer synchronisiert immer die neuesten Blöcke, die er vom Prüfknoten erhält. Du kannst einen Nicht-Prüfer-Knoten starten, indem du den folgenden Befehl ausführst. + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +Du kannst zum Beispiel den **fünften** Nicht-Prüfer-Client hinzufügen, indem du den folgenden Befehl ausführst : + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info Lege das Preislimit fest + +Ein Polygon Edge-Knoten kann mit einem festgelegten **Preislimit** für eingehende Transaktionen gestartet werden. + +Die Einheit für das Preislimit ist `wei`. + +Das Setzen eines Preislimits bedeutet, dass jede Transaktion, die vom aktuellen Knoten verarbeitet wird, einen Gaspreis haben muss, **der höher** +dann das gesetzte Preislimit, sonst wird es nicht in einem Block enthalten. + +Wenn die Mehrheit der Knoten ein bestimmtes Preislimit einhält, wird die Regel durchgesetzt, dass die Transaktionen im Netzwerk +nicht unter einer bestimmten Preisgrenze liegen können. + +Der Standardwert für das Preislimit ist `0`, d. h. es wird standardmäßig überhaupt nicht durchgesetzt. + +Beispiel für die Verwendung des `--price-limit` Flags: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Es ist erwähnenswert, dass Preislimits ** nur für nicht-lokale Transaktionen** durchgesetzt werden, +was bedeutet, dass das Preislimit nicht für Transaktionen gilt, die lokal auf dem Knoten hinzugefügt werden. + +::: + +:::info WebSocket URL + +Wenn du den Polygon Edge ausführst, erzeugt er standardmäßig eine WebSocket-URL, die auf dem Standort der Chain basiert. +Das URL-Schema `wss://` wird für HTTPS-Links und `ws://` für HTTP verwendet. + +Localhost WebSocket URL: +````bash +ws://localhost:10002/ws +```` +Bitte beachte, dass die Portnummer von dem gewählten JSON-RPC-Port für den Knoten abhängt. + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## Schritt 5: Interagiere mit dem Polygon-Edge-Netzwerk {#step-5-interact-with-the-polygon-edge-network} + +Nun, da du mindestens 1 laufende Client eingerichtet hast, kannst du mit dem Konto mit der Blockchain interagieren, das du oben vorbereitet hast und indem du die JSON-RPC-URL auf einen der 4 Knoten spezifizierst: +- Knoten 1:`http://localhost:10002` +- Node 2:`http://localhost:20002` +- Node 3:`http://localhost:30002` +- Knoten 4:`http://localhost:40002` + +Folgen Sie diesem Leitfaden, um Operatorbefehle an den neu erstellten Cluster zu geben: [Wie man die Informationen des Operators abfragt](/docs/edge/working-with-node/query-operator-info) (die GRPC für den Cluster, den wir gebaut haben, sind `10000`/`20000`/`30000`/ `40000`für jeden Knoten) diff --git a/archive/edge/de-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/de-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..530c25b5a2 --- /dev/null +++ b/archive/edge/de-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,445 @@ +--- +id: set-up-ibft-on-the-cloud +title: Cloud-Einrichtung +description: "Schritt-für-Schritt-Leitfaden zur Einrichtung der Cloud." +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info Dieser Leitfaden ist für Mainnet- oder Testnet-Einrichtungen gedacht + +In diesem Leitfaden erfährst du, wie du ein Polygon-Edge-Netzwerk bei einem Cloud-Anbieter für die Produktion deines Testnets oder Mainnets einrichtest. + +Wenn du ein Polygon Edge-Netzwerk lokal einrichten möchtest, um `polygon-edge` vor einer produktionsähnlichen Einrichtung schnell zu testen, lies bitte +**[Lokale Einrichtung](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## Voraussetzungen {#requirements} + +Siehe [Installation](/docs/edge/get-started/installation) zur Installation von Polygon Edge. + +### Einrichten der VM-Verbindung {#setting-up-the-vm-connectivity} + +Je nachdem, für welchen Cloud-Anbieter du dich entscheidest, kannst du die Verbindung und die Regeln zwischen den VMs mithilfe einer Firewall, +von Sicherheitsgruppen oder Zugriffskontrolllisten einrichten. + +Da der einzige Teil von `polygon-edge`, der für andere VMs zugänglich sein muss, der libp2p-Server ist, reicht es aus, +die gesamte Kommunikation zwischen den VMs über den Standard-libp2p-Port `1478` zu erlauben. + +## Übersicht {#overview} + +![Cloud-Einrichtung](/img/edge/ibft-setup/cloud.svg) + +In diesem Leitfaden geht es darum, ein funktionierendes `polygon-edge` Blockchain-Netzwerk aufzubauen, das mit dem [IBFT-Konsensprotokoll](https://github.com/ethereum/EIPs/issues/650) arbeitet. +Das Blockchain-Netzwerk wird aus 4 Knoten bestehen, von denen alle 4 Prüfknoten sind. Als solche sind sie berechtigt, sowohl Blöcke vorzuschlagen als auch Blöcke zu validieren, die von anderen Antragstellern stammen. +Jeder der 4 Knoten wird auf einer eigenen VM ausgeführt, denn die Idee dieses Leitfadens ist es, dir ein voll funktionsfähiges Polygon Edge-Netzwerk zu bieten und gleichzeitig die Validator Keys privat zu halten, um eine vertrauenswürdige Netzwerkeinrichtung zu gewährleisten. + +Um das zu erreichen, führen wir dich durch 4 einfache Schritte: + +0. Sieh dir die Liste der **Voraussetzungen** oben an +1. Erstelle die Private Keys für jeden der Prüfer und initialisiere das Datenverzeichnis +2. Bereite den Verbindungsstring für den Bootnode vor, der in die gemeinsame `genesis.json` eingefügt werden soll +3. Erstelle die `genesis.json` auf deinem lokalen Gerät und sende/übertrage sie an jeden der Knoten +4. Starte alle Knoten + +:::info Anzahl der Prüfer + +Es gibt keine Mindestanzahl von Knoten in einem Cluster, d. h. Cluster mit nur einem Prüfknoten sind möglich. +Bedenke, dass es bei einem _Einzelknotencluster_ **keine Absturztoleranz** und **keine BFT-Garantie** gibt. + +Die empfohlene Mindestanzahl von Knoten, um eine BFT-Garantie zu erreichen, ist 4, denn in einem Cluster mit 4 Knoten kann der Ausfall +eines Knotens toleriert werden, während die übrigen 3 normal funktionieren. + +::: + +## Schritt 1: Initialisiere Datenordner und generiere Validator Keys {#step-1-initialize-data-folders-and-generate-validator-keys} + +Um mit Polygon Edge loslegen zu können, musst du die Datenordner auf jedem Knoten initialisieren: + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +Jeder dieser Befehle gibt den Validator Key, den öffentlichen Key von BLS und die [Knoten-ID](https://docs.libp2p.io/concepts/peer-id/) aus. Für den nächsten Schritt benötigst du die Knoten-ID des ersten Knotens. + +### Ausgabe von Secrets {#outputting-secrets} +Die Ausgabe der Secrets kann bei Bedarf wieder abgerufen werden. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning Behalte dein Datenverzeichnis für dich! + +Die oben erstellten Datenverzeichnisse initialisieren nicht nur die Verzeichnisse für den Blockchain-Status, sondern erzeugen auch die Private Keys deines Prüfers. +**Dieser Key sollte geheim gehalten werden, denn wenn er gestohlen wird, kann sich jemand als Prüfer im Netzwerk ausgeben!** + +::: + +## Schritt 2: Bereite den multiaddr-Verbindungsstring für den Bootnode vor {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Damit ein Knoten erfolgreich eine Verbindung herstellen kann, muss er wissen, mit welchem `bootnode` Server er sich verbinden muss, +um Informationen über alle anderen Knoten im Netzwerk zu erhalten. Der `bootnode` wird im P2P-Jargon manchmal auch als `rendezvous` Server bezeichnet. + +`bootnode` ist kein spezielles Beispiel für einen Polygon Edge-Knoten. Jeder Polygon Edge-Knoten kann als `bootnode` dienen und +jeder Polygon Edge-Knoten muss eine Reihe von Bootnodes festgelegt haben, die kontaktiert werden, um Informationen darüber zu erhalten, +wie man sich mit allen übrigen Knoten im Netzwerk verbindet. + +Um den Verbindungsstring für die Angabe des Bootnodes zu erstellen, +müssen wir das [multiaddr-Format](https://docs.libp2p.io/concepts/addressing/) einhalten: +``` +/ip4//tcp//p2p/ +``` + +In diesem Leitfaden werden wir den ersten und zweiten Knoten als Bootnode für alle anderen Knoten behandeln. In diesem Szenario +werden die Knoten, die sich mit dem `node 1` oder `node 2` verbinden, Informationen darüber erhalten, wie sie sich über den gegenseitig kontaktierten Bootnode miteinander +verbinden können. + +:::info Du musst mindestens einen Bootnode angeben, um einen Knoten zu beginnen + +Mindestens **ein** Bootnode ist erforderlich, damit sich andere Knoten im Netzwerk finden können. Es werden mehrere Bootnodes empfohlen, da +sie das Netzwerk im Falle von Ausfällen schützen. +In diesem Leitfaden werden wir zwei Knoten auflisten (kann spontan geändert werden, ohne dass dies Auswirkungen auf die Gültigkeit der `genesis.json` Datei hat). +::: + +Da der erste Teil des multiaddr-Verbindungsstrings die `` ist, musst du hier die IP-Adresse eingeben, die für andere Knoten erreichbar ist. Je nach deiner Einrichtung kann dies eine private oder eine öffentliche IP-Adresse sein, nicht aber `127.0.0.1`. + +Für `` werden wir `1478` verwenden, da dies der Standard-libp2p-Port ist. + +Und schließlich brauchen wir die ``, die wir aus der Ausgabe des zuvor ausgeführten Befehls `polygon-edge secrets init --data-dir data-dir` (mit dem die Keys und Datenverzeichnisse für die `node 1` erzeugt wurden) erhalten können + +Nach dem Assembly sieht der multiaddr-Verbindungsstring zu der `node 1`, die wir als Bootnode verwenden werden, etwa so aus (nur die `` am Ende sollte anders sein): +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +In ähnlicher Weise konstruieren wir multiaddr für den zweiten Bootnode wie unten gezeigt +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info DNS-Hostnamen anstelle von ips + +Polygon Edge unterstützt die Verwendung von DNS-Hostnamen für die Konfiguration der Knoten. Dies ist eine sehr hilfreiche Funktion für cloudbasierte Einsätze, da sich die IP des Knotens aus verschiedenen Gründen ändern kann. + +Das multiaddr-Format für den Verbindungsstring bei der Verwendung von DNS-Hostnamen lautet wie folgt: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## Schritt 3: Erstelle die Genesis-Datei mit den 4 Knoten als Prüfer {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +Dieser Schritt kann auf deinem lokalen Gerät ausgeführt werden, aber du brauchst die öffentlichen Prüfer-Keys für jeden der 4 Prüfer. + +Die Prüfer können die `Public key (address)`, die unten in der Ausgabe ihrer `secrets init`-Befehle angezeigt wird, sicher weitergeben, so dass +du die genesis.json sicher mit den Prüfern im anfänglichen Prüfer-Set erzeugen kannst, die durch ihre öffentlichen Schlüssel identifiziert werden: + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +Wenn du alle 4 öffentlichen Schlüssel der Prüfer erhalten hast, kannst du den folgenden Befehl ausführen, um `genesis.json` zu erstellen + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +Was dieser Befehl tut: + +* Der `--ibft-validator` legt den öffentlichen Key des Prüfers fest, der in das anfängliche Prüfer-Set im Genesis-Block aufgenommen werden soll. Es kann viele erste Prüfer geben. +* Der `--bootnode` legt die Adresse des Bootnodes fest, über den sich die Knoten gegenseitig finden können. Wir werden den Multiaddr-String des `node 1` verwenden, wie in **Schritt 2** erwähnt, obwohl du so viele Bootnodes hinzufügen kannst, wie du willst, wie oben angezeigt. + +:::info Wechseln zu ECDSA + +BLS ist der default von block Wenn du möchtest, dass deine Chain im ECDSA Modus läuft, kannst du die `—ibft-validator-type`Flagge verwenden, mit dem Argument `ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info Premining der Kontosalden + +Wahrscheinlich wirst du dein Blockchain-Netzwerk so einrichten wollen, dass einige Adressen bereits vorabgebaute (Pre-Mining) Salden haben. + +Um dies zu erreichen, übergibst du so viele `--premine` Flags wie du willst pro Adresse, die mit einem bestimmten Saldo +auf der Blockchain initialisiert werden soll. + +Wenn wir zum Beispiel 1000 ETH an die Adresse `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` in unserem Genesis-Block preminen möchten, müssen wir das folgende Argument angeben: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Beachte, dass der vorausbezahlte Betrag in WEI und nicht in ETH angegeben ist.** + +::: + +:::info Stelle das Blockgaslimit ein + +Der Standard-Gasgrenzwert für jeden Block ist `5242880`. Dieser Wert steht in der Genesis-Datei. Du kannst ihn aber auch +erhöhen oder verringern. + +Dazu kannst du das Flag `--block-gas-limit` verwenden, gefolgt von dem gewünschten Wert, wie unten gezeigt: + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Setze das Limit für Systemdateideskriptoren + +Die Standardgrenze für Dateideskriptoren (maximale Anzahl der geöffneten Dateien) ist auf einigen Betriebssystemen ziemlich niedrig. +Wenn von den Knoten ein hoher Durchsatz erwartet wird, kannst du in Erwägung ziehen, diese Grenze auf Betriebssystemebene zu erhöhen. + +Für die Ubuntu-Distribution ist die Vorgehensweise wie folgt (wenn du keine Ubuntu/Debian-Distribution verwendest, siehe die offiziellen Dokumenten für dein Betriebssystem): +- Überprüfe aktuelle Betriebssystemgrenzen (offene Dateien) +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- Erhöhe das Limit für offene Dateien + - Lokal - betrifft nur die aktuelle Sitzung: + ```shell + ulimit -u 65535 + ``` + - Global oder pro Benutzer (Grenzen am Ende der Datei /etc/security/limits.conf hinzufügen): + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +Optional kannst du weitere Parameter ändern, die Datei speichern und das System neu starten. Überprüfe nach dem Neustart erneut das Limit des Dateideskriptors. +Dieser sollte auf den Wert gesetzt werden, den du in der Datei limits.conf festgelegt hast. + +::: + +Nach der Angabe der: +1. Öffentlichen Keys der Prüfer, die als Prüfer-Set in den Genesis-Block aufgenommen werden sollen +2. Bootnode multiaddr-Verbindungsstrings +3. Wenn du Konten und Salden für den Genesis-Block vorabbaust (Pre-Mining) + +und die `genesis.json` erstellst, solltest du sie auf alle VMs im Netzwerk übertragen. Je nach Einrichtung kannst du +sie kopieren/einfügen, an den Betreiber des Knotens senden oder einfach per SCP/FTP übertragen. + +Die Struktur der Genesis-Datei wird im Abschnitt [CLI-Befehle](/docs/edge/get-started/cli-commands) behandelt. + +## Schritt 4: Führe alle Clients aus {#step-4-run-all-the-clients} + +:::note Vernetzung von Cloud-Anbietern + +Die meisten Cloud-Anbieter stellen die IP-Adressen (vor allem die öffentlichen) nicht als direkte Netzwerkschnittstelle auf deiner VM zur Verfügung, sondern richten einen unsichtbaren NAT-Proxy ein. + + +Damit sich die Knoten untereinander verbinden können, müsstest du in diesem Fall auf der `0.0.0.0` IP-Adresse abhören, um an alle Schnittstellen zu binden. Du müsstest aber immer noch die IP-Adresse oder DNS-Adresse angeben, die andere Knoten verwenden können, um sich mit deiner Instanz zu verbinden. Dazu verwendest du entweder das Argument `--nat` oder `--dns`, in dem du deine externe IP- bzw. DNS-Adresse angeben kannst. + +#### Beispiel {#example} + +Die zugehörige IP-Adresse, die du abhören möchtest, ist `192.0.2.1`, aber sie ist nicht direkt an eine deiner Netzwerkschnittstellen gebunden. + +Damit sich die Knoten verbinden können, musst du die folgenden Parameter übergeben: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +Oder, wenn du eine DNS-Adresse `dns/example.io` angeben möchtest, übergibst du folgende Parameter: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +Dadurch wird dein Knoten an allen Schnittstellen abgehört, aber er weiß auch, dass sich die Clients über die angegebene `--nat` oder `--dns` Adresse mit ihm verbinden. + +::: + +Um den **ersten** Client auszuführen: + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Um den **zweiten** Client auszuführen: + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Um den **dritten** Client auszuführen: + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Um den **vierten** Client auszuführen: + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Nachdem du die vorherigen Befehle ausgeführt hast, hast du ein 4-Knoten-Polygon-Edge-Netzwerk eingerichtet, das in der Lage ist, Blöcke zu versiegeln und sich von +Knotenausfällen wieder zu erholen. + +:::info Starte den Client mit der Konfigurationsdatei + +Anstatt alle Konfigurationsparameter als CLI-Argumente anzugeben, kann der Client auch mit einer Konfigurationsdatei gestartet werden, indem du den folgenden Befehl ausführst: + +````bash +polygon-edge server --config +```` +Beispiel: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Derzeit unterstützen wir nur die `json`basierte Konfigurationsdatei, die Beispiel-Konfigurationsdatei findet ihr **[hier](/docs/edge/configuration/sample-config)** + +::: + +:::info Schritte zur Ausführung eines Nicht-Prüfer-Knotens + +Ein Nicht-Prüfer synchronisiert immer die neuesten Blöcke, die er vom Prüfknoten erhält. Du kannst einen Nicht-Prüfer-Knoten starten, indem du den folgenden Befehl ausführst. + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +Du kannst zum Beispiel den **fünften** Nicht-Prüfer-Client hinzufügen, indem du den folgenden Befehl ausführst : + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info Lege das Preislimit fest + +Ein Polygon Edge-Knoten kann mit einem festgelegten **Preislimit** für eingehende Transaktionen gestartet werden. + +Die Einheit für das Preislimit ist `wei`. + +Das Setzen eines Preislimits bedeutet, dass jede Transaktion, die vom aktuellen Knoten verarbeitet wird, einen Gaspreis haben muss, **der höher** +als das gesetzte Preislimit ist, sonst wird sie nicht in einen Block aufgenommen. + +Wenn die Mehrheit der Knoten ein bestimmtes Preislimit einhält, wird die Regel durchgesetzt, dass die Transaktionen im Netzwerk +nicht unter einer bestimmten Preisgrenze liegen können. + +Der Standardwert für das Preislimit ist `0`, d. h. es wird standardmäßig überhaupt nicht durchgesetzt. + +Beispiel für die Verwendung des `--price-limit` Flags: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Es ist erwähnenswert, dass Preislimits ** nur für nicht-lokale Transaktionen** durchgesetzt werden, +was bedeutet, dass das Preislimit nicht für Transaktionen gilt, die lokal auf dem Knoten hinzugefügt werden. + +::: + +:::info WebSocket URL + +Wenn du den Polygon Edge ausführst, erzeugt er standardmäßig eine WebSocket-URL, die auf dem Standort der Chain basiert. +Das URL-Schema `wss://` wird für HTTPS-Links und `ws://` für HTTP verwendet. + +Localhost WebSocket URL: +````bash +ws://localhost:10002/ws +```` +Bitte beachte, dass die Portnummer von dem gewählten JSON-RPC-Port für den Knoten abhängt. + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/de-edge/get-started/terraform-aws-deployment.md b/archive/edge/de-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..1738e4c99b --- /dev/null +++ b/archive/edge/de-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,176 @@ +--- +id: terraform-aws-deployment +title: Terraform AWS Bereitstellung +description: "Bereitstellen des Polygon Edge-Netzwerks auf dem AWS-Cloud-Anbieter mit Terraform" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info Leitfaden zur Produktionsbereitstellung + +Dies ist der offizielle, produktionsreife, vollständig automatisierte AWS-Bereitstellungsleitfaden. + +Manuelle Bereitstellungen in der ***[Cloud](set-up-ibft-on-the-cloud)*** oder ***[lokal](set-up-ibft-locally)*** +werden für Tests empfohlen und/oder wenn dein Cloud-Anbieter nicht AWS ist. +::: + +:::info + +Diese Bereitstellung ist nur PoA. +Wenn du einen PoS-Mechanismus brauchst, folge einfach diesem ***[Leitfaden](/docs/edge/consensus/migration-to-pos)***, um von PoA zu PoS zu wechseln. + +::: + +In diesem Leitfaden wird detailliert beschrieben, wie ein Polygon Edge-Blockchain-Netzwerk auf dem AWS Cloud-Anbieter +bereitgestellt wird. Dieses Netzwerk ist produktionsbereit, da die Prüfknoten über mehrere Verfügbarkeitszonen verteilt sind. + +## Voraussetzungen {#prerequisites} + +### System-Tools {#system-tools} +* [terraform](https://www.terraform.io/) +* [aws cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [aws access key ID und secret access key](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Terraform Variablen {#terraform-variables} +Zwei Variablen, die bereitgestellt werden müssen, bevor du die Bereitstellung durchführst: + +* `alb_ssl_certificate` - die ARN des Zertifikats aus dem AWS Certificate Manager, das vom ALB für das https-Protokoll verwendet werden soll. + Das Zertifikat muss vor dem Start der Bereitstellung erstellt werden und den Status **ausgestellt** haben. +* `premine` - das Konto, das die vorabgebaute (Pre-Mining) native Währung erhält. +Der Wert muss der offiziellen [CLI](/docs/edge/get-started/cli-commands#genesis-flags)-Flag-Spezifikation entsprechen + +## Informationen zur Bereitstellung {#deployment-information} +### Bereitgestellte Ressourcen {#deployed-resources} +Überblick über die Ressourcen, die bereitgestellt werden sollen: + +* Dedizierter VPC +* 4 Prüfknoten (die auch Boot-Knoten sind) +* 4 NAT-Gateways, um Knoten für den ausgehenden Internetverkehr zuzulassen +* Lambda-Funktion zur Generierung des ersten (Genesis-)Blöcke und zum Starten der Chain +* Dedizierte Sicherheitsgruppen und IAM-Rollen +* S3 Bucket für die Speicherung der genesis.json-Datei +* Anwendungs-Load-Balancer, der für die Bereitstellung des JSON-RPC-Endpunkts verwendet wird + +### Fehlertoleranz {#fault-tolerance} + +Für diese Bereitstellung werden nur Regionen mit 4 Verfügbarkeitszonen benötigt. Jeder Knoten ist in einem einzelnen AZ bereitgestellt. + +Durch die Platzierung jedes Knotens in einem einzelnen AZ ist der gesamte Blockchain-Cluster fehlertolerant gegenüber dem Ausfall eines einzelnen Knotens (AZ). Polygon Edge implementiert den IBFT- +Konsens, der den Ausfall eines einzelnen Knotens in einem Cluster aus 4 Prüfknoten ermöglicht. + +### Befehlszeilenzugriff {#command-line-access} + +Die Prüfknoten sind in keinster Weise dem öffentlichen Internet ausgesetzt (auf JSON-PRC wird nur über ALB zugegriffen) +und sie haben nicht einmal öffentliche IP-Adressen. +Der Zugriff auf die Befehlszeile des Knotens ist nur über [den AWS Systems Manager - Session Manager](https://aws.amazon.com/systems-manager/features/) möglich. + +### Grundlegendes AMI-Upgrade {#base-ami-upgrade} + +Diese Bereitstellung verwendet `ubuntu-focal-20.04-amd64-server` AWS AMI. Es wird **keine** erneute EC2-*Bereitstellung* ausgelöst, wenn das AWS AMI aktualisiert wird. + +Wenn aus irgendeinem Grund das Basis-AMI aktualisiert werden muss, +kann dies erreicht werden, indem der Befehl `terraform taint` für jede Instanz vor `terraform apply` ausgeführt wird. +Instanzen können durch den Befehl +`terraform taint module.instances[].aws_instance.polygon_edge_instance` beschädigt werden. + +Beispiel: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info + +In einer Produktionsumgebung sollte `terraform taint` einzeln nacheinander ausgeführt werden, um das Blockchain-Netzwerk funktionsfähig zu halten. + +::: + +## Bereitstellungsverfahren {#deployment-procedure} + +### Schritte zur Vorbereitung der Bereitstellung {#pre-deployment-steps} +* Lies dir die Readme-Seite der Terraform [Polygon-Technology-Edge](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) durch +* Füge das `polygon-technology-edge` Modul deiner `main.tf`-Datei hinzu, indem du die *Breitstellungs-Anweisungen* auf der Readme-Seite der Module verwendest. +* Führe den Befehl `terraform init` aus, um alle notwendigen Terraform-Abhängigkeiten zu installieren. +* Stelle ein neues Zertifikat im [AWS Certificate Manager](https://aws.amazon.com/certificate-manager/) bereit. +* Vergewissere dich, dass sich das bereitgestellte Zertifikat im Status **Ausgestellt** befindet und notiere dir die **ARN** des Zertifikats. +* Richte deine Ausgabeanweisung ein, um die Ausgabe der Module in CLI zu erhalten. + +#### `main.tf` Beispiel {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### `terraform.tfvars` Beispiel {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### Schritte zur Bereitstellung {#deployment-steps} +* Erstelle die `terraform.tfvars`-Datei. +* Stelle die erforderlichen Terraform-Variablen in dieser Datei ein (wie oben erklärt). +:::info + +Es gibt noch weitere, nicht obligatorische Variablen, mit denen du diese Bereitstellung vollständig anpassen kannst. +Du kannst die Standardwerte außer Kraft setzen, indem du deine eigenen Werte in die `terraform.tfvars`-Datei einträgst. + +Die Angabe aller verfügbaren Variablen findest du in der Terraform-***[Registry](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)*** der Module + +::: +* Vergewissere dich, dass du die aws cli-Authentifizierung richtig eingerichtet hast, indem du `aws s3 ls` ausführst - es sollten keine Fehler auftreten. +* Stelle die Infrastruktur `terraform apply` bereit. + +### Schritte nach der Bereitstellung {#post-deployment-steps} +* Sobald die Bereitstellung abgeschlossen ist, notiere dir den Wert der Variablen `json_rpc_dns_name`, der in cli erscheint. +* Erstelle einen öffentlichen dns cname-Eintrag, der deinen Domänennamen mit dem angegebenen `json_rpc_dns_name` Wert ausrichtet. Beispiel: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* Sobald der cname-Datensatz übertragen wurde, überprüfe, ob die Chain richtig funktioniert, indem du deinen JSON-PRC-Endpunkt aufrufst. + Aus dem obigen Beispiel: + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## Zerstörungsverfahren {#destroy-procedure} +:::warning + +Das folgende Verfahren löscht deine gesamte Infrastruktur, die mit diesen Terraform-Skripten eingerichtet wurde. +Vergewissere dich, dass du ordnungsgemäße [Blockchain-Datensicherungen](docs/edge/working-with-node/backup-restore) hast und/oder mit einer Testumgebung arbeitest. + +::: + +Falls du die gesamte Infrastruktur entfernen musst, führe folgenden Befehl aus `terraform destroy`. +Außerdem musst du die im AWS [Parameter Store](https://aws.amazon.com/systems-manager/features/) gespeicherten Geheimnisse für die Region, +in der die Bereitstellung stattfand, manuell entfernen. diff --git a/archive/edge/de-edge/overview.md b/archive/edge/de-edge/overview.md new file mode 100644 index 0000000000..c434c1cdb0 --- /dev/null +++ b/archive/edge/de-edge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Polygon Edge +sidebar_label: What is Edge +description: "Eine Einführung in Polygon Edge." +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +Polygon Edge ist ein modulares und erweiterbares Framework zum Aufbau von Ethereum-kompatiblen Blockchain-Netzwerken, Sidechains und allgemeinen Skalierungslösungen. + +Es dient in erster Linie dazu, ein neues Blockchain-Netzwerk zu erstellen, und bietet gleichzeitig volle Kompatibilität mit Ethereum Smart-Contracts und Transaktionen. Es verwendet den IBFT (Istanbul Byzantine Fault Tolerant) Konsensmechanismus, der in zwei Varianten als [PoA (Proof of Authority (Autoritätsnachweis](/docs/edge/consensus/poa))) und [PoS (Proof of Stake (Anspruchsnachweis))](/docs/edge/consensus/pos-stake-unstake) unterstützt wird. + +Polygon Edge unterstützt auch die Kommunikation mit mehreren Blockchain-Netzwerken und ermöglicht die Übertragung von [ERC-20-](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) und [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721)-Tokens, indem es die [zentralisierte Bridge-Lösung](/docs/edge/additional-features/chainbridge/overview) nutzt. + +Standardmäßige Wallets können zur Interaktion mit Polygon Edge über die [JSON-RPC](/docs/edge/working-with-node/query-json-rpc)-Endpunkte verwendet werden. Bediener von Knotenpunkten können über das [gRPC](/docs/edge/working-with-node/query-operator-info)-Protokoll verschiedene Aktionen auf den Knotenpunkten durchführen. + +Um mehr über Polygon zu erfahren, besuche die [offizielle Website](https://polygon.technology). + +**[GitHub Repository](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +Es handelt sich um ein Projekt, an dem noch gearbeitet wird. Es kann also sein, dass sich die Architektur in Zukunft ändert. Der Code wurde noch nicht geprüft. +Bitte kontaktiere das Polygon-Team, wenn du ihn in der Produktion verwenden möchtest. + +::: + + + +Um mit der lokalen Ausführung eines `polygon-edge` Netzwerks zu beginnen, lies bitte: [Installation](/docs/edge/get-started/installation) und [lokale Einrichtung](/docs/edge/get-started/set-up-ibft-locally). diff --git a/archive/edge/de-edge/performance-reports/overview.md b/archive/edge/de-edge/performance-reports/overview.md new file mode 100644 index 0000000000..8af601fa3f --- /dev/null +++ b/archive/edge/de-edge/performance-reports/overview.md @@ -0,0 +1,32 @@ +--- +id: overview +title: Übersicht +description: "Einführung in den Polygon Edge Test." +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +Bitte beachte, dass unsere , `loadbot`die für die Durchführung dieser Tests verwendet wurde, jetzt abgeschrieben wird. +::: + +| Art | Wert | Link zum Test | +| ---- | ----- | ------------ | +| Regelmäßige Transfers | 1428 tps | [4. Juli 2022](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| ERC-20-Transfers | 1111 tps | [4. Juli 2022](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| NFT-Minting | 714 tps | [4. Juli 2022](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +Unser Ziel ist es, eine hochperformante, funktionsreiche und einfach einzurichtende und zu wartende Blockchain-Client-Software zu entwickeln. +Alle Tests wurden mit dem Polygon Edge Loadbot durchgeführt. +Jeder Leistungsbericht, den du in diesem Abschnitt findest, ist ordnungsgemäß datiert, die Umgebung klar beschrieben und die Prüfmethode deutlich erklärt. + +Das Ziel dieser Leistungstests ist es, die reale Leistung des Polygon Edge Blockchain-Netzwerks zu zeigen. +Alle sollten in der Lage sein, mit unserem Loadbot in der gleichen Umgebung die gleichen Ergebnisse zu erzielen wie hier gezeigt. + +Alle Leistungstests wurden auf der AWS-Plattform auf einer Kette (Chain) bestehend aus EC2-Instanzknoten durchgeführt. \ No newline at end of file diff --git a/archive/edge/de-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/de-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..14db2bdc44 --- /dev/null +++ b/archive/edge/de-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,130 @@ +--- +id: test-2022-01-21 +title: 21. Januar 2022 +description: "Performance Test ab dem 21. Januar." +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## 21. Januar 2022 {#january-21st-2022} + +### Zusammenfassung {#summary} + +:::caution +Bitte beachte, dass unsere , `loadbot`die für die Durchführung dieser Tests verwendet wurde, jetzt abgeschrieben wird. +::: + +Dieser Test wurde nach dem TxPool refactor durchgeführt, der [die](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0) Leistung erheblich verbessert hat (veröffentlicht in v0.2.0). + +Das Ziel war es, ein großes Netzwerk zu gründen, bestehend aus 30 aktiv teilnehmenden Prüfern consensus und TxPool Transaktion Gossiping da alle Transaktionen an den JSON-RPC eines einzelnen Knotens gesendet wurden. + +Unser Ziel war es nicht, zu versuchen, eine maximal mögliche TPS zu erreichen, da die Netzwerkgröße die Leistung negativ beeinflusst, und da die Zeit von block begrenzt & block auf Werte eingestellt sind, die nicht viele Systemressourcen verbrauchen, und es erlauben würde, auf der commodity zu laufen. + +### Ergebnisse {#results} + +| Metrik | Wert | +| ------ | ----- | +| Transaktionen pro Sekunde | 344 | +| Transaktionen fehlgeschlagen | 0 | +| Transaktionen erfolgreich | 10000 | +| Gesamtlaufzeit | 30 s | + +### Umgebung {#environment} + +
+ Host-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud-AnbieterAWS
Instanzgrößet2.xlarge
Vernetzungprivates Subnetz
BetriebssystemLinux Ubuntu 20.04 LTS - Focal Fossa
Datei-Deskriptor-Grenze65535
Maximale Benutzerprozesse65535
+
+
+
+
+ +
+ Blockchain-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge VersionCommit 8377162281d1a2e4342ae27cd4e5367c4364aee2 auf Entwicklungszweig
Validator-Knoten30
Nicht-Validator-Knoten0
KonsensIBFT PoA
Blockzeit2000 ms
Blockgaslimit5242880
+
+
+
+
+ +
+ Loadbot-Konfiguration +
+
+ + + + + + + + + + + + + +
Gesamttransaktionen10000
Gesendete Transaktionen pro Sekunde400
Art der TransaktionenEOA-zu-EOA-Transfers
+
+
+
+
diff --git a/archive/edge/de-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/de-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..c6950fc934 --- /dev/null +++ b/archive/edge/de-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,389 @@ +--- +id: test-2022-03-02 +title: 2. März 2022 +description: "Performance-Test vom 2. März." +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### Zusammenfassung {#summary} + +:::caution +Bitte beachte, dass unsere , `loadbot`die für die Durchführung dieser Tests verwendet wurde, jetzt abgeschrieben wird. +::: + +Dieser Test wurde durchgeführt, um die SC ERC20 Token-Transfers und die SC ERC721 token mit schweren Lasten und Geschwindigkeit der Transaktionen zu messen. + +Das Ziel war es, zu überprüfen, ob bei hoher Belastung alles wie erwartet funktioniert. Das war auch der Grund, warum wir in der Loadbot-Ausgabe Gas-Metriken eingeführt haben, die uns zeigen, ob die Blöcke richtig mit Transaktionen gefüllt sind. + +Alle Transaktionen wurden über die GRPC-API an den einzelnen Knotenpunkt gesendet, und die Belege wurden über die JSON-RPC-API empfangen. Nachdem alle Transaktionen abgeschlossen waren, wurden die Informationen zum Gas von jedem Block mit der JSON-RPC-Methode eth_getBlockByNumber gelesen. + +Unser Ziel war es nicht, zu versuchen, eine maximal mögliche TPS erreichen, und da die Zeit von block begrenzt & block auf Werte eingestellt sind, die nicht viele Systemressourcen verbrauchen, und es erlauben würde, auf der commodity zu laufen. + +### Ergebnisse ERC20 {#results-erc20} + +| Metrik | Wert | +| ------ | ----- | +| Transaktionsart | ERC20 | +| Transaktionen pro Sekunde | 65 | +| Transaktionen fehlgeschlagen | 0 | +| Transaktionen erfolgreich | 5000 | +| ERC20-Transaktionslaufzeit | 76.681690s | +| SC Bereitstellungszeit | 4.048250s | + +### Ergebnisse ERC721 {#results-erc721} + +| Metrik | Wert | +| ------ | ----- | +| Transaktionsart | ERC721 | +| Transaktionen pro Sekunde | 20 | +| Transaktionen fehlgeschlagen | 0 | +| Transaktionen erfolgreich | 2000 | +| ERC721-Transaktionslaufzeit | 97.239920s | +| SC Bereitstellungszeit | 3.048970s | + +### Umgebung ERC20 {#environment-erc20} + +
+ Host-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud-AnbieterAWS
Instanzgrößet2.micro
Vernetzungprivates Subnetz
BetriebssystemLinux Ubuntu 20.04 LTS - Focal Fossa
Datei-Deskriptor-Grenze65535
Maximale Benutzerprozesse65535
+
+
+
+
+ +
+ Blockchain-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge VersionCommit 8a033aa1afb191abdac04636d318f83f32511f3c auf der Entwicklungsstelle
Validator-Knoten6
Nicht-Validator-Knoten0
KonsensIBFT PoA
Blockzeit2s
Blockgaslimit5242880
Durchschnittliche Blockauslastung95%
+
+
+
+
+ +
+ Loadbot-Konfiguration +
+
+ + + + + + + + + + + + + +
Gesamttransaktionen5000
Gesendete Transaktionen pro Sekunde200
Art der TransaktionenERC20-zu-ERC20-Transfers
+
+
+
+
+ +
+ Loadbot-Protokoll + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### Umgebung ERC721 {#environment-erc721} + +
+ Host-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud-AnbieterAWS
Instanzgrößet2.micro
Vernetzungprivates Subnetz
BetriebssystemLinux Ubuntu 20.04 LTS - Focal Fossa
Datei-Deskriptor-Grenze65535
Maximale Benutzerprozesse65535
+
+
+
+
+ +
+ Blockchain-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge VersionCommit 8a033aa1afb191abdac04636d318f83f32511f3c auf der Entwicklungsstelle
Validator-Knoten6
Nicht-Validator-Knoten0
KonsensIBFT PoA
Blockzeit2s
Blockgaslimit5242880
Durchschnittliche Blockauslastung94%
+
+
+
+
+ +
+ Loadbot-Konfiguration +
+
+ + + + + + + + + + + + + +
Gesamttransaktionen2000
Gesendete Transaktionen pro Sekunde200
Art der TransaktionenERC721-Token-Mint
+
+
+
+
+ +
+ Loadbot-Protokoll + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/de-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/de-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..ea6c59b015 --- /dev/null +++ b/archive/edge/de-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,955 @@ +--- +id: test-2022-03-23 +title: 23. März 2022 +description: "Performance-Test vom 23. März." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### Zusammenfassung {#summary} + +:::caution +Bitte beachte, dass unsere , `loadbot`die für die Durchführung dieser Tests verwendet wurde, jetzt abgeschrieben wird. +::: + +Dieser Test wurde durchgeführt, um die Funktionen der SC ERC20-Token-Transfers, des SC ERC721-Token-Minting und der EOA-zu-EOA-Transaktionen unter hoher Belastung und die Geschwindigkeit der Transaktionen auf den Knotenpunkten mit höheren Hardware-Ressourcen zu messen. + +Das Ziel war es, zu überprüfen, ob bei hoher Belastung alles wie erwartet funktioniert. Das war auch der Grund, warum wir in der Loadbot-Ausgabe Gas-Metriken eingeführt haben, die uns zeigen, ob die Blöcke richtig mit Transaktionen gefüllt sind. + +Alle Transaktionen wurden über die GRPC-API an den einzelnen Knotenpunkt gesendet, und die Belege wurden über die JSON-RPC-API empfangen. Nachdem alle Transaktionen abgeschlossen waren, wurden die Informationen zum Gas von jedem Block mit der JSON-RPC-Methode eth_getBlockByNumber gelesen. + +Unser Ziel war es, mit den zur Verfügung stehenden Hardware-Ressourcen eine möglichst hohe TPS zu erreichen. +Um dies zu erreichen, haben wir die Parameter für das Blockgaslimit und die Blockzeit geändert, um die bestmöglichen tps-Ergebnisse zu erzielen und die Integrität und Stabilität des Systems zu erhalten. + +:::info Block Gas Limit +Blockgaslimit kann auf eine relativ hohe Anzahl erhöht werden, wenn die Transaktionen viel Gas ausführen. Im angeführten Beispiel wurde der ERC721 Token-Minting viel schneller mit einer Blockgaslimit auf 80 000 000 (statt 20 Mil.) gearbeitet, aber mit ERC20-Token-Transfers mit 80 Mil. Blockgaslimit stürzte der Server ab. +::: + +:::info Produktionsumgebungen + +Wenn du eine Produktionsumgebung konfigurierst, musst du vorsichtig sein, wenn du eine hohe Leistung der Kette (Chain) erreichen willst. +Wenn der Parameter für das Blockgaslimit auf einen hohen Wert und die Blockzeit auf 1s eingestellt ist und eine hohe Transaktionslast auf einem einzelnen Knoten vorliegt, verbraucht dieser Knoten viel (wenn nicht sogar den gesamten verfügbaren) Arbeitsspeicher und kann einen Serverabsturz verursachen. +Nutze den Loadbot, um alles gründlich zu testen, die Auslastung der Systemressourcen zu überwachen und deine Konfigurationsparameter entsprechend einzustellen. + +::: + +:::info Out of Memory Fehler +Einige linux distros töten den Prozess automatsich, der eine sehr hohe RAM-Auslastung (OMM Fehler) hat, um die Systemstabilität zu erhalten. Die Protokollausgabe dieses OMM Fehlers sieht wie u. a. aus. +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### Ergebnisse von EOA-zu-EOA-Transfers {#results-of-eoa-to-eoa-transfers} +| Metrik | Wert | +| ------ | ----- | +| Transaktionsart | EOA zu EOA | +| Transaktionen pro Sekunde | 689 | +| Transaktionen fehlgeschlagen | 0 | +| Transaktionen erfolgreich | 20000 | +| Verwendete Blöcke insgesamt | 25 | +| Gesamtlaufzeit | 29.921110s | + +### Ergebnisse von ERC20-Token-Transfers {#results-of-erc20-token-transfers} + +| Metrik | Wert | +| ------ | ----- | +| Transaktionsart | ERC20 | +| Transaktionen pro Sekunde | 500 | +| Transaktionen fehlgeschlagen | 0 | +| Transaktionen erfolgreich | 20000 | +| Verwendete Blöcke insgesamt | 33 | +| ERC20-Transaktionslaufzeit | 40.402900s | +| SC Bereitstellungszeit | 2.004140s | + +### Ergebnisse des ERC721-Token-Minting {#results-of-erc721-token-minting} + +| Metrik | Wert | +| ------ | ----- | +| Transaktionsart | ERC721 | +| Transaktionen pro Sekunde | 157 | +| Transaktionen fehlgeschlagen | 0 | +| Transaktionen erfolgreich | 20000 | +| Verwendete Blöcke insgesamt | 124 | +| ERC721-Transaktionslaufzeit | 127.537340s | +| SC Bereitstellungszeit | 2.004420s | + + +### Ergebnisse der ERC721-Token-Minting mit einer sehr hohen block gas limit (80 Mil.) {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| Metrik | Wert | +| ------ | ----- | +| Transaktionsart | ERC721 | +| Transaktionen pro Sekunde | 487 | +| Transaktionen fehlgeschlagen | 0 | +| Transaktionen erfolgreich | 20000 | +| Verwendete Blöcke insgesamt | 34 | +| ERC721-Transaktionslaufzeit | 41.098410s | +| SC Bereitstellungszeit | 2.004300s | + + +### Umgebung EOA zu EOA {#environment-eoa-to-eoa} +
+ Host-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud-AnbieterAWS
Instanzgrößec5.2xlarge
Vernetzungprivates Subnetz
BetriebssystemAmazon Linux 2 AMI (HVM) - Kernel 5.10
Datei-Deskriptor-Grenze65535
Maximale Benutzerprozesse65535
+
+
+
+
+ +
+ Blockchain-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge VersionCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 auf Entwicklungszweig
Validator-Knoten4
Nicht-Prüfknoten0
KonsensIBFT PoA
Blockzeit1 s
Blockgaslimit20000000
Max. Slots1000000
Durchschnittliche Blockauslastung84.00%
+
+
+
+
+ +
+ Loadbot-Konfiguration +
+
+ + + + + + + + + + + + + +
Gesamttransaktionen20000
Gesendete Transaktionen pro Sekunde689
Art der TransaktionenEOA-zu-EOA-Transfers
+
+
+
+
+ +
+ Loadbot-Protokoll + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### Umgebung ERC20 {#environment-erc20} +
+ Host-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud-AnbieterAWS
Instanzgrößec5.2xlarge
Vernetzungprivates Subnetz
BetriebssystemAmazon Linux 2 AMI (HVM) - Kernel 5.10
Datei-Deskriptor-Grenze65535
Maximale Benutzerprozesse65535
+
+
+
+
+ +
+ Blockchain-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge VersionCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 auf Entwicklungszweig
Validator-Knoten4
Nicht-Prüfknoten0
KonsensIBFT PoA
Blockzeit1 s
Blockgaslimit20000000
Max. Slots1000000
Durchschnittliche Blockauslastung88.38%
+
+
+
+
+ +
+ Loadbot-Konfiguration +
+
+ + + + + + + + + + + + + +
Gesamttransaktionen20000
Gesendete Transaktionen pro Sekunde500
Art der TransaktionenERC20-zu-ERC20-Transfers
+
+
+
+
+ +
+ Loadbot-Protokoll + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### Umgebung ERC721 {#environment-erc721} +
+ Host-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud-AnbieterAWS
Instanzgrößec5.2xlarge
Vernetzungprivates Subnetz
BetriebssystemAmazon Linux 2 AMI (HVM) - Kernel 5.10
Datei-Deskriptor-Grenze65535
Maximale Benutzerprozesse65535
+
+
+
+
+ +
+ Blockchain-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge VersionCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 auf Entwicklungszweig
Validator-Knoten4
Nicht-Prüfknoten0
KonsensIBFT PoA
Blockzeit1 s
Blockgaslimit20000000
Max. Slots1000000
Durchschnittliche Blockauslastung92.90%
+
+
+
+
+ +
+ Loadbot-Konfiguration +
+
+ + + + + + + + + + + + + +
Gesamttransaktionen20000
Gesendete Transaktionen pro Sekunde157
Art der TransaktionenERC721-Token-Mint
+
+
+
+
+ +
+ Loadbot-Protokoll + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### Umgebung ERC20 - sehr hohes Blockgaslimit {#environment-erc20-very-high-block-gas-limit} +
+ Host-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud-AnbieterAWS
Instanzgrößec5.2xlarge
Vernetzungprivates Subnetz
BetriebssystemAmazon Linux 2 AMI (HVM) - Kernel 5.10
Datei-Deskriptor-Grenze65535
Maximale Benutzerprozesse65535
+
+
+
+
+ +
+ Blockchain-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge VersionCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 auf Entwicklungszweig
Validator-Knoten4
Nicht-Prüfknoten0
KonsensIBFT PoA
Blockzeit1 s
Blockgaslimit80000000
Max. Slots1000000
Durchschnittliche Blockauslastung---
+
+
+
+
+ +
+ Loadbot-Konfiguration +
+
+ + + + + + + + + + + + + +
Gesamttransaktionen20000
Gesendete Transaktionen pro Sekunde---
Art der TransaktionenERC20-zu-ERC20-Transfers
+
+
+
+
+ +
+ OOM Error log + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### Umgebung ERC721 - sehr hohes Blockgaslimit {#environment-erc721-very-high-block-gas-limit} +
+ Host-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud-AnbieterAWS
Instanzgrößec5.2xlarge
Vernetzungprivates Subnetz
BetriebssystemAmazon Linux 2 AMI (HVM) - Kernel 5.10
Datei-Deskriptor-Grenze65535
Maximale Benutzerprozesse65535
+
+
+
+
+ +
+ Blockchain-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge VersionCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 auf Entwicklungszweig
Validator-Knoten4
Nicht-Prüfknoten0
KonsensIBFT PoA
Blockzeit1 s
Blockgaslimit80000000
Max. Slots1000000
Durchschnittliche Blockauslastung84.68%
+
+
+
+
+ +
+ Loadbot-Konfiguration +
+
+ + + + + + + + + + + + + +
Gesamttransaktionen20000
Gesendete Transaktionen pro Sekunde487
Art der TransaktionenERC721-Token-Mint
+
+
+
+
+ +
+ Loadbot-Protokoll + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/de-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/de-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..cf17da8adc --- /dev/null +++ b/archive/edge/de-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,568 @@ +--- +id: test-2022-07-04 +title: 4. Juli 2022 +description: "Leistungstest vom 4. Juli" +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### Zusammenfassung {#summary} + +:::caution +Bitte beachte, dass unsere , `loadbot`die für die Durchführung dieser Tests verwendet wurde, jetzt abgeschrieben wird. +::: + +Dieser Test wurde durchgeführt, um die Funktionen der SC ERC20-Token-Transfers, des SC ERC721-Token-Minting und der EOA-zu-EOA-Transaktionen unter hoher Belastung und die Geschwindigkeit der Transaktionen auf den Knotenpunkten mit höheren Hardware-Ressourcen zu messen. + +Das Ziel war es, zu überprüfen, ob bei hoher Belastung alles wie erwartet funktioniert. Das war auch der Grund, warum wir in der Loadbot-Ausgabe Gas-Metriken eingeführt haben, die uns zeigen, ob die Blöcke richtig mit Transaktionen gefüllt sind. + +Alle Transaktionen wurden über die GRPC-API an den einzelnen Knotenpunkt gesendet, und die Belege wurden über die JSON-RPC-API empfangen. Nachdem alle Transaktionen abgeschlossen waren, wurden die Informationen zum Gas von jedem Block mit der JSON-RPC-Methode eth_getBlockByNumber gelesen. + +Unser Ziel war es, mit den zur Verfügung stehenden Hardware-Ressourcen eine möglichst hohe TPS zu erreichen. +Um dies zu erreichen, haben wir die Parameter für das Blockgaslimit und die Blockzeit geändert, um die bestmöglichen tps-Ergebnisse zu erzielen und die Integrität und Stabilität des Systems zu erhalten. + + +:::info Produktionsumgebungen + +Wenn du eine Produktionsumgebung konfigurierst, musst du vorsichtig sein, wenn du eine hohe Leistung der Kette (Chain) erreichen willst. +Wenn der Parameter für das Blockgaslimit auf einen hohen Wert und die Blockzeit auf 1s eingestellt ist und eine hohe Transaktionslast auf einem einzelnen Knoten vorliegt, verbraucht dieser Knoten viel (wenn nicht sogar den gesamten verfügbaren) Arbeitsspeicher und kann einen Serverabsturz verursachen. +Nutze den Loadbot, um alles gründlich zu testen, die Auslastung der Systemressourcen zu überwachen und deine Konfigurationsparameter entsprechend einzustellen. + +::: + + + +### Ergebnisse von EOA-zu-EOA-Transfers {#results-of-eoa-to-eoa-transfers} +| Metrik | Wert | +| ------ | ----- | +| Transaktionsart | EOA zu EOA | +| Transaktionen pro Sekunde | 1428 | +| Fehlgeschlagene Transaktionen | 0 | +| Erfolgreiche Transaktionen | 30.000 | +| Verwendete Blöcke insgesamt | 15 | +| Gesamtlaufzeit | 21,374620 s | + +### Ergebnisse von ERC20-Token-Transfers {#results-of-erc20-token-transfers} + +| Metrik | Wert | +| ------ | ----- | +| Transaktionsart | ERC20 | +| Transaktionen pro Sekunde | 1111 | +| Fehlgeschlagene Transaktionen | 0 | +| Erfolgreiche Transaktionen | 50.000 | +| Verwendete Blöcke insgesamt | 38 | +| ERC20-Transaktionslaufzeit | 45,906450 s | +| SC Bereitstellungszeit | 2,006580 s | + +### Ergebnisse des ERC721-Token-Minting {#results-of-erc721-token-minting} + +| Metrik | Wert | +| ------ | ----- | +| Transaktionsart | ERC721 | +| Transaktionen pro Sekunde | 714 | +| Fehlgeschlagene Transaktionen | 0 | +| Erfolgreiche Transaktionen | 30.000 | +| Verwendete Blöcke insgesamt | 39 | +| ERC721-Transaktionslaufzeit | 42,864140 s | +| SC Bereitstellungszeit | 2,005500 s | + + + + +### Umgebung EOA zu EOA {#environment-eoa-to-eoa} +
+ Host-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud-AnbieterAWS EC2
Instanzgrößec6a.48xlarge
Vernetzungprivates Subnetz
BetriebssystemLinux Ubuntu 20.04 LTS - Focal Fossa
Datei-Deskriptor-Grenze65535
Maximale Benutzerprozesse65535
+
+
+
+
+ +
+ Blockchain-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge VersionRelease v0.4.1
Prüfknoten4
Nicht-Prüfknoten0
KonsensIBFT PoA
Blockzeit1 s
Blockgaslimit70778880
Max. Slots276480
Durchschnittliche Blockauslastung59,34 %
+
+
+
+
+ +
+ Loadbot-Konfiguration +
+
+ + + + + + + + + + + + + +
Gesamttransaktionen30.000
Gesendete Transaktionen pro Sekunde1428
Art der TransaktionenEOA-zu-EOA-Transfers
+
+
+
+
+ +
+ Loadbot-Protokoll + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### Umgebung ERC20 {#environment-erc20} +
+ Host-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud-AnbieterAWS EC2
Instanzgrößec6a.48xlarge
Vernetzungprivates Subnetz
BetriebssystemLinux Ubuntu 20.04 LTS - Focal Fossa
Datei-Deskriptor-Grenze65535
Maximale Benutzerprozesse65535
+
+
+
+
+ +
+ Blockchain-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge VersionRelease v0.4.1
Prüfknoten4
Nicht-Prüfknoten0
KonsensIBFT PoA
Blockzeit1 s
Blockgaslimit47185920
Max. Slots184320
Durchschnittliche Blockauslastung81,29 %
+
+
+
+
+ +
+ Loadbot-Konfiguration +
+
+ + + + + + + + + + + + + +
Gesamttransaktionen50.000
Gesendete Transaktionen pro Sekunde1111
Art der TransaktionenERC20-zu-ERC20-Transfers
+
+
+
+
+ +
+ Loadbot-Protokoll + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### Umgebung ERC721 {#environment-erc721} +
+ Host-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud-AnbieterAWS EC2
Instanzgrößec6a.48xlarge
Vernetzungprivates Subnetz
BetriebssystemLinux Ubuntu 20.04 LTS - Focal Fossa
Datei-Deskriptor-Grenze65535
Maximale Benutzerprozesse65535
+
+
+
+
+ +
+ Blockchain-Konfiguration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge VersionRelease v0.4.1
Prüfknoten4
Nicht-Prüfknoten0
KonsensIBFT PoA
Blockzeit1 s
Blockgaslimit94371840
Max. Slots1000000
Durchschnittliche Blockauslastung93,88 %
+
+
+
+
+ +
+ Loadbot-Konfiguration +
+
+ + + + + + + + + + + + + +
Gesamttransaktionen30.000
Gesendete Transaktionen pro Sekunde714
Art der TransaktionenERC721-Token-Mint
+
+
+
+
+ +
+ Loadbot-Protokoll + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/de-edge/troubleshooting.md b/archive/edge/de-edge/troubleshooting.md new file mode 100644 index 0000000000..d2818dcfc6 --- /dev/null +++ b/archive/edge/de-edge/troubleshooting.md @@ -0,0 +1,68 @@ +--- +id: troubleshooting +title: Fehlerbehebung +description: "Fehlerbehebung für Polygon Edge" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# Fehlerbehebung {#troubleshooting} + +## `method=eth_call err="invalid signature"`Fehler {#error} + +Wenn Sie ein Wallet verwenden, um eine Transaktion mit Polygon Edge durchzuführen, stelle sicher, dass im lokalen Netzwerk Ihrer Wallets + +1. Das `chainID`ist das richtige. Der Standard `chainID`für Edge ist `100`, aber es kann mit dem genesis Flag angepasst `--chain-id`werden. + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. Stelle sicher, dass auf der “RPC-URL” das Feld den JSON RPC Port des Knoten, mit dem du dich verbindest, verwendet. + + +## Wie man eine WebSocket URL erhält {#how-to-get-a-websocket-url} + + +Wenn du den Polygon Edge ausführst, erzeugt er standardmäßig eine WebSocket, die auf dem Standort der Chain basiert. +Das URL-Schema `wss://` wird für HTTPS-Links und `ws://` für HTTP verwendet. + +Localhost WebSocket URL: +````bash +ws://:/ws +```` +Bitte beachte, dass die Portnummer von dem gewählten JSON-RPC-Port für den Knoten abhängt. + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## `insufficient funds`Fehler beim Versuch, einen Vertrag bereitzustellen {#error-when-trying-to-deploy-a-contract} + +Wenn du diesen Fehler erhältst, stelle sicher, dass du genügend Geld auf der gewünschten Adresse hast, und die verwendete Adresse die richtige
ist. Um das premined Gleichgewicht einzustellen, kannst du das genesis `genesis [--premine ADDRESS:VALUE]`beim Erzeugen der genesis Datei verwenden. Beispiel für die Verwendung dieser Flag: +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +Dies premines 1000000000000000000000 WEI auf 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862 + + +## ERC20 Token nicht veröffentlicht bei der Verwendung von Chainbridge {#erc20-tokens-not-released-while-using-chainbridge} + +Wenn du versuchst, ERC20 Token zwischen Polygon POS und einem lokalen Edge Netzwerk zu transferieren und deine ERC20 Token hinterlegt sind, wird auch der Vorschlag bei ausgeführt, die Token aber nicht in deinem Edge-Netzwerk veröffentlicht, stelle sicher, dass der ERC20 Handler in der Polygon Edge Kette genügend Token zur Veröffentlichung
hat. Der Handler-Vertrag in der destination muss genügend Token haben, um für den lock-release freizugeben. Wenn du im ERC20 Handler deines lokalen Edge Netzwerks keine ERC20 Token hast, mint bitte neue Token aus und transferiere sie an den ERC20 Handler. + +## `Incorrect fee supplied`Fehler bei der Verwendung von Chainbridge {#error-when-using-chainbridge} + +Möglicherweise erhält man diesen Fehler, wenn man versucht, ERC20 Token zwischen der Mumbai Polygon POS Kette und einem lokalen Polygon Edge Setup zu übertragen. Dieser Fehler wird angezeigt, wenn Sie die Gebühr auf die Bereitstellung mit `--fee` Flag, aber Sie setzen nicht den gleichen Wert in der Einzahlungstransaktion ein. Du kannst den folgenden Befehl verwenden, um die Gebühr zu ändern: +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +Mehr Informationen zu dieser Flagge findest du [hier](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md). + + + + + diff --git a/archive/edge/de-edge/validator-hosting.md b/archive/edge/de-edge/validator-hosting.md new file mode 100644 index 0000000000..00d29d27a1 --- /dev/null +++ b/archive/edge/de-edge/validator-hosting.md @@ -0,0 +1,263 @@ +--- +id: validator-hosting +title: Prüfer-Hosting +description: "Hosting-Anforderungen für Polygon Edge" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +Im Folgenden findest du Vorschläge, wie du einen Prüfknoten in einem Polygon Edge-Netzwerk richtig hosten kannst. Bitte achte auf alle unten aufgeführten Punkte, um sicherzustellen, +dass dein Prüfer richtig konfiguriert ist, damit er sicher, stabil und leistungsfähig ist. + +## Wissensbasis {#knowledge-base} + +Bevor du versuchst, den Prüfknoten auszuführen, lies bitte dieses Dokument gründlich durch. +Weitere Dokumente, die hilfreich sein könnten, sind: + +- [Installation](get-started/installation) +- [Cloud-Einrichtung](get-started/set-up-ibft-on-the-cloud) +- [CLI-Befehle](get-started/cli-commands) +- [Server-Konfigurationsdatei](configuration/sample-config) +- [Private Schlüssel](configuration/manage-private-keys) +- [Prometheus-Metriken](configuration/prometheus-metrics) +- [Secret Managers](/docs/category/secret-managers) +- [Backup/Wiederherstellung](working-with-node/backup-restore) + +## Mindest-Systemanforderungen {#minimum-system-requirements} + +| Art | Wert | Beeinflusst von | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 2 Kerne |
  • Anzahl der JSON-RPC-Abfragen
  • Größe des Blockchain-Zustands
  • Blockgaslimit
  • Blockzeit
| +| RAM | 2 GB |
  • Anzahl der JSON-RPC-Abfragen
  • Größe des Blockchain-Zustands
  • Blockgaslimit
| +| Festplatte |
  • 10 GB Root-Partition
  • 30 GB Root-Partition mit LVM für die Festplattenerweiterung
|
  • Größe des Blockchain-Zustands
| + + +## Service-Konfiguration {#service-configuration} + +`polygon-edge` Binärdatei muss bei bestehender Netzwerkverbindung automatisch als Systemdienst ausgeführt werden und über Start-, Stopp- und Neustart- +Funktionen verfügen. Wir empfehlen, einen Service Manager wie `systemd.` zu verwenden + +Beispiel `systemd` Systemkonfigurationsdatei: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### Binärdatei {#binary} + +In der Produktion sollten `polygon-edge` Binärdateien nur aus vorgefertigten GitHub-Version-Binärdateien bereitgestellt werden - nicht durch manuelles Kompilieren. +:::info + +Wenn du den `develop` GitHub-Branch manuell kompilierst, kann es sein, dass du Änderungen an deiner Umgebung vornimmst. +Aus diesem Grund wird empfohlen, die Polygon Edge-Binärdateien ausschließlich aus den Releases einzusetzen, da sie Informationen über +Änderungen und deren Behebung enthalten. + +::: + +Unter [Installation](/docs/edge/get-started/installation) findest du einen vollständigen Überblick über die Installationsmethode. + +### Datenspeicherung {#data-storage} + +Der `data/` Ordner, der den gesamten Blockchain-Zustand enthält, sollte auf einer dedizierten Festplatte/einem Volume gemountet werden, um +automatische Festplatten-Backups, Volume-Erweiterungen und optional das Mounten der Festplatte/des Volumes in einer anderen Instanz im Falle eines Ausfalls zu ermöglichen. + + +### Protokolldateien {#log-files} + +Die Protokolldateien müssen täglich rotiert werden (mit einem Tool wie `logrotate`). +:::warning + +Wenn die Konfiguration ohne Protokollrotation erfolgt, können die Protokolldateien den gesamten verfügbaren Speicherplatz belegen, was die Betriebszeit des Prüfers beeinträchtigen kann. + +::: + +Beispiel `logrotate` Konfiguration: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +Im Abschnitt [Protokollierung](#logging) findest du unten Empfehlungen zur Protokollspeicherung. + +### Zusätzliche Abhängigkeiten {#additional-dependencies} + +`polygon-edge` ist statisch kompiliert und benötigt keine zusätzlichen Abhängigkeiten vom Host-Betriebssystem. + +## Wartung {#maintenance} + +Im Folgenden findest du die besten Methoden, um einen laufenden Prüfknoten eines Polygon Edge-Netzwerks zu warten. + +### Backup {#backup} + +Es gibt zwei Arten von Sicherungsverfahren, die für Polygon Edge-Knoten empfohlen werden. + +Wenn möglich, solltest du beide verwenden, wobei das Polygon Edge-Backup immer verfügbar sein sollte. + +* ***Volume-Backup***: + Tägliches inkrementelles Backup des `data/` Volumes des Polygon Edge-Knotens oder der kompletten VM, wenn möglich. + + +* ***Polygon Edge-Backup***: + Es wird ein täglicher CRON-Auftrag empfohlen, der regelmäßige Backups von Polygon Edge durchführt und die `.dat` Dateien an einen externen Speicherort oder in einen sicheren Cloud-Objektspeicher verschiebt. + +Das Polygon Edge-Backup sollte sich idealerweise nicht mit dem oben beschriebenen Volume Backup überschneiden. + +Unter [Backup/Wiederherstellung der Knoteninstanz](working-with-node/backup-restore) findest du Anweisungen, wie du Backups von Polygon Edge durchführst. + +### Protokollierung {#logging} + +Die Protokolle, die von den Polygon Edge-Knoten ausgegeben werden, sollten: +- an einen externen Datenspeicher mit Indizierungs- und Suchfunktionen gesendet werden +- eine Aufbewahrungsfrist für Protokolle von 30 Tagen haben + +Wenn du zum ersten Mal einen Polygon Edge Prüfer einrichtest, empfehlen wir dir, den Knoten +mit der Option `--log-level=DEBUG` zu starten, damit du eventuell auftretende Probleme schnell beheben kannst. + +:::info + +Die Option `--log-level=DEBUG` sorgt dafür, dass das Protokoll des Knotens so ausführlich wie möglich ist. +Debug-Protokolle erhöhen die Größe der Protokolldatei erheblich, was bei der Einrichtung einer +Protokollrotationslösung berücksichtigt werden muss. + +::: +### OS Sicherheits-Patches {#os-security-patches} + +Administratoren müssen sicherstellen, dass das Betriebssystem der Prüferinstanz mindestens einmal im Monat mit den neuesten Patches aktualisiert wird. + +## Metriken {#metrics} + +### Systemmetriken {#system-metrics} + +Administratoren müssen eine Art Systemmetrik-Monitor einrichten (z. B. Telegraf + InfluxDB + Grafana oder eine SaaS-Lösung eines Drittanbieters). + +Metriken, die überwacht und für die Alarmbenachrichtigungen eingerichtet werden müssen: + +| Metrik Name | Alarmschwelle | +|-----------------------|-------------------------------| +| CPU-Nutzung (%) | > 90 % für mehr als 5 Minuten | +| RAM-Nutzung (%) | > 90 % für mehr als 5 Minuten | +| Nutzung der Root-Disk | > 90 % | +| Datenträgernutzung | > 90 % | + +### Prüfer-Metriken {#validator-metrics} + +Administratoren müssen die Sammlung von Metriken über die Prometheus API von Polygon Edge einrichten, +um die Leistung der Blockchain überwachen zu können. + +Unter [Prometheus-Metriken](configuration/prometheus-metrics) erfährst du, welche Metriken veröffentlicht werden und wie du die Erfassung von Prometheus-Metriken einrichtest. + + +Den folgenden Metriken muss besondere Aufmerksamkeit gewidmet werden: +- ***Blockproduktionszeit*** - wenn die Blockproduktionszeit höher als normal ist, liegt möglicherweise ein Problem mit dem Netzwerk vor. +- ***Anzahl der Konsensrunden*** - wenn es mehr als eine Runde gibt, gibt es möglicherweise ein Problem mit dem Prüfer im Netzwerk. +- ***Anzahl der Peers*** - wenn die Anzahl der Peers sinkt, gibt es ein Verbindungsproblem im Netzwerk. + +## Sicherheit {#security} + +Im Folgenden findest du die besten Methoden zur Sicherung eines laufenden Prüfknotens eines Polygon Edge-Netzwerks. + +### API-Services {#api-services} + +- ***JSON-RPC*** - +Der einzige API-Service, der der Öffentlichkeit zugänglich gemacht werden muss (über Load Balancer oder direkt). +Diese API sollte auf allen Schnittstellen oder auf einer bestimmten IP-Adresse ausgeführt werden (Beispiel: `--json-rpc 0.0.0.0:8545` oder `--json-prc 192.168.1.1:8545`). +:::info +Da es sich um eine öffentlich zugängliche API handelt, wird empfohlen, ihr einen Load Balancer/Reverse Proxy vorzuschalten, um Sicherheit und Ratenbegrenzung zu gewährleisten. +::: + + +- ***LibP2P*** - +Dies ist die Netzwerk-API, die von den Knoten für die Peer-Kommunikation verwendet wird. Sie muss auf allen Schnittstellen oder auf einer bestimmten IP-Adresse ausgeführt werden +(`--libp2p 0.0.0.0:1478` oder `--libp2p 192.168.1.1:1478`). Diese API sollte zwar nicht öffentlich zugänglich sein, +aber sie sollte von allen anderen Knoten erreichbar sein. +:::info + +Wenn sie auf localhost (`--libp2p 127.0.0.1:1478`) ausgeführt wird, können andere Knoten keine Verbindung herstellen. + +::: + + +- ***GRPC*** - +Diese API wird nur zum Ausführen von Bediener-Befehlen verwendet und für nichts anderes. Als solches sollte sie ausschließlich auf localhost ausgeführt werden (`--grpc-address 127.0.0.1:9632`). + +### Polygon Edge-Geheimnisse {#polygon-edge-secrets} + +Die Polygon Edge-Geheimnisse (`ibft` und `libp2p` Keys) sollten nicht in einem lokalen Dateisystem gespeichert werden. +Stattdessen sollte ein unterstützter [Secret Manager](configuration/secret-managers/set-up-aws-ssm) verwendet werden. + Das Speichern von Geheimnissen im lokalen Dateisystem sollte nur in Nicht-Produktionsumgebungen verwendet werden. + +## Update {#update} + +Im Folgenden wird das gewünschte Aktualisierungsverfahren für Prüfknoten als Schritt-für-Schritt-Anleitung beschrieben. + +### Update-Verfahren {#update-procedure} + +- Lade die neueste Polygon Edge-Binärdatei aus den offiziellen GitHub [Releases](https://github.com/0xPolygon/polygon-edge/releases) herunter +- Beende den Polygon Edge-Service (Beispiel: `sudo systemctl stop polygon-edge.service`) +- Ersetze die vorhandene `polygon-edge` Binärdatei durch die heruntergeladene (Beispiel: `sudo mv polygon-edge /usr/local/bin/`) +- Überprüfe, ob die richtige `polygon-edge` Version vorhanden ist, indem du `polygon-edge version` ausführst - sie sollte der Release-Version entsprechen +- Prüfe in der Versions-Dokumentation, ob vor dem Start des `polygon-edge` Services Schritte zur Rückwärtskompatibilität unternommen werden müssen +- Starte `polygon-edge` Service (Beispiel: `sudo systemctl start polygon-edge.service`) +- Überprüfe schließlich die `polygon-edge` Protokollausgabe und stelle sicher, dass alles ohne `[ERROR]` Protokolle funktioniert + +:::warning + +Wenn es eine neue Version (Release) gibt, muss dieser Aktualisierungsvorgang auf allen Knoten durchgeführt werden, +da die aktuell laufende Binärdatei nicht mit der neuen Version kompatibel ist. + +Das bedeutet, dass die Chain für eine kurze Zeit angehalten werden muss (bis die `polygon-edge` Binärdateien ersetzt und der Service neu gestartet wurde), +plane also entsprechend. + +Du kannst Tools wie **[Ansible](https://www.ansible.com/)** oder ein eigenes Skript verwenden, um die Aktualisierung effizient durchzuführen +und die Ausfallzeit der Chain zu minimieren. + +::: + +## Startverfahren {#startup-procedure} + +Im Folgenden ist der gewünschte Ablauf des Startvorgangs für den Polygon Edge-Prüfer dargestellt. + +- Lies dir die Dokumente durch, die im Abschnitt [Wissensbasis](#knowledge-base) aufgeführt sind. +- Wende die neuesten Betriebssystem-Patches auf dem Prüfknoten an. +- Lade die neueste `polygon-edge` Binärdatei aus den offiziellen GitHub [Releases](https://github.com/0xPolygon/polygon-edge/releases) herunter und platziere sie in der lokalen Instanz `PATH`. +- Initialisiere einen der unterstützten [Secret Manager](/docs/category/secret-managers) mit dem `polygon-edge secrets generate` CLI-Befehl. +- Erstelle und speichere Geheimnisse mit dem `polygon-edge secrets init`[CLI-Befehl](/docs/edge/get-started/cli-commands#secrets-init-flags). +- Beachte die `NodeID` und `Public key (address)`-Werte. +- Erstelle eine `genesis.json`-Datei wie unter [Cloud-Einrichtung](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators) beschrieben mit `polygon-edge genesis` [CLI-Befehl](/docs/edge/get-started/cli-commands#genesis-flags). +- Erstelle die Standardkonfigurationsdatei mit dem `polygon-edge server export` [CLI-Befehl](/docs/edge/configuration/sample-config). +- Bearbeite die `default-config.yaml` Datei, um sie an die lokale Umgebung des Prüfknotens anzupassen (Dateipfade usw.). +- Erstelle einen Polygon Edge-Service (`systemd` oder ähnlich), dessen `polygon-edge` Binärdatei den Server von einer `default-config.yaml` Datei aus ausführen wird. +- Starte den Polygon Edge-Server, indem du den Service startest (Beispiel: `systemctl start polygon-edge`). +- Überprüfe die `polygon-edge` Protokollausgabe und stelle sicher, dass die Blöcke generiert werden und dass keine `[ERROR]` Protokolle vorhanden sind. +- Überprüfe die Funktion der Chain durch den Aufruf einer JSON-RPC-Methode wie [`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid). diff --git a/archive/edge/de-edge/working-with-node/backup-restore.md b/archive/edge/de-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..6001b98311 --- /dev/null +++ b/archive/edge/de-edge/working-with-node/backup-restore.md @@ -0,0 +1,93 @@ +--- +id: backup-restore +title: Backup/Wiederherstellung der Knoteninstanz +description: "Wie du eine Polygon Edge-Knoteninstanz sicherst und wiederherstellst." +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## Übersicht {#overview} + +In diesem Leitfaden wird detailliert beschrieben, wie du eine Polygon Edge-Knoteninstanz sicherst und wiederherstellst. +Darin geht es um die Basisordner und ihre Inhalte sowie um die Dateien, die für eine erfolgreiche Sicherung und Wiederherstellung wichtig sind. + +## Basisordner {#base-folders} + +Polygon Edge nutzt LevelDB als Speicher-Engine. +Wenn du einen Polygon Edge-Knoten startest, werden die folgenden Unterordner im angegebenen Arbeitsverzeichnis erstellt: +* **blockchain** - speichert die Blockchain-Daten +* **trie** - speichert die Merkle-Tries (Weltzustandsdaten) +* **keystore** - speichert Private Keys für den Client. Dazu gehören der Private Key für libp2p und der des Sealers/Prüfers +* **consensus** - speichert alle Konsensinformationen, die der Client während der Arbeit benötigt. Er speichert zunächst den *Private Key des Prüfers* des Knotens + +Es ist wichtig, dass diese Ordner erhalten bleiben, damit die Polygon Edge-Instanz reibungslos funktioniert. + +## Backup von einem laufenden Knoten erstellen und für einen neuen Knoten wiederherstellen {#create-backup-from-a-running-node-and-restore-for-new-node} + +Dieser Leitfaden führt dich durch die Erstellung von Archivdaten der Blockchain in einem laufenden Knoten und deren Wiederherstellung in einer anderen Instanz. + +### Backup {#backup} + +`backup` Befehl ruft Blöcke von einem laufenden Knotenpunkt per gRPC ab und erstellt eine Archivdatei. Wenn `--from` und `--to` im Befehl nicht angegeben werden, ruft dieser Befehl Blöcke von der ersten bis zur letzten Version ab. + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### Wiederherstellen {#restore} + +Ein Server importiert Blöcke aus einem Archiv am Anfang, wenn er mit dem `--restore`-Flag startet. Bitte vergewissere dich, dass es einen Key für den neuen Knoten gibt. Wenn du mehr über den Import oder die Erstellung von Keys erfahren möchtest, besuche den [Abschnitt Secret Managers](/docs/edge/configuration/secret-managers/set-up-aws-ssm). + +```bash +$ polygon-edge server --restore archive.dat +``` + +## Sichern/Wiederherstellen ganzer Daten {#back-up-restore-whole-data} + +Dieser Leitfaden führt dich durch die Datensicherung einschließlich der Statusdaten und des Keys und die Wiederherstellung in der neuen Instanz. + +### Schritt 1: Beende den laufenden Client {#step-1-stop-the-running-client} + +Da Polygon Edge **LevelDB** für die Datenspeicherung verwendet, muss der Knoten für die Dauer des Backups angehalten werden, +da **LevelDB** keinen gleichzeitigen Zugriff auf seine Datenbankdateien zulässt. + +Außerdem führt Polygon Edge beim Schließen eine „Datenspülung“ (Data Flushing) durch. + +Der erste Schritt besteht darin, den laufenden Client anzuhalten (entweder über einen Dienstmanager oder einen anderen Mechanismus, der ein SIGINT-Signal an den Prozess sendet), +damit er 2 Events auslösen kann, während er ordnungsgemäß heruntergefahren wird: +* Datenflush auf die Festplatte durchführen +* Freigabe der DB-Dateien durch LevelDB + +### Schritt 2: Sichere das Verzeichnis {#step-2-backup-the-directory} + +Da der Client nun nicht mehr ausgeführt wird, kann das Datenverzeichnis auf einem anderen Datenträger gesichert werden. +Denk daran, dass die Dateien mit der Erweiterung `.key` die Private Key-Daten enthalten, die dazu verwendet werden können, sich als der aktuelle Knoten auszugeben. +Diese Daten sollten niemals an Dritte weitergegeben werden. + +:::info + +Bitte sichere die generierte `genesis` Datei und stelle sie manuell wieder her, damit der wiederhergestellte Knoten voll funktionsfähig ist. + +::: + +## Wiederherstellen {#restore-1} + +### Schritt 1: Beende den laufenden Client {#step-1-stop-the-running-client-1} + +Wenn eine Instanz von Polygon Edge ausgeführt wird, muss sie gestoppt werden, damit Schritt 2 erfolgreich durchgeführt werden kann. + +### Schritt 2: Kopiere das Verzeichnis der gesicherten Daten in den gewünschten Ordner {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +Sobald der Client nicht mehr ausgeführt wird, kann das Datenverzeichnis, das zuvor gesichert wurde, in den gewünschten Ordner kopiert werden. +Stelle außerdem die zuvor kopierte `genesis` Datei wieder her. + +### Schritt 3: Führe den Polygon Edge Client aus und gib dabei das richtige Datenverzeichnis an {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +Damit Polygon Edge das wiederhergestellte Datenverzeichnis verwenden kann, muss der Benutzer beim Start den Pfad zum +Datenverzeichnis angeben. Informationen zum `data-dir`-Flag findest du im Abschnitt [CLI-Befehle](/docs/edge/get-started/cli-commands). diff --git a/archive/edge/de-edge/working-with-node/query-json-rpc.md b/archive/edge/de-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..a90b7f3bd1 --- /dev/null +++ b/archive/edge/de-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,85 @@ +--- +id: query-json-rpc +title: Abfrage JSON RPC Endpunkte +description: "Daten abfragen und die Chain mit einem premined Konto starten." +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## Übersicht {#overview} + +Die JSON-RPC-Ebene des Polygon Edge bietet Entwicklern die Funktionalität des einfachen Interagieren mit der Blockchain, durch HTTP Requests. + +Dieses Beispiel umfasst die Verwendung von Tools wie **curl** zum Abfragen von Informationen sowie das Starten der Chain mit einem premined Konto, und Senden einer Transaktion. + +## Schritt 1: Erstelle eine genesis Datei mit einem premined Konto {#step-1-create-a-genesis-file-with-a-premined-account} + +Um eine genesis Datei zu generieren, führe den folgenden Befehl aus: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +Das **premine** Flag setzt die Adresse, die mit einem Startguthaben in der **genesis** Datei enthalten sein
sollte. In diesem Fall `0x1010101010101010101010101010101010101010`wird die Adresse einen starting **Standardbalance** von`0xD3C21BCECCEDA1000000`haben (1 Million native currency + +`:`Wenn wir eine Balance spezifizieren wollten, können wir die Balance und Adresse mit einem trennen, wie: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +`hex``uint256`Das Guthaben kann entweder ein oder Wert sein. + +:::warning Nur premine Konten, für die du einen privaten Schlüssel hast! +Wenn du premine Konten und keinen privaten Schlüssel hast, um auf sie zuzugreifen, wirst du premined Guthaben nicht verwenden können +::: + +## Schritt 2: Starten Sie das Polygon Edge im dev Modus {#step-2-start-the-polygon-edge-in-dev-mode} + +Um den Polygon Edge Entwicklungsmodus zu starten, der im [CLI Commands](/docs/edge/get-started/cli-commands) Abschnitt erklärt wird, Führe das folgende aus: +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## Schritt 3: Abfrage des Kontostands {#step-3-query-the-account-balance} + +Nun, da der Client up ist und im dev Modus läuft, mit der genesis Datei generiert in **Schritt 1**, können wir ein Tool wie **curl** zum Abfragen des Kontostands verwenden: +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +Der Befehl sollte die folgende Ausgabe zurückgeben: +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## Schritt 4: Senden einer Transfertransaktion {#step-4-send-a-transfer-transaction} + +Nun, da wir das Konto bestätigt haben, das wir als premined eingerichtet haben und das richtige Guthaben hat, können wir einige Ether transferieren: + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/de-edge/working-with-node/query-operator-info.md b/archive/edge/de-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..8ad2167f61 --- /dev/null +++ b/archive/edge/de-edge/working-with-node/query-operator-info.md @@ -0,0 +1,85 @@ +--- +id: query-operator-info +title: Operator-Informationen abfragen +description: "Wie man Operator-Informationen abfragt." +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## Voraussetzungen {#prerequisites} + +Dieser Leitfaden setzt voraus, dass du den Leitfaden [Lokale Einrichtung](/docs/edge/get-started/set-up-ibft-locally) oder den [Leitfaden zum Einrichten eines IBFT-Clusters in der Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) befolgt hast. + +Ein funktionierender Knotenpunkt ist Voraussetzung für die Abfrage jeglicher Art von Operator-Informationen. + +Mit dem Polygon Edge haben die Node-Operators die Kontrolle und sind darüber informiert, was der Knoten, den sie bedienen, gerade tut.
+Sie können jederzeit die auf gRPC aufbauende Knoteninformationsschicht nutzen und aussagekräftige Informationen abrufen - ohne die Protokolle zu durchforsten. + +:::note + +Wenn dein Knoten nicht auf `127.0.0.1:8545` läuft, solltest du ein Flag `--grpc-address ` zu den in diesem Dokument aufgeführten Befehlen hinzufügen. + +::: + +## Peer-Informationen {#peer-information} + +### Peer-Liste {#peers-list} + +Um eine vollständige Liste der verbundenen Peers zu erhalten (einschließlich des laufenden Knotens selbst), führe folgenden Befehl aus: +````bash +polygon-edge peers list +```` + +Dies gibt eine Liste der libp2p-Adressen zurück, die derzeit Peers des laufenden Clients sind. + +### Peer-Status {#peer-status} + +Um den Status eines bestimmten Peers zu erfahren, führe Folgendes aus: +````bash +polygon-edge peers status --peer-id
+```` +Der *address*-Parameter ist die libp2p-Adresse des Peers. + +## IBFT-Info {#ibft-info} + +Es kommt häufig vor, dass ein Operator über den Zustand des Betriebsknotens im IBFT-Konsens Bescheid wissen möchte. + +Zum Glück bietet Polygon Edge eine einfache Möglichkeit, diese Informationen zu finden. + +### Snapshots {#snapshots} + +Wenn du den folgenden Befehl ausführst, erhältst du den aktuellsten Snapshot. +````bash +polygon-edge ibft snapshot +```` +Um den Snapshot auf einer bestimmten Höhe (Blocknummer) abzufragen, kann der Operator Folgendes ausführen: +````bash +polygon-edge ibft snapshot --num +```` + +### Kandidaten {#candidates} + +Um die neuesten Informationen über die Kandidaten zu erhalten, kann der Operator Folgendes ausführen: +````bash +polygon-edge ibft candidates +```` +Dieser Befehl fragt die aktuelle Menge der vorgeschlagenen Kandidaten ab, sowie die Kandidaten, die noch nicht aufgenommen wurden + +### Status {#status} + +Der folgende Befehl gibt den aktuellen Validierungsschlüssel des laufenden IBFT-Clients zurück: +````bash +polygon-edge ibft status +```` + +## Transaktionspool {#transaction-pool} + +Um die aktuelle Anzahl der Transaktionen im Transaktionspool zu ermitteln, kann der Operator Folgendes ausführen: +````bash +polygon-edge txpool status +```` diff --git a/archive/edge/es-edge/additional-features/blockscout.md b/archive/edge/es-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..c4d6e2e833 --- /dev/null +++ b/archive/edge/es-edge/additional-features/blockscout.md @@ -0,0 +1,415 @@ +--- +id: blockscout +title: Blockscout +description: Cómo configurar una instancia de Blockscout para que funcione con Polygon Edge. +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## Descripción general {#overview} +Esta guía ahonda en los detalles sobre cómo compilar y desplegar una instancia de Blockscout para que funcione con Polygon Edge. +Blockscout tiene su propia [documentación](https://docs.blockscout.com/for-developers/manual-deployment), pero esta guía se centra en instrucciones paso a paso simples y detalladas sobre cómo configurar la instancia de Blockscout. + +## Entorno {#environment} +* Sistema operativo: Ubuntu Server 20.04 LTS [descarga el enlace](https://releases.ubuntu.com/20.04/) con los permisos de sudo (superusuario). +* Hardware del servidor: 8 CPU, 16 GB de RAM, HDD (LVM) de 50 GB +* Servidor de la base de datos: servidor dedicado con 2 CPU, 4 GB de RAM, SSD 100 GB, PostgreSQL 13.4 + +### Servidor de base de datos {#db-server} +El requisito para seguir esta guía es tener un servidor de base de datos listo, una base de datos y un usuario de base de datos configurado. Esta guía no ahondará en los detalles de cómo desplegar y configurar el servidor PostgreSQL. Hay muchas guías en este momento para hacerlo, por ejemplo, la [Guía de DigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart). + +:::info DESCARGO DE RESPONSABILIDAD + +El propósito de esta guía es ayudarte a configurar y ejecutar Blockscout en una única instancia, lo que no es una configuración de producción ideal. +Para producción, probablemente debas introducir el proxy inverso, el equilibrador de carga, opciones de escalabilidad, etc. en la arquitectura. + +::: + +# Procedimiento de despliegue de Blockscout {#blockscout-deployment-procedure} + +## Parte 1: instalación de dependencias {#part-1-install-dependencies} +Antes de comenzar, debemos cerciorarnos de tener instalados todos los binarios de los que depende Blockscout. + +### Actualiza el sistema {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### Adición de repositorio de Erlang {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### Agrega el repositorio de NodeJS {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### Instala Rust {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### Instala la versión necesaria de Erlang {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### Instala la versión necesaria de Elixir {#install-required-version-of-elixir} +La versión de Elixir debe ser `1.13`. Si intentamos instalar esta versión desde el repositorio oficial, +`erlang` se actualizará a `Erlang/OTP 25`, lo cual debemos evitar. +Debido a eso, debemos instalar la versión `elixir` específica y precompilada de la página de publicaciones de GitHub. + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +Ahora, necesitamos configurar correctamente el sistema de binarios `exlixir`. +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +Revisa si `elixir` y `erlang` están correctamente instalados ejecutando `elixir -v`. +Este debería ser el resultado: +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning + +`Erlang/OTP` debe ser versión `24` y `Elixir` debe ser versión `1.13.*`. +Si no es así, tendrás problemas con la compilación o ejecución de Blockscout. + +::: +:::info + +Dale un vistazo a la ***[página oficial de los requisitos de Blockscout](https://docs.blockscout.com/for-developers/information-and-settings/requirements)***. + +::: + +### Instala NodeJS {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### Instala Cargo {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### Instala otras dependencias {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### Opcionalmente, instala el cliente postgresql para comprobar tu conexión de base de datos {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## Parte 2: configuración de las variables del entorno {#part-2-set-environment-variables} +Necesitamos configurar las variables del entorno antes de comenzar con la compilación de Blockscout. En esta guía únicamente configuraremos el mínimo básico para que funcione. +Puedes encontrar una lista completa de variables configurables [aquí](https://docs.blockscout.com/for-developers/information-and-settings/env-variables). + +### Configura la conexión de la base de datos como variable del entorno {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +Ahora, prueba tu conexión a la base de datos con los parámetros proporcionados. +Como has proporcionado las variables del entorno de PG, deberías poder conectarte a la base de datos con solo ejecutar: +```bash +psql +``` + +Si la base de datos está configurada correctamente, deberías ver un mensaje de psql: +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +De lo contrario, puede que veas un error como este: +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +Si es así, [estos documentos](https://ubuntu.com/server/docs/databases-postgresql) te ayudarán. + +:::info Conexión a la base de datos + +Cerciórate de haber ordenado todos los problemas de conexión a la base de datos antes de pasar a la siguiente parte. +Tendrás que darle privilegios de superusuario al usuario de Blockscout. + +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## Parte 3: clonación y compilación de Blockscout {#part-3-clone-and-compile-blockscout} +Ahora, finalmente empezamos con la instalación de Blockscout. + +### Clona el repositorio de Blockscout {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### Genera una base clave secreta para proteger la construcción de la producción {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +En la última línea, deberías ver una larga cadena de caracteres aleatorios. +Esta debería estar configurada como tu variable de entorno `SECRET_KEY_BASE` antes de pasar al siguiente paso. +Por ejemplo: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### Configura el modo de producción {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### Compila {#compile} +Cambia de directorio al directorio clonado y empieza a compilar + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info + +Si ya has hecho el despliegue antes, elimina los activos estáticos de la mezcla anterior de construcción de ***mix phx.digest.clean***. + +::: + +### Migra las bases de datos {#migrate-databases} +:::info + +Esta parte fallará si no configuraste correctamente tu conexión a la base de datos correctamente, o si no suministraste +los parámetros en la variable del entorno DATABASE_URL, o si los definiste de forma incorrecta. +El usuario de la base de datos debe tener privilegios de superusuario. + +::: +```bash +mix do ecto.create, ecto.migrate +``` + +Si tienes que eliminar la base de datos primero, ejecuta +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### Instala las dependencias npm y compila los activos de la interfaz del usuario {#install-npm-dependencies-and-compile-frontend-assets} +Deberás mover el directorio a la carpeta que contiene los activos de la interfaz del usuario. + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info Ten paciencia. + +La compilación de estos activos puede demorar algunos minutos y no mostrará resultados. +Puede parecer que el proceso está trabado, pero ten paciencia. +Cuando termine el proceso de compilación, el resultado debe ser similar a este: `webpack 5.69.1 compiled with 3 warnings in 104942 ms` + +::: + +### Construye activos estáticos {#build-static-assets} +Para este paso, debes volver a la raíz de tu carpeta de clones de Blockscout. +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### Genera certificados autofirmados {#generate-self-signed-certificates} +:::info + +Puedes omitir paso si no vas a usar `https`. + +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## Parte 4: creación y ejecución del servicio de Blockscout {#part-4-create-and-run-blockscout-service} +En esta parte, tenemos que configurar un servicio del sistema, ya que queremos que Blockscout se ejecute en segundo plano y persista después de reiniciar el sistema. + +### Crea un archivo de servicio {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### Edita el archivo de servicio {#edit-service-file} +Utiliza tu editor de texto favorito de Linux para editar este archivo y configurar el servicio. +```bash +sudo vi /etc/systemd/system/explorer.service +``` +El contenido del archivo explorer.service debe verse así: +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### Habilita el servicio de inicio en el arranque del sistema {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### Mueve tu carpeta de clones de Blockscout a la ubicación en el sistema general. {#move-your-blockscout-clone-folder-to-system-wide-location} +El servicio de Blockscout requiere tener acceso a la carpeta que clonaste del repositorio de Blockscout y compilado todos los activos. +```bash +sudo mv ~/blockscout /usr/local +``` + +### Crea un archivo de variables del entorno que será utilizado por el servicio de Blockscout {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info + +Utiliza `SECRET_KEY_BASE` que generaste en la parte 3. + +::: +Guarda el archivo y sal. + +### Finalmente, inicia el servicio de Blockscout. {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## Parte 5: prueba de la funcionalidad de tu instancia de Blockscout. {#part-5-test-out-the-functionality-of-your-blockscout-instance} +Lo único que falta hacer es comprobar que el servicio de Blockscout se esté ejecutando. +Revisa el estado del servicio con: +```bash +sudo systemctl status explorer.service +``` + +Para revisar los resultados del servicio: +```bash +sudo journalctl -u explorer.service -f +``` + +Puedes revisar si hay algunos nuevos puertos de escucha: +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +Deberías obtener una lista de puertos de escucha; en esa lista, debería haber algo como esto: +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +El servicio web de Blockscout ejecuta el puerto y el protocolo definidos en el archivo del entorno. En este ejemplo, se ejecuta en `4000` (http) +Si todo está bien, debes poder acceder al portal web de Blockscout con `http://:4000`. + +## Consideraciones {#considerations} +Para obtener el mejor desempeño, es aconsejable tener un nodo completo no validador de archivos `polygon-edge` dedicado o local, +que se utilizará exclusivamente para consultas de Blockscout. +La API `json-rpc` de este nodo no tiene que estar expuesta públicamente, ya que Blockscout ejecuta todas las consultas desde el modo administrador. + + +## Reflexiones finales {#final-thoughts} +Acabamos de desplegar una única instancia de Blockscout que funciona bien, pero, para la producción, deberías considerar ubicar esta instancia detrás de un proxy inverso, como Nginx. +También, deberías pensar en la escalabilidad de las bases de datos y de las instancias, según tu caso de uso. + +Definitivamente, deberías darle un vistazo a la [documentación oficial de Blockscout](https://docs.blockscout.com/), ya que hay muchas opciones de personalización. \ No newline at end of file diff --git a/archive/edge/es-edge/additional-features/chainbridge/definitions.md b/archive/edge/es-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..b7d580c83a --- /dev/null +++ b/archive/edge/es-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,221 @@ +--- +id: definitions +title: Definiciones generales +description: Definiciones generales de los términos utilizados en Chain Bridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## Repetidor {#relayer} +Chainbridge es un puente de tipo repetidor. El papel de un repetidor es votar por la ejecución de una solicitud (cuántos tokens quemar o liberar, por ejemplo). +Este monitorea los eventos de cada cadena y vota a favor de una propuesta en el contrato de puente de la cadena de destino cuando recibe un evento `Deposit` de una cadena. Un repetidor llama a un método en el contrato del puente para ejecutar la propuesta después de enviar el número de votos requerido. El puente delega la ejecución en el contrato del manejador (Handler). + + +## Tipos de contratos {#types-of-contracts} +En ChainBridge, hay tres tipos de contratos en cada cadena denominados Bridge (puente), Handler (manejador) y Target (meta). + +| **Tipo** | **Descripción** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Contrato de puente | Es necesario desplegar en cada cadena un contrato de puente que gestione las solicitudes, los votos y las ejecuciones. Para iniciar una transferencia, los usuarios llamarán a `deposit` en el puente y este delega el proceso en el contrato manejador correspondiente al contrato meta. Cuando el contrato manejador ha logrado llamar al contrato meta, el contrato de puente emite un evento `Deposit` para notificar a los repetidores. | +| Contrato manejador | Este contrato interactúa con el contrato meta para ejecutar un depósito o una propuesta. Este valida la solicitud del usuario, llama al contrato meta y ayuda con algunos ajustes para el contrato meta. Hay ciertos contratos manejadores para llamar a cada contrato meta que tiene una interfaz diferente. Las llamadas indirectas del contrato manejador hacen que el puente habilite la transferencia de cualquier tipo de activos o datos. Actualmente, hay tres tipos de contratos manejadores implementados por ChainBridge: ERC20Handler, ERC721Handler y GenericHandler. | +| Contrato meta | Un contrato que gestiona los activos que se intercambian o los mensajes que se transfieren entre cadenas. La interacción con este contrato se hará desde cada lado del puente. | + +
+ +![Arquitectura de ChainBridge](/img/edge/chainbridge/architecture.svg) +*Arquitectura de ChainBridge* + +
+ +
+ +![Flujo de trabajo de la transferencia de un token ERC-20](/img/edge/chainbridge/erc20-workflow.svg) +*ejemplo de Flujo de trabajo de la transferencia de un token ERC-20* + +
+ +## Tipos de cuentas {#types-of-accounts} + +Por favor, asegúrate de que las cuentas tengan suficientes tokens nativos para crear transacciones antes de empezar. En Polygon Edge, puedes asignar saldos preminados a las cuentas al generar el bloque de génesis. + +| **Tipo** | **Descripción** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Administrador | A esta cuenta se le asignará el rol de administrador por defecto. | +| Usuario | La cuenta del emisor o receptor que envía o recibe los activos. La cuenta del emisor paga las tarifas de gas al aprobar las transferencias de token y al llamar al depósito en el contrato de puente para iniciar una transferencia. | + +:::info El rol de administrador + +Ciertas acciones solo pueden ser realizadas por la cuenta con rol de administrador. Por defecto, el desplegador del contrato de puente tiene el rol de administrador. A continuación encontrarás cómo otorgarle el rol de administrador a otra cuenta o eliminarlo. + +### Añade el rol de administrador {#add-admin-role} + +Añade un administrador + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### Revoca el rol de administrador {#revoke-admin-role} + +Elimina un administrador + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## Las operaciones que permite la cuenta `admin` son las siguientes. {#account-are-as-below} + +### Establecer un recurso {#set-resource} + +Registrar una ID de recurso con una dirección de contrato para un manejador. + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Hacer el contrato quemable o acuñable {#make-contract-burnable-mintable} + +Establecer un contrato de token como acuñable o quemable en un manejador. + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Cancelar una propuesta {#cancel-proposal} + +Cancelar la propuesta de ejecución + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### Pausar o continuar {#pause-unpause} + +Pon en pausa de forma temporal los depósitos, la creación de propuestas, las votaciones y las ejecuciones de depósitos. + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### Cambiar tarifa {#change-fee} + +Cambiar la tarifa que se le pagará al contrato puente + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### Añadir o eliminar un repetidor {#add-remove-a-relayer} + +Añadir una cuenta como nuevo repetidor o eliminar una cuenta de los repetidores + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### Cambiar el umbral del repetidor {#change-relayer-threshold} + +Cambiar el número de votos necesarios para la ejecución de una propuesta + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## ID de la cadena {#chain-id} + +El `chainId`de Chainbridge es un valor arbitrario utilizado en el puente diferenciar entre las redes de cadenas de bloques y tiene que estar en el rango de uint8. No hay que confundirlo con la ID de la cadena de la red; no son lo mismo. Es necesario que este valor sea único, pero no tiene que ser el mismo que la ID de la red. + +En este ejemplo, establecemos `99`en `chainId`, porque la ID de la cadena de la red de prueba Mumbai es `80001`, que no puede representarse con un uint8. + +## ID del recurso {#resource-id} + +La ID de un recurso es un valor único de 32 bytes en un entorno entre cadenas, que se asocia a un determinado activo (recurso) que se transfiere entre redes. + +La ID del recurso es arbitraria, pero, como una convención, normalmente el último byte contiene la ID de la cadena de origen (la red de la que procede ese activo). + +## URL de RPC JSON para las pruebas de participación (PoS) de Polygon {#json-rpc-url-for-polygon-pos} + +Para esta guía, utilizaremos https://rpc-mumbai.matic.today, un URL de RPC JSON público suministrada por Polygon, que puede tener límites de tráfico o de velocidad. Se utilizará únicamente para conectarse con la red de pruebas Mumbai de Polygon. Te aconsejamos que obtengas tu URL de RPC JSON a través de un servicio externo como Infura, ya que el despliegue de contratos enviará muchas consultas o solicitudes a la RPC JSON. + +## Formas de procesar transferencia de tokens {#ways-of-processing-the-transfer-of-tokens} +Al transferir los tokens ERC-20 entre las cadenas, se pueden procesar en dos modos diferentes: + +### Modo de bloqueo y modo de liberación {#lock-release-mode} +Cadena de origen: los tokens que envíes estarán bloqueados en el contrato manejador.
+Cadena de destino: la misma cantidad de tokens que enviaste en la cadena de origen se desbloquearía y se transferiría desde el contrato manejador a la cuenta del destinatario en la cadena de destino. + +### Modo de quemado o acuñación {#burn-mint-mode} +Cadena de origen: los tokens que envíes serán quemados.
+Cadena de destino: la misma cantidad de tokens que enviaste y quemaste en la cadena de origen se acuñará en la cadena de destino y se enviará a la cuenta del destinatario. + +Puedes utilizar diferentes modos para cada cadena. Eso significa que se puede bloquear un token en la cadena principal mientras se acuña un token en la subcadena para su transferencia. Por ejemplo, puede tener sentido bloquear o liberar tokens si está controlada la oferta total o el calendario de acuñación. Los tokens deberían ser acuñados o quemados si el contrato en la subcadena tiene que seguir el suministro en la cadena principal. + +El modo por defecto es el de bloqueo o liberación. Si quieres hacer que los tokens sean acuñables o quemables, tienes que llamar al método `adminSetBurnable`. Si quieres acuñar los tokens en la ejecución, tendrás que otorgarle un rol de `minter` al contrato manejador ERC-20. + + diff --git a/archive/edge/es-edge/additional-features/chainbridge/overview.md b/archive/edge/es-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..278bfa7f3f --- /dev/null +++ b/archive/edge/es-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Descripción general +description: Descripción de ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## ¿Qué es ChainBridge? {#what-is-chainbridge} + +ChainBridge es un puente modular de la cadena de bloques multidireccional que admite cadenas compatibles con EVM y Substrate, construido por ChainSafe. Permite a los usuarios transferir todo tipo de activos o mensajes entre dos cadenas diferentes. + +Para obtener más información sobre ChainBridge, consulta primero la [documentación oficial](https://chainbridge.chainsafe.io/) proporcionada por sus desarrolladores. + +Esta guía ayuda a integrar Chainbridge en Polygon Edge. Explica la configuración a través de un puente entre un PoS de Polygon en funcionamiento (red de pruebas Mumbai) y una red local de Polygon Edge. + +## Requisitos {#requirements} + +En esta guía, ejecutarás los nodos Polygon Edge, un repetidor ChainBridge (más información sobre este [aquí](/docs/edge/additional-features/chainbridge/definitions)), y la herramienta cb-sol-cli, que es una herramienta CLI para desplegar contratos localmente, registrar recursos, y cambiar la configuración del puente (puedes comprobarla [aquí](https://chainbridge.chainsafe.io/cli-options/#cli-options)). Los siguientes entornos son necesarios antes de iniciar la configuración: + +* Go: >= 1.17 +* Node.js >= 16.13.0 +* Git + + +Además, tendrás que clonar los siguientes repositorios con las versiones para ejecutar algunas aplicaciones. + +* [Polygon Edge](https://github.com/0xPolygon/polygon-edge): en la ramificación `develop` +* [ChainBridge](https://github.com/ChainSafe/ChainBridge): v1.1.5 +* [ChainBridge Deploy Tools](https://github.com/ChainSafe/chainbridge-deploy): `f2aa093`en la ramificación `main` + + +Tienes que configurar una red de Polygon Edge antes de pasar a la siguiente sección. Si necesitas más información, por favor, comprueba la [configuración local](/docs/edge/get-started/set-up-ibft-locally) o [ la configuración de la nube](/docs/edge/get-started/set-up-ibft-on-the-cloud). \ No newline at end of file diff --git a/archive/edge/es-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/es-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..b083124164 --- /dev/null +++ b/archive/edge/es-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,142 @@ +--- +id: setup-erc20-transfer +title: Transferencia de tokens ERC-20 +description: Cómo configurar la transferencia ERC-20 en chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Hasta el momento, hemos creado un puente para intercambiar activos o datos entre la cadena de PoS de Polygon y la de Polygon Edge. Esta sección te explicará cómo configurar un puente ERC-20 y enviar los tokens entre las diferentes cadenas de bloques. + +## Paso 1: registra la ID del recurso {#step-1-register-resource-id} + +Lo primero es registrar una ID de recurso que asocie los recursos en un entorno entre cadenas. Una ID de recurso es un valor de 32 bytes que debe ser único para el recurso que estamos transfiriendo entre estas cadenas de bloques. Las ID de los recursos son arbitrarias, aunque pueden tener la ID de la cadena de origen en el último byte, como convención (la cadena de origen se refiere a la red en la que se originaron esos recursos). + +Para registrar la ID del recurso, puedes utilizar el comando `cb-sol-cli bridge register-resource`. Deberás suministrar la clave privada de la cuenta `admin`. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (Opcional) Haz que los contratos sean acuñables o quemables {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## Paso 2: transfiere el token ERC-20 {#step-2-transfer-erc20-token} + +Enviaremos los tokens ERC-20 desde la cadena PoS de Polygon a la cadena de Polygon Edge. + +En primer lugar, obtendrás los tokens mediante la acuñación. Una cuenta con el rol `minter` puede acuñar los nuevos tokens. La cuenta que ha desplegado el contrato ERC-20 tiene el rol `minter` por defecto. Para especificar otras cuentas como miembros del rol `minter`, es necesario ejecutar el comando `cb-sol-cli erc20 add-minter`. + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +Para comprobar el saldo actual, puedes utilizar el comando `cb-sol-cli erc20 balance`. + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +Seguidamente, debes aprobar la transferencia del token ERC-20 desde la cuenta por parte del manejador de ERC-20 + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +Para transferir los tokens a las cadenas de Polygon Edge, deberás llamar a `deposit`. + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Cuando la transacción del depósito haya culminado correctamente, el repetidor recibirá el evento y votará por la propuesta. Ejecuta una transacción para enviar los tokens a la cuenta del destinatario en la cadena de Polygon Edge después de haber enviado el número requerido de votos. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Después de que la transacción de ejecución haya culminado correctamente, obtendrás los tokens en la cadena de Polygon Edge. + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/es-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/es-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..d843808219 --- /dev/null +++ b/archive/edge/es-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,134 @@ +--- +id: setup-erc721-transfer +title: Transferencia de NFT ERC-721 +description: Cómo configurar la transferencia ERC-721 en chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Esta sección te guía en la configuración de un puente ERC-721 y en el envío de NFT entre redes de cadenas de bloques. + +## Paso 1: registra la ID del recurso {#step-1-register-resource-id} + +Lo primero que tendrás que hacer es registrar la ID del recurso para el token ERC-721 en los contratos puente de ambas cadenas. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (Opcional): haz que los contratos sean acuñables o quemables {#optional-make-contracts-mintable-burnable} + +Para hacer que los tokens sean acuñables o quemables, tendrás que llamar a los siguientes comandos: + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## Paso 2: transfiere NFT {#step-2-transfer-nft} + +En primer lugar, acuñarás un NFT si lo necesitas. + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Para revisar el propietario del NFT, puedes utilizar `cb-sol-cli erc721 owner` + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +A continuación, aprobarás una transferencia del NFT por parte del manejador de ERC-721 + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Por último, iniciarás la transferencia + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +El repetidor recibirá el evento y votará por la propuesta. Se ejecuta una transacción para enviar los NFT a la cuenta del destinatario en la cadena de Polygon Edge después de que se envía el número de votos necesario. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Puedes comprobar el propietario del NFT en la red de Polygon Edge después de que la ejecución haya finalizado. + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/es-edge/additional-features/chainbridge/setup.md b/archive/edge/es-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..2d3ccb9409 --- /dev/null +++ b/archive/edge/es-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,198 @@ +--- +id: setup +title: Configuración +description: Cómo configurar ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Despliegue de contratos {#contracts-deployment} + +En esta sección, desplegarás los contratos requeridos a la cadena de Polygon Edge y PoS de Polygon con `cb-sol-cli`. + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +En primer lugar, desplegaremos contratos a la cadena de PoS de Polygon mediante el comando `cb-sol-cli deploy`. El indicador `--all` hace que el comando despliegue todos los contratos, incluyendo el puente, el manejador de ERC-20, el manejador de ERC-721, el manejador genérico, el contrato ERC-721 y el contrato ERC-20. Además, establecerá la dirección por defecto de la cuenta del repetidor y el umbral. + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +Aprende sobre la ID de la cadena y los URL de RPC JSON [aquí](/docs/edge/additional-features/chainbridge/definitions). + +:::caution + +El precio de gas por defecto en `cb-sol-cli` es `20000000` (`0.02 Gwei`). Para establecer el precio de gas apropiado en una transacción. establece el valor usando el argumento `--gasPrice`. + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +El despliegue del contrato del puente toma aproximadamente 0x3f97b8 (4167608) de gas para desplegarse. Asegúrate de que los bloques que se generen tengan suficiente límite de gas de los bloques para contener la transacción de la creación del contrato. Para obtener más información sobre el cambio del límite del gas de los bloques en Polygon Edge, visita +la [configuración local](/docs/edge/get-started/set-up-ibft-locally). + +::: + +Cuando los contratos se hayan desplegado, obtendrás el siguiente resultado: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +Ahora podemos desplegar los contratos a la cadena de Polygon Edge. + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Guarda los resultados de la terminal con las direcciones del contrato inteligente desplegado, ya que las necesitaremos para el siguiente paso. + +## Configuración del repetidor {#relayer-setup} + +En esta sección, iniciarás un repetidor para intercambiar datos entre dos cadenas. + +Primero, debemos clonar y construir el repositorio de ChainBridge. + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +A continuación, deberás crear `config.json` y establecer los URL de RPC JSON, la dirección del repetidor y la dirección de los contratos para cada cadena. + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +Para iniciar un repetidor, debes importar la clave privada correspondiente a la dirección de la cuenta del repetidor. Tendrás que ingresar la contraseña cuando importes la clave privada. Cuando la importación haya culminado, la clave se almacenará en `keys/
.key`. + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +Después, podrás iniciar el repetidor. Deberás ingresar la misma contraseña que elegiste para almacenar la clave al principio. + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +Cuando el repetidor haya iniciado, empezará a observar nuevos bloques en cada cadena. diff --git a/archive/edge/es-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/es-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..9cf58e700a --- /dev/null +++ b/archive/edge/es-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,255 @@ +--- +id: use-case-erc20-bridge +title: Caso de uso - puente de ERC-20 +description: Ejemplo de cómo hacer un contrato de puente de ERC-20 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +Esta sección tiene como objetivo explicarte el flujo de la configuración del puente de ERC-20 para un caso de uso práctico. + +En esta guía, utilizarás la red de pruebas de PoS Mumbai de Polygon y la cadena local de Polygon Edge. Debes tener la terminal RPC JSON para Mumbai y haber configurado Polygon Edge en el entorno local. Consulta la [configuración local](/docs/edge/get-started/set-up-ibft-locally) o [ la configuración de la nube](/docs/edge/get-started/set-up-ibft-on-the-cloud) para obtener más información. + +## Escenario {#scenario} + +Este escenario es para configurar el puente para el token ERC-20 que ya se ha desplegado en la cadena pública (PoS de Polygon) para habilitar una transferencia de bajo costo en una cadena privada (Polygon Edge) para usuarios en un caso regular. En un caso así, el suministro total de tokens se ha definido en la cadena pública, y en la cadena privada solo debe existir la cantidad de tokens que se ha transferido de la cadena pública a la cadena privada. Por esa razón, deberás usar el modo de bloquear o liberar en la cadena pública, y el modo de quemado o acuñado en la cadena privada. + +Al enviar tokens de la cadena pública a la privada, el token se bloqueará en el contrato manejador de ERC-20 de la cadena pública, y la misma cantidad de tokens se acuñará en la cadena privada. Por otro lado, en el caso de la transferencia de la cadena privada a la cadena pública, el token en la cadena privada se quemará, y la misma cantidad de tokens se liberará desde el contrato del manejador de ERC-20 en la cadena pública. + +## Contratos {#contracts} + +Explicación con contratos simples de ERC-20 en lugar del contrato desarrollado por ChainBridge Para el modo de quemado o acuñado, el contrato de ERC-20 debe tener los métodos `mint` y `burnFrom` , además de los métodos para ERC-20 así: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +Todos los códigos y secuencias de comandos se encuentran en en el repositorio de Github, [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Paso 1: despliega los contratos del puente y del manejador de ERC-20 {#step1-deploy-bridge-and-erc20-handler-contracts} + +En primer lugar, deberás desplegar los contratos del puente y del manejador de ERC-20 mediante el uso de `cb-sol-cli` en las dos cadenas. + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Obtendrás direcciones del contrato del puente y del manejador de ERC-20 como esta: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Paso 2: despliega tu contrato de ERC-20 {#step2-deploy-your-erc20-contract} + +Desplegarás tu contrato de ERC-20. Este ejemplo te guiará con un proyecto de Hardhat, [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Crea un archivo `.env` y establece los siguientes valores. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +A continuación, despliega el contrato de ERC-20 en ambas cadenas. + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +Una vez realizado el despliegue correctamente, obtendrás direcciones de contrato como esta: + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## Paso 3: registra la ID de recursos en el puente {#step3-register-resource-id-in-bridge} + +Registra una ID de recursos que asocie los recursos en un entorno entre cadenas. Tendrás que usar la misma ID de recursos en ambas cadenas. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## Paso 4: establece el modo de acuñado o quemado en el puente de ERC-20 de Edge {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +Se espera que el puente funcione en modo de quemado o acuñado en Polygon Edge. Configura el modo de quemado y acuñado mediante el uso de `cb-sol-cli`. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +Deberás otorgarle un rol de acuñador y quemador al contrato manejador de ERC-20. + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Paso 5: acuña los tokens {#step5-mint-token} + +Acuña los nuevos tokens de ERC-20 en la cadena de Mumbai. + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +Una vez que realizada correctamente la transacción, la cuenta tendrá los tokens acuñados. + +## Paso 6: inicia la transferencia de ERC-20 {#step6-start-erc20-transfer} + +Antes de iniciar este paso, asegúrate de haber iniciado un repetidor. Revisa [Configuración](/docs/edge/additional-features/chainbridge/setup) para obtener más información. + +Durante la transferencia de tokens de Mumbai a Edge, el contrato manejador de ERC-20 en Mumbai retira tokens de tu cuenta. Ejecuta una llamada de autorización antes de la transferencia. + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +Finalmente, inicia la transferencia de tokens de Mumbai a Edge con `cb-sol-cli`. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Una vez culminada correctamente la transacción del depósito, el repetidor recibirá el evento y votará por la propuesta. Este ejecuta una transacción para enviar los tokens a la cuenta del destinatario en la cadena de Polygon Edge después de haber enviado el número requerido de votos. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Después de que la transacción de ejecución se haya realizado correctamente, obtendrás los tokens en la cadena de Polygon Edge. diff --git a/archive/edge/es-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/es-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..9c6d77cc1b --- /dev/null +++ b/archive/edge/es-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,308 @@ +--- +id: use-case-erc721-bridge +title: Caso práctico - puente ERC-721 +description: Ejemplo de contrato puente ERC-721 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +Esta sección tiene como objetivo explicarte el flujo de configuración de un puente ERC-721 para un caso de uso práctico. + +En esta guía, utilizarás la red de pruebas con PoS Mumbai de Polygon y la cadena local de Polygon Edge. Debes tener la terminal RPC JSON para Mumbai y haber configurado Polygon Edge en el entorno local. Consulta la [configuración local](/docs/edge/get-started/set-up-ibft-locally) o [ la configuración de la nube](/docs/edge/get-started/set-up-ibft-on-the-cloud) para obtener más información. + +## Escenario {#scenario} + +Este escenario consiste en configurar un puente para el NFT ERC-721 que ya ha sido implementado en la cadena pública (PoS de Polygon) con el fin de permitir la transferencia de bajo costo en una cadena privada (Polygon Edge) para los usuarios en un caso regular. En este caso, los metadatos originales se han definido en la cadena pública y los únicos NFT que se han transferido desde la cadena pública pueden existir en la cadena privada. Por esa razón, deberás usar el modo de bloquear o liberar en la cadena pública, y el modo de quemado o acuñado en la cadena privada. + +Al enviar un NFT de la cadena pública a la cadena privada, el NFT se bloqueará en el contrato ERC-721 del contrato manejador en la cadena pública y el mismo NFT se acuñará en la cadena privada. Por otro lado, en el caso de la transferencia de la cadena privada a la cadena pública, el NFT en la cadena privada se quemará y el mismo NFT se liberará del contrato manejador de ERC-721 en la cadena pública. + +## Contratos {#contracts} + +Explicación con un contrato ERC-721 simple en lugar del contrato desarrollado por ChainBridge Para la modalidad de quemado o acuñado, se requiere que el contrato ERC-721 tenga los métodos `burn` y `mint` además de los definidos en el ERC-721, como por ejemplo: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +Todos los códigos y secuencias de comandos se encuentran en el repositorio de Github, [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Paso 1: despliega los contratos del puente y del manejador ERC-721 {#step1-deploy-bridge-and-erc721-handler-contracts} + +En primer lugar, se despliegan los contratos puente y manejador ERC-721 `cb-sol-cli` en las dos cadenas. + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Obtendrás las direcciones de los contratos puente y manejador ERC-721 así: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Paso 2: despliega tu contrato ERC-721 {#step2-deploy-your-erc721-contract} + +Implementa tu contrato ERC-721. Este ejemplo te explicará un proyecto de Hardhat, [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Crea un archivo `.env` y establece los siguientes valores. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +A continuación, despliega el contrato ERC-721 en las dos cadenas. + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +Una vez que el despliegue culmine, obtendrás una dirección de contrato como la siguiente: + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## Paso 3: registra la ID de recursos en el puente {#step3-register-resource-id-in-bridge} + +Registra una ID de recurso que asocie los mismos en un entorno entre cadenas. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## Paso 4: establece el modo de acuñación o quemado en el puente ERC-721 de Edge {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +Se espera que el puente funcione como el modo de quemado o acuñación en Edge. Configura el modo de quemado o acuñación. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +Y debes asignar un rol de acuñador y quemador al contrato manejador ERC-721. + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Paso 5: acuña el NFT {#step5-mint-nft} + +Acuña el nuevo NFT ERC-721 en la cadena de Mumbai. + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +Cuando la transacción culmine, la cuenta tendrá el NFT acuñado. + +## Paso 6: inicia la transferencia ERC-721 {#step6-start-erc721-transfer} + +Antes de comenzar este paso, cerciórate de haber iniciado el repetidor. Consulta [Configuración](/docs/edge/additional-features/chainbridge/setup) para obtener más información. + +Durante la transferencia de NFT de Mumbai a Edge, el contrato manejador ERC-721 en Mumbai retira el NFT de tu cuenta. Ejecuta una llamada de autorización antes de la transferencia. + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +Por último, comienza el traslado de NFT de Mumbai a Edge. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +Cuando la transacción del depósito culmine correctamente, el repetidor recibirá el evento y votará por la propuesta. +Ejecuta una transacción para enviar NFT a la cuenta del destinatario en la cadena de Polygon Edge después de que se presente el número requerido de votos. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Cuando la transacción de ejecución culmine correctamente, obtendrás NFT en la cadena de Polygon Edge. diff --git a/archive/edge/es-edge/additional-features/permission-contract-deployment.md b/archive/edge/es-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..2b0c9ce29c --- /dev/null +++ b/archive/edge/es-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,86 @@ +--- +id: permission-contract-deployment +title: Permiso de despliegue de contratos +description: Cómo añadir el permiso de despliegue de contratos inteligentes +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## Descripción general {#overview} + +Esta guía explica la forma de incluir en la lista blanca las direcciones que pueden desplegar los contratos inteligentes. +En ocasiones, los operadores de la red quieren evitar que los usuarios desplieguen los contratos inteligentes que no están relacionados con el propósito de la red. Los operadores de la red pueden: + +1. Direcciones de la lista blanca para el despliegue de los contratos inteligentes +2. Eliminar las direcciones de la lista blanca para el despliegue de los contratos inteligentes. + +## Presentación en vídeo {#video-presentation} + +[![despliegue de contrato de permiso - vídeo](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## ¿Cómo utilizarlo? {#how-to-use-it} + + +Puedes encontrar todos los comandos relacionados con la lista blanca de despliegue en la página de [Comandos CLI](/docs/edge/get-started/cli-commands#whitelist-commands). + +* `whitelist show`: muestra información de la lista blanca +* `whitelist deployment --add`: añade una nueva dirección a la lista blanca de despliegue de contratos +* `whitelist deployment --remove`: elimina una nueva dirección de la lista blanca de despliegue de contratos + +#### Muestra todas las direcciones en la lista blanca de despliegue {#show-all-addresses-in-the-deployment-whitelist} + +Existen 2 formas de encontrar las direcciones de la lista blanca de despliegue. +1. Mirar dónde se guardan las `genesis.json` de las listas blancas +2. Ejecutar `whitelist show`, lo que imprime la información de todas las listas blancas admitidas por Polygon Edge + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### Añadir una dirección a la lista blanca de despliegue {#add-an-address-to-the-deployment-whitelist} + +Para añadir una nueva dirección a la lista blanca de despliegue ejecuta el comando CLI `whitelist deployment --add [ADDRESS]` No existe límite en el número de direcciones presentes en la lista blanca. Solo las direcciones que existen en la lista blanca de despliegue de contratos pueden desplegar contratos. Si la lista blanca está vacía, cualquier dirección puede realizar el despliegue + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### Eliminar una dirección de la lista blanca de despliegue {#remove-an-address-from-the-deployment-whitelist} + +Para eliminar una dirección de la lista blanca de despliegue ejecuta el comando CLI `whitelist deployment --remove [ADDRESS]`. Solo las direcciones que existen en la lista blanca de despliegue de contratos pueden desplegar contratos. Si la lista blanca está vacía, cualquier dirección puede realizar el despliegue + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/es-edge/architecture/modules/blockchain.md b/archive/edge/es-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..a651a4cbfa --- /dev/null +++ b/archive/edge/es-edge/architecture/modules/blockchain.md @@ -0,0 +1,160 @@ +--- +id: blockchain +title: Cadena de bloques +description: Explicación de los módulos de la cadena de bloques y estado de Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## Descripción general {#overview} + +Uno de los módulos principales de Polygon Edge es **cadena de bloques** y otro es **estado**.
+ +**Cadena de bloques** es el motor que se encarga de la reorganización de los bloques. Eso significa que se ocupa de toda la lógica que opera cuando se incluye un bloque nuevo en la cadena de bloques. + +**Estado** representa el objeto de la *transición del estado*. Se ocupa de cómo cambia el estado cuando se incluye un bloque nuevo.
Entre otras cosas, **Estado** se encarga de: +* Ejecución de transacciones +* Ejecución de la máquina virtual de Ethereum (EVM) +* Cambio de los árboles de Merkle +* Y mucho más, que puedes encontrar en la sección correspondiente de **Estado**. 🙂 + +El punto clave es que estas dos partes están muy conectadas y cooperan estrechamente para que el cliente funcione.
Por ejemplo, cuando la **cadena de bloques** recibe un bloque nuevo (y no hay reorganización), llama a **Estado** para que haga la transición del estado. + +**Cadena de bloques** también debe ocuparse de algunas partes relacionadas con el consenso (por ejemplo, *¿este ethHash es correcto?*, *¿esta prueba de trabajo (PoW) es correcta?*)
. En otras palabras, **es el núcleo principal de lógica a través del cual se incluyen todos los bloques**. + +## *WriteBlocks* (Escribir bloques) + +Una de las partes más importantes relacionadas con la capa de **cadena de bloques** es el método *WriteBlocks* (Escribir bloques): + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +El método *WriteBlocks* (Escribir bloques) es el punto de entrada para escribir bloques en la cadena de bloques. Como parámetro, se encuentra en una gama de bloques.
+En primer lugar, se validan los bloques. En segundo lugar, se escriben en la cadena. + +La *transición del estado* en sí se hace llamando al método *processBlock*(procesar bloque), dentro de *WriteBlocks*. + +Vale la pena mencionar que, como es el punto de entrada para escribir bloques en la cadena de bloques, otros módulos (como **Sealer** [Sellador]) utilizan este método. + +## Suscripciones de Blockchain {#blockchain-subscriptions} + +Es necesario que haya una forma de monitorear los cambios relacionados con la cadena de bloques.
+Para eso están las **suscripciones**. + +Las suscripciones son una forma de aprovechar las publicaciones de eventos de las cadenas de bloques y recibir datos significativos inmediatamente. + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +Los **eventos de la cadena de bloques** contienen información sobre cualquier cambio realizado en la cadena real. Eso incluye las reorganizaciones, así como nuevos bloques: + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip Repaso + +¿Recuerdas cuando mencionamos el comando del ***monitoreo*** en los [comandos CLI](/docs/edge/get-started/cli-commands)? + +Los eventos de la cadena de bloques son los eventos originales que ocurren en Polygon Edge y que, después, se mapean en un formato de mensaje de búfer de protocolo, para facilitar su transferencia. + +::: \ No newline at end of file diff --git a/archive/edge/es-edge/architecture/modules/consensus.md b/archive/edge/es-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..3c243dde16 --- /dev/null +++ b/archive/edge/es-edge/architecture/modules/consensus.md @@ -0,0 +1,512 @@ +--- +id: consensus +title: Consenso +description: Explicación del módulo de consenso de Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## Descripción general {#overview} + +El módulo de **consenso** ofrece una interfaz para los mecanismos del consenso. + +Actualmente, están disponibles los siguientes motores de consenso: +* **Prueba de autoridad (PoA) tolerante a fallas bizantinas de Estambul (IBFT)** +* **Prueba de participación (PoS) tolerante a fallas bizantinas de Estambul (IBFT)** + +Polygon Edge quiere mantener un estado de modularidad y capacidad de conexión.
+Por eso se ha abstraído la lógica central del consenso, para que nuevos mecanismos de consenso se puedan construir a partir de ella, sin +comprometer la usabilidad ni la facilidad de uso. + +## Interfaz del consenso {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + +La interfaz del ***consenso*** es un aspecto central de la abstracción mencionada.
+* El método **VerifyHeader** (Verificar encabezado) representa una función de ayuda en la que la capa de consenso se expone a la capa de la **cadena de bloques**. +Su función es manejar la verificación de encabezados. +* El método **Start** (Iniciar) simplemente inicia el proceso de consenso y todo aquello con lo que está asociado. Eso incluye la sincronización, +el sellado y todo lo que haya que hacer. +* El método **Close** (Cerrar) cierra la conexión del consenso. + +## Configuración del consenso {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +Puede que haya momentos en los que quieras pasar una ubicación personalizada para el protocolo de consenso, para almacenar datos, o tal vez +un mapa con valor personalizado de claves que quieras que el mecanismo de consenso utilice. Eso se puede lograr mediate la estructura de ***configuración***, +que se lee cuando se crea una nueva instancia de consenso. + +## IBFT {#ibft} + +### ExtraData {#extradata} + +El objeto del encabezado de la cadena de bloques, entre otros campos, tiene un campo llamado **ExtraData** (Datos adicionales). + +IBFT utiliza ese campo adicional para almacenar información operativa con respecto al bloque y responde preguntas como: +* "¿Quién firmó este bloque?" +* "¿Quiénes son los validadores de este bloque?" + +Esos campos adicionales para IBFT se definen de la siguiente manera: +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### Datos de la firma {#signing-data} + +Para que el nodo firme información en IBFT, usa el método *signHash*: +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +Otro método notable es *VerifyCommittedFields* (Verificar campos comprometidos), que verifica que los sellos comprometidos sean de validadores válidos: +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### Instantáneas {#snapshots} + +Las fotos instantáneas, como el nombre lo indica, sirven para mostrar una *foto instantánea* o el *estado* de un sistema a cualquier altura de bloque (número). + +Las instantáneas contienen un conjunto de nodos que son validadores, así como información de votación (los validadores pueden votar por otros validadores). +Los validadores incluyen información de votación en el campo del encabezado **Miner** (Minero) archivado y cambian el valor de **nonce**: +* Nonce es **todo de 1 s** si el nodo quiere eliminar un validador. +* Nonce es **todo de 0 s** si el nodo quiere añadir un validador. + +Las instantáneas se calculan con el método ***processHeaders*** (Procesar encabezados): + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +Este método se suele llamar con un encabezado, pero el flujo es el mismo, incluso con múltiples encabezados.
+Para cada encabezado pasado, IBFT debe verificar que el proponente del encabezado sea el validador. Eso se puede hacer fácilmente +tomar la foto instantánea más reciente y revisar si el nodo está en el conjunto de validadores. + +Después, se debe verificar el nonce. Se incluye y se cuenta el voto y, si hay suficientes votos, se agrega o se elimina un nodo del +conjunto de validadores y después se guarda la nueva foto instantánea. + +#### Depósito de fotos instantáneas {#snapshot-store} + +El servicio de fotos instantáneas gestiona y actualiza una entidad llamada **snapshotStore** (Depósito de fotos instantáneas), que almacena la lista de todas las instantáneas disponibles. +Con él, el servicio puede averiguar rápidamente cuál de las instantáneas está asociada con cuál altura de bloque. +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### Inicio de IBFT {#ibft-startup} + +Para iniciar la IBFT, Polygon Edge primero debe configurar el transporte de la IBFT: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +Esencialmente, crea un nuevo tema con el protocolo de IBFT, con un nuevo mensaje de búfer de protocolo.
+Se supone que los validadores deben utilizar los mensajes. Polygon Edge después se suscribe al tema y gestiona los mensajes en consecuencia. + +#### MessageReq {#messagereq} + +El mensaje intercambiado por los validadores: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +El campo **View** en **MessageReq** representa la posición actual del nodo dentro de la cadena. +Tiene una *round* (ronda) y un atributo de *sequence* (secuencia). +* **round** (ronda) representa la ronda de proponentes para la altura. +* **sequence** (secuencia) representa la altura de la cadena de bloques. + +El campo *msgQueue* archivado en la implementación de la IBFT tiene el objetivo de almacenar las solicitudes de mensajes. Este ordena los mensajes por +*vistas* (primero, por secuencia y luego, por ronda). La implementación de la IBFT también posee diferentes colas para diferentes estados en el sistema. + +### Estados de IBFT {#ibft-states} + +Después de iniciar el mecanismo de consenso con el método **Start** (Iniciar), este ejecuta un ciclo infinito que simula una máquina de estado: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### SyncState (Estado de sincronización) {#syncstate} + +Todos los nodos inician en el estado de **Sync** (sincronización). + +Eso se debe a que los datos nuevos se deben obtener de la cadena de bloques. El cliente debe averiguar si es el validador +y encuentra la foto instantánea actual. Este estado resuelve cualquier bloque pendiente. + +Tras terminar la sincronización y la verificación por parte del cliente de si es un validador, debe transferir a **AcceptState**. +Si el cliente **no** es validador, seguirá sincronizando y se quedará en **SyncState** (estado de sincronización). + +#### AcceptState (Aceptar estado) {#acceptstate} + +El estado **Accept** (Aceptar) siempre revisa la foto instantánea y el conjunto de validadores. Si el nodo actual no está en el conjunto de validadores, +retorna al estado de **Sync** (sincronización). + +Por otro lado, si el nodo **sí** es validador, calcula al proponente. Si resulta que el nodo actual es el +proponente, construye un bloque, envía una preparación preliminar y luego prepara los mensajes. + +* Mensajes de preparación preliminar: son mensajes enviados por los proponentes a los validadores para darles a conocer la propuesta. +* Mensajes de preparación: son mensajes en los que los validadores están de acuerdo con una propuesta. Todos los nodos reciben todos los mensajes de preparación. +* Mensajes de compromiso: son mensajes que contienen información de compromiso de la propuesta. + +Si el nodo actual **no** es validador, utiliza el método *getNextMessage* (Obtener siguiente mensaje) para leer un mensaje de una cola mostrada previamente.
+Este espera a los mensajes de preparación preliminar. Cuando se confirma que todo es correcto, el nodo pasa al estado de **Validate** (Validar). + +#### ValidateState (Validar estado) {#validatestate} + +El estado **Validate** (Validar) es muy simple: lo que todos los nodos hacen en este estado es leer mensajes y agregarlos a su estado de foto instantánea local. diff --git a/archive/edge/es-edge/architecture/modules/json-rpc.md b/archive/edge/es-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..3271871eee --- /dev/null +++ b/archive/edge/es-edge/architecture/modules/json-rpc.md @@ -0,0 +1,181 @@ +--- +id: json-rpc +title: RPC JSON +description: Explicación del módulo RPC JSON de Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## Descripción general {#overview} + +El módulo **RPC JSON** implementa la **capa de la API RPC JSON**, algo que los desarrolladores de aplicaciones descentralizadas (dApp) usan para interactuar con la +cadena de bloques. + +Incluye soporte para las **[terminales RPC JSON](https://eth.wiki/json-rpc/API)** estándar, al igual que para +las terminales de los websockets. + +## Interfaz de la cadena de bloques {#blockchain-interface} + +Polygon Edge usa la ***interfaz de la cadena de bloques*** para definir todos los métodos que el módulo RPC JSON necesita utilizar +para entregar sus terminales. + +La interfaz de la cadena de bloques es implementada por el servidor **[Minimal](/docs/edge/architecture/modules/minimal)**. Es la implementación base +que pasa a la capa RPC JSON. + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## Terminales de ETH {#eth-endpoints} + +Todas las terminales estándar de RPC JSON se implementan en: + +````bash +jsonrpc/eth_endpoint.go +```` + +## Filter Manager {#filter-manager} + +**Filter Manager** (Administrador de filtros) es un servicio que se ejecuta junto al servidor RPC JSON. + +Da soporte para filtrar bloques en la cadena de bloques.
+Específicamente, incluye un filtro de niveles de los**registros** y de los **bloques**. + +Filter Manager depende en gran medida de los eventos de suscripción, mencionados en +la sección [cadena de bloques](blockchain#blockchain-subscriptions). + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +Los eventos de Filter Manager se ejecutan desde el método *Run* (Ejecutar): + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## 📜 Recursos {#resources} +* **[Ethereum RPC JSON](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/es-edge/architecture/modules/minimal.md b/archive/edge/es-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..3c8778f1f3 --- /dev/null +++ b/archive/edge/es-edge/architecture/modules/minimal.md @@ -0,0 +1,119 @@ +--- +id: minimal +title: Minimal +description: Explicación del módulo Minimal de Polygon. +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## Descripción general {#overview} + +Como ya se mencionó, Polygon Edge es un conjunto de módulos, todos conectados entre sí.
+La **cadena de bloques** está conectada al **estado** o, por ejemplo, a la **sincronización**, que introduce nuevos bloques en la **cadena de bloques**. + +**Minimal** es el pilar de esos módulos interconectados.
+Funciona como eje central para todos los servicios que se ejecutan en Polygon Edge. + +## Magia de inicio {#startup-magic} + +Entre otras cosas, Minimal se encarga de: +* Configuración de los directorios de datos +* Creación de un almacén de claves para la comunicación libp2p +* Creación de almacenamiento +* Configuración de consenso +* Configuración del objeto de la cadena de bloques con GRPC, JSON RPC y sincronización + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/es-edge/architecture/modules/networking.md b/archive/edge/es-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..ab9b44a84b --- /dev/null +++ b/archive/edge/es-edge/architecture/modules/networking.md @@ -0,0 +1,80 @@ +--- +id: networking +title: Interconexión +description: Explicación del módulo de interconexión de Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## Descripción general {#overview} + +Un nodo tiene que comunicarse con otros nodos de la red para intercambiar información útil.
+Para realizar esa tarea, Polygon Edge usa el marco **libp2p** probado en situaciones difíciles. + +La decisión de usar**libp2p** se centra principalmente en: +* **Velocidad**: libp2p tiene una mejora significativa de desempeño sobre devp2p (utilizado en GETH y otros clientes) +* **Posibilidad de ampliación**: sirve como una base excelente para otras características del sistema +* **Modularidad**: libp2p es modular por naturaleza, al igual que Polygon Edge. Eso ofrece mayor flexibilidad, especialmente porque las partes del Polygon Edge deben ser intercambiables. + +## GRPC {#grpc} + +Además de **libp2p**, Polygon Edge utiliza el protocolo **GRPC**
+Técnicamente, Polygon Edge utiliza varios protocolos GRPC, que serán explicados más adelante. + +La capa GRPC ayuda a resumir todos los protocolos de solicitud o respuesta y a simplificar los protocolos de transmisión necesarios para que Polygon Edge funcione. + +GRPC depende de los **búfers de protocolo ** para definir *los servicios* y las *estructuras de los mensajes*.
+Los servicios y las estructuras se definen en los archivos *.proto*, que son compilados y son agnósticos con respecto al idioma. + +Ya mencionamos que Polygon Edge usa varios protocolos GRPC.
+Eso se hizo para impulsar la expriencia general del usuario para el operador de nodos, algo que muchas veces se queda atrás con clientes como GETH y Parity. + +El operador del nodo dispone de una mejor visión general de lo que ocurre en el sistema llamando al servicio GRPC, en lugar de rebuscar en los registros para encontrar la información que busca. + +### GRPC para operadores de nodos {#grpc-for-node-operators} + +Puede que la siguiente sección parezca conocida porque fue tratada brevemente en la sección de [Comandos CLI](/docs/edge/get-started/cli-commands). + +El servicio GRPC que está destinado a ser utilizado por los **operadores de nodos** se define de la manera siguiente: +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip + +Los comandos CLI realmente llaman a las implementaciones de estos métodos de servicio. + +Esos métodos están implementados en ***minimal/system_service.go***. + +::: + +### GRPC para otros nodos {#grpc-for-other-nodes} + +Polygon Edge también implementa varios métodos de servicio que son utilizados por otros nodos de la red.
+El servicio mencionado se describe en la sección **[de protocolo](docs/edge/architecture/modules/consensus)**. + +## 📜 Recursos {#resources} +* **[Búferes de protocolo](https://developers.google.com/protocol-buffers)** +* **[libp2p](https://libp2p.io/)** +* **[GRPC](https://grpc.io/)** diff --git a/archive/edge/es-edge/architecture/modules/other-modules.md b/archive/edge/es-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..2b472e652a --- /dev/null +++ b/archive/edge/es-edge/architecture/modules/other-modules.md @@ -0,0 +1,36 @@ +--- +id: other-modules +title: Otros módulos +description: Explicación de algunos módulos de Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## Criptografía {#crypto} + +El módulo de **criptografía** contiene funciones de utilidad de cripto. + +## Cadena {#chain} + +El módulo **Cadena** contiene los parámetros de la cadena (bifurcaciones activas, motor de consenso, etc.) + +* **cadenas**: Configuraciones de cadenas predefinidas (Red principal, Goerli, IBFT) + +## Ayudante {#helper} + +El módulo **Ayudante** contiene paquetes de ayuda. + +* **dao** - Dao utils +* **enode**: Función de codificación/decodificación Enode +* **hex**: funciones de codificación/decodificación hexadecimal +* **ipc**: funciones de conexión IPC +* **keccak**: funciones Keccak +* **rlputil** - función de ayudante de codificación/decodificación Rlp + +## Comando {#command} + +El módulo **Comando** contiene interfaces para los comandos CLI. \ No newline at end of file diff --git a/archive/edge/es-edge/architecture/modules/sealer.md b/archive/edge/es-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..86ccf50494 --- /dev/null +++ b/archive/edge/es-edge/architecture/modules/sealer.md @@ -0,0 +1,72 @@ +--- +id: sealer +title: Sealer +description: Explicación del módulo Sealer de Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## Descripción general {#overview} + +**Sealer** es una entidad que reúne transacciones y crea un bloque nuevo.
+Luego, el bloque se envía al módulo **Consensus** para sellarlo. + +La lógica final de sellado está ubicada dentro del módulo **Consensus**. + +## Ejecutar método {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution En progreso + +Los módulos **Sealer** y **Consensus** se combinarán en una sola entidad en un futuro cercano. + +El nuevo módulo incorporará lógica modular para distintos tipos de mecanismos de consenso que requieren diferentes implementaciones de sellado: +* Prueba de participación (**PoS**) +* Prueba de autoridad (**PoA**) + +Actualmente, los módulos **Sealer** y **Consensus** trabajan con la prueba de trabajo (PoW). +::: \ No newline at end of file diff --git a/archive/edge/es-edge/architecture/modules/state.md b/archive/edge/es-edge/architecture/modules/state.md new file mode 100644 index 0000000000..50abefe31e --- /dev/null +++ b/archive/edge/es-edge/architecture/modules/state.md @@ -0,0 +1,248 @@ +--- +id: state +title: Estado +description: Explicación del módulo de estado de Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +Para entender realmente cómo funciona el **estado**, debes entender algunos conceptos básicos de Ethereum.
+ +Sobre todo, recomendamos leer el **[Estado en la guía de Ethereum](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)**. + +## Descripción general {#overview} + +Ahora que nos hemos familiarizado con los conceptos básicos de Ethereum, la siguiente descripción general debería ser fácil de entender. + +Mencionamos que el **árbol de estado mundial** tiene todas las cuentas de Ethereum que existen.
+Esas cuentas son las hojas del árbol de Merkle. Cada hoja ha codificado la información del **Estado de cuenta**. + +Eso permite que Polygon Edge obtenga un árbol de Merkle específico, para un punto específico en el tiempo.
+Por ejemplo, podemos obtener el hash del estado en el bloque 10. + +El árbol de Merkle en cualquier punto del tiempo se llama ***foto instantánea***. + +Podemos tener ***fotos instantáneas*** para el **árbol de estado**, o para el **árbol de almacenamiento**; son básicamente lo mismo.
+La única diferencia está en lo que representan las hojas: + +* En el caso del árbol de almacenamiento, las hojas contienen un estado arbitrario, que no podemos procesar ni saber qué hay ahí. +* En el caso del árbol de estado, las hojas representan cuentas. + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + +La interfaz de **fotos instantáneas** se define como tal: + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +La información que se puede comprometer está definida por la *estructura del objeto*: + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +La implementación del árbol de Merkle está en la carpeta *state/immutable-trie*
. +*state/immutable-trie/state.go* implementa la interfaz **Estado**. + +*state/immutable-trie/trie.go* es el principal objeto del árbol de Merkle. Este representa una versión optimizada del árbol de Merkle, +que reutiliza la mayor cantidad de memoria posible. + +## Ejecutor {#executor} + +*state/executor.go* incluye toda información necesaria para que Polygon Edge decida cómo un bloque cambia el actual +estado. La implementación de *ProcessBlock* (Procesar bloque) se encuentra aquí. + +El método de *aplicación* realiza la transición de estado real. El ejecutor llama a la máquina virtual de Ethereum (EVM). + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## Tiempo de ejecución {#runtime} + +Cuando un estado de transición se ejecuta, el módulo principal que ejecuta el estado de transición es la EVM (ubicado en +state/runtime/evm). + +La **tabla de envío** busca una coincidencia entre el **código de operación** y la instrucción. + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +La lógica principal que impulsa la EVM es el ciclo *Ejecutar*.
+ +Ese es el punto de entrada principal para la EVM. Hace un bucle y revisa el código de operación actual, obtiene la instrucción, comprueba +si se puede ejecutar, consume gas y ejecuta la instrucción hasta que falle o se detenga. + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/es-edge/architecture/modules/storage.md b/archive/edge/es-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..e730b21f0a --- /dev/null +++ b/archive/edge/es-edge/architecture/modules/storage.md @@ -0,0 +1,118 @@ +--- +id: storage +title: Storage (Almacenamiento) +description: Explicación del módulo Storage de Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## Descripción general {#overview} + +Polygon Edge actualmente utiliza **LevelDB** para el almacenamiento de datos, al igual que una **memoria interna** para almacenar datos. + +En todo Polygon Edge, cuando los módulos deben interactuar con el depósito de datos subyacente, +no necesitan saber con cuál motor o servicio de base de datos están hablando. + +La capa de la base de datos se abstrae entre un módulo llamado **Storage** (Almacenamiento), que exporta las interfaces que los módulos consultan. + +Cada capa de base de datos, por ahora solo **LevelDB**, implementa esos métodos por separado, asegurándose de que coincidan con su implementación. + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### Prefijos {#prefixes} + +Para hacer que las consultas de LevelDB sean deterministas y evitar choques de almacenamiento de claves, Polygon Edge usa +los prefijos y los subprefijos al almacenar datos. + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## Planes hacia el futuro {#future-plans} + +Los planes para el futuro cercano incluyen agregar algunas de las soluciones de bases de datos más populares, tales como: +* PostgreSQL +* MySQL + + +## 📜 Recursos {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/es-edge/architecture/modules/syncer.md b/archive/edge/es-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..b8a164cd42 --- /dev/null +++ b/archive/edge/es-edge/architecture/modules/syncer.md @@ -0,0 +1,68 @@ +--- +id: syncer +title: Sincronizador +description: Explicación del módulo sincronizador de Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## Descripción general {#overview} + +Este módulo contiene la lógica del protocolo de sincronización. Se utiliza para sincronizar un nodo nuevo con la red en ejecución, o para validar o insertar nuevos bloques para los nodos que no participan en el consenso (no validadores). + +Polygon Edge utiliza **libp2p** como capa de interconexión y, además, ejecuta **gRPC**. + +Esencialmente, hay dos tipos de sincronización en Polygon Edge: +* Bulk Sync (Sincronización en volumen): sincronización de una gran variedad de bloques al mismo tiempo +* Sincronización de observación: sincronización por bloques + +### Sincronización en volumen {#bulk-sync} + +Los pasos para la sincronización en volumen son bastante sencillos para adaptarse al objetivo de sincronizar en volumen: la sincronización de tantos bloques como sea posible (disponibles) de los demás pares, para ponerse al día lo más rápidamente posible. + +Este es el flujo del proceso de sincronización en volumen: + +1. ** Determina si el nodo necesita sincronización en volumen **: en este paso, el nodo revisa el mapa de pares para ver si hay alguien con más bloques de los que tiene el nodo localmente. +2. ** Busca el mejor par (con el mapa de pares de sincronización) **: en este paso, el nodo busca el mejor par con el cual sincronizarse, con base en los criterios mencionados en el ejemplo anterior. +3. ** Abre una secuencia de sincronización en volumen **: en este paso, el nodo le abre una secuencia de gRPC al mejor par para sincronizar en volumen los bloques desde el número de bloques común. +4. ** El mejor par cierra la secuencia cuando completa el envío en volumen **: en este paso, el mejor par del nodo se sincroniza con el que cerrará la secuencia tan pronto como envíe todos los bloques que tenga disponibles. +5. ** Cuando culmina la sincronización en volumen, revisa si el nodo es validador **: en este paso, el mejor par cierra la secuencia y, después de la sincronización en volumen, el nodo debe revisar si son validadores. + * Si lo son, salen del estado de sincronización y empiezan a participar en el consenso. + * Si no lo son, siguen con la ** Sincronización por observación ** + +### Sincronización por observación {#watch-sync} + +:::info + +El paso de sincronización por observación solo se ejecuta si el nodo no es un validador, sino un nodo regular no validador en la red que solo escucha bloques entrantes. + +::: + +El comportamiento de la sincronización por observación es bastante sencillo: el nodo ya está sincronizado con el resto de la red y solo debe analizar los bloques nuevos que entran. + +Este es el flujo del proceso de sincronización por observación: + +1. ** Añade un bloque nuevo cuando se actualiza el estado de un par **:eEn este paso, los nodos escuchan los eventos de los nuevos bloques. Cuando tiene un bloque nuevo, ejecuta una llamada de función gRPC, obtiene el bloque y actualiza el estado local. +2. ** Revisa si el nodo es validador después de sincronizar el bloque más reciente ** + * Si lo es, sale del estado de sincronización. + * Si no lo es, continúa escuchando eventos de bloques nuevos. + +## Informe de rendimiento {#perfomance-report} + +:::info + +El rendimiento se midió en una máquina local sincronizando ** un millón de bloques ** + +::: + +| Nombre | Resultado | +|----------------------|----------------| +| Sincronización de un millón de bloques | ~ 25 minutos | +| Transferencia de un millón de bloques | ~ 1 minuto | +| Número de llamadas de GRPC | 2 | +| Cobertura de la prueba | ~ 93 % | \ No newline at end of file diff --git a/archive/edge/es-edge/architecture/modules/txpool.md b/archive/edge/es-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..1763586ab2 --- /dev/null +++ b/archive/edge/es-edge/architecture/modules/txpool.md @@ -0,0 +1,230 @@ +--- +id: txpool +title: TxPool +description: Explicación del módulo TxPool (Grupo de transacciones) de Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## Descripción general {#overview} + +El módulo TxPool (Grupo de transacciones) representa la implementación del grupo de transacciones, donde se agregan transacciones desde diferentes partes del +sistema. El módulo también expone varias funciones útiles para los operadores de nodos, que se describen a continuación. + +## Comandos del operador {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +Los operadores de los nodos pueden consultar estos terminales de GRPC, tal y como se describe en la sección **[Comandos CLI](/docs/edge/get-started/cli-commands#transaction-pool-commands)**. + +## Procesamiento de transacciones {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +El método ***addImpl*** es el elemento principal del módulo **TxPool**. +Es el lugar central donde las transacciones se añaden en el sistema y se llaman desde el servicio GRPC, terminales de RPC JSON +y cuando el cliente recibe una transacción a través del protocolo **gossip**. + +Se admite como un argumento **ctx**, que acaba de denominar el contexto desde el que se están agregando las transacciones (GRPC, JSON RPC...)
. +El otro parámetro es la lista de transacciones que se le agregarán al grupo. + +La clave aquí es revisar el campo **From** dentro de la transacción: +* Si el campo **From** está **vacío**, se considera una transacción no cifrada o no firmada. Ese tipo de transacciones son +aceptadas solo en modo de desarrollo +* Si el campo **From** no **está vacío**, se trata de una transacción firmada, por lo que se hace la verificación de la firma. + +Después de todas esas validaciones, las transacciones se consideran válidas. + +## Estructuras de datos {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +Los campos del objeto TxPool (Grupo de transacciones) que pueden causar confusión son **queues** (colas) y las listas **sorted** (ordenadas). +* **queue**: implementación en pila de una lista ordenada de transacciones de cuentas (por nonce) +* **sorted**: lista ordenada para todas las transacciones promovidas actuales (todas las transacciones ejecutables). Clasificada por el precio de gas + +## Gestión de errores del límite de gas {#gas-limit-error-management} + +Cada vez que envías una transacción, hay tres maneras en que puede ser procesada por el TxPool. + +1. Todas las transacciones pendientes pueden caber en un bloque +2. Una o más transacciones pendientes pueden no caber en un bloque +3. Una o más transacciones pendientes nunca caben en un bloque + +Aquí, la palabra **_fit_** (caber) significa que la transacción tiene un límite de gas que es más bajo que el gas restante en el grupo de transacciones. + +El primer escenario no produce ningún error. + +### Segundo escenario {#second-scenario} + +- El gas restante del grupo de transacciones está establecido en el límite de gas del último bloque, por ejemplo **5000** +- La primera transacción se procesa y consume **3000** de gas del grupo de transacciones + - El gas restante del grupo de transacciones ahora es **2000** +- Se envía la segunda transacción, que es igual a la primera, ya que ambas consumen 3000 unidades de gas +- Dado que el gas restante del grupo de transacciones es **más bajo** que el gas de la transacción, no se puede procesar en el actual +bloque + - Se vuelve a poner en una cola de transacciones pendientes para que pueda ser procesado en el bloque siguiente +- El primer bloque se escribe, llamémoslo **bloque n.º 1** +- El gas restante del grupo de transacciones se ajusta al límite de gas del bloque primario, **el bloque n.° 1** +- La transacción que se volvió a poner en la cola de transacciones pendientes del grupo de transacciones se procesa y se escribe en el bloque + - El gas restante del grupo de transacciones ahora es **2000** +- Se escribe el segundo bloque +- ... + +![Escenario de error del grupo de transacciones n.º 1](/img/edge/txpool-error-1.png) + +### Tercer escenario {#third-scenario} +- El gas restante del grupo de transacciones está establecido en el límite de gas del último bloque, por ejemplo **5000** +- La primera transacción se procesa y consume **3000** de gas del grupo de transacciones + - El gas restante del grupo de transacciones ahora es **2000** +- Se envía la segunda transacción, con un campo de gas establecido en **6000** +- Como el límite de gas del bloque es **más bajo** que el gas de la transacción, esta se descarta. + - Nunca podra caber en un bloque +- Se escribe el primer bloque +- ... + + +![Escenario de error del grupo de transacciones n.º 2](/img/edge/txpool-error-2.png) + +> Eso ocurre cada vez que se obtiene el siguiente error: +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## Meta de gas del bloque {#block-gas-target} + +Hay situaciones en las que los nodos quieren mantener el límite de gas de los bloques por debajo o en una determinada meta en una cadena en funcionamiento. + +El operador del nodo puede establecer el límite de gas meta en un nodo específico, que intentará aplicarle ese límite a los bloques recién creados. +Si la mayoría de los demás nodos también cuentan con un límite de gas meta similar (o igual), el límite de gas del bloque siempre +rondará ese límite de gas meta del bloque, avanzando lentamente hacia él (a un máximo de `1/1024 * parent block gas limit`) a medida que se crean nuevos bloques. + +### Escenario de ejemplo {#example-scenario} + +* El operador del nodo establece el límite de gas del bloque para un solo nodo para ser `5000` +* Otros nodos están configurados para ser `5000`también, aparte de un único nodo que está configurado para ser `7000` +* Cuando los nodos que tienen su meta de gas establecida para `5000`se convierten en proponentes, revisarán si el límite de gas ya está en la meta +* Si el límite de gas no ha llegado a la meta (es mayor / menor), el nodo proponente establecerá la meta de gas del bloque a lo sumo (1/1024 * límite de gas principal) en la dirección de la meta + 1. Ej: `parentGasLimit = 4500`y `blockGasTarget = 5000`, el proponente calculará el límite de gas para el nuevo bloque como `4504.39453125`(`4500/1024 + 4500`) + 2. Ej: `parentGasLimit = 5500`y `blockGasTarget = 5000`, el proponente calculará el límite de gas para el nuevo bloque como `5494.62890625`(`5500 - 5500/1024`) +* Eso garantiza que el límite de gas en el bloque en la cadena se mantendrá en la meta, porque el único proponente que tiene la meta configurada en `7000`no puede incrementar mucho el límite y la mayoría de los nodos que lo han establecido en `5000`siempre intentarán mantenerlo allí \ No newline at end of file diff --git a/archive/edge/es-edge/architecture/modules/types.md b/archive/edge/es-edge/architecture/modules/types.md new file mode 100644 index 0000000000..75595a11b2 --- /dev/null +++ b/archive/edge/es-edge/architecture/modules/types.md @@ -0,0 +1,42 @@ +--- +id: types +title: Tipos +description: Explicación del módulo Types (Tipos) de Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## Descripción general {#overview} + +El módulo **Types** implementa tipos principales de objetos, por ejemplo: + +* **Dirección** +* **Hash** +* **Encabezado** +* Muchas funciones de ayuda + +## Codificación y decodificación con RLP {#rlp-encoding-decoding} + +A diferencia de clientes como GETH, Polygon Edge no utiliza la reflexión para la codificación.
+Se prefirió no utilizar la reflexión porque introduce nuevos problemas, como de rendimiento, degradación y dificultad de escalabilidad. + +El módulo **Types** ofrece una interfaz fácil de usar para marshalling (presentar) y unmarshalling (reconstruir) el RLP mediante el uso del paquete FastRLP. + +Marshaling se realiza a través de los métodos *MarshalRLPWith* y *MarshalRLPTO*. Existen métodos análogos para +unmarshalling. + +Al definir estos métodos manualmente, Polygon Edge no necesita utilizar la reflexión. En *rlp_marshal.go*, puedes encontrar +métodos para marshalling: + +* **Cuerpos** +* **Bloques** +* **Encabezados** +* **Recibos** +* **Registros** +* **Transacciones** \ No newline at end of file diff --git a/archive/edge/es-edge/architecture/overview.md b/archive/edge/es-edge/architecture/overview.md new file mode 100644 index 0000000000..2dd591fd87 --- /dev/null +++ b/archive/edge/es-edge/architecture/overview.md @@ -0,0 +1,61 @@ +--- +id: overview +title: Descripción general de la arquitectura +sidebar_label: Overview +description: Introducción a la arquitectura de Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +Comenzamos con la idea de crear software *modular*. + +Eso está presente en casi todas las partes de Polygon Edge. Más adelante, encontrarás una breve descripción general de la +arquitectura integrada y sus capas. + +## Capas de Polygon Edge {#polygon-edge-layering} + +![Arquitectura de Polygon Edge](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +Todo comienza en la capa de redes base, la cual utiliza **libp2p**. Optamos por esta tecnología porque +encaja con las filosofías de diseño de Polygon Edge. Libp2p es: + +- Modular +- Ampliable +- Rápido + +Lo más importante es que proporciona una base excelente para características más avanzadas, acerca de las cuales hablaremos más adelante. + + +## Sincronización y consenso {#synchronization-consensus} +La separación de los protocolos de sincronización y consenso permite la modularidad e implementación de mecanismos **personalizados** de sincronización y consenso, en función de cómo se está ejecutando el cliente. + +Polygon Edge está diseñado para ofrecer algoritmos de consenso conectables y disponibles de inmediato. + +La lista actual de algoritmos de consenso admitidos: + +* Prueba de autoridad (PoA) tolerante a falla bizantina de Estambul (IBFT) +* Prueba de participación (PoS) IBFT + +## Cadena de bloques {#blockchain} +La capa de la cadena de bloques es la capa central que coordina todo en el sistema de Polygon Edge. La sección correspondiente de *Módulos* profundiza sobre ella. + +## Estado {#state} +La capa interna Estado contiene la lógica de las transiciones de estado. Se ocupa de cómo cambia el estado cuando se incluye un bloque nuevo. La sección correspondiente de *Módulos* profundiza sobre ella. + +## RPC JSON {#json-rpc} +La capa de RPC JSON es la capa de la API que los desarrolladores de aplicaciones descentralizadas usan para interactuar con la cadena de bloques. La sección correspondiente de *Módulos* profundiza sobre ella. + +## TxPool {#txpool} +La capa TxPool representa el grupo de transacciones y está estrechamente vinculada con otros módulos en el sistema, ya que se pueden agregar transacciones desde múltiples puntos de entrada. + +## grpc {#grpc} + o llamada de procedimiento remoto de Google, es un sólido marco de código abierto que creó inicialmente para crear API escalables y rápidas. La capa GRPC es vital para las interacciones de los operadores. A través de ella, los operadores de nodos pueden interactuar fácilmente con el cliente y proporcionar una experiencia del usuario agradable. diff --git a/archive/edge/es-edge/community/propose-new-feature.md b/archive/edge/es-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..3da70ec8b4 --- /dev/null +++ b/archive/edge/es-edge/community/propose-new-feature.md @@ -0,0 +1,60 @@ +--- +id: propose-new-feature +title: Propón una nueva característica +description: "Plantilla de PR e instrucciones para proponer una nueva característica" +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## Descripción general {#overview} + +Si quieres incluir una solución o simplemente contribuir al código, se recomienda encarecidamente que primero te pongas en contacto con el equipo.
+Polygon Edge utiliza una plantilla de propuesta de características relativamente básica, que es concisa y va al grano. + +## Plantilla PR {#pr-template} + +### Descripción {#description} + +Por favor, describe en detalle lo que se hizo en esta PR. + +### Los cambios incluyen {#changes-include} + +- [ ] Bugfix (cambio que no perturba el sistema y resuelve un problema) +- [ ] Hotfix (cambio que resuelve un problema muy urgente y requiere atención inmediata) +- [ ] Nueva característica (cambio no radical que añade funcionalidad) +- [ ] Cambio de ruptura (cambio que no es compatible con las versiones anteriores y/o cambia la funcionalidad actual) + +### Cambios de ruptura {#breaking-changes} + +Por favor, rellena esta sección si se han realizado cambios de ruptura; de lo contrario, elimínala. + +### Lista de comprobación {#checklist} + +- [ ] me asigné este PR a mí mismo. +- [ ] añadí al menos 1 revisor. +- [ ] añadí las etiquetas correspondientes. +- [ ] actualicé la documentación oficial. +- [ ] añadí suficiente documentación en el código. + +### Pruebas {#testing} + +- [ ] sometí a pruebas este código con el paquete de pruebas oficial. +- [ ] sometí a pruebas este código manualmente. + +## Pruebas manuales {#manual-tests} + +Por favor, rellena esta sección si has ejecutado pruebas manuales para esta funcionalidad; de lo contrario, elimínala. + +### Documentación actualizada {#documentation-update} + +Por favor, enlaza la actualización de la documentación de PR en esta sección si está presente; de lo contrario, elimínala. + +### Comentarios adicionales {#additional-comments} + +Por favor, publica los comentarios adicionales en esta sección si los tienes; de lo contrario, elimínalos. \ No newline at end of file diff --git a/archive/edge/es-edge/community/report-bug.md b/archive/edge/es-edge/community/report-bug.md new file mode 100644 index 0000000000..e5189f74ed --- /dev/null +++ b/archive/edge/es-edge/community/report-bug.md @@ -0,0 +1,55 @@ +--- +id: report-bug +title: Reporta un problema +description: Plantilla e instrucciones para reportar problemas de Polygon Edge +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## Descripción general {#overview} + +A veces las cosas dejan de funcionar.
+Siempre es mejor avisarle al equipo sobre cualquier problema que encuentres.
+En la página de GitHub de Polygon Edge, puedes reportar un problema nuevo y hablarlo con el equipo. + +## Plantilla de problemas {#issue-template} + +## [Tema del problema] + +### Descripción {#description} + +Describe tu problema con el mayor detalle posible aquí. + +### Tu entorno {#your-environment} + +* Sistema operativo y versión +* Versión de Polygon Edge +* Rama que causó el problema + +### Pasos para reproducir {#steps-to-reproduce} + +* Cómo reproducir este problema
+* Dónde está el problema, si sabes
+* Qué comandos desencadenaron el problema, si aplica + +### Comportamiento esperado {#expected-behaviour} + +Lo que debería suceder + +### Comportamiento real {#actual-behaviour} + +Lo que sucede en su lugar + +### Registros {#logs} + +Por favor, pega cualquier registro aquí que muestre el problema, de haberlo. + +### Solución propuesta {#proposed-solution} + +Si tienes idea de cómo solucionar el problema, escríbela aquí, para que podamos empezar a hablar sobre ella. \ No newline at end of file diff --git a/archive/edge/es-edge/configuration/manage-private-keys.md b/archive/edge/es-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..d2838cca7a --- /dev/null +++ b/archive/edge/es-edge/configuration/manage-private-keys.md @@ -0,0 +1,78 @@ +--- +id: manage-private-keys +title: Adminsitración de claves privadas +description: "Cómo administrar las claves privadas y qué tipos de claves existen" +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## Descripción general {#overview} + +Polygon Edge tiene dos tipos de claves privadas que administra directamente: + +* **Claves privada utilizada para el mecanismo de consenso** +* **Clave privada utilizada por libp2p para interconexión** +* **(Opcional) Clave privada BLS utilizada por el mecanismo de consenso para agregar las firmas de los validadores** + +Actualmente, Polygon Edge no ofrece soporte para la administración directa de cuentas. + +Con base en la estructura del directorio descrita en la [guía de copia de seguridad y restauración](/docs/edge/working-with-node/backup-restore), Polygon Edge almacena esos archivos clave mencionados en dos directorios distintos: **consenso** y **almacén de claves**. + +## Formato de la clave {#key-format} + +Las claves privadas se guardan en **formato Base64** simple, para que puedan ser legibles por el ser humano y portátiles. + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info Tipo de claves + +Todos los archivos de claves privadas generados y utilizados dentro de Polygon Edge dependen de ECDSA con la curva [secp256k1](https://en.bitcoin.it/wiki/Secp256k1). + +Como la curva no es estándar, no se puede codificar ni almacenar en ningún formato PEM estandarizado. +No se admite la importación de claves que no se ajusten a este tipo de clave. + +::: +## Clave privada de consenso {#consensus-private-key} + +El archivo de claves privadas mencionado como *clave privada de consenso*consenso1 también se denomina **clave privada de validador**. +Esta clave privada se utiliza cuando el nodo actúa como validador en la red y debe firmar nuevos datos. + +El archivo de clave privada se encuentra en `consensus/validator.key` y se adhiere al [formato de clave](/docs/edge/configuration/manage-private-keys#key-format) mencionado. + +:::warning + +La clave privada del validador es única para cada nodo validador. La misma clave no debe compartirse entre todos los validadores, ya que eso puede comprometer la seguridad de tu cadena. + +::: + +## Clave privada de interconexión {#networking-private-key} + +El archivo de clave privada que se menciona para interconectarse es utilizado por libp2p para generar la correspondiente ID de par y permitir que el nodo partícipe en la red. + +Se encuentra en `keystore/libp2p.key` y se adhiere al [formato de clave](/docs/edge/configuration/manage-private-keys#key-format) mencionado. + +## Clave secreta BLS {#bls-secret-key} + +El archivo de clave secreta BLS se utiliza para agregar los sellos comprometidos en la capa de consenso. El tamaño de los sellos comprometidos agregados por BLS es menor que las firmas ECDSA comprometidas serializadas. + +La característica BLS es opcional y es posible elegir si se utiliza. Consulta [BLS](/docs/edge/consensus/bls) para más detalles. + +## Importación y exportación {#import-export} + +Como los archivos de claves se almacenan en Base64 simple en el disco, es fácil hacer una copia de seguridad o importarlos. + +:::caution Cambio de clave de archivos + +Cualquier tipo de cambio realizado en los archivos de claves en una red ya configurada o que esté funcionando puede conducir a una grave interrupción de la red o del consenso, +ya que los mecanismos de consenso y de descubrimiento de pares almacenan los datos derivados de estas claves en el almacenamiento específico del nodo y dependen de ellos para +iniciar las conexiones y ejecutar la lógica del consenso + +::: \ No newline at end of file diff --git a/archive/edge/es-edge/configuration/prometheus-metrics.md b/archive/edge/es-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..a69b9e3b2b --- /dev/null +++ b/archive/edge/es-edge/configuration/prometheus-metrics.md @@ -0,0 +1,35 @@ +--- +id: prometheus-metrics +title: Métricas de Prometheus +description: "Cómo habilitar las métricas de Prometheus para Polygon Edge." +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## Descripción general {#overview} + +Polygon Edge puede reportar y proveer las métricas de Prometheus, las cuales a su vez pueden ser consumidas mediante los colectores de Prometheus. + +Las métricas de Prometheus están deshabilitadas por defecto. Puede habilitarse indicando la dirección del oyente a través de una `--prometheus`marca o`Telemetry.prometheus` un campo en el archivo de configuración. +Las métricas son servidas bajo `/metrics`en la dirección especificada. + +## Métricas disponibles {#available-metrics} + +Están disponibles las siguientes métricas: + +| **Nombre** | **Tipo** | **Descripción** | +|-----------------------------------------------|---------------|-------------------------------------------------| +| txpool_pending_transactions | Medidor | Número de transacciones pendientes en TxPool | +| consensus_validators | Medidor | Número de validadores | +| consensus_rounds | Medidor | Número de rondas | +| consensus_num_txs | Medidor | Número de transacciones en el bloque más reciente | +| consensus_block_interval | Medidor | Tiempo entre este y el último bloque en segundos | +| network_peers | Medidor | Número de pares conectados | +| network_outbound_connections_count | Medidor | Número de conexiones salientes | +| network_inbound_connections_count | Medidor | Número de conexiones entrantes | +| network_pending_outbound_connections_count | Medidor | Número de conexiones salientes pendientes | +| network_pending_inbound_connections_count | Medidor | Número de conexiones entrantes pendientes | \ No newline at end of file diff --git a/archive/edge/es-edge/configuration/sample-config.md b/archive/edge/es-edge/configuration/sample-config.md new file mode 100644 index 0000000000..15323fa6b3 --- /dev/null +++ b/archive/edge/es-edge/configuration/sample-config.md @@ -0,0 +1,150 @@ +--- +id: sample-config +title: Archivo de configuración del servidor +description: "Inicia el servidor de Polygon Edge utilizando un archivo de configuración." +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# Archivo de configuración del servidor {#server-configuration-file} +Se puede iniciar el servidor con varias opciones de configuración utilizando un archivo de configuración en lugar de utilizar solo indicadores. +El comando utilizado para iniciar el servidor con un archivo de configuración: `polygon-edge server --config ` + +## Exporta el archivo de configuración con la configuración por defecto {#export-config-file-with-default-configuration} +La configuración con los ajustes por defecto del servidor de Polygon Edge se puede exportar a un archivo de configuración `yaml`o `json`en cualquiera de los dos formatos. Este archivo se puede utilizar como plantilla para ejecutar el servidor utilizando un archivo de configuración. + +### YAML {#yaml} +Para generar el archivo de configuración en: `yaml` +```bash +polygon-edge server export --type yaml +``` +o simplemente +```bash +polygon-edge server export +``` +el archivo de configuración nombrado `default-config.yaml` se creará en el mismo directorio desde donde se ejecutó este comando. + +Ejemplo de archivo: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +Para generar el archivo de configuración en: `json` +```bash +polygon-edge server export --type json +``` +el archivo de configuración nombrado `default-config.json` se creará en el mismo directorio desde donde se ejecutó este comando. + +Ejemplo de archivo: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +Consulta la sección [Comandos CLI](/docs/edge/get-started/cli-commands) para obtener información sobre cómo utilizar estos parámetros. + +### Esquema de los Typescript {#typescript-schema} + +El siguiente es el formato de ejemplo para el archivo de configuración. Está escrito en TypeScript para expresar los tipos de propiedades (`string`,`number`,`boolean`) a partir de él podría derivar tu configuración. Es importante mencionar que el tipo `PartialDeep`desde `type-fest` se utiliza para expresar que todas las propiedades son opcionales. + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/es-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/es-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..1d40a6db3c --- /dev/null +++ b/archive/edge/es-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,137 @@ +--- +id: set-up-aws-ssm +title: Configurar el Agente de administración de sistemas (SSM) de AWS +description: "Configura el SSM (Agente de administración de sistemas) de AWS para Polygon Edge" +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## Descripción general {#overview} + +En la actualidad, Polygon Edge se encarga de mantener 2 importantes secretos de ejecución: +* La **clave privada del validador** utilizada por el nodo, si el nodo es un validador +* La **clave privada de interconexión** utilizada por libp2p para participar en subastas y comunicarse con otros pares + +Para obtener información adicional, lee la [guía de gestión de claves privadas](/docs/edge/configuration/manage-private-keys). + +Los módulos de Polygon Edge **no deberían tener que saber cómo guardar secretos**. Finalmente, a un módulo no debería importarle si +un secreto se almacena en un servidor lejano o localmente, en el disco del nodo. + +Todo lo que un módulo necesita saber sobre guardar secretos es **saber utilizar el secreto** y** saber qué secretos obtener +o guardar**. Los detalles de implementación más precisos de estas operaciones se le delegan a `SecretsManager`, que es, lógicamente, una abstracción. + +El operador de nodos que está iniciando Polygon Edge ya puede especificar qué administrador de secretos quiere utilizar, y tan pronto +el administrador de secretos correcto es instanciado, los módulos se ocupan de los secretos por medio de la interfaz mencionada +independientemente de si los secretos se almacenan en un disco o en un servidor. + +Este artículo detalla los pasos necesarios para que Polygon Edge inicie y se ejecute con +la [tienda de parámetros del administrador de sistemas de AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html). + +:::info Guías anteriores + +Se **recomienda enfáticamente** que, antes de leer este artículo, leas los artículos acerca de la [**configuración local**](/docs/edge/get-started/set-up-ibft-locally) +y la [**configuración de la nube**](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +::: + + +## Prerrequisitos {#prerequisites} +### Política de Administración de identidad y acceso (IAM) {#iam-policy} +El usuario debe crear una política de IAM que permita leer y escribir operaciones para la tienda de parámetros del administrador de sistemas de AWS. Después de crear la política de IAM con éxito, el usuario debe conectarla con la instancia de EC2 que está ejecutando el servidor de Polygon Edge. +La política de IAM debería verse así: +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +Obten más información sobre los roles de IAM del administrador de sistemas de AWS que puedes encontrar en la [documentación de AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html). + +Información necesaria antes de continuar: +* **Región**: la región en la que están ubicados el administrador de sistemas y los nodos +* **Ruta de los parámetros**: ruta arbitraria en la que se ubicará el secreto, por ejemplo, `/polygon-edge/nodes`) + +## Paso 1: genera la configuración del administrador de secretos {#step-1-generate-the-secrets-manager-configuration} + +Para que Polygon Edge pueda comunicarse sin problemas con el administrador de sistemas de AWS, debe analizar un +archivo de configuración ya generado, el cual contiene toda la información necesaria para almacenar secretos en el SSM de AWS. + +Para generar la configuración, ejecuta el siguiente comando: + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +Parámetros presentes: +* `PATH` es la ruta a la que se debe exportar el archivo de configuración. `./secretsManagerConfig.json` por defecto +* `NODE_NAME` es el nombre del nodo actual para el que se está configurando la el SSM de AWS. Puede ser un valor arbitrario. `polygon-edge-node` por defecto +* `REGION` es la región en la que está ubicado el SSM de AWS. Debe ser la misma región que la del nodo que utiliza el SSM de AWS. +* `SSM_PARAM_PATH` es el nombre de la ruta en la que se almacenará el secreto. Por ejemplo, si se especifican `--name node1` y `ssm-parameter-path=/polygon-edge/nodes`, +el secreto se guardará como `/polygon-edge/nodes/node1/`. + +:::caution Nombres de los nodos + +Ten cuidado al especificar los nombres de los nodos. + +Polygon Edge utiliza el nombre del nodo especificado para hacerle seguimiento a los secretos que genera y utiliza en el SSM de AWS. Especificar un nombre de nodo existente puede causar la imposibilidad de escribir el secreto en el SSM de AWS. + +Los secretos se guardan en la siguiente ruta base: `SSM_PARAM_PATH/NODE_NAME` + +::: + +## Paso 2: inicializa las claves secretas con la configuración {#step-2-initialize-secret-keys-using-the-configuration} + +Ahora que el archivo de configuración está presente, podemos inicializar las claves secretas necesarias con el archivo +de configuración, establecido en el paso 1, con: `--config` + +```bash +polygon-edge secrets init --config +``` + +El parámetro `PATH` es la ubicación del parámetro del administrador de secretos previamente generado en el paso 1. + +:::info Política de Administración de identidad y acceso (IAM) + +Ese paso fallará si la política de IAM que permite las operaciones de lectura y escritura no está configurada correctamente o no está vinculada con la instancia de EC2 que ejecuta ese comando. + +::: + +## Paso 3: genera el archivo génesis {#step-3-generate-the-genesis-file} + +El archivo génesis debe generarse de manera similar a como lo indican las guías de la [**configuración local**](/docs/edge/get-started/set-up-ibft-locally) +y de la [**configuración de la nube**](/docs/edge/get-started/set-up-ibft-on-the-cloud), con pocos cambios. + +Dado que el SSM de AWS se está utilizando en lugar del sistema de archivos local, se deben agregar las direcciones de los validadores a través de la indicación `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Paso 4: inicia el cliente de Polygon Edge {#step-4-start-the-polygon-edge-client} + +Ahora que las claves están configuradas y el archivo génesis ha sido generado, el paso final de este proceso será iniciar +Polygon Edge con el comando `server`. + +El comando `server` se utiliza de la misma manera que en las guías ya mencionadas, con una pequeña adición, el indicador `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +El parámetro `PATH` es la ubicación del parámetro del administrador de secretos previamente generado en el paso 1. \ No newline at end of file diff --git a/archive/edge/es-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/es-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..68a05dff9c --- /dev/null +++ b/archive/edge/es-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,121 @@ +--- +id: set-up-gcp-secrets-manager +title: Configura el Administrador de secretos en la plataforma de Google Cloud (GCP) +description: "Configura el Administrador de secretos de GCP para Polygon Edge" +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## Descripción general {#overview} + +En la actualidad, Polygon Edge se encarga de mantener 2 importantes secretos de ejecución: +* La **clave privada del validador** utilizada por el nodo, si el nodo es un validador +* La **clave privada de interconexión** utilizada por libp2p para participar en subastas y comunicarse con otros pares + +Para obtener información adicional, lee la [guía de gestión de claves privadas](/docs/edge/configuration/manage-private-keys). + +Los módulos de Polygon Edge **no deberían tener que saber cómo guardar secretos**. Finalmente, a un módulo no debería importarle si +un secreto se almacena en un servidor lejano o localmente, en el disco del nodo. + +Todo lo que un módulo necesita saber sobre guardar secretos es **saber utilizar el secreto** y** saber qué secretos obtener +o guardar**. Los detalles de implementación más precisos de estas operaciones se le delegan a `SecretsManager`, que es, lógicamente, una abstracción. + +El operador de nodos que está iniciando Polygon Edge ya puede especificar qué administrador de secretos quiere utilizar, y tan pronto +el administrador de secretos correcto es instanciado, los módulos se ocupan de los secretos por medio de la interfaz mencionada +independientemente de si los secretos se almacenan en un disco o en un servidor. + +Este artículo explica los pasos necesarios para iniciar Polygon Edge con el [Administrador de secretos de GCP](https://cloud.google.com/secret-manager). + +:::info Guías anteriores + +Se **recomienda enfáticamente** que, antes de leer este artículo, leas los artículos acerca de la [**configuración local**](/docs/edge/get-started/set-up-ibft-locally) +y la [**configuración de la nube**](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +::: + + +## Prerrequisitos {#prerequisites} +### Cuenta de facturación de GCP {#gcp-billing-account} +Para poder utilizar el Adminsitrador de secretos de GCP, el usuario debe tener la [Cuenta de facturación](https://console.cloud.google.com/) habilitada en el portal de GCP. +Las nuevas cuentas de Google en la plataforma de GCP tienen algunos fondos para empezar, como parte de la prueba gratuita. +Información más detallada [sobre los documentos de GCP](https://cloud.google.com/free) + +### API del Adminsitrador de secretos {#secrets-manager-api} +El usuario deberá habilitar la API del Adminsitrador de secretos de GCP antes de poder utilizarla. +Eso se puede hacer mediante el [portal de la API del Administrador de secretos](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com). +Información más detallada: [Configuración de Administrador de secretos](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + +### Credenciales de GCP {#gcp-credentials} +Por último, el usuario debe generar nuevas credenciales que se utilizarán para la autenticación. +Eso se puede hacer siguiendo las instrucciones publicadas [aquí](https://cloud.google.com/secret-manager/docs/reference/libraries) +El archivo json generado que contiene credenciales debe transferirse a cada uno de los nodos que necesita utilizar el administrador de secretos de GCP. + +Información necesaria antes de continuar: +* **ID del proyecto** (la ID del proyecto definido en la plataforma GCP) +* **Ubicación del archivo de credenciales** (la ruta del archivo json que contiene las credenciales) + +## Paso 1: Genera la configuración del administrador de secretos {#step-1-generate-the-secrets-manager-configuration} + +Para que el Polygon Edge pueda comunicarse sin problemas con el administrador de secretos de GCP, debe analizar un archivo de configuración +ya generado, que contiene toda la información necesaria para el almacenamiento de secretos en el administrador de secretos de GCP. + +Para generar la configuración, ejecuta el siguiente comando: + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +Parámetros presentes: +* `PATH` es la ruta a la que se debe exportar el archivo de configuración. `./secretsManagerConfig.json` por defecto +* `NODE_NAME`es el nombre del nodo actual para el cual se está estableciendo la configuración del administrador de secretos de GCP. Puede ser un valor arbitrario. `polygon-edge-node` por defecto +* `PROJECT_ID`es la ID del proyecto que es definida por el usuario en la consola de GCP durante la configuración de la cuenta y la activación de la API del Administrador de secretos. +* `GCP_CREDS_FILE` es la ruta del archivo json que contiene las credenciales que permitirán el acceso de lectura o escritura al administrador de secretos. + +:::caution Nombres de los nodos + +Ten cuidado al especificar los nombres de los nodos. + +Polygon Edge utiliza el nombre del nodo especificado para hacerle seguimiento a los secretos que genera y utiliza en el administrador de secretos de GCP. +Especificar un nombre de nodo existente puede provocar que no se escriba el secreto en el administrador de secretos de GCP. + +Los secretos se guardan en la siguiente ruta base: `projects/PROJECT_ID/NODE_NAME` + +::: + +## Paso 2: inicializa las claves secretas con la configuración {#step-2-initialize-secret-keys-using-the-configuration} + +Ahora que el archivo de configuración está presente, podemos inicializar las claves secretas necesarias con el archivo +de configuración, establecido en el paso 1, con: `--config` + +```bash +polygon-edge secrets init --config +``` + +El parámetro `PATH` es la ubicación del parámetro del administrador de secretos previamente generado en el paso 1. + +## Paso 3: genera el archivo génesis {#step-3-generate-the-genesis-file} + +El archivo génesis debe generarse de manera similar a como lo indican las guías de la [**configuración local**](/docs/edge/get-started/set-up-ibft-locally) +y de la [**configuración de la nube**](/docs/edge/get-started/set-up-ibft-on-the-cloud), con pocos cambios. + +Dado que el administrador de secretos de GCP se está utilizando en lugar del sistema de archivos local, se deben agregar las direcciones de los validadores mediante la indicación`--ibft-validator`. +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Paso 4: inicia el cliente de Polygon Edge {#step-4-start-the-polygon-edge-client} + +Ahora que las claves están configuradas y el archivo génesis ha sido generado, el paso final de este proceso será iniciar +Polygon Edge con el comando `server`. + +El comando `server` se utiliza de la misma manera que en las guías ya mencionadas, con una pequeña adición, el indicador `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +El parámetro `PATH` es la ubicación del parámetro del administrador de secretos previamente generado en el paso 1. \ No newline at end of file diff --git a/archive/edge/es-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/es-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..48741b00dd --- /dev/null +++ b/archive/edge/es-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,118 @@ +--- +id: set-up-hashicorp-vault +title: Configuración de Vault de Hashicorp +description: "Configurar Vault de Hashicorp para Polygon Edge" +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## Descripción general {#overview} + +En la actualidad, Polygon Edge se encarga de mantener 2 importantes secretos de ejecución: +* La **clave privada del validador** utilizada por el nodo, si el nodo es un validador +* La **clave privada de interconexión** utilizada por libp2p para participar y comunicarse con otros pares + +:::warning + +La clave privada del validador es única para cada nodo validador. La misma clave no debe compartirse entre todos los validadores, ya que eso puede comprometer la seguridad de tu cadena. + +::: + +Para obtener información adicional, lee la [guía de administración de claves privadas](/docs/edge/configuration/manage-private-keys). + +Los módulos de Polygon Edge **no deberían tener que saber cómo guardar secretos**. Finalmente, a un módulo no debería importarle si +un secreto se almacena en un servidor lejano o localmente, en el disco del nodo. + +Todo lo que un módulo necesita saber sobre guardar secretos es **saber utilizar el secreto** y** saber qué secretos obtener +o guardar**. Los detalles de implementación más precisos de estas operaciones se le delegan a `SecretsManager`, que es, lógicamente, una abstracción. + +El operador de nodos que está iniciando Polygon Edge ya puede especificar qué administrador de secretos quiere utilizar, y tan pronto +el administrador de secretos correcto es instanciado, los módulos se ocupan de los secretos por medio de la interfaz mencionada +independientemente de si los secretos se almacenan en un disco o en un servidor. + +Este artículo detalla los pasos necesarios para iniciar Polygon Edge con un servidor de [Vault de Hashicorp](https://www.vaultproject.io/). + +:::info Guías anteriores + +Se **recomienda enfáticamente** que, antes de leer este artículo, leas los artículos acerca de la [**configuración local**](/docs/edge/get-started/set-up-ibft-locally) +y la [**configuración de la nube**](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +::: + + +## Prerrequisitos {#prerequisites} + +Este artículo asume que una instancia en funcionamiento del servidor Vault de Hashicorp **ya está configurada**. + +Además, es necesario que el servidor de Vault de Hashicorp que se utilice para Polygon Edge tenga **habilitado el almacenamiento clave-valor (KV)**. + +Información necesaria antes de continuar: +* **El URL** del servidor (el URL de la API del servidor de Vault de Hashicorp) +* **Token** (token de acceso utilizado para acceder al motor de almacenamiento de KV) + +## Paso 1: Genera la configuración del administrador de secretos {#step-1-generate-the-secrets-manager-configuration} + +Para que Polygon Edge pueda comunicarse sin problemas con el servidor de Vault, debe analizar un archivo de configuración +ya generado, que contenga toda la información necesaria para el almacenamiento de secretos en Vault. + +Para generar la configuración, ejecuta el siguiente comando: + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +Parámetros presentes: +* `PATH` es la ruta a la que se debe exportar el archivo de configuración. `./secretsManagerConfig.json` por defecto +* `TOKEN` es el token de acceso ya mencionado en la [sección de prerrequisitos](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `SERVER_URL`es el URL de la API para el servidor de Vault, también mencionada en la [sección de prerrequisitos](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `NODE_NAME`es el nombre del nodo actual para el que la configuración de Vault se está configurando. Puede ser un valor arbitrario. `polygon-edge-node` por defecto + +:::caution Nombres de los nodos + +Ten cuidado al especificar los nombres de los nodos. + +Polygon Edge utiliza el nombre del nodo especificado para hacerle seguimiento a los secretos que genera y utiliza en la instancia de Vault. +La especificación del nombre de un nodo existente podría tener como consecuencia la sobrescritura de los datos en el servidor de Vault. + +Los secretos se guardan en la siguiente ruta base: `secrets/node_name` + +::: + +## Paso 2: inicializa las claves secretas con la configuración {#step-2-initialize-secret-keys-using-the-configuration} + +Ahora que el archivo de configuración está presente, podemos inicializar las claves secretas necesarias con el archivo +de configuración, establecido en el paso 1, con: `--config` + +```bash +polygon-edge secrets init --config +``` + +El parámetro `PATH` es la ubicación del parámetro del administrador de secretos previamente generado en el paso 1. + +## Paso 3: genera el archivo génesis {#step-3-generate-the-genesis-file} + +El archivo génesis debe generarse de manera similar a como lo indican las guías de la [**configuración local**](/docs/edge/get-started/set-up-ibft-locally) +y de la [**configuración de la nube**](/docs/edge/get-started/set-up-ibft-on-the-cloud), con pocos cambios. + +Dado que Vault de Hashicorp se está utilizando en lugar del sistema de archivos local, se deben agregar las direcciones de los validadores por medio del indicador `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Paso 4: Inicia el cliente de Polygon Edge {#step-4-start-the-polygon-edge-client} + +Ahora que las claves están configuradas y el archivo génesis ha sido generado, el paso final de este proceso será iniciar +Polygon Edge con el comando `server`. + +El comando `server` se utiliza de la misma manera que en las guías ya mencionadas, con una pequeña adición, el indicador `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +El parámetro `PATH` es la ubicación del parámetro del administrador de secretos previamente generado en el paso 1. \ No newline at end of file diff --git a/archive/edge/es-edge/consensus/bls.md b/archive/edge/es-edge/consensus/bls.md new file mode 100644 index 0000000000..b7f7612c49 --- /dev/null +++ b/archive/edge/es-edge/consensus/bls.md @@ -0,0 +1,144 @@ +--- +id: bls +title: BLS +description: "Explicación e instrucciones con respecto al modo Boneh–Lynn–Shacham (BLS)" +keywords: + - docs + - polygon + - edge + - bls +--- + +## Descripción general {#overview} + +BLS también conocido como Boneh–Lynn–Shacham (BLS)) es un esquema de firma criptográfica que permite a un usuario verificar que un firmador es auténtico. Es un esquema de firma que puede agregar varias firmas. BLS se utiliza en Polygon Edge por defecto para dar más seguridad en el modo de consenso de tolerancia a fallas bizantinas de Estambul (IBFT). BLS puede agregarle firmas a un solo grupo de bytes y reducir el tamaño del encabezado de los bloques. Cada cadena puede elegir si utilizará BLS. La clave del algoritmo digital de firma de curva elíptica (ECDSA) se utiliza independientemente de si el modo BLS está habilitado. + +## Presentación en vídeo {#video-presentation} + +[![bls - vídeo](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## Cómo configurar una cadena nueva con BLS {#how-to-setup-a-new-chain-using-bls} + +Consulta las secciones de [configuración local](/docs/edge/get-started/set-up-ibft-locally) y de[ configuración de la nube](/docs/edge/get-started/set-up-ibft-on-the-cloud) para obtener instrucciones detalladas de instalación. + +## Cómo migrar de una cadena con pruebas de autoridad (PoA) de ECDSA existente a la cadena de PoA de BLS {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +Esta sección describe cómo utilizar el modo BLS en una cadena de PoA existente. +Los siguientes pasos son necesarios para habilitar BLS en una cadena de PoA. + +1. Detener todos los nodos +2. Generar las claves de BLS para los validadores +3. Agregarle un ajuste de bifurcación a genesis.json +4. Reiniciar todos los nodos + +### 1. Detén todos los nodos {#1-stop-all-nodes} + +Finaliza todos los procesos de los validadores presionando Ctrl + c (Control + c). Recuerde la altura de bloque más reciente (el número de secuencia más alto en el registro comprometido del bloque). + +### 2. Genera la clave de BLS {#2-generate-the-bls-key} + +`secrets init` con `--bls` genera una clave de BLS. Para mantener la clave de red y ECDSA existentes y añadir una nueva clave de BLS, se deben desactivar `--ecdsa` y `--network`. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Añade un ajuste de bifurcación {#3-add-fork-setting} + +El comando `ibft switch` añade un ajuste de bifurcación, el cual habilita BLS en la cadena existente, en `genesis.json`. + +Para redes con PoA, se deben suministrar los validadores en el comando. Al igual que con el modo de comando `genesis`, se pueden utilizar los indicadores `--ibft-validators-prefix-path` o `--ibft-validator` para especificar el validador. + +Especifica la altura desde la que comienza la cadena mediante el uso de BLS con el indicador `--from`. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. Reinicia todos los nodos {#4-restart-all-nodes} + +Reinicia todos los nodos con el comando `server`. Después de crear el bloque en `from`, especificado en el paso anterior, la cadena habilita el BLS y muestra los registros así: + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +Además, los registros muestran qué modo de verificación se utiliza para generar cada bloque después de crear el bloque. + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## Cómo migrar de una cadena con PoS de ECDSA existente a la cadena con PoS de BLS {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +Esta sección describe cómo utilizar el modo BLS en una cadena de PoS existente. +Los siguientes pasos son necesarios para habilitar BLS en la cadena de PoS. + +1. Detener todos los nodos +2. Generar las claves de BLS para los validadores +3. Agregarle un ajuste de bifurcación a genesis.json +4. Llamar al contrato de participación en subastas para registrar la clave pública de BLS +5. Reiniciar todos los nodos + +### 1. Detén todos los nodos {#1-stop-all-nodes-1} + +Finaliza todos los procesos de los validadores presionando Ctrl + c (Control + c). Recuerde la altura de bloque más reciente (el número de secuencia más alto en el registro comprometido del bloque). + +### 2. Genera la clave de BLS {#2-generate-the-bls-key-1} + +`secrets init` con la indicación `--bls` generan la clave de BLS. Para mantener la clave de red y ECDSA existentes y añadir una nueva clave de BLS, se deben desactivar `--ecdsa` y `--network`. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Añade un ajuste de bifurcación {#3-add-fork-setting-1} + +El comando `ibft switch` añade un ajuste de bifurcación, el cual habilita BLS desde el centro de la cadena, a `genesis.json`. + +Especifica la altura desde la que la cadena comienza a usar el modo BLS con el indicador `from` y la altura en la que el contrato se actualiza con la indicación `development`. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. Registra la clave pública de BLS en el contrato de participación en subastas {#4-register-bls-public-key-in-staking-contract} + +Después de que se añade la bifurcación y los validadores se reinician, cada validador debe llamar a `registerBLSPublicKey` en el contrato de participación en subastas para registrar la clave pública de BLS. Eso se debe hacer después de la altura especificada en `--deployment` y antes de la altura especificada en `--from`. + +La secuencia de comandos para registrar la clave pública de BLS se define en el [repositorio de contratos inteligentes de participación en subastas](https://github.com/0xPolygon/staking-contracts). + +Establece que `BLS_PUBLIC_KEY` se registre en el archivo `.env`. Consulta [PoS de participación y eliminación de participación en subastas](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) para obtener más información acerca de los otros parámetros. + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +El siguiente comando registra la clave pública de BLS suministrada en `.env` al contrato. + +```bash +npm run register-blskey +``` + +:::warning Los validadores deben registrar la clave pública de BLS manualmente. + +En el modo BLS, los validadores deben tener su propia dirección y la clave pública de BLS. La capa de consenso ignora los validadores que no han registrado la clave pública de BLS en el contrato cuando el consenso trae la información del validador desde el contrato. + +::: + +### 5. Reinicia todos los nodos {#5-restart-all-nodes} + +Reinicia todos los nodos con el comando `server`. La cadena habilita el BLS después de crear el bloque en `from`, especificado en el paso anterior. diff --git a/archive/edge/es-edge/consensus/migration-to-pos.md b/archive/edge/es-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..3f01632acf --- /dev/null +++ b/archive/edge/es-edge/consensus/migration-to-pos.md @@ -0,0 +1,40 @@ +--- +id: migration-to-pos +title: Migración de PoA a PoS +description: "Cómo migrar de prueba de autoridad (PoA) a prueba de participación (PoS) y viceversa en modo IBFT " +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## Descripción general {#overview} + +Esta sección te explicará la migración de PoA a PoS y viceversa en modo IBFT para un grupo en ejecución, sin tener que reiniciar la cadena de bloques. + +## Cómo migrar a PoS {#how-to-migrate-to-pos} + +Deberás detener todos los nodos, añadir la configuración de la bifurcación en genesis.json con el comando `ibft switch` y reiniciar los nodos. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution Cambio mientras utiliza ECDSA +Cuando se utiliza ECDSA, la `--ibft-validator-type`bandera se debe agregar al interruptor, mencionando que se utiliza ECDSA. Si no está incluido, Edge se cambiará automáticamente a BLS. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::Para cambiar a PoS, deberás especificar 2 alturas de bloques: `deployment`y . `from`es la altura para desplegar el contrato de participación y `from`es `deployment`la altura del comienzo de PoS. El contrato de participación en subastas se desplegará en la dirección `0x0000000000000000000000000000000000001001` en `deployment`, como en el caso del contrato predesplegado. + +Revisa la [prueba de participación](/docs/edge/consensus/pos-concepts) para obtener más detalles sobre los contratos de participación en subastas. + +:::warning Los validadores deben participar en subastas manualmente. + +Cada validador debe participar después de que su contrato se despliegue en `deployment` y antes de `from` para poder ser un validador al comienzo de la PoS. Cada validador actualizará cada conjunto de validadores en el contrato de participación en subastas, al inicio de la PoS. + +Para obtener más información sobre participar en este proceso, visita la **[configuración y utiliza la prueba de participación ](/docs/edge/consensus/pos-stake-unstake)**. +::: diff --git a/archive/edge/es-edge/consensus/poa.md b/archive/edge/es-edge/consensus/poa.md new file mode 100644 index 0000000000..ffe6e4c492 --- /dev/null +++ b/archive/edge/es-edge/consensus/poa.md @@ -0,0 +1,110 @@ +--- +id: poa +title: Prueba de autoridad (PoA) +description: "Explicación e instrucciones de la prueba de autoridad." +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## Descripción general {#overview} + +La PoA con tolerancia a la falla bizantina de Estambul (IBFT) es el mecanismo de consenso por defecto en Polygon Edge. En las PoA, los validadores son los responsables de crear los bloques y de añadirlos a la cadena de bloques en una serie. + +Todos los validadores forman un conjunto de validadores dinámicos, en el que se pueden añadir o eliminar validadores al conjunto mediante la utilización de un mecanismo de votación. Esto significa que se puede votar para que los validadores entren o salgan del conjunto de validadores si la mayoría (51 %) de los nodos validadores votan para añadir o eliminar ciertos validadores al conjunto. De esa manera, se pueden reconocer y eliminar los validadores maliciosos de la red, a la vez que se pueden añadir nuevos validadores confiables a la red. + +Todos los validadores toman turnos para proponer el siguiente bloque (round-robin), y para validar o insertar el bloque en la cadena de bloques. Una supermayoría (más de dos terceras partes) de los validadores debe aprobar el bloque mencionado. + +Además de los validadores, hay no validadores que no participan en la creación del bloque, pero que sí participan en el proceso de validación del bloque. + +## Adición de un validador al conjunto de validadores {#adding-a-validator-to-the-validator-set} + +Esta guía describe cómo añadir un nuevo nodo validador a una red IBFT activa con cuatro nodos validadores. +Si necesitas ayuda para configurar la red, consulta las secciones [de configuración local/configuración en](/edge/get-started/set-up-ibft-on-the-cloud.md)[](/edge/get-started/set-up-ibft-locally.md) la nube. + +### Paso 1: inicializa las carpetas de datos para IBFT y genera claves​ de validador para el nodo nuevo {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +Para iniciar y ejecutar con IBFT en el nuevo nodo, primero debes inicializar las carpetas de datos y generar las claves: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +Este comando imprimirá la clave del validador (dirección) y la ID del nodo. Para el siguiente paso, necesitarás la clave del validador (dirección). + +### Paso 2: propón un nuevo candidato de otros nodos validadores {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +Para que un nodo nuevo se convierta en validador, al menos el 51 % de los validadores deben proponerlo. + +Ejemplo de cómo proponer un nuevo validador (`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`) del nodo validador existente en la dirección de grpc: 127.0.0.1:1000: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +La estructura de los comandos de IBFT se encuentra en la sección de [comandos CLI](/docs/edge/get-started/cli-commands). + +:::info Clave pública de BLS + +La clave pública de BLS solo es necesaria si la red se está ejecutando con BLS, para la red que no se está ejecutando en modo BLS `--bls` no es necesario + +::: + +### Paso 3: ejecuta el nodo cliente {#step-3-run-the-client-node} + +Dado que en este ejemplo estamos tratando de ejecutar la red donde todos los nodos están en la misma máquina, debemos procurar que no haya conflictos de puertos. + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +Después de traer todos los bloques, notarás que dentro de tu consola hay un nodo nuevo participando en la validación. + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info Promoción de un no validador a un validador + +Naturalmente, un no validador puede convertirse en validador mediante el proceso de votación, pero para que se incluya correctamente en el conjunto de validadores después del proceso de votación, el nodo se debe reiniciar con el indicador `--seal`. + +::: + +## Eliminar un validador del conjunto de validadores {#removing-a-validator-from-the-validator-set} + +Esta operación es bastante simple. Para eliminar un nodo validador del conjunto de validadores, este comando se debe ejecutar para la mayoría de los nodos validadores. + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info Clave pública de BLS + +La clave pública de BLS solo es necesaria si la red se está ejecutando con BLS, para la red que no se está ejecutando en modo BLS `--bls` no es necesario + +::: + +Después de ejecutar los comandos, observa que el número de validadores se ha reducido (en este ejemplo de registro, de 4 a 3). + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/es-edge/consensus/pos-concepts.md b/archive/edge/es-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..9914f323fe --- /dev/null +++ b/archive/edge/es-edge/consensus/pos-concepts.md @@ -0,0 +1,122 @@ +--- +id: pos-concepts +title: Prueba de participación +description: "Explicación e instrucciones de la prueba de participación" +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## Descripción general {#overview} + +El objetivo de esta sección es describir mejor algunos conceptos presentes actualmente en la implementación +de la prueba de participación (PoS) en Polygon Edge. + +La implementación de la prueba de participación (PoS) de Polygon Edge busca ser una alternativa a la implementación de la IBFT en la Prueba de autoridad (PoA) existente, +lo que les da a los operadores de nodos la capacidad de elegir fácilmente entre ambas opciones al iniciar la cadena. + +## Características de las pruebas de participación (PoS) {#pos-features} + +La lógica central de la implementación de la prueba de participación está dentro +el **[contrato inteligente de participación](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)** + +Este contrato se predespliega cada vez que se inicia una cadena de Polygon Edge con mecanismo PoS y está disponible en la dirección +`0x0000000000000000000000000000000000001001` del bloque `0`. + +### Épocas {#epochs} + +Las épocas son un concepto introducido con la adición de PoS a Polygon Edge. + +Se considera que una época es un marco temporal especial (en bloques) en el que un conjunto de validadores puede producir bloques. +Su duración es modificable, lo que significa que los operadores de los nodos pueden configurar la duración de una época durante la generación de génesis. + +Al final de cada época se crea un _bloque de época_ y, después de ese evento, comienza una nueva época. Para conocer más acerca de +los bloques de época, consulta la sección de [bloques de época](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Los conjuntos de validadores se actualizan al final de cada época. Los nodos consultan al conjunto de validadores del contrato inteligente de participación en subastas +durante la creación del bloque de época y guardan los datos obtenidos en el almacenamiento local. Esta consulta y ciclo de almacenamiento +se repite al final de cada época. + +Esencialmente, asegura que el contrato inteligente de participación en subastas tenga pleno control de las direcciones en el conjunto de validadores y +les deja una única responsabilidad a los nodos: consultar el contrato una vez durante una época para buscar la información +más reciente del conjunto de validadores. Eso alivia la responsabilidad de los nodos individuales de cuidar a los conjuntos de validadores. + +### Participación en subastas {#staking} + +Las direcciones pueden invertir fondos en el contrato inteligente de participación en subastas invocando el método `stake` y especificando un valor para +la suma invertida en la transacción: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +Al invertir fondos en el contrato inteligente de participación en subastas, las direcciones pueden ingresar al conjunto de validadores y así pueden participar en +el proceso de producción de bloques. + +:::info Umbral para participar en subastas + +Actualmente, el umbral mínimo para ingresar al conjunto de validadores es invertir `1 ETH`. + + +::: + +### Eliminar una participación {#unstaking} + +Las direcciones que tienen fondos invertidos solo pueden **desinvertir todos los fondos invertidos simultáneamente**. + +La eliminación de participaciones se puede invocar llamando al método `unstake`en el contrato inteligente de participación en subastas: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +Después de desinvertir sus fondos, las direcciones se eliminan del conjunto de validadores en el contrato inteligente de participación en subastas y no se +considerarán validadores durante la siguiente época. + +## Bloques de época {#epoch-blocks} + +Los **bloques de época** son un concepto introducido en la implementación de PoS de IBFT en Polygon Edge. + +En esencia, los bloques de época son bloques especiales que **no contienen transacciones** y se producen solo al **final de una época**. +Por ejemplo, si el **tamaño** de la época está establecido en bloques, los bloques de la época se considerarán como `50`bloques `50`, `100``150`etc. + +Se utilizan para representar una lógica adicional que no debería ocurrir durante la producción regular de bloques. + +Lo más importante es que son una indicación al nodo de que **debe traer la información más reciente del conjunto de validadores** +del contrato inteligente de participación en subastas. + +Tras actualizar el conjunto de validadores en el bloque de época, el conjunto de validadores (modificado o no) +se utiliza para los bloques `epochSize - 1` posteriores, hasta que se vuelva a actualizar extrayendo la información más reciente +del contrato inteligente de participación en subastas. + +Las duraciones de las épocas (en bloques) son modificables al generar el archivo génesis mediante el uso de un indicador especial `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +Por defecto, en Polygon Edge, el tamaño de una época es de `100000` bloques. + +## Predespliegue del contrato {#contract-pre-deployment} + +Polygon Edge _predespliega_ +el [contrato inteligente de participación en subastas](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol) +durante la **generación de génesis** a la dirección `0x0000000000000000000000000000000000001001`. + +Lo hace sin ejecutar la máquina virtual de Ethereum (EVM) modificando el estado de la cadena de bloques del contrato inteligente directamente, utilizando los valores de configuración +aprobados en el comando de génesis. diff --git a/archive/edge/es-edge/consensus/pos-stake-unstake.md b/archive/edge/es-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..39b9ef750c --- /dev/null +++ b/archive/edge/es-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,175 @@ +--- +id: pos-stake-unstake +title: Configura y usa la prueba de participación (PoS) +description: "Participación, eliminación de participaciones y otras instrucciones relacionadas con las participaciones en subastas." +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## Descripción general {#overview} + +Esta guía profundiza en cómo configurar una red de pruebas de participación con Polygon Edge, cómo invertir fondos para que los nodos +se conviertan en validadores y cómo eliminar la participación de fondos. + +Se **anima encarecidamente** a leer y pasar por las secciones de [configuración local](/docs/edge/get-started/set-up-ibft-locally) y +de la [configuración de la nube](/docs/edge/get-started/set-up-ibft-on-the-cloud) antes de continuar +con esta guía de PoS. Estas secciones describen los pasos necesarios para iniciar un grupo de pruebas de autoridad (PoA) con Polygon Edge. + +Actualmente, en el contrato inteligente de participación en subastas no hay límite en la cantidad de validadores que pueden invertir fondos. + +## Contrato inteligente de participación en subastas {#staking-smart-contract} + +El repositorio del contrato inteligente de participación en subastas se encuentra [aquí](https://github.com/0xPolygon/staking-contracts). + +Este posee las secuencias de comandos necesarias, los archivos de la interfaz binaria de aplicación (ABI) y, lo más importante, el contrato inteligente de participación en subastas. + +## Configuración de un grupo de nodos N {#setting-up-an-n-node-cluster} + +La configuración de redes con Polygon Edge se describe en +las secciones de [configuración local](/docs/edge/get-started/set-up-ibft-locally) y +[configuración de la nube](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +La **única diferencia** entre configurar un grupo de PoS y PoA está en la parte de la generación de génesis. + +**Al generar el archivo génesis para un grupo de PoS, se necesita un indicador adicional `--pos`**: + +```bash +polygon-edge genesis --pos ... +``` + +## Establecimiento de la duración de una época {#setting-the-length-of-an-epoch} + +Las épocas se describen en detalle en la sección de [bloques de épocas](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Para establecer la duración de una época para un grupo (en bloques) al generar el archivo génesis, se especifica un +indicador adicional `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +Este valor especificado en el archivo génesis indica que la duración de la época debería ser de `50` bloques. + +El valor por defecto del tamaño de una época (en bloques) es `100000`. + +:::info Disminución de la duración de una época + +Como se describe en la sección de [bloques de épocas](/docs/edge/consensus/pos-concepts#epoch-blocks), +los bloques de épocas se utilizan para actualizar los conjuntos de validadores para los nodos. + +Por defecto, la duración de la época en bloques (`100000`) puede requerir mucho tiempo de espera para las actualizaciones de los conjuntos de validadores. Teniendo en cuenta que +a los bloques nuevos se les agregan ~2 s, el conjunto de validadores se demoraría ~55,5 para cambiar. + +Establecer un valor inferior para la duración de la época garantiza que el conjunto de validadores se actualice con más frecuencia. + +::: + +## Uso de las secuencias de comandos de los contratos inteligentes de participación en subastas {#using-the-staking-smart-contract-scripts} + +### Prerrequisitos {#prerequisites} + +El repositorio de contratos inteligentes de participación en subastas es el proyecto Hardhat, el cual requiere NPM. + +Para inicializarlo correctamente, en el directorio principal puedes ejecutar: + +```bash +npm install +```` + +### Configuración de las secuencias de comandos de ayuda suministradas {#setting-up-the-provided-helper-scripts} + +Las secuencias de comandos para interactuar con el contrato inteligente de participación en subastas desplegado se ubican en +el [repositorio de contratos inteligentes de participación en subastas](https://github.com/0xPolygon/staking-contracts). + +Crea un archivo `.env` con los siguientes parámetros en la ubicación del repositorio de contratos inteligentes: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +Ubicaciones de los parámetros: + +* **JSONRPC_URL**: la terminal de RPC JSON para el nodo en ejecución +* **PRIVATE_KEYS**: claves privadas de la dirección del participante en subastas +* **STAKING_CONTRACT_ADDRESS**: la dirección del contrato inteligente de participación en subastas ( +por defecto `0x0000000000000000000000000000000000001001`) +* **BLS_PUBLIC_KEY**: la clave pública de BLS del participante Solo se necesita si la red se está ejecutando con BLS. + +### Inversión de fondos en subastas {#staking-funds} + +:::info Dirección de la participación en subastas + +El contrato inteligente de la participación en subastas se despliega en +la dirección `0x0000000000000000000000000000000000001001`. + +Cualquier tipo de interacción con el mecanismo de participación en subastas se hace a través del contrato inteligente de participación en subastas en la dirección especificada. + +Para conocer más sobre el contrato inteligente de participación en subastas, visita la sección del +el **[contrato inteligente de participación](/docs/edge/consensus/pos-concepts#contract-pre-deployment)** . + +::: + +Para volverse parte del conjunto de validadores, una dirección debe invertir cierta cantidad de fondos por encima de un umbral. + +Actualmente, el umbral por defecto para convertirse en parte del conjunto de validadores es `1 ETH`. + +Se puede iniciar la participación en subastas llamando al método `stake` del contrato inteligente de participación en subastas y especificar un valor `>= 1 ETH`. + +Después de que el archivo `.env`, mencionado en +la [sección anterior](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) ha sido configurado y una +cadena se ha iniciado en el modo de PoS, se puede participar en subastas con el siguiente comando en el repositorio de contratos inteligentes de participación en subastas: + +```bash +npm run stake +``` + +La secuencia de comandos `stake` de Hardhat invierte una cantidad por defecto de `1 ETH`, que se puede cambiar modificando el archivo `scripts/stake.ts`. + +Si los fondos invertidos son `>= 1 ETH`, el conjunto de validadores en el contrato inteligente de participación en subastas se actualiza y la dirección +será parte del conjunto de validadores a partir de la siguiente época. + +:::info Registro de las claves de BLS + +Si la red se está ejecutando en modo BLS, para que los nodos se conviertan en validadores, deben registrar sus claves públicas de BLS después de participar en subastas. + +Eso se puede hacer con el siguiente comando: + +```bash +npm run register-blskey +``` +::: + +### Desinversión de fondos {#unstaking-funds} + +Las direcciones que tienen participaciones en subastas solo pueden **desinvertir todos sus fondos** a la vez. + +Después de que el archivo `.env`, mencionado en +la [sección anterior](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) +ha sido configurado y se ha iniciado una cadena en modo de PoS, se pueden eliminar las participaciones con el siguiente comando en el +repositorio de contratos inteligentes de participación en subastas: + +```bash +npm run unstake +``` + +### Búsqueda de la lista de los participantes {#fetching-the-list-of-stakers} + +Todas las direcciones que invierten fondos se guardan en el contrato inteligente de participación en subastas. + +Después de que el archivo `.env`, mencionado en +la [sección anterior](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) +ha sido configurado y se ha iniciado una cadena en el modo de PoS, se puede traer la lista de validadores con +el siguiente comando en el repositorio de contratos inteligentes de participación en subastas: + +```bash +npm run info +``` diff --git a/archive/edge/es-edge/faq/Contracts.md b/archive/edge/es-edge/faq/Contracts.md new file mode 100644 index 0000000000..214531b03a --- /dev/null +++ b/archive/edge/es-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: Preguntas frecuentes sobre contratos inteligentes +description: "Preguntas frecuentes sobre contratos inteligentes de Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## ¿Polygon Edge admite contratos inteligentes? {#does-polygon-edge-support-smart-contracts} + +Sí. Las redes de Polygon Edge son cadenas de bloques compatibles con Ethereum, de modo que los contratos inteligentes que se pueden desplegar en Ethereum también se pueden desplegar en las cadenas de Polygon Edge. + +## ¿Se puede actualizar la lógica de las participaciones en subastas para pruebas de participación (PoS) después del despliegue? {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +Por ahora, después de haber iniciado la red de PoS, no se puede cambiar la lógica del contrato de participación en subastas, ya que es parte del archivo génesis. Así que no se puede, por ejemplo, cambiar el número mínimo o máximo de validadores. Lo que sí se puede hacer es participar o eliminar una participación para añadir o eliminar validadores. + + + diff --git a/archive/edge/es-edge/faq/Gas.md b/archive/edge/es-edge/faq/Gas.md new file mode 100644 index 0000000000..ecb784a6c7 --- /dev/null +++ b/archive/edge/es-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: Preguntas frecuentes sobre el gas +description: "Preguntas frecuentes sobre el gas para Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## ¿Cómo hacer cumplir un precio de gas mínimo? {#how-to-enforce-a-minimum-gas-price} +Puedes utilizar el indicador `--price-limit`, proporcionado en el comando del servidor. Esto hará que tu nodo solo acepte transacciones con el mismo o más gas que el límite de precio que hayas establecido. Para asegurarte de que esto se cumpla en toda la red de trabajo, debes asegurarte de que todos los nodos tengan el mismo límite de precio. + + +## ¿Puedes realizar transacciones con tarifas de cero gas? {#can-you-have-transactions-with-0-gas-fees} +Sí, puedes. Por defecto, el límite de precio que los nodos hacen cumplir es `0`, lo que significa que los nodos aceptarán transacciones que tengan un precio del gas establecido en `0`. + +## ¿Cómo establecer el suministro total de tokens de gas (nativo)? {#how-to-set-the-gas-native-token-total-supply} + +Puedes establecer un saldo preminado en las cuentas (direcciones) mediante el uso de `--premine flag`. Nota que esta es una configuración del archivo génesis y no se puede cambiar más tarde. + +Ejemplo de cómo utilizar `--premine flag`: + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +Esto establece un saldo preminado de 1000 ETH a 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862 (the amount from the argument is in wei). + +La cantidad preminada del token de gas será el suministro total. Ninguna otra cantidad de la moneda nativa (token de gas) se podrá acuñar después. + +## ¿Edge soporta ERC-20 como token de gas? {#does-edge-support-erc-20-as-a-gas-token} + +Edge no soporta el token ERC-20 como token de gas. Solo la moneda nativa de Edge es soportada para gas. + +## ¿Cómo aumentar el límite de gas? {#how-to-increase-the-gas-limit} + +Existen dos opciones para aumentar el límite de gas en Polygon Edge: +1. Limpiar la cadena y aumentar `block-gas-limit`hasta el máximo valor de en el archivo génesis +2. Utiliza la `--block-gas-target`bandera con un alto valor para aumentar el límite de gas de todos los nodos. Esto requiere de reinicio de nodos. [Aquí](/docs/edge/architecture/modules/txpool/#block-gas-target) \ No newline at end of file diff --git a/archive/edge/es-edge/faq/Tokens.md b/archive/edge/es-edge/faq/Tokens.md new file mode 100644 index 0000000000..3f4610c1bd --- /dev/null +++ b/archive/edge/es-edge/faq/Tokens.md @@ -0,0 +1,23 @@ +--- +id: tokens +title: Preguntas frecuentes sobre los tokens +description: "Preguntas frecuentes sobre los tokens de Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## ¿Polygon Edge es compatible con EIP-1559? {#does-polygon-edge-support-eip-1559} +Por el momento, Polygon Edge no es compatible con EIP-1559. + +## ¿Cómo configurar el símbolo de la moneda (token)? {#how-to-set-the-currency-token-symbol} + +El símbolo del token es solo un elemento de la interfaz de usuario, de modo que no se puede configurar ni escribir directamente en ningún lugar de la red. +Sin embargo, puedes cambiarlo cuando añades la red a una billetera, como Metamask, por ejemplo. + +## ¿Qué sucede con las transacciones cuando una cadena se detiene? {#what-happens-to-transactions-when-a-chain-halts} + +Todas las transacciones que no se han procesado se encuentran dentro de la cola (enqueued o promovido). Si la cadena se detiene (toda la producción de bloques se detiene), estas transacciones nunca entrarán en bloques.
Este no es solo el caso cuando la cadena se detiene. Si los nodos se detienen o se reinician, todas las transacciones que no se han ejecutado y todavía están en TxPool, se eliminarán en silencio.
Lo mismo sucederá con las transacciones cuando se introduzca un cambio de ruptura, ya que es necesario para que los nodos se reinicien. diff --git a/archive/edge/es-edge/faq/Validators.md b/archive/edge/es-edge/faq/Validators.md new file mode 100644 index 0000000000..0baf2d919f --- /dev/null +++ b/archive/edge/es-edge/faq/Validators.md @@ -0,0 +1,85 @@ +--- +id: validators +title: Preguntas frecuentes sobre los validadores +description: "Preguntas frecuentes sobre los validadores de Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## ¿Cómo agregar o quitar un validador? {#how-to-add-remove-a-validator} + +### Prueba de autoridad (PoA) {#poa} +La adición o eliminación de validadores se realiza mediante votación. [Aquí](/docs/edge/consensus/poa) puedes encontrar una guía completa al respecto. + +### PoS {#pos} +[Aqui](/docs/edge/consensus/pos-stake-unstake)puedes encontrar un guía sobre cómo invertir fondos, de modo que un nodo pueda convertirse en validador y sobre cómo desinvertir (eliminar el validador). + +Ten en cuenta que: +- Puedes utilizar el indicador de génesis `--max-validator-count` para establecer un número máximo de participantes que pueden unirse al conjunto de validadores. +- Puedes utilizar el indicador de génesis `--min-validator-count ` para establecer el número mínimo de participantes necesarios para unirse al conjunto de validadores (`1`por defecto). +- Cuando se ha alcanzado el número máximo de validadores, no puedes añadir otro validador hasta que se elimine uno existente del conjunto (no importa si la cantidad invertida del nuevo es mayor). Si se elimina un validador, el número de validadores restantes no puede ser inferior a `--min-validator-count`. +- Existe un umbral por defecto de la unidad `1` de la moneda de la red(gas) nativa para convertirse en validador. + + + +## ¿Cuánto espacio en disco se recomienda para un validador? {#how-much-disk-space-is-recommended-for-a-validator} + +Recomendamos comenzar con 100 G de forma conservadora, y asegurarte de que es posible escalar el disco después. + + +## ¿Existe límite en el número de validadores? {#is-there-a-limit-to-the-number-of-validators} + +Si hablamos de limitaciones técnicas, Polygon Edge no tiene un límite explicito del número de nodos que puedes tener en una red. Puedes establecer límites de conexión (número de conexiones de entrada o salida) por cada nodo. + +Si hablamos de las limitaciones prácticas, un grupo de 100 nodos tendrá menos rendimiento que un grupo de 10 nodos. Al aumentar el número de nodos en el grupo, se incrementa la complejidad de la comunicación y la sobrecarga de la red en general. Todo depende del tipo de red que utilices y del tipo de topología de red que tengas. + +## ¿Cómo cambiar de Prueba de autoridad (PoA) a Prueba de participación (PoS) {#how-to-switch-from-poa-to-pos} + +Prueba de autoridad (PoA) es el mecanismo de consenso por defecto. En un grupo nuevo, para cambiar a Prueba de participación (PoS) tendrás que añadir la indicación `--pos`al generar el archivo genesis. Si tienes un grupo en ejecución, [aquí](/docs/edge/consensus/migration-to-pos) puedes encontrar cómo hacer el cambio. Cualquier información que necesites sobre nuestros mecanismos de consenso y configuración se puede encontrar en nuestra [sección de consenso](/docs/edge/consensus/poa). + +## ¿Cómo puedo actualizar mis nodos cuando hay un cambio súbito? {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +[Aquí](/docs/edge/validator-hosting#update) puedes encontrar una guía detallada sobre cómo hacer ese procedimiento. + +## ¿Se puede configurar la cantidad mínima de participación para PoS Edge? {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +La cantidad mínima de participación por defecto es `1 ETH`y no es configurable. + +## ¿Por qué los comandos de RPC JSON `eth_getBlockByNumber`y `eth_getBlockByHash`no arrojan la dirección del minero? {#not-return-the-miner-s-address} + +El consenso utilizado actualmente en Polygon Edge es la IBFT 2.0, que, a su vez, se basa en el mecanismo de votación explicado en la PoA de Clique: [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225). + +Al observar el EIP-225 (PoA en Clique), esta es la parte relevante que explica para qué se utiliza el `miner`(también llamado `beneficiary`): + +
+Reconvertimos los campos del encabezado ethash de la siguiente manera: +
    +
  • beneficiario o minero: dirección con la que se propone modificar la lista de firmantes autorizados.
  • +
      +
    • Normalmente debe rellenarse con ceros y se modifica solo mientras se vota.
    • +
    • No obstante, se permiten los valores arbitrarios (incluso los que no tienen sentido, como la expulsión de los no firmantes) para evitar una complejidad adicional en las implementaciones relacionadas con la dinámica de la votación.
    • +
    • Debe rellenarse con ceros en los bloques de punto de control (Ej. transición de época).
    • +
    + +
+ +
+ +Así, el campo `miner`se utiliza para proponer un voto para determinada dirección, no para mostrar al proponente del bloque. + +La información sobre el proponente del bloque puede encontrarse recuperando la clave pública del campo Seal (Sello) del campo de datos adicionales de Estambul codificado en RLP en los encabezados del bloque. + +## ¿Qué partes y valores de Genesis se pueden modificar de forma segura? {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +Por favor, asegúrate de crear una copia manual del archivo genesis.json existente antes de intentar editarlo. Además, toda la cadena debe ser detenida antes de editar el archivo genesis.json. Una vez que el archivo génesis se modifique, la nueva versión de este tiene que distribuir en todos los nodos no validadores y valdiator + +::: + +**Solo la sección de nodos de inicio del archivo génesis se puede modificar de forma segura**, donde puedes añadir o eliminar nodos de inicio de la lista. \ No newline at end of file diff --git a/archive/edge/es-edge/get-started/cli-commands.md b/archive/edge/es-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..52055dbc3c --- /dev/null +++ b/archive/edge/es-edge/get-started/cli-commands.md @@ -0,0 +1,2220 @@ +--- +id: cli-commands +title: Comandos de la CLI (Interfaz de línea de comandos) +description: "Lista de comandos de la interfaz de línea de comandos (CLI) y opciones de comando para Polygon Edge." +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +Esta sección detalla los comandos actuales y las opciones de comando en Polygon Edge, al igual que cómo se utilizan. + +:::tip Soporte de salida de JSON + +La opción `--json` se apoya en algunos comandos. Esta indicación le indica al comando que imprima la salida en formato JSON. + +::: + +## Comandos de inicio {#startup-commands} + +| **Comando** | **Descripción** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| server | El comando por defecto que inicia el cliente de la cadena de bloques arrancando todos los módulos juntos | +| genesis | Genera un archivo de *genesis.json*, que se utiliza para establecer un estado de cadena predefinido antes de iniciar el cliente. La estructura del archivo génesis se describe más adelante. | +| | Predespliega un contrato inteligente para redes nuevas | + +### server flags {#server-flags} + + +| **Todos los indicadores del servidor** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [prometheus](/docs/edge/get-started/cli-commands#prometheus) | [block-gas-target](/docs/edge/get-started/cli-commands#block-gas-target) | +| [max-peers](/docs/edge/get-started/cli-commands#max-peers) | [max-inbound-peers](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [max-outbound-peers](/docs/edge/get-started/cli-commands#max-outbound-peers) | [max-enqueued](/docs/edge/get-started/cli-commands#max-enqueued) | +| [log-level](/docs/edge/get-started/cli-commands#log-level) | [log-to](/docs/edge/get-started/cli-commands#log-to) | +| [chain](/docs/edge/get-started/cli-commands#chain) | [join](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [límite de precios](/docs/edge/get-started/cli-commands#price-limit) | [Ranuras máximas](/docs/edge/get-started/cli-commands#max-slots) | +| [Configuración](/docs/edge/get-started/cli-commands#config) | [secrets-config](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-interval](/docs/edge/get-started/cli-commands#dev-interval) | +| [no-discover](/docs/edge/get-started/cli-commands#no-discover) | [restore](/docs/edge/get-started/cli-commands#restore) | +| [block-time](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +Se utiliza para especificar el directorio de datos utilizado para almacenar los datos de los clientes de Polygon Edge. Por defecto: `./test-chain`. + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +Establece la dirección y el puerto para el servicio de RPC JSON `address:port`. +Si solo se define el puerto `:10001`, se unirá a todas las interfaces `0.0.0.0:10001`. +Si se omite, el servicio se unirá al `address:port` por defecto. +Dirección por defecto: `0.0.0.0:8545`. + +--- + +####

json-rpc-block-range-limit + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +Establece el rango máximo de bloques que se deben considerar al ejecutar las solicitudes de rpc json que incluyen valores fromBlock/toBlock (por ejemplo, eth_getLogs). Por defecto:`1000` + +--- + +####

json-rpc-batch-request-limit + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +Establece la longitud máxima que se debe considerar al manejar las solicitudes de tandas de rpc json. Por defecto: `20`. + +--- + +####

grpc + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +Establece la dirección y el puerto para el servicio de gRPC `address:port`. Dirección por defecto: `127.0.0.1:9632`. + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +Establece la dirección y el puerto para el servicio `address:port` de libp2p. Dirección por defecto: `127.0.0.1:1478`. + +--- + +####

prometheus + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +Establece la dirección y el puerto para el servidor `address:port` de prometheus. +Si solo se define el puerto `:5001`, el servicio se unirá a todas las interfaces `0.0.0.0:5001`. +Si se omite, el servicio no se iniciará. + +--- + +####

block-gas-target + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +Establece el límite de gas de los bloques de destino para la cadena. Por defecto (no se hace cumplir): `0`. + +Puedes encontrar una explicación más detallada sobre el gas de los bloques de destino en la [sección TxPool](/docs/edge/architecture/modules/txpool#block-gas-target). + +--- + +####

max-peers + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +Establece el número máximo de pares del cliente. Por defecto: `40`. + +El límite de pares se debería especificar con la indicación `max-peers` o `max-inbound/outbound-peers`. + +--- + +####

max-inbound-peers + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +Establece el número de pares entrantes máximo del cliente. Si se establece `max-peers`, el límite máximo de pares entrantes se calcula con las siguientes fórmulas. + +`max-inbound-peer = InboundRatio * max-peers`, donde `InboundRatio` es `0.8`. + +--- + +####

max-outbound-peers + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +Establece el número de pares salientes máximo del cliente. Si se establece `max-peers`, el número de pares salientes máximo se calcula con las siguientes fórmulas. + +`max-outbound-peer = OutboundRatio * max-peers`, donde `OutboundRatio` es `0.2`. + +--- + +####

max-enqueued + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +Establece el número máximo de transacciones en cola por cuenta. Por defecto:`128` + +--- + +####

log-level + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +Establece el nivel de registro para la salida de la consola. Por defecto: `INFO`. + +--- + +####

log-to + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +Define el nombre del archivo de registro que mantendrá todas las salidas del comando del servidor. +Por defecto, todos los registros del servidor saldrán a la consola (stdout), +pero si se establece la indicación, no habrá salida a la consola cuando se ejecute el comando del servidor. + +--- + +####

chain + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +Especifica el archivo génesis utilizado para iniciar la cadena. Por defecto: `./genesis.json`. + +--- + +####

join + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Especifica la dirección del par al que se debe unir. + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +Establece la dirección IP externa sin el puerto, ya que puede ser vista por pares. + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +Establece la dirección DNS del anfitrión. Se puede utilizar para publicitar un DNS externo. Soporta `dns`,`dns4`,`dns6`. + +--- + +####

límite de precios + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +Establece un límite mínimo de precio de gas para hacer cumplir su aceptación en el grupo. Por defecto: `1`. + +--- + +####

Ranuras máximas + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +Establece un máximo de ranuras en el grupo. Por defecto: `4096`. + +--- + +####

Configuración + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +Especifica la ruta hacia la configuración de CLI. Soporta `.json`. + +--- + +####

secrets-config + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +Establece la ruta hacia el archivo de configuración de Secrets Manager (Administrador de secretos). Se utiliza para Hashicorp Vault, SSM de AWS y Secrets Manager de GCP. Si se omite, se utiliza el administrador Secrets Manager FS local. + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +Pone al cliente en modo desarrollador. Por `false`defecto: En el modo , el descubrimiento de los compañeros se desactiva de forma predeterminada. + +--- + +####

dev-interval + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +Establece el intervalo de notificaciones de desarrollo del cliente en segundos. Por defecto: `0`. + +--- + +####

no-discover + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +Evita que el cliente descubra otros pares. Por defecto: `false`. + +--- + +####

restore + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +Restaura bloques desde el archivo especificado. + +--- + +####

block-time + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +Establece el tiempo de producción de bloques en segundos. Por defecto: `2` + +--- + +####

access-control-allow-origins + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +Establece los dominios autorizados para poder compartir respuestas de solicitudes de RPC JSON. +Añade múltiples indicaciones `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"` para autorizar múltiples dominios . +Si se omite, el encabezado Access-Control-Allow-Origins se establecerá en `*` y todos los dominios serán autorizados. + +--- + +### genesis flags {#genesis-flags} +| **Todas las banderas génesis** | +|---------------------------------------|---------------------------------------------| +| [dir](/docs/edge/get-started/cli-commands#dir) | [name](/docs/edge/get-started/cli-commands#name) | +| [pos](/docs/edge/get-started/cli-commands#pos) | [epoch-size](/docs/edge/get-started/cli-commands#epoch-size) | +| [premine](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [ibft-validator-type](/docs/edge/get-started/cli-commands#ibft-validator-type) | [ibft-validators-prefix-path](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [ibft-validator](/docs/edge/get-started/cli-commands#ibft-validator) | [block-gas-limit](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [consensus](/docs/edge/get-started/cli-commands#consensus) | [bootnode](/docs/edge/get-started/cli-commands#bootnode) | +| [max-validator-count](/docs/edge/get-started/cli-commands#max-validator-count) | [min-validator-count](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

dir + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +Establece el directorio para los datos de génesis de Polygon Edge. Por defecto: `./genesis.json`. + +--- + +####

Nombre + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +Establece el nombre para la cadena. Por defecto: `polygon-edge`. + +--- + +####

pos + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +Establece la indicación de que el cliente debería usar la prueba de participación IBFT. +Se pone por defecto en prueba de autoridad si no se suministra la indicación o `false`. + +--- + +####

epoch-size + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +Establece el tamaño de la época para la cadena. Por defecto, `100000`. + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +Establece las cuentas y los saldos preminados en formato `address:amount`. +La cantidad puede estar en decimales o en hexadecimales. +Saldo preminado por defecto: `0xD3C21BCECCEDA1000000`(1 millón de tokens de moneda nativa). + +--- + +####

chainid + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +Establece la ID de la cadena. Por defecto: `100`. + +--- + +####

ibft-validator-type + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +Especifica el modo de validación de los encabezados de los bloques. Valores posibles: `[ecdsa, bls]`. Por defecto: `bls`. + +--- + +####

ibft-validators-prefix-path + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +Ruta de prefijo para el directorio de la carpeta de validadores. Debe estar presente si se omite la indicación `ibft-validator`. + +--- + +####

ibft-validator + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Establece las direcciones pasadas como validadores IBFT. Debe estar presente si se omite la indicación `ibft-validators-prefix-path`. +1. Si la red se está ejecutando con ECDSA, el formato es `--ibft-validator [ADDRESS]`. +2. Si la red se está ejecutando con BLS, el formato es `--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]`. + +--- + +####

block-gas-limit + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +Se refiere a la cantidad de gas que utilizan todas las operaciones en un bloque. Por defecto: `5242880`. + +--- + +####

consensus + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +Establece el protocolo de consenso. Por defecto: `pow`. + +--- + +####

bootnode + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +URL multidirección para el arranque del descubrimiendo p2p. Esta indicación se puede usar muchas veces. +En vez de una dirección IP, se puede suministrar la dirección DNS del nodo de arranque. + +--- + +####

max-validator-count + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +El número máximo de participantes en subastas que se pueden unirse al conjunto de validadores en un consenso de PoS. +Este número no puede superar el valor de MAX_SAFE_INTEGER (2^53 - 2). + +--- + +####

min-validator-count + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +El número mínimo de participantes necesario para unirse al conjunto de validadores en un consenso de PoS. +Este número no puede superar el valor de max-validator-count. +Por defecto se establece en 1. + +--- + +### banderas de predespliegue de génesis {#genesis-predeploy-flags} + +

ruta de los artefactos

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +Establece la ruta hacia los artefactos contractuales que contiene `abi`el , `bytecode`y .`deployedBytecode` + +--- + +

chain

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +Establece la ruta al `genesis.json`archivo que se debe actualizar . Por defecto, `./genesis.json`. + +--- + +

constructor-args

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +Establece los argumentos de constructor de contratos inteligentes, si los hay. Para una guía detallada sobre cómo deberían ser estos argumentos, consulta [el artículo previo a la implementación](/docs/edge/additional-features/predeployment). + +--- + +

predespliegue

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +Establece la dirección a la que se desea desplegar en . Por defecto, `0x0000000000000000000000000000000000001100`. + +--- + + +## Comandos del operador {#operator-commands} + +### Comandos del par {#peer-commands} + +| **Comando** | **Descripción** | +|------------------------|-------------------------------------------------------------------------------------| +| peers add | Añade un nuevo par con su dirección de libp2p. | +| peers list | Enumera todos los pares con los que el cliente está conectado a través de libp2p. | +| peers status | Arroja el estado de un par específico de la lista de pares mediante el uso de la dirección de libp2p. | + +

peers add flags

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Dirección de libp2p del par en formato multidirección. + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +Dirección de la API de gRPC. Por defecto: `127.0.0.1:9632`. + +

peers list flags

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +Dirección de la API de gRPC. Por defecto: `127.0.0.1:9632`. + +

peers status flags

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +ID del nodo de libp2p de un par específico dentro de la red p2p. + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +Dirección de la API de gRPC. Por defecto: `127.0.0.1:9632`. + +### Comandos IBFT {#ibft-commands} + +| **Comando** | **Descripción** | +|------------------------|-------------------------------------------------------------------------------------| +| ibft snapshot | Arroja la foto instantánea de IBFT. | +| ibft candidates | Consulta el conjunto actual de candidatos propuestos, así como los candidatos que aún no se han incluido. | +| ibft propose | Propone a un nuevo candidato para añadir o eliminar del conjunto de validadores. | +| ibft status | Arroja el estado general del cliente IBFT. | +| ibft switch | Agrega configuraciones de bifurcación en el archivo genesis.json para cambiar el tipo de IBFT. | +| ibft quorum | Especifica el número de bloque después del cual se utilizará el método de tamaño de quorum óptimo para llegar al consenso. | + + +

ibft snapshot flags

+ +

number

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +Es la altura del bloque (número) para la foto instantánea. + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +Dirección de la API de gRPC. Por defecto: `127.0.0.1:9632`. + +

ibft candidates flags

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Dirección de la API de gRPC. Por defecto: `127.0.0.1:9632`. + +

ibft propose flags

+ +

vote

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +Propone un cambio en el conjunto de validadores. Valores posibles: `[auth, drop]`. + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +Dirección de la cuenta por la cual se votará + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +Clave pública BLS de la cuenta por la que se votará, necesaria solo en modo BLS. + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Dirección de la API de gRPC. Por defecto: `127.0.0.1:9632`. + +

ibft status flags

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +Dirección de la API de gRPC. Por defecto: `127.0.0.1:9632`. + +

ibft switch flags

+ +

chain

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +Especifica el archivo génesis que se va a actualizar. Por defecto: `./genesis.json`. + +--- + +

Tipo

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +Especifica el tipo de IBFT que se va a cambiar. Valores posibles: `[PoA, PoS]`. + +--- + +

despliegue

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +Especifica la altura del despliegue del contrato. Solo está disponible con PoS. + +--- + +

from

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +Especifica el modo de validación de los encabezados de los bloques. Valores posibles: `[ecdsa, bls]`. Por defecto: `bls`. + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +Ruta prefijada para los directorios de los nuevos validadores. Debe estar presente si se omite la indicación `ibft-validator`. Solo está disponible cuando el modo IBFT es PoA (se omite la indicación `--pos`). + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Conjuntos aprobados en direcciones como validadores IBFT utilizados después de la bifurcación. Debe estar presente si se omite la indicación `ibft-validators-prefix-path`. Solo están disponibles en modo de PoA. +1. Si la red se está ejecutando con ECDSA, el formato es `--ibft-validator [ADDRESS]`. +2. Si la red se está ejecutando con BLS, el formato es `--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]`. + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +El número máximo de participantes en subastas que se pueden unirse al conjunto de validadores en un consenso de PoS. +Este número no puede superar el valor de MAX_SAFE_INTEGER (2^53 - 2). + +--- + +

min-validator-count

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +El número mínimo de participantes necesario para unirse al conjunto de validadores en un consenso de PoS. +Este número no puede superar el valor de max-validator-count. +Por defecto se establece en 1. + +Especifica la altura inicial de la bifurcación. + +--- + +

ibft quorum flags

+ +

from

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +Es la altura para cambiar el cálculo del quorum a QuorumOptimal, que utiliza la fórmula `(2/3 * N)`, donde `N` es el número de nodos validadores. Fíjate que esto es para la compatibilidad con versiones anteriores, es decir, solo para cadenas que utilizaron un cálculo heredado de quorum hasta cierta altura de bloque. + +--- + +

chain

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +Especifica el archivo génesis que se va a actualizar. Por defecto: `./genesis.json`. + +### Comandos del grupo de transacciones {#transaction-pool-commands} + +| **Comando** | **Descripción** | +|------------------------|--------------------------------------------------------------------------------------| +| txpool status | Arroja el número de transacciones en el grupo. | +| txpool subscribe | Suscripciones para eventos en el grupo de transacciones. | + +

txpool status flags

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +Dirección de la API de gRPC. Por defecto: `127.0.0.1:9632`. + +

txpool subscribe flags

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +Dirección de la API de gRPC. Por defecto: `127.0.0.1:9632`. + +--- + +

promoted

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +Suscribe a eventos de transacción promovidos en el grupo de transacciones. + +--- + +

dropped

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +Suscribe a eventos de transacción dejados en el grupo de transacciones. + +--- + +

demoted

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +Suscribe a eventos de transacción degradados en el grupo de transacciones. + +--- + +

added

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +Suscribe a eventos de transacción agregados al grupo de transacciones. + +--- + +

enqueued

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +Suscribe a eventos de transacción que estén en las colas de la cuenta. + +--- + +### Comandos de la cadena de bloques {#blockchain-commands} + +| **Comando** | **Descripción** | +|------------------------|-------------------------------------------------------------------------------------| +| status | Arroja el estado del cliente. La respuesta detallada se puede encontrar más adelante. | +| monitor | Suscribe al flujo de eventos de la cadena de bloques. La respuesta detallada se puede encontrar más adelante. | +| version | Muestra la versión actual del cliente. | + +

status flags

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +Dirección de la API de gRPC. Por defecto: `127.0.0.1:9632`. + +

monitor flags

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +Dirección de la API de gRPC. Por defecto: `127.0.0.1:9632`. + +--- +

comando de la versión

+ + + + + + version + + + + +Muestra la versión de liberación, rama git, comite hash y construir tiempo. + +## Comandos de Secrets {#secrets-commands} + +| **Comando** | **Descripción** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| secrets init | Inicializa las claves privadas del administrador de secretos correspondiente. | +| secrets generate | Genera un archivo de configuración del administrador de secretos que puede ser analizado por Polygon Edge. | +| Salida de secretos | Imprime la dirección de la clave pública de BLS, la dirección de la clave pública de validador y el id del nodo para referencia | + +### secrets init flags {#secrets-init-flags} + +

Configuración

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +Establece la ruta hacia el archivo de configuración de Secrets Manager (Administrador de secretos). Hashicorp Vault lo usa. Si se omite, se utiliza el administrador Secrets Manager FS local. + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +Establece el directorio de los datos de Polygon Edge si se utiliza FS local. + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +Establece la indicación de si generar una clave de ECDSA. Por defecto: `true`. + +--- + +

network

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +Establece la indicación de si generar una clave de la red Libp2p. Por defecto: `true`. + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +Establece la indicación de si generar una clave de BLS. Por defecto: `true`. + +### secrets generate flags {#secrets-generate-flags} + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +Establece el directorio del archivo de configuración por defecto de Secrets Manager (Administrador de secretos): `./secretsManagerConfig.json` + +--- + +

Tipo

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +Especifica el tipo de Secrets Manager (Administrador de secretos) [`hashicorp-vault`]. Por defecto: `hashicorp-vault` + +--- + +

token

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +Especifica el token de acceso para el servicio. + +--- + +

server-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +Especifica el URL del servidor para el servicio. + +--- + +

Nombre

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +Especifica el nombre del nodo para el mantenimiento de registros en servicio. Por defecto: `polygon-edge-node` + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Especifica el espacio del nombre utilizado para el administrador de secretos de Hashicorp Vault. Por defecto: `admin` + +### secretos de las banderas de salida {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +Establece la bandera que indica si solo se debe transmitir la clave pública . Por defecto: `true` + +--- + +

Configuración

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +Establece la ruta hacia el archivo de configuración de Secrets Manager (Administrador de secretos). Si se omite, se utiliza el administrador Secrets Manager FS local. + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +Establece el directorio de los datos de Polygon Edge si se utiliza FS local. + +--- + +

nodo

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +Establece la bandera que indica si solo se debe transmitir la ID del nodo de red. Por defecto: `true` + +--- + +

Validador

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +Establece la bandera que indica si solo se debe producir la dirección del validador. Por defecto: `true` + +--- + +## Respuestas {#responses} + +### Respuesta del estado {#status-response} + +El objeto de respuesta se define mediante el uso de búferes de protocolo. +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### Respuesta del monitor {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## Utilidades {#utilities} + +### whitelist commands {#whitelist-commands} + +| **Comando** | **Descripción** | +|------------------------|-------------------------------------------------------------------------------------| +| whitelist show | Muestra información de la lista blanca | +| whitelist deployment | Actualiza la lista blanca del despliegue del contrato inteligente | + +

whitelist show

+ + + + + whitelist show + + + + +Muestra información de la lista blanca. + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +Especifica el archivo génesis que se va a actualizar. Por defecto: `./genesis.json`. + +--- + +

whitelist deployment

+ +

chain

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +Especifica el archivo génesis que se va a actualizar. Por defecto: `./genesis.json`. + +--- + +

add

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Añade una nueva dirección a la lista blanca de despliegue de contratos. Solo las direcciones de la lista blanca de despliegue de contratos pueden desplegar contratos. Si está vacía, cualquier dirección puede ejecutar el despliegue del contrato. + +--- + +

remove

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Elimina una dirección de la lista blanca de despliegue de contratos. Solo las direcciones de la lista blanca de despliegue de contratos pueden desplegar contratos. Si está vacía, cualquier dirección puede ejecutar el despliegue del contrato. + +--- + +### backup flags {#backup-flags} + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +Dirección de la API de gRPC. Por defecto: `127.0.0.1:9632`. + +--- + +

out

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +Ruta del archivo que se va a guardar + +--- + +

from

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +Altura inicial de los bloques en el archivo Por defecto: 0. + +--- + +

to

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +Altura final de los bloques en el archivo + +--- + +## Plantilla de génesis {#genesis-template} +El archivo de génesis se debe utilizar para establecer el estado inicial de la cadena de bloques (por ejemplo, si algunas cuentas deberían tener un saldo inicial). + +Se genera el siguiente archivo *./genesis.json*: +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### Directorio de datos {#data-directory} + +Al ejecutar la indicación *data-dir*, se genera una carpeta de **cadena de prueba**. +La estructura de la carpeta consta de las siguientes subcarpetas: +* **blockchain**: guarda el LevelDB para los objetos de la cadena de bloques +* **trie**: guarda el LevelDB para los árboles de Merkle +* **keystore**: guarda las claves privadas para el cliente Esto incluye la clave privada de libp2p y la clave privada de sellado y validación. +* **consensus**: guarda cualquier información del consenso que el cliente pueda necesitar mientras trabaja + +## Recursos {#resources} +* **[Búferes de protocolo](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/es-edge/get-started/installation.md b/archive/edge/es-edge/get-started/installation.md new file mode 100644 index 0000000000..224d9b2309 --- /dev/null +++ b/archive/edge/es-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: Instalación +description: "Cómo instalar Polygon Edge" +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +Por favor, consulta el método de instalación más adecuado para ti. + +Nuestra recomendación es usar las versiones previamente construidas y verificar las sumas de control suministradas. + +## Versiones construidas previamente {#pre-built-releases} + +Por favor, consulta la página de las [publicaciones de GitHub](https://github.com/0xPolygon/polygon-edge/releases) para obtener una lista de las publicaciones. + +Polygon Edge se presenta con binarios AMD64/ARM64 compilados de forma cruzada para Darwin y Linux. + +--- + +## Imagen de Docker {#docker-image} + +Las imágenes oficiales de Docker se alojan en el [registro hub.docker.com](https://hub.docker.com/r/0xpolygon/polygon-edge). + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## Construcción desde la fuente {#building-from-source} + +Antes de usarlo, `go install`asegúrate de que tienes Go `>=1.18`instalado y configurado correctamente. + +La ramificación estable es la rama de la última versión. + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## Uso de `go install` + +Antes de usarlo, `go install`asegúrate de que tienes Go `>=1.17`instalado y configurado correctamente. + +`go install github.com/0xPolygon/polygon-edge@release/` + +El binario estará disponible en tu variable de `GOBIN`entorno, e incluirá los cambios de la última versión. Puedes salir de [las versiones de GitHub](https://github.com/0xPolygon/polygon-edge/releases) para averiguar cuál es la última. diff --git a/archive/edge/es-edge/get-started/set-up-ibft-locally.md b/archive/edge/es-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..6b0948bcf2 --- /dev/null +++ b/archive/edge/es-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,429 @@ +--- +id: set-up-ibft-locally +title: Configuración local +description: "Guía de configuración local paso a paso" +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution Esta guía es únicamente para hacer pruebas. + +La siguiente guía te indicará cómo configurar una red de Polygon Edge en tu máquina local para propósitos de pruebas +y desarrollo. + +El procedimiento difiere mucho de la forma en que hay que configurar la red de Polygon Edge para un escenario de uso real +un proveedor de **[la](/docs/edge/get-started/set-up-ibft-on-the-cloud)** nube: + +::: + + +## Requisitos {#requirements} + +Consulta [Instalación](/docs/edge/get-started/installation) para instalar Polygon Edge. + +## Descripción general {#overview} + +![Configuración local](/img/edge/ibft-setup/local.svg) + +En esta guía, nuestro objetivo es crear una `polygon-edge`red de cadenas de bloques que funcione con[ el protocolo de consenso IBFT](https://github.com/ethereum/EIPs/issues/650). +La red de la cadena de bloques constará de cuatro nodos, de los cuales todos son nodos validadores y, por eso, son elegibles tanto para proponer bloques como para validar bloques que vinieron de otros proponentes. +Los cuatro nodos se ejecutarán en la misma máquina, ya que la idea de esta guía es darte un grupo IBFT completamente funcional en la menor cantidad de tiempo. + +Para lograrlo, te guiaremos por cuatro sencillos pasos: + +1. Inicializar los directorios de datos generará las claves validadores para cada uno de los cuatro nodos e inicializará los directorios de datos vacíos de la cadena de bloques. Las claves validadoras son importantes, ya que debemos arrancar el bloque génesis con el conjunto inicial de validadores que utilizan estas claves. +2. Preparar la cadena de conexión para el nodo de arranque contendrá la información vital para todos los nodos que ejecutemos, en cuanto a cual nodo conectarse la primera vez. +3. Generar el archivo `genesis.json` requerirá, como entrada, las claves validadoras generadas en el **paso 1**, utilizadas para configurar los validadores iniciales de la red en el bloque génesis, y la cadena de conexión del nodo de arranque del **paso 2**. +4. El objetivo de esta guía es ejecutar todos los nodos y será el último paso. Les daremos a los nodos la indicación de qué directorio de datos utilizar y dónde encontrar el `genesis.json`, que arranca el estado de red inicial. + +Como los cuatro nodos se ejecutarán en el anfirtrión local, durante el proceso de configuración se espera que todos los directorios de datos +para cada uno de los nodos se encuentren en el mismo directorio primario. + +:::info Número de validadores + +No hay un número mínimo de nodos en un grupo, lo que significa que puede haber grupos con solo un nodo validador. +Ten en cuenta que con un grupo de _un solo_ nodo, no hay **tolerancia a colapsos** ni **garantías de BFT**. + +Se recomiendan mínimo cuatro nodos para lograr la garantía de tolerancia a fallas bizantinas (BFT), ya que, en un grupo de cuatro nodos, la falla de +la falla de un nodo, si los tres nodos restantes funcionan normalmente. + +::: + +## Paso 1: inicia las carpetas de datos para IBFT y genera las claves validadoras {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +Para empezar a ejecutar con IBFT, debes inicializar las carpetas de datos, +una para cada nodo: + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +Cada uno de estos comandos imprimirá la clave validadora, la clave pública BLS y la [ID del nodo](https://docs.libp2p.io/concepts/peer-id/). Para el siguiente paso, necesitarás la ID del primer nodo. + +### Secretos de salida {#outputting-secrets} +La salida de los secretos se puede recuperar de nuevo, si es necesario. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## Paso 2: Preparar la cadena de conexión multidirección para el nodo de arranque {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Para que un nodo logre establecer conectividad, debe saber a qué servidor `bootnode` conectarse para obtener +información sobre todos los nodos restantes en la red. A veces, en la jerga p2p, `bootnode` también se conoce como el servidor `rendezvous`. + +`bootnode` no es una instancia especial del nodo de Polygon Edge. Cada nodo de Polygon Edge sirve como un `bootnode`, pero +cada nodo de Polygon Edge necesita tener un conjunto de nodos de arranque especificados que serán contactados, para suministrar información sobre cómo conectar con +todos los nodos restantes en la red. + +Para crear la cadena de conexión para especificar el nodo de arranque, necesitaremos ajustarnos +al [formato multidirección](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +En esta guía, trataremos al primer y segundo nodo como nodos de arranque para todos los demás nodos. Lo que sucederá en este escenario +es que los nodos que se conectan a `node 1` o a `node 2` obtendrán información sobre cómo conectarse entre ellos a través de un +nodo de arranque mutuamente contactado. + +:::info Debes especificar al menos un nodo de arranque para iniciar un nodo. + +Se requiere al menos **un** nodo de arranque para que otros nodos en la red puedan descubrirse entre ellos. Se recomienda que haya más nodos de arranque, ya que +le dan resiliencia a la red en caso de una caída del sistema. +En esta guía, enumeraremos dos nodos, pero eso puede cambiar sobre la marcha, sin que afecte la validez del archivo `genesis.json`. + +::: + +Dado que estamos ejecutando en un anfitrión local, es seguro asumir que `` es `127.0.0.1`. + +Para ``, utilizaremos `10001`, ya que configuraremos el servidor libp2p para que `node 1` escuche en este puerto después. + +Por último, necesitamos ``, que podemos obtener de los resultados del comando `polygon-edge secrets init --data-dir test-chain-1`, ejecutado anteriormente (que se utilizó para generar claves y directorios de datos para `node1`). + +Después del ensamblaje, la cadena de conexión multidirección a `node 1`, que utilizaremos como nodo de arranque, se verá más o menos así (solo que ``, que debería estar al final, se debería ver diferente): +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Del mismo modo, construimos la multidirección para el segundo nodo de arranque, tal como se muestra abajo. +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info Nombres de los anfitriones de DNS en vez de IPS + +Polygon Edge admite el uso de los nombres de los anfitriones de DNS para la configuración de los nodos. Esa es una característica muy útil para las implementaciones basadas en la nube, ya que la dirección IP del nodo puede cambiar debido a varias razones. + +El formato multidirección para la cadena de conexión mientras se usan nombres de anfitriones de DNS es el siguiente: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## Paso 3: genera el archivo génesis con los cuatro nodos como validadores {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +Lo que este comando hace: + +* `--ibft-validators-prefix-path` establece la ruta de la carpeta a una especificada, que IBFT en Polygon Edge puede utilizar. Este directorio se usa para almacenar la carpeta `consensus/`, donde se guarda la clave privada del validador. La +clave privada del validador se necesita para construir el archivo génesis, el paso inicial de los nodos de arranque. +Esa indicación solo tiene sentido al configurar la red en el anfitrión local, ya que en un escenario real no esperamos +que todos los directorios de datos de los nodos estén en el mismo sistema de archivos desde donde podamos leer sus claves privadas. +* `--bootnode` establece la dirección del nodo de arranque que habilitará la facultad de los nodos de encontrarse unos a otros. +Usaremos la cadena multidirección de `node 1`, como se menciona en el **paso 2**. + +El resultado de este comando es el archivo `genesis.json`, que contiene el bloque génesis de nuestra cadena de bloques nueva, con el conjunto de validadores predefinido y la configuración de cuál nodo se debe contactar primero para establecer la conectividad. + +:::info Cambiar a ECDSA + +BLS es el modo de validación por defecto de los encabezados de bloque. Si quieres que tu cadena se ejecute en modo ECDSA, puedes utilizar la bandera `—ibft-validator-type`, con el `ecdsa`argumento: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info Preminado de saldos de cuentas + +Probablemente quieras configurar tu red de cadena de bloques con algunas direcciones que tengan saldos "preminados". + +Para lograrlo, aprueba tantos indicadores `--premine` como quieras por dirección que quieras que inicie con cierto saldo +en la cadena de bloques. + +Por ejemplo, si quisiéramos preminar 1000 ETH a la dirección `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` en nuestro bloque génesis, tendríamos que suministrar el siguiente argumento: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Fíjate que la cantidad preminada está en WEI, no en ETH.** + +::: + +:::info Establece el límite de gas de los bloques + +El límite por defecto de gas de los bloques es `5242880`. Este valor está escrito en el archivo génesis, pero puedes +incrementarlo o reducirlo. + +Para ello, debes usar el indicador `--block-gas-limit` seguido del valor deseado, como se muestra a continuación: + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Establece el límite del descriptor de archivos del sistema. + +El límite del descriptor de archivos por defecto (número máximo de archivos abiertos) en algunos sistemas es muy bajo. +Si se espera que los nodos tengan alto rendimiento, podrías aumentar ese límite en el sistema operativo (SO). + +Para distribuciones de Ubuntu, el procedimiento es el siguiente (si no estás utilizando la distribución de Ubunto o Debian, revisa los documentos oficiales para tu SO): +- Revisa los límites actuales del SO (archivos abiertos). +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- Incrementa el límite de archivos abiertos. + - Localmente, solo afecta la sesión actual: + ```shell + ulimit -u 65535 + ``` + - Globalmente o por usuario (agrega límites al final del archivo /etc/security/limits.conf): + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +Opcionalmente, modifica los parámetros adicionales, guarda el archivo y reinicia el sistema. +Después de reiniciar, vuelve a revisar el límite del descriptor de archivos. +Debería establecerse al valor que definiste en el archivo limits.conf. + +::: + + +## Paso 4: ejecuta todos los clientes {#step-4-run-all-the-clients} + +Como ya estás tratando de ejecutar una red de Polygon Edge que consta de cuatro nodos, todos en la misma máquina, debemos procurar +evitar conflictos de los puertos. Por eso usamos el siguiente razonamiento para determinar los puertos de escucha de cada servidor de un nodo: + +- `10000` para el servidor gRPC de `node 1`, `20000` para el servidor GRPC de `node 2`, etc. +- `10001` para el servidor libp2p de `node 1`, `20001` para el servidor libp2p de `node 2`, etc. +- `10002` para el servidor JSON-RPC de `node 1`, `20002` para el servidor JSON-RPC de `node 2`, etc. + +Para ejecutar el **primer** cliente (nota el puerto `10001`, ya que se utilizó como parte de la multidirección libp2p en el **paso 2**, junto con la ID de nodo del primer nodo): + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +Para ejecutar el **segundo** cliente: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +Para ejecutar el **tercer** cliente: + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +Para ejecutar el **cuatro** cliente: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +Para revisar brevemente lo que se ha hecho hasta ahora: + +* El directorio de datos de los clientes se ha especificado como **./test-chain-\***. +* Los servidores GRPC se han iniciado en los puertos **10000**, **20000**, **30000** y **40000** para cada nodo, respectivamente. +* Los servidores libp2p se han iniciado en los puertos **10001**, **20001**, **30001** y **40001** para cada nodo, respectivamente. +* Los servidores JSON-RPC se han iniciado en los puertos **10002**, **20002**, **30002** y **40002** para cada nodo, respectivamente. +* La indicación *sello* significa que el nodo que se está iniciando participará en el sellado de bloques. +* La indicación *cadena* especifica qué archivo génesis se debería usar para la configuración de la cadena. + +La estructura del archivo génesis se detalla en la sección de [comandos CLI](/docs/edge/get-started/cli-commands). + +Después de ejecutar los comandos anteriores, has configurado una red de cuatro nodos de Polygon Edge, capaz de sellar bloques y recuperarse +de fallos de nodos. + +:::info Inicia el cliente con el archivo de configuración + +En lugar de especificar todos los parámetros de configuración como argumentos CLI, el cliente también puede comenzar a utilizar un archivo de configuración ejecutando el siguiente comando: + +````bash +polygon-edge server --config +```` +Ejemplo: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Actualmente, apoyamos `yaml`y `json`basamos los archivos de configuración, aquí se pueden encontrar los **[archivos](/docs/edge/configuration/sample-config)** de configuración de la muestra + +::: + +:::info Pasos para ejecutar un nodo no validador + +Un no validador siempre sincronizará los bloques más recientes recibidos del nodo validador. Puedes iniciar un nodo validador ejecutando el siguiente comando. + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +Por ejemplo, puedes añadir el **quinto** cliente no validador mediante la ejecución del siguiente comando: + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info Especifica el límite del precio + +Un nodo de Polygon Edge se puede iniciar con un **límite del precio** establecido para las transacciones entrantes. + + +La unidad del límite del precio es `wei`. + +Establecer un límite del precio significa que cualquier transacción procesada por el nodo actual deberá tener un precio de gas **más alto** +y un límite del precio; de otro modo, no se incluirá en un bloque. + +El hecho de que la mayoría de los nodos respeten un determinado límite del precio hace cumplir la regla de que las transacciones en la red +no pueden estar por debajo de cierto umbral del precio. + +El valor por defecto del límite del precio es `0`, lo que significa que, por defecto, no se aplica. + +Ejemplo de uso del indicador `--price-limit`: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Cabe señalar que los límites de los precios **solo se hacen cumplir en las transacciones no locales**, es decir, +que el límite del precio no aplica a las transacciones añadidas localmente en el nodo. + +::: + +:::info URL de WebSocket + +Por defecto, al ejecutar Polygon Edge, se genera un URL de WebSocket con base en la ubicación de la cadena. +El esquema de URL `wss://` se utiliza para enlaces de HTTPS y `ws://` para HTTP. + +URL de WebSocket del anfitrión local: +````bash +ws://localhost:10002/ws +```` +Fíjate que el número del puerto depende del puerto RPC JSON elegido para el nodo. + +URL de Edgenet WebSocket: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## Paso 5: interactúa con la red de Polygon Edge {#step-5-interact-with-the-polygon-edge-network} + +Ahora que has configurado por lo menos un cliente activo, puedes interactuar con la cadena de bloques mediante el uso de la cuenta que ya preminaste anteriormente +y especificando el URL de RPC JSON a cualquiera de los cuatro nodos: +- Nodo 1: `http://localhost:10002` +- Nodo 2: `http://localhost:20002` +- Nodo 3: `http://localhost:30002` +- Nodo 4: `http://localhost:40002` + +Sigue esta guía para emitir comandos de operador al grupo recién construido: [Cómo consultar información del operador](/docs/edge/working-with-node/query-operator-info) (los puertos de GRPC del grupo que hemos construido son `10000`, `20000`, `30000` y `40000`, respectivamente) diff --git a/archive/edge/es-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/es-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..2f49ca25df --- /dev/null +++ b/archive/edge/es-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,449 @@ +--- +id: set-up-ibft-on-the-cloud +title: Configuración de la nube +description: "Guía de configuración de la nube paso a paso" +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info Esta guía es para las configuraciones de la red principal o la red de pruebas. + +La siguiente guía te enseñará cómo configurar una red Polygon Edge en un proveedor de nube para una configuración de producción de tu red de prueba o la red principal. + +Si deseas configurar una red Polygon Edge localmente para poner a prueba rápidamente al `polygon-edge`antes de hacer una configuración de tipo productivo, consulta +**[Configuración local](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## Requisitos {#requirements} + +Consulta [Instalación](/docs/edge/get-started/installation) para instalar Polygon Edge. + +### Configuración de la conectividad de la máquina virtual {#setting-up-the-vm-connectivity} + +Dependiendo del proveedor de la nube que hayas elegido, puedes configurar la conectividad y las reglas entre las máquinas virtuales mediante un cortafuegos, +grupos de seguridad o listas de control de acceso. + +Como la única parte de `polygon-edge` que necesita ser expuesta a otras máquinas virtuales es el servidor libp2p, simplemente permitir +toda la comunicación entre las máquinas virtuales en el puerto libp2p `1478` por defecto es suficiente. + +## Descripción general {#overview} + +![Configuración de la nube](/img/edge/ibft-setup/cloud.svg) + +En esta guía, nuestro objetivo es crear una red de cadenas de bloques de `polygon-edge` que funcione con el [protocolo de consenso tolerante a fallas bizantinas de Estambul (IBFT)](https://github.com/ethereum/EIPs/issues/650). +La red de la cadena de bloques constará de 4 nodos, de los cuales todos son nodos validadores y, como tal, son elegibles tanto para proponer bloques como para validar bloques que vengan de otros proponentes. +Cada uno de los 4 nodos se ejecutará en su propia máquina virtual, ya que la idea de esta guía es ofrecerte una red Polygon Edge totalmente funcional, manteniendo las claves del validador privadas para asegurar una configuración de red sin confianza. + +Para lograrlo, te guiaremos por 4 sencillos pasos: + +0. Échale un vistazo a la lista de **Requisitos** anterior +1. Genera las claves privadas para cada uno de los validadores e inicializa el directorio de datos +2. Prepara la cadena de conexión para el nodo de arranque que se pondrá en el `genesis.json` compartido +3. Crea el `genesis.json` en tu máquina local y enviarlo o transferirlo a cada uno de los nodos +4. Inicia todos los nodos + +:::info Número de validadores + +No hay un número mínimo de nodos en un grupo, lo que significa que puede haber grupos con solo un nodo validador. +Ten en cuenta que con un grupo de _un solo_ nodo, no hay **tolerancia a colapsos** ni **garantías de BFT**. + +Se recomiendan mínimo cuatro nodos para lograr la garantía de tolerancia a fallas bizantinas (BFT), ya que, en un grupo de cuatro nodos, la falla de +un nodo se puede tolerar, si los tres nodos restantes funcionan normalmente. + +::: + +## Paso 1: Inicializa las carpetas de datos y genera las claves de validador {#step-1-initialize-data-folders-and-generate-validator-keys} + +Para ejecutar Polygon Edge es necesario que inicialices las carpetas de datos en cada nodo: + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +Cada uno de estos comandos imprimirá la clave validadora, la clave pública BLS y la [ID del nodo](https://docs.libp2p.io/concepts/peer-id/). Para el siguiente paso, necesitarás la ID del primer nodo. + +### Secretos de salida {#outputting-secrets} +La salida de los secretos se puede recuperar de nuevo, si es necesario. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning ¡Guarda tu directorio de datos y no lo compartas! + +Los directorios de datos generados con anterioridad, además de inicializar los directorios para mantener el estado de la cadena de bloques también generan las claves privadas de tu validador. +**¡Esta clave debe mantenerse en secreto, ya que el robo de la misma haría posible que alguien se hiciera pasar por el validador en la red!** + +::: + +## Paso 2: Preparar la cadena de conexión multidirección para el nodo de arranque {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Para que un nodo logre establecer conectividad, debe saber a cuál servidor `bootnode` conectarse para obtener +información sobre todos los nodos restantes en la red. A veces, en la jerga p2p, `bootnode` también se conoce como el servidor `rendezvous`. + +`bootnode` no es una instancia especial de un nodo de Polygon Edge. Cada nodo del Polygon Edge puede servir como un `bootnode`y +cada nodo de Polygon Edge debe tener un conjunto de nodos de arranque especificados que serán contactados para proporcionar información sobre cómo conectarse con +todos los nodos restantes en la red. + +Para crear la cadena de conexión para especificar el nodo de arranque, necesitaremos ajustarnos +al [formato multidirección](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +En esta guía, trataremos al primer y segundo nodo como nodos de arranque para todos los demás nodos. Lo que sucederá en este escenario +es que los nodos que se conectan a `node 1` o a `node 2` obtendrán información sobre cómo conectarse entre ellos a través de un +nodo de arranque mutuamente contactado. + +:::info Debes especificar al menos un nodo de arranque para iniciar un nodo. + +Se requiere al menos **un** nodo de arranque para que otros nodos en la red puedan descubrirse entre ellos. Se recomienda que haya más nodos de arranque, ya que +le dan resiliencia a la red en caso de una caída del sistema. +En esta guía, enumeraremos dos nodos, pero eso puede cambiar sobre la marcha, sin que afecte la validez del archivo `genesis.json`. + +::: + +Ya que la primera parte de la cadena de conexión multidirección es el ``, aquí , deberás introducir la dirección IP para que sea contactable por otros nodos; dependiendo de tu configuración, esta puede ser privada o pública, no`127.0.0.1` + +Para el `` utilizaremos `1478`, ya que es el puerto por defecto de libp2p. + +Por último, necesitamos ``, que podemos obtener de los resultados del comando `polygon-edge secrets init --data-dir data-dir`, ejecutado anteriormente (que se utilizó para generar claves y directorios de datos para `node 1`). + +Después del ensamblaje, la cadena de conexión multidirección a `node 1`, que utilizaremos como nodo de arranque, se verá más o menos así (solo que ``, que está al final, debe ser diferente): +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Del mismo modo, construimos multidirección parda el segundo nodo de arranque, tal como se muestra a continuación. +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info Nombres de los anfitriones de DNS en vez de IPS + +Polygon Edge admite el uso de los nombres de los anfitriones de DNS para la configuración de los nodos. Esa es una característica muy útil para las implementaciones basadas en la nube, ya que la dirección IP del nodo puede cambiar debido a varias razones. + +El formato multidirección para la cadena de conexión mientras se usan nombres de anfitriones de DNS es el siguiente: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## Paso 3: genera el archivo génesis con los 4 nodos como validadores {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +Este paso se puede ejecutar en tu máquina local, pero se necesitarán las claves públicas del validador para cada uno de los 4 validadores. + +Los validadores podrán compartir con seguridad el `Public key (address)` como se muestra más adelante en la salida a sus comandos `secrets init` de modo que +puedes generar de forma segura el genesis.json con esos validadores en el conjunto inicial de validadores, identificados con sus claves públicas: + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +Ya que recibiste las 4 claves públicas de los validadores, puede ejecutar el siguiente comando para generar el `genesis.json`. + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +Lo que este comando hace: + +* El `--ibft-validator` establece la clave pública del validador que debería incluirse en el conjunto inicial de validadores en el bloque génesis. Puede haber muchos validadores iniciales. +* El `--bootnode` establece la dirección del nodo de arranque que posibilitará que los nodos se encuentren entre sí. +Utilizaremos la cadena multidirección del `node 1`, como se menciona en el **paso 2**, aunque puedes añadir tantos nodos de arranque como desees, como ya se mostró. + +:::info Cambiar a ECDSA + +BLS es el modo de validación por defecto de los encabezados de bloque. Si quieres que tu cadena se ejecute en modo ECDSA, puedes utilizar la bandera `—ibft-validator-type`, con el `ecdsa`argumento: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info Preminado de saldos de cuentas + +Probablemente quieras configurar tu red de cadena de bloques con algunas direcciones que tengan saldos "preminados". + +Para lograrlo, aprueba tantos indicadores `--premine` como quieras por dirección que quieras que inicie con cierto saldo +en la cadena de bloques. + +Por ejemplo, si quisiéramos preminar 1000 ETH a la dirección `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` en nuestro bloque génesis, tendríamos que suministrar el siguiente argumento: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Fíjate que la cantidad preminada está en WEI, no en ETH.** + +::: + +:::info Establece el límite de gas de los bloques + +El límite por defecto de gas de los bloques es `5242880`. Este valor está escrito en el archivo génesis, pero puedes +incrementarlo o reducirlo. + +Para ello, debes usar el indicador `--block-gas-limit` seguido del valor deseado, como se muestra a continuación: + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Establece el límite del descriptor de archivos del sistema. + +El límite del descriptor de archivos por defecto (número máximo de archivos abiertos) en algunos sistemas es muy bajo. +Si se espera que los nodos tengan alto rendimiento, podrías aumentar ese límite en el sistema operativo (SO). + +Para distribuciones de Ubuntu, el procedimiento es el siguiente (si no estás utilizando la distribución de Ubunto o Debian, revisa los documentos oficiales para tu SO): +- Revisa los límites actuales del SO (archivos abiertos). +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- Incrementa el límite de archivos abiertos. + - Localmente, solo afecta la sesión actual: + ```shell + ulimit -u 65535 + ``` + - Globalmente o por usuario (agrega límites al final del archivo /etc/security/limits.conf): + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +Opcionalmente, modifica los parámetros adicionales, guarda el archivo y reinicia el sistema. +Después de reiniciar, vuelve a revisar el límite del descriptor de archivos. +Debería establecerse al valor que definiste en el archivo limits.conf. + +::: + +Después de especificar el: +1. Claves públicas de los validadores que se incluirán en el bloque génesis como conjunto de validadores +2. Cadenas de conexión multidirección del nodo de arranque +3. Cuentas y saldos preminados que se incluirán en el bloque génesis + +y generando el `genesis.json`, deberías copiarlo en todas las máquinas virtuales de la red. Dependiendo de tu configuración puedes +copiar y pegar, enviarlo al operador del nodo o simplemente entregarlo por SCP o FTP. + +La estructura del archivo génesis se detalla en la sección de [comandos CLI](/docs/edge/get-started/cli-commands). + +## Paso 4: ejecuta todos los clientes {#step-4-run-all-the-clients} + +:::note Conexión en red con los proveedores de la nube + +La mayoría de los proveedores de la nube no muestran las direcciones IP (especialmente las públicas) como una interfaz de red directa en tu máquina virtual, sino que configuran un proxy NAT invisible. + + +Para permitir que los nodos se conecten entre sí en este caso tendrías que escuchar en la dirección IP `0.0.0.0`para enlazar en todas las interfaces, pero aún tendrías que especificar la dirección IP o la dirección DNS que otros nodos pueden utilizar para conectarse a tu instancia. Eso se logra usando el argumento `--dns`o `--nat` donde puedes indicar tu dirección IP externa o DNS respectivamente. + +#### Ejemplo {#example} + +La dirección IP asociada que deseas escuchar es `192.0.2.1`, pero no está directamente asociada a ninguna de tus interfaces de red. + +Para permitir que los nodos se conecten hay que pasar los siguientes parámetros: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +O, si deseas especificar una dirección DNS `dns/example.io`, pasa los siguientes parámetros: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +Eso haría que tu nodo escuchara en todas las interfaces, pero también que supiera que los clientes se están conectando a él mediante la dirección `--nat`o `--dns`especificada. + +::: + +Para ejecutar el **primer** cliente: + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Para ejecutar el **segundo** cliente: + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Para ejecutar el **tercer** cliente: + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Para ejecutar el **cuatro** cliente: + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Después de ejecutar los comandos anteriores, habrás configurado una red de 4 nodos de Polygon Edge, capaz de sellar bloques y recuperarse +de fallos de nodos. + +:::info Inicia el cliente con el archivo de configuración + +En lugar de especificar todos los parámetros de configuración como argumentos CLI, el cliente también puede comenzar a utilizar un archivo de configuración ejecutando el siguiente comando: + +````bash +polygon-edge server --config +```` +Ejemplo: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Actualmente, solo soportamos el archivo de configuración `json`basado **[en](/docs/edge/configuration/sample-config)** , el archivo de configuración de la muestra se puede encontrar aquí + +::: + +:::info Pasos para ejecutar un nodo no validador + +Un no validador siempre sincronizará los bloques más recientes recibidos del nodo validador. Puedes iniciar un nodo validador ejecutando el siguiente comando. + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +Por ejemplo, puedes añadir el **quinto** cliente no validador mediante la ejecución del siguiente comando: + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info Especifica el límite del precio + +Un nodo de Polygon Edge se puede iniciar con un **límite del precio** establecido para las transacciones entrantes. + + +La unidad del límite del precio es `wei`. + +Establecer un límite del precio significa que cualquier transacción procesada por el nodo actual deberá tener un precio de gas **más alto** +que el límite de precio establecido, de lo contrario no se incluirá en un bloque. + +El hecho de que la mayoría de los nodos respeten un determinado límite del precio hace cumplir la regla de que las transacciones en la red +no pueden estar por debajo de cierto umbral del precio. + +El valor por defecto del límite del precio es `0`, lo que significa que, por defecto, no se aplica. + +Ejemplo de uso del indicador `--price-limit`: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Cabe señalar que los límites de los precios **solo se hacen cumplir en las transacciones no locales**, es decir, +que el límite del precio no aplica a las transacciones añadidas localmente en el nodo. + +::: + +:::info URL de WebSocket + +Por defecto, al ejecutar Polygon Edge, se genera un URL de WebSocket con base en la ubicación de la cadena. +El esquema de URL `wss://` se utiliza para enlaces de HTTPS y `ws://` para HTTP. + +URL de WebSocket del anfitrión local: +````bash +ws://localhost:10002/ws +```` +Fíjate que el número del puerto depende del puerto RPC JSON elegido para el nodo. + +URL de Edgenet WebSocket: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/es-edge/get-started/terraform-aws-deployment.md b/archive/edge/es-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..91bc2e3a5e --- /dev/null +++ b/archive/edge/es-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,177 @@ +--- +id: terraform-aws-deployment +title: Despliegue de Terraform en AWS +description: "Despliega la red Polygon Edge en el proveedor de la nube AWS utilizando Terraform" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info Guía de despliegue de producción + +Esta es la guía de despliegue de AWS oficial, lista para producción, totalmente automatizada. + +Se recomienda hacer despliegues manuales en la ***[nube](set-up-ibft-on-the-cloud)*** o ***[en](set-up-ibft-locally)*** la ubicación local +para hacer pruebas o si su proveedor de la nube no es AWS. + +::: + +:::info + +Este despliegue es solo con pruebas de autoridad (PoA). + Si se necesita el mecanismo de pruebas de participación (PoS), solo hay que seguir esta ***[guía](/docs/edge/consensus/migration-to-pos)*** para hacer el cambio de PoA a PoS. + +::: + +Esta guía describirá, en detalle, el proceso de despliegue de una red de cadena de bloques de Polygon Edge en el proveedor de la nube de AWS, +que está listo para la producción, ya que los nodos validadores están repartidos en varias zonas de disponibilidad. + +## Prerrequisitos {#prerequisites} + +### Herramientas del sistema {#system-tools} +* [terraform](https://www.terraform.io/) +* [aws cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [ID de la clave de acceso a AWS y clave de acceso secreta](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Variables de Terraform {#terraform-variables} +Dos variables que se deben proporcionar antes de ejecutar la implementación: + +* `alb_ssl_certificate`: el nombre de recursos de Amazon (ARN) del administrador de certificados de AWS que será utilizado por el equilibrador de carga de las aplicaciones (ALB) para el protocolo. + El certificado debe generarse antes de iniciar el despliegue y debe tener el estado **emitido** +* `premine`: la cuenta que recibirá la moneda nativa preminada. +El valor debe cumplir con la especificación oficial del indicador [CLI](/docs/edge/get-started/cli-commands#genesis-flags) + +## información de despliegue {#deployment-information} +### Recursos desplegados {#deployed-resources} +Descripción general de alto nivel de los recursos que se desplegarán: + +* Nube privada virtual (VPC) dedicada +* 4 nodos validadores (que también son nodos de arranque) +* 4 pasarelas de traducción de dirección de la red (NAT) para permitir el tráfico de salida de los nodos de Internet +* Función lambda utilizada para generar el primer bloque (génesis) e iniciar la cadena +* Grupos de seguridad dedicados y roles de IAM +* Bucket S3 utilizado para el almacenamiento del archivo genesis.json +* Equilibrador de carga de aplicaciones usado para exponer el terminal JSON-RPC + +### Tolerancia a fallas {#fault-tolerance} + +Para este despliegue solo se requieren regiones que tengan 4 zonas de disponibilidad. Cada nodo se despliega en una sola zona de aplicación (AZ). + +Al ubicar cada nodo en una única AZ, el conjunto de la cadena de bloques es tolerante a los fallos de un solo nodo (AZ), puesto que Polygon Edge despliega +el consenso de tolerancia a fallas bizantinas de Estambul (IBFT) que permite que un solo nodo falle en un grupo de 4 nodos validadores. + +### Acceso a la línea de comandos {#command-line-access} + +Los nodos validadores no están expuestos de ninguna manera a la Internet pública ( el acceso a la RPC JSON se hace únicamente por medio del ALB) +y ni siquiera tienen direcciones IP públicas adjuntas a ellos. +El acceso a la línea de comandos del nodo es posible únicamente a través del [administrador de sesión del administrador de sistemas de AWS](https://aws.amazon.com/systems-manager/features/). + +### Actualización de la imagen de máquina de Amazon (AMI) base {#base-ami-upgrade} + +Este despliegue utiliza la AMI de AWS `ubuntu-focal-20.04-amd64-server`. Eso **no** desencadenará el *redespliegue* de EC2 si la AMI de AWS se actualiza. + +Si, por alguna razón, la AMI base es obligatoria para actualizar, +se puede lograr ejecutando el comando `terraform taint` para cada instancia, antes de `terraform apply` . +Las instancias se pueden contaminar ejecutando el comando `terraform taint module.instances[].aws_instance.polygon_edge_instance` + comando. + +Ejemplo: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info + +En un entorno de producción `terraform taint`debe ser ejecutado uno a uno para mantener la red de la cadena de bloques funcional. + +::: + +## Procedimiento de despliegue {#deployment-procedure} + +### Pasos previos al despliegue {#pre-deployment-steps} +* Lee el archivo Readme de registro de Terraform [polygon-technology-edge](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) +* Añade el `polygon-technology-edge`módulo a tu archivo `main.tf` utilizando *las instrucciones* de la página readme de los módulos +* Ejecuta el comando `terraform init`para instalar todas las dependencias necesarias de Terraform +* Proporciona un nuevo certificado en el [administrador de certificados de AWS](https://aws.amazon.com/certificate-manager/) +* Cerciórate de que el certificado suministrado esté en el estado **Emitido** y anota el **ARN** del certificado +* Configura tu estado de salida para obtener la salida de los módulos en el CLI + +#### Ejemplo de `main.tf` {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### Ejemplo de `terraform.tfvars` {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### Pasos para el despliegue {#deployment-steps} +* Crea el archivo `terraform.tfvars` +* Establece las variables de Terraform necesarias en este archivo (como ya se explicó). +:::info + +Hay otras variables no obligatorias que pueden personalizar plenamente este despliegue +Puedes anular por defecto añadiendo los tuyos al archivo `terraform.tfvars`. + + La especificación de todas las variables disponibles se puede encontrar en el ***[registro](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)*** de los módulos de Terraform + +::: +* Asegúrate de haber configurado correctamente una autenticación de CLI de AWS ejecutando `aws s3 ls`. No debe haber errores. +* Implementa la infraestructura `terraform apply` + +### Pasos posteriores al despliegue {#post-deployment-steps} +* Una vez finalizado el despliegue anota el valor de la variable `json_rpc_dns_name`impreso en el CLI +* Crea un cname del DNS público que apunte tu nombre de dominio al valor `json_rpc_dns_name`suministrado. Por ejemplo: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* Cuando el registro cname se propague, comprueba si la cadena funciona correctamente llamando a su extremo de RPC JSON. + Del ejemplo anterior: + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## Procedimiento de destrucción {#destroy-procedure} +:::warning + +El siguiente procedimiento eliminará permanentemente toda la infraestructura desplegada con estas secuencias de comandos de Terraform +Asegúrate de tener [las copias de seguridad de datos de la cadena de bloques](docs/edge/working-with-node/backup-restore) apropiadas o de estar trabajando con un entorno de prueba. + +::: + +Si necesitas eliminar toda la infraestructura, ejecuta el siguiente comando `terraform destroy` . +Además, tendrás que eliminar manualmente los secretos almacenados en la [tienda de parámetros](https://aws.amazon.com/systems-manager/features/) de AWS +para la región en la que tuvo lugar el despliegue. diff --git a/archive/edge/es-edge/overview.md b/archive/edge/es-edge/overview.md new file mode 100644 index 0000000000..9b20b6b9b5 --- /dev/null +++ b/archive/edge/es-edge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Polygon Edge +sidebar_label: What is Edge +description: "Introducción a Polygon Edge" +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +Polygon Edge es una estructura modular y expandible para la construcción de redes de cadenas de bloques compatibles con Ethereum, cadenas laterales y soluciones generales de escalado. + +Su principal uso es el de iniciar una nueva red de cadenas de bloques, a la vez que proporciona plena compatibilidad con los contratos inteligentes y las transacciones de Ethereum. Utiliza el mecanismo de consenso de tolerancia a fallas bizantinas de Estambul (IBFT), con dos variantes: [PoA (pruebas de autoridad)](/docs/edge/consensus/poa) y [PoS (pruebas de participación)](/docs/edge/consensus/pos-stake-unstake). + +Polygon Edge también admite la comunicación con varias redes de cadenas de bloques, lo que permite la transferencia de tokens [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) y [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721), utilizando la [solución de puente centralizado](/docs/edge/additional-features/chainbridge/overview). + +Las billeteras estándar de la industria pueden ser utilizadas para interactuar con Polygon Edge a través de los terminales de [RPC JSON](/docs/edge/working-with-node/query-json-rpc) y los operadores de nodos pueden realizar varias acciones en los nodos por medio del protocolo [gRPC](/docs/edge/working-with-node/query-operator-info). + +Para obtener más información sobre Polygon, consulta el [sitio web oficial](https://polygon.technology). + +**[Repositorio de GitHub](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +Se trata de un trabajo en curso, por lo que pueden producirse cambios arquitectónicos en el futuro. El código no ha sido auditado +todavía, así que por favor, contacta al equipo de Polygon si quieres usarlo en producción. + +::: + + + +Para comenzar a ejecutar una red `polygon-edge` localmente, por favor, lee: [Instalación](/docs/edge/get-started/installation) y [configuración local](/docs/edge/get-started/set-up-ibft-locally). diff --git a/archive/edge/es-edge/performance-reports/overview.md b/archive/edge/es-edge/performance-reports/overview.md new file mode 100644 index 0000000000..e7372db92c --- /dev/null +++ b/archive/edge/es-edge/performance-reports/overview.md @@ -0,0 +1,32 @@ +--- +id: overview +title: Descripción general +description: "Introducción a las pruebas de Polygon Edge." +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +Ten en cuenta que nuestro , `loadbot`que se utilizó para realizar estas pruebas, ahora se deprecia. +::: + +| Tipo | Valor | Enlace a la prueba | +| ---- | ----- | ------------ | +| Transferencias regulares | 1428 tps | [4 de julio de 2022](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| Transferencias ERC-20 | 1111 tps | [4 de julio de 2022](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| Acuñamiento de NFT | 714 tps | [4 de julio de 2022](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +Nuestro objetivo es crear un software para clientes de cadenas de bloques de alto rendimiento, rico en funciones y fácil de configurar y mantener. +Todas las pruebas se hicieron usando Polygon Edge Loadbot. +Cada uno de los informes de rendimiento que encontrarás en esta sección está debidamente fechado, el entorno claramente descrito y el método de prueba claramente explicado. + +El objetivo de esas pruebas de rendimiento es mostrar el rendimiento en el mundo real de la red de cadenas de bloques de Polygon Edge. +Cualquier usuario debería poder obtener los mismos resultados que se han publicado aquí, en el mismo entorno, utilizando nuestro Loadbot. + +Todas las pruebas de rendimiento se realizaron en la plataforma de AWS en una cadena formada por nodos de instancia EC2. \ No newline at end of file diff --git a/archive/edge/es-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/es-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..ab38cc2cd6 --- /dev/null +++ b/archive/edge/es-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,130 @@ +--- +id: test-2022-01-21 +title: 21 de enero de 2022 +description: "Prueba de rendimiento del 21 de enero" +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## 21 de enero de 2022 {#january-21st-2022} + +### Resumen {#summary} + +:::caution +Ten en cuenta que nuestro , `loadbot`que se utilizó para realizar estas pruebas, ahora se deprecia. +::: + +Esta prueba se realizó después de que el refactor TxPool mejorara significativamente el rendimiento (lanzado en [v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0)). + +El objetivo era establecer una gran red de 30 validadores activamente participantes para hacer adecuadamente la prueba de estrés del consenso y los chismes de la transacción de TxPool, ya que todas las transacciones se enviaron al único nodo JSON-RPC. + +Nuestro objetivo no fue esforzarnos para llegar a un posible TPS máximo, ya que el tamaño de la red afecta negativamente el rendimiento, y dado que el límite del gas de los bloques y el tiempo de los bloques se establecieron en valores sanos que no consumieran muchos recursos del sistema y que permitieran la ejecución de esto en hardware básico. + +### Resultados {#results} + +| Métrica | Valor | +| ------ | ----- | +| Transacciones por segundo | 344 | +| Transacciones fallidas | 0 | +| Transacciones exitosas | 10 000 | +| Tiempo total de ejecución | 30 s | + +### Entorno {#environment} + +
+ Configuración del anfitrión +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Proveedor de la nubeAWS
Tamaño de la instanciat2.xlarge
RedesSubred privada
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Límite del descriptor de archivos65535
Procesos máximos de usuario65535
+
+
+
+
+ +
+ Configuración de la cadena de bloques +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Versión de Polygon EdgeComprometer 8377162281d1a2e4342ae27cd4e5367c4364aee2 en la rama de desarrollado
Nodos validadores30
Nodos no validadores0
ConsensoPrueba de autoridad (PoA) tolerante a falta bizantina de Estambul (IBFT)
Tiempo del bloque2000 ms
Límite de gas de los bloques5242880
+
+
+
+
+ +
+ Configuración del bot de carga +
+
+ + + + + + + + + + + + + +
Total de transacciones10 000
Transacciones enviadas por segundo400
Tipo de transaccionesTransferencias de EOA a EOA
+
+
+
+
diff --git a/archive/edge/es-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/es-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..efff9f8078 --- /dev/null +++ b/archive/edge/es-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,390 @@ +--- +id: test-2022-03-02 +title: 2 de marzo de 2022 +description: "Prueba de rendimiento del 2 de marzo" +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### Resumen {#summary} + +:::caution +Ten en cuenta que nuestro , `loadbot`que se utilizó para realizar estas pruebas, ahora se deprecia. +::: + +Esta prueba se realizó para medir las transferencias de tokens SC ERC-20 y la funcionalidad de acuñación de tokens SC ERC-721 con trabajo pesado y velocidad de transacciones. + +El objetivo era comprobar que todo funcionaba según lo esperado cuando había trabajo pesado. También por eso introdujimos las métricas de gas en la salida del bot de carga, que nos muestran si los bloques se llenaban de transacciones correctamente. + +Todas las transacciones se enviaron al nodo único mediante la API de GRPC y los recibos se recibieron a través de la API de RPC JSON. Una vez realizadas todas las transacciones, se leyó la información del gas de cada bloque con el método de RPC JSON eth_getBlockByNumber. + +Nuestro objetivo no fue esforzarnos por llegar a un máximo TPS posible, +ya que el límite de gas de los bloques y el tiempo de los bloques se establecieron en valores sanos que no consumieran muchos recursos del sistema y que permitieran la ejecución de esto en hardware básico. + +### Resultados de ERC-20 {#results-erc20} + +| Métrica | Valor | +| ------ | ----- | +| Tipo de transacción | ERC-20 | +| Transacciones por segundo | 65 | +| Transacciones fallidas | 0 | +| Transacciones culminadas | 5000 | +| Tiempo de ejecución de la transacción de ERC-20 | 76,681690 s | +| Tiempo de despliegue de SC | 4,048250 s | + +### Resultados de ERC-721 {#results-erc721} + +| Métrica | Valor | +| ------ | ----- | +| Tipo de transacción | ERC-721 | +| Transacciones por segundo | 20 | +| Transacciones fallidas | 0 | +| Transacciones culminadas | 2000 | +| Tiempo de ejecución de transacciones de ERC-721 | 97,239920 s | +| Tiempo de despliegue de SC | 3,048970 s | + +### Entorno ERC-20 {#environment-erc20} + +
+ Configuración del anfitrión +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Proveedor de la nubeAWS
Tamaño de la instanciat2.micro
RedesSubred privada
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Límite del descriptor de archivos65535
Procesos máximos de usuario65535
+
+
+
+
+ +
+ Configuración de la cadena de bloques +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versión de Polygon EdgeCompromete 8a033aa1afb191abdac04636d318f83f32511f3c en la rama de desarrollo
Nodos validadores6
Nodos no validadores0
ConsensoPrueba de autoridad (PoA) tolerante a falta bizantina de Estambul (IBFT)
Tiempo del bloque2 s
Límite de gas de los bloques5242880
Utilización promedio de los bloques95 %
+
+
+
+
+ +
+ Configuración del bot de carga +
+
+ + + + + + + + + + + + + +
Total de transacciones5000
Transacciones enviadas por segundo200
Tipo de transaccionesTransferencias de ERC-20 a ERC-20
+
+
+
+
+ +
+ Registro del bot de carga + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### Entorno ERC-721 {#environment-erc721} + +
+ Configuración del anfitrión +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Proveedor de la nubeAWS
Tamaño de la instanciat2.micro
RedesSubred privada
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Límite del descriptor de archivos65535
Procesos máximos de usuario65535
+
+
+
+
+ +
+ Configuración de la cadena de bloques +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versión de Polygon EdgeCompromete 8a033aa1afb191abdac04636d318f83f32511f3c en la rama de desarrollo
Nodos validadores6
Nodos no validadores0
ConsensoPrueba de autoridad (PoA) tolerante a falta bizantina de Estambul (IBFT)
Tiempo del bloque2 s
Límite de gas de los bloques5242880
Utilización promedio de los bloques94 %
+
+
+
+
+ +
+ Configuración del bot de carga +
+
+ + + + + + + + + + + + + +
Total de transacciones2000
Transacciones enviadas por segundo200
Tipo de transaccionesAcuñación de tokens ERC-721
+
+
+
+
+ +
+ Registro del bot de carga + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/es-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/es-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..cc865fe83e --- /dev/null +++ b/archive/edge/es-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,960 @@ +--- +id: test-2022-03-23 +title: 23 de marzo de 2022 +description: "Prueba de desempeño del 23 de marzo." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### Resumen {#summary} + +:::caution +Ten en cuenta que nuestro , `loadbot`que se utilizó para realizar estas pruebas, ahora se deprecia. +::: + +Esta prueba se realizó para medir las transferencias de los tokens SC ERC-20, la acuñación de tokens SC ERC-721 y la funcionalidad de las transacciones de EOA (Cuenta de propietario externo) a EOA con cargas pesadas, al igual que la velocidad de las transacciones en nodos con mayores recursos de hardware. + +El objetivo fue comprobar que todo funcionaba según lo esperado durante las cargas pesadas. También por eso introdujimos las métricas de gas en la salida del bot de carga, que nos muestran si los bloques se llenaban de transacciones correctamente. + +Todas las transacciones se enviaron al nodo único por medio de la API de GRPC y los recibos se recibieron por medio de la API de RPC JSON. Una vez realizadas todas las transacciones, se leyó la información del gas de cada bloque con el método de RPC JSON eth_getBlockByNumber. + +Nuestra meta era esforzarnos para llegar a un máximo posible de transacciones por segundo (TPS) en los recursos de hardware disponibles. +Para lograrlo, modificamos el límite del gas de los bloques y los parámetros de tiempo del bloque, para obtener los mejores resultados de TPS posibles y mantener la integridad y la estabilidad del sistema. + +:::info Límite del gas de los bloques + +El límite del gas se puede incrementar hasta una cifra relativamente alta si las transacciones están usando mucho gas para su ejecución. +En el ejemplo de abajo, la acuñación de los tokens ERC-721 funcionó mucho más rápido con un límite de gas para los bloques de 80 000 000 (en lugar de 20 millones), pero en el caso de las transferencias de tokens ERC-20, con 80 millones de límite de gas de los bloques, el servidor colapsó. + +::: + +:::info Entornos de producción + +Al configurar un entorno de producción, tienes que tener cuidado si estás tratando de lograr un alto rendimiento de la cadena. +Si el parámetro del límite de gas de los bloques está establecido en un valor alto, el tiempo del bloque está establecido en 1 segundo y hay una alta carga de transacciones en un solo nodo, ese nodo consumirá mucha RAM (si no toda la que está disponible) y puede causar un bloqueo en el servidor. +Usa el bot de carga para someter todo a exhaustivas pruebas, monitorea la utilización de recursos del sistema y configura tus parámetros de configuración de acuerdo con ello. + +::: + +:::info Errores por falta de memoria + +Algunas distribuciones de Linux automáticamente eliminan el proceso que usa mucha RAM (error OOM o sin memoria), para preservar la estabilidad del sistema. +El resultado del registro de este error OOM se ve como se muestra a continuación. +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### Resultados de transferencias de EOA a EOA {#results-of-eoa-to-eoa-transfers} +| Métrica | Valor | +| ------ | ----- | +| Tipo de transacción | EOA a EOA | +| Transacciones por segundo | 689 | +| Transacciones fallidas | 0 | +| Transacciones culminadas | 20 000 | +| Total de bloques utilizados | 25 | +| Tiempo total de ejecución | 29,921110 s | + +### Resultados de las transferencias de tokens ERC-20 {#results-of-erc20-token-transfers} + +| Métrica | Valor | +| ------ | ----- | +| Tipo de transacción | ERC-20 | +| Transacciones por segundo | 500 | +| Transacciones fallidas | 0 | +| Transacciones culminadas | 20 000 | +| Total de bloques utilizados | 33 | +| Tiempo de ejecución de la transacción de ERC-20 | 40,402900 s | +| Tiempo de despliegue de SC | 2,004140 s | + +### Resultados de la acuñación de tokens ERC-721 {#results-of-erc721-token-minting} + +| Métrica | Valor | +| ------ | ----- | +| Tipo de transacción | ERC-721 | +| Transacciones por segundo | 157 | +| Transacciones fallidas | 0 | +| Transacciones culminadas | 20 000 | +| Total de bloques utilizados | 124 | +| Tiempo de ejecución de la transacción de ERC-721 | 127,537340 s | +| Tiempo de despliegue de SC | 2,004420 s | + + +### Resultados de la acuñación de tokens ERC-721 con un límite de gas de bloques muy alto (80 millones) {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| Métrica | Valor | +| ------ | ----- | +| Tipo de transacción | ERC-721 | +| Transacciones por segundo | 487 | +| Transacciones fallidas | 0 | +| Transacciones culminadas | 20 000 | +| Total de bloques utilizados | 34 | +| Tiempo de ejecución de la transacción de ERC-721 | 41,098410 s | +| Tiempo de despliegue de SC | 2,004300 s | + + +### Entorno de EOA a EOA {#environment-eoa-to-eoa} +
+ Configuración del anfitrión +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Proveedor de la nubeAWS
Tamaño de la instanciac5.2xlarge
RedesSubred privada
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Límite del descriptor de archivos65535
Procesos máximos de usuario65535
+
+
+
+
+ +
+ Configuración de la cadena de bloques +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versión de Polygon EdgeConsolida 06e11eac8da98c79c938fc53dda2da3318cfbe04 en la rama de desarrollo
Nodos validadores4
Nodos no validadores0
ConsensoPrueba de autoridad (PoA) tolerante a falta bizantina de Estambul (IBFT)
Tiempo del bloque1 s
Límite de gas de los bloques20 000 000
Máximo de ranuras1000000
Utilización promedio de bloques84,00 %
+
+
+
+
+ +
+ Configuración del bot de carga +
+
+ + + + + + + + + + + + + +
Total de transacciones20 000
Transacciones enviadas por segundo689
Tipo de transaccionesTransferencias de EOA a EOA
+
+
+
+
+ +
+ Registro del bot de carga + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### Entorno ERC-20 {#environment-erc20} +
+ Configuración del anfitrión +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Proveedor de la nubeAWS
Tamaño de la instanciac5.2xlarge
RedesSubred privada
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Límite del descriptor de archivos65535
Procesos máximos de usuario65535
+
+
+
+
+ +
+ Configuración de la cadena de bloques +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versión de Polygon EdgeConsolida 06e11eac8da98c79c938fc53dda2da3318cfbe04 en la rama de desarrollo
Nodos validadores4
Nodos no validadores0
ConsensoPrueba de autoridad (PoA) tolerante a falta bizantina de Estambul (IBFT)
Tiempo del bloque1 s
Límite de gas de los bloques20 000 000
Máximo de ranuras1000000
Utilización promedio de bloques88,38 %
+
+
+
+
+ +
+ Configuración del bot de carga +
+
+ + + + + + + + + + + + + +
Total de transacciones20 000
Transacciones enviadas por segundo500
Tipo de transaccionesTransferencias de ERC-20 a ERC-20
+
+
+
+
+ +
+ Registro del bot de carga + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### Entorno ERC-721 {#environment-erc721} +
+ Configuración del anfitrión +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Proveedor de la nubeAWS
Tamaño de la instanciac5.2xlarge
RedesSubred privada
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Límite del descriptor de archivos65535
Procesos máximos de usuario65535
+
+
+
+
+ +
+ Configuración de la cadena de bloques +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versión de Polygon EdgeConsolida 06e11eac8da98c79c938fc53dda2da3318cfbe04 en la rama de desarrollo
Nodos validadores4
Nodos no validadores0
ConsensoPrueba de autoridad (PoA) tolerante a falta bizantina de Estambul (IBFT)
Tiempo del bloque1 s
Límite de gas de los bloques20 000 000
Máximo de ranuras1000000
Utilización promedio de bloques92,90 %
+
+
+
+
+ +
+ Configuración del bot de carga +
+
+ + + + + + + + + + + + + +
Total de transacciones20 000
Transacciones enviadas por segundo157
Tipo de transaccionesAcuñación de tokens ERC-721
+
+
+
+
+ +
+ Registro del bot de carga + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### Entorno ERC-20: límite del gas de los bloques muy alto {#environment-erc20-very-high-block-gas-limit} +
+ Configuración del anfitrión +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Proveedor de la nubeAWS
Tamaño de la instanciac5.2xlarge
RedesSubred privada
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Límite del descriptor de archivos65535
Procesos máximos de usuario65535
+
+
+
+
+ +
+ Configuración de la cadena de bloques +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versión de Polygon EdgeConsolida 06e11eac8da98c79c938fc53dda2da3318cfbe04 en la rama de desarrollo
Nodos validadores4
Nodos no validadores0
ConsensoPrueba de autoridad (PoA) tolerante a falta bizantina de Estambul (IBFT)
Tiempo del bloque1 s
Límite de gas de los bloques80 000 000
Máximo de ranuras1000000
Utilización promedio de bloques---
+
+
+
+
+ +
+ Configuración del bot de carga +
+
+ + + + + + + + + + + + + +
Total de transacciones20 000
Transacciones enviadas por segundo---
Tipo de transaccionesTransferencias de ERC-20 a ERC-20
+
+
+
+
+ +
+ Registro de errores OOM (sin memoria) + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### Entorno de ERC-721: límite del gas de los bloques muy alto {#environment-erc721-very-high-block-gas-limit} +
+ Configuración del anfitrión +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Proveedor de la nubeAWS
Tamaño de la instanciac5.2xlarge
RedesSubred privada
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Límite del descriptor de archivos65535
Procesos máximos de usuario65535
+
+
+
+
+ +
+ Configuración de la cadena de bloques +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versión de Polygon EdgeConsolida 06e11eac8da98c79c938fc53dda2da3318cfbe04 en la rama de desarrollo
Nodos validadores4
Nodos no validadores0
ConsensoPrueba de autoridad (PoA) tolerante a falta bizantina de Estambul (IBFT)
Tiempo del bloque1 s
Límite de gas de los bloques80 000 000
Máximo de ranuras1000000
Utilización promedio de bloques84,68 %
+
+
+
+
+ +
+ Configuración del bot de carga +
+
+ + + + + + + + + + + + + +
Total de transacciones20 000
Transacciones enviadas por segundo487
Tipo de transaccionesAcuñación de tokens ERC-721
+
+
+
+
+ +
+ Registro del bot de carga + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/es-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/es-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..fa5c53c76b --- /dev/null +++ b/archive/edge/es-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,568 @@ +--- +id: test-2022-07-04 +title: 4 de julio de 2022 +description: "Prueba de rendimiento a partir del 4 de julio." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### Resumen {#summary} + +:::caution +Ten en cuenta que nuestro , `loadbot`que se utilizó para realizar estas pruebas, ahora se deprecia. +::: + +Esta prueba se realizó para medir las transferencias de los tokens SC ERC-20, la acuñación de tokens SC ERC-721 y la funcionalidad de las transacciones de EOA (Cuenta de propietario externo) a EOA con cargas pesadas, al igual que la velocidad de las transacciones en nodos con mayores recursos de hardware. + +El objetivo fue comprobar que todo funcionaba según lo esperado durante las cargas pesadas. También por eso introdujimos las métricas de gas en la salida del bot de carga, que nos muestran si los bloques se llenaban de transacciones correctamente. + +Todas las transacciones se enviaron al nodo único por medio de la API de GRPC y los recibos se recibieron por medio de la API de RPC JSON. Una vez realizadas todas las transacciones, se leyó la información del gas de cada bloque con el método de RPC JSON eth_getBlockByNumber. + +Nuestra meta era esforzarnos para llegar a un máximo posible de transacciones por segundo (TPS) en los recursos de hardware disponibles. +Para lograrlo, modificamos el límite del gas de los bloques y los parámetros de tiempo de los bloques, para obtener los mejores resultados de TPS posibles y mantener la integridad y la estabilidad del sistema. + + +:::info Entornos de producción + +Al configurar un entorno de producción, tienes que tener cuidado si estás tratando de lograr un alto rendimiento de la cadena. +Si el parámetro del límite de gas de los bloques está establecido en un valor alto, el tiempo del bloque está establecido en 1 segundo y hay una alta carga de transacciones en un solo nodo, ese nodo consumirá mucha RAM (si no toda la que está disponible) y puede causar un bloqueo en el servidor. +Usa el bot de carga para someter todo a exhaustivas pruebas, monitorea la utilización de recursos del sistema y configura tus parámetros de configuración de acuerdo con ello. + +::: + + + +### Resultados de transferencias de EOA (cuenta externa) a EOA {#results-of-eoa-to-eoa-transfers} +| Métrica | Valor | +| ------ | ----- | +| Tipo de transacción | EOA a EOA | +| Transacciones por segundo | 1428 | +| Transacciones fallidas | 0 | +| Transacciones efectivas | 30000 | +| Total de bloques utilizados | 15 | +| Tiempo total de ejecución | 21.374620 s | + +### Resultados de las transferencias de tokens ERC-20 {#results-of-erc20-token-transfers} + +| Métrica | Valor | +| ------ | ----- | +| Tipo de transacción | ERC-20 | +| Transacciones por segundo | 1111 | +| Transacciones fallidas | 0 | +| Transacciones efectivas | 50000 | +| Total de bloques utilizados | 38 | +| Tiempo de ejecución de la transacción de ERC-20 | 45.906450 s | +| Tiempo de despliegue de SC | 2.006580 s | + +### Resultados de la acuñación de tokens ERC-721 {#results-of-erc721-token-minting} + +| Métrica | Valor | +| ------ | ----- | +| Tipo de transacción | ERC-721 | +| Transacciones por segundo | 714 | +| Transacciones fallidas | 0 | +| Transacciones efectivas | 30000 | +| Total de bloques utilizados | 39 | +| Tiempo de ejecución de la transacción de ERC-721 | 42.864140 s | +| Tiempo de despliegue de SC | 2.005500 s | + + + + +### Entorno de EOA a EOA {#environment-eoa-to-eoa} +
+ Configuración del anfitrión +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Proveedor de la nubeEC2 de AWS
Tamaño de la instanciac6a.48xlarge
RedesSubred privada
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Límite del descriptor de archivos65535
Procesos máximos de usuario65535
+
+
+
+
+ +
+ Configuración de la cadena de bloques +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versión de Polygon EdgeVersión v0.4.1
Nodos validadores4
Nodos no validadores0
ConsensoPrueba de autoridad (PoA) tolerante a falta bizantina de Estambul (IBFT)
Tiempo del bloque1 s
Límite de gas de los bloques70778880
Máximo de ranuras276480
Utilización promedio de bloques59,34 %
+
+
+
+
+ +
+ Configuración del bot de carga +
+
+ + + + + + + + + + + + + +
Total de transacciones30000
Transacciones enviadas por segundo1428
Tipo de transaccionesTransferencias de EOA a EOA
+
+
+
+
+ +
+ Registro del bot de carga + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### Entorno ERC-20 {#environment-erc20} +
+ Configuración del anfitrión +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Proveedor de la nubeEC2 de AWS
Tamaño de la instanciac6a.48xlarge
RedesSubred privada
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Límite del descriptor de archivos65535
Procesos máximos de usuario65535
+
+
+
+
+ +
+ Configuración de la cadena de bloques +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versión de Polygon EdgeVersión v0.4.1
Nodos validadores4
Nodos no validadores0
ConsensoPrueba de autoridad (PoA) tolerante a falta bizantina de Estambul (IBFT)
Tiempo del bloque1 s
Límite de gas de los bloques47185920
Máximo de ranuras184320
Utilización promedio de bloques81,29 %
+
+
+
+
+ +
+ Configuración del bot de carga +
+
+ + + + + + + + + + + + + +
Total de transacciones50000
Transacciones enviadas por segundo1111
Tipo de transaccionesTransferencias de ERC-20 a ERC-20
+
+
+
+
+ +
+ Registro del bot de carga + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### Entorno ERC-721 {#environment-erc721} +
+ Configuración del anfitrión +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Proveedor de la nubeEC2 de AWS
Tamaño de la instanciac6a.48xlarge
RedesSubred privada
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Límite del descriptor de archivos65535
Procesos máximos de usuario65535
+
+
+
+
+ +
+ Configuración de la cadena de bloques +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versión de Polygon EdgeVersión v0.4.1
Nodos validadores4
Nodos no validadores0
ConsensoPrueba de autoridad (PoA) tolerante a falta bizantina de Estambul (IBFT)
Tiempo del bloque1 s
Límite de gas de los bloques94371840
Máximo de ranuras1000000
Utilización promedio de bloques93,88 %
+
+
+
+
+ +
+ Configuración del bot de carga +
+
+ + + + + + + + + + + + + +
Total de transacciones30000
Transacciones enviadas por segundo714
Tipo de transaccionesAcuñación de tokens ERC-721
+
+
+
+
+ +
+ Registro del bot de carga + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/es-edge/troubleshooting.md b/archive/edge/es-edge/troubleshooting.md new file mode 100644 index 0000000000..6392624e6a --- /dev/null +++ b/archive/edge/es-edge/troubleshooting.md @@ -0,0 +1,69 @@ +--- +id: troubleshooting +title: Solución de problemas +description: "Sección de solución de problemas para Polygon Edge" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# Solución de problemas {#troubleshooting} + +## error `method=eth_call err="invalid signature"` {#error} + +Cuando utilices una billetera para hacer una transacción con Polygon Edge, cerciórate de lo siguiente en la configuración de red local de tu billetera: + +1. `chainID` es el correcto. El `chainID` por defecto para Edge es `100`, pero se puede personalizar mediante el uso de la indicación de génesis `--chain-id`. + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. Asegúrate de usar el puerto JSON RPC del nodo al que te estás conectando en el campo "RPC URL". + + +## Cómo obtener un URL de WebSocket {#how-to-get-a-websocket-url} + +Por defecto, al ejecutar Polygon Edge, se expone una terminal de WebSocket con base en la ubicación de la cadena. +El esquema de URL `wss://` se utiliza para enlaces de HTTPS y `ws://` para HTTP. + +URL de WebSocket del anfitrión local: +````bash +ws://:/ws +```` +Fíjate que el número del puerto depende del puerto RPC JSON elegido para el nodo. + +URL de Edgenet WebSocket: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## Error `insufficient funds` al intentar desplegar un contrato {#error-when-trying-to-deploy-a-contract} + +Si te sale este error, asegúrate de tener suficientes fondos en la dirección deseada, y de que la dirección utilizada sea la correcta.
Para establecer el saldo preminado, puedes usar la indicación de génesis `genesis [--premine ADDRESS:VALUE]` al generar el archivo de génesis. Ejemplo del uso de esta indicación: +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +Esto premina 1000000000000000000000 WEI a 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862. + + +## Los tokens ERC-20 no se liberan mientras se usa Chainbridge (puente entre cadenas) {#erc20-tokens-not-released-while-using-chainbridge} + +Si intentas transferir tokens ERC-20 entre PoS de Polygon y una red local de Edge, y se depositan tus tokens ERC-20, también se ejecuta una propuesta en el repetidor, pero los tokens no se liberan en la red de Edge, asegúrate de que el manejador (handler) de ERC-20 en la cadena de Polygon Edge tenga suficientes tokens para liberar.
+El contrato del manejador (handler) en la cadena de destino debe tener suficientes tokens para liberar el modo de liberación del bloqueo. Si no tienes ningún token ERC20 en el manejador de ERC20 de tu red local de Edge, acuña nuevos tokens y transfiérelos al manejador de ERC20. + +## Error `Incorrect fee supplied` al usar Chainbridge (puente entre cadenas) {#error-when-using-chainbridge} + +Es posible que se presente este error cuando intentes transferir tokens ERC20 entre la cadena PoS de Mumbai de Polygon y una configuración local de Polygon Edge. Este error aparece cuando se establece la tarifa del despliegue con la indicación `--fee`, pero no se establece el mismo valor en la transacción del depósito. +Puedes usar el siguiente comando para cambiar la tarifa: +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +Aquí puedes encontrar más información sobre esta [bandera](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md). + + + + + diff --git a/archive/edge/es-edge/validator-hosting.md b/archive/edge/es-edge/validator-hosting.md new file mode 100644 index 0000000000..614bb3f438 --- /dev/null +++ b/archive/edge/es-edge/validator-hosting.md @@ -0,0 +1,262 @@ +--- +id: validator-hosting +title: Alojamiento del validador +description: "Requisitos de alojamiento para Polygon Edge" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +A continuación se presentan las sugerencias para alojar correctamente un nodo validador en una red de Polygon Edge. Préstale mucha atención a todos los elementos que se enumeran a continuación y asegúrate +de que la configuración de tu validador está configurada correctamente para que sea segura, estable y eficaz. + +## Base de conocimiento {#knowledge-base} + +Antes de intentar ejecutar el nodo validador, lee detenidamente este documento. +Otros documentos que pueden ser útiles son: + +- [Instalación](get-started/installation) +- [Configuración de la nube](get-started/set-up-ibft-on-the-cloud) +- [Comandos de CLI](get-started/cli-commands) +- [Archivo de configuración del servidor](configuration/sample-config) +- [Claves privadas](configuration/manage-private-keys) +- [Métricas de Prometheus](configuration/prometheus-metrics) +- [Administradores secretos](/docs/category/secret-managers) +- [Copia de seguridad o restauración](working-with-node/backup-restore) + +## Requisitos mínimos del sistema {#minimum-system-requirements} + +| Tipo | Valor | Influenciado por | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 2 núcleos |
  • Número de consultas JSON RPC
  • Tamaño del estado de la cadena de bloques
  • Límite de gas de los bloques
  • Tiempo del bloque
| +| RAM | 2 GB |
  • Número de consultas JSON RPC
  • Tamaño del estado de la cadena de bloques
  • Límite de gas de los bloques
| +| Disco |
  • 10 GB de partición de la raíz
  • Partición de la raíz de 30 GB con administración del volumen lógico (LVM) para la extensión del disco
|
  • Tamaño del estado de la cadena de bloques
| + + +## Configuración de servicio {#service-configuration} + +El binario `polygon-edge` debe ejecutarse como un servicio del sistema automáticamente al establecerse la conectividad de la red y tener las funcionalidades inicio, parada y reinicio. +funcionalidades. Recomendamos utilizar un administrador de servicios como `systemd.` + +Ejemplo de archivo de configuración del sistema `systemd`: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### Binario {#binary} + +En las cargas de trabajo de producción, los binarios `polygon-edge` solo deberían desplegarse a partir de los binarios publicados y precompilados de GitHub, y no mediante la compilación manual. +:::info + +Al compilar manualmente la rama de `develop` de GitHub, puedes introducir cambios de ruptura en tu entorno. +Por eso, se recomienda desplegar el binario de Polygon Edge exclusivamente a partir de las publicaciones, dado que contendrá +información sobre los cambios de ruptura y cómo superarlos. + +::: + +Consulta la sección de [Instalación](/docs/edge/get-started/installation) para ver la descripción completa del método de instalación. + +### Almacenamiento de datos {#data-storage} + +La carpeta `data/` que contiene todo el estado de la cadena de bloques debe ser montada en un disco o volumen dedicado que permita +hacer copias de seguridad automáticas del disco, ampliar el volumen y, opcionalmente, montar el disco o volumen en otra instancia en caso de falla. + + +### Archivos de registro {#log-files} + +Los archivos de registro deben ser rotados diariamente (con una herramienta como `logrotate`) +:::warning + +Si se configura sin rotación de registros, los archivos de registro pueden utilizar todo el espacio de disco disponible y eso podría interrumpir el tiempo de funcionamiento del validador. + +::: + +Ejemplo de configuración `logrotate`: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +Consulta la sección de [Registro](#logging) a continuación para conocer las recomendaciones sobre el almacenamiento de registros. + +### Dependencias adicionales {#additional-dependencies} + +`polygon-edge` es compilado estáticamente, por lo que no requiere dependencias adicionales del sistema operativo anfitrión. + +## Mantenimiento {#maintenance} + +A continuación se presentan las mejores prácticas para mantener un nodo validador en funcionamiento de una red de Polygon Edge. + +### Copia de seguridad {#backup} + +Existen dos tipos de procedimientos de copia de seguridad recomendados para los nodos de Polygon Edge. + +Si es posible, se sugiere utilizar ambos, y la copia de seguridad de Polygon Edge siempre es una opción disponible. + +* ***Copia de seguridad del volumen***: + Copia de seguridad progresiva diaria del volumen del nodo `data/` de Polygon Edge o de la máquina virtual (VM) completa si es posible. + + +* ***Copia de seguridad de Polygon Edge***: + Se recomienda un trabajo de CRON diario que haga copias de seguridad periódicas de Polygon Edge y mueva los archivos `.dat` a una ubicación externa o a un almacenamiento seguro de objetos en la nube. + +Lo ideal es que la copia de seguridad de Polygon Edge no se superponga con la copia de seguridad del volumen descrita anteriormente. + +Consulta la [instancia de nodo de copia de seguridad o restauración](working-with-node/backup-restore) para conocer las instrucciones sobre cómo hacer copias de seguridad de Polygon Edge. + +### Registro {#logging} + +Los registros emitidos por los nodos de Polygon Edge deben: +- enviarse a un almacén de datos externo con capacidad de indexación y búsqueda +- tener un período de retención de registros de 30 días + +Si es la primera vez que configuras un validador de Polygon Edge, te recomendamos que inicies el nodo +con la opción `--log-level=DEBUG` para poder depurar rápidamente cualquier problema que se te presente. + +:::info + +La `--log-level=DEBUG`.hará que la salida del registro del nodo sea lo más verbosa posible. +Los registros de depuración aumentarán drásticamente el tamaño del archivo de registro, lo que debe tenerse en cuenta al configurar +la solución de rotación del registro. + +::: +### Parches de seguridad del sistema operativo {#os-security-patches} + +Los administradores deben asegurarse de que el sistema operativo de la instancia validadora se actualice siempre con los últimos parches al menos una vez al mes. + +## Métricas {#metrics} + +### Métricas del sistema {#system-metrics} + +Los administradores deben configurar algún tipo de monitor de métricas del sistema, (por ejemplo, Telegraf + InfluxDB + Grafana o un SaaS de terceros). + +Métricas que deben monitorearse y tener notificaciones de alarma configuradas: + +| Nombre de la métrica | Umbral de alarma | +|-----------------------|-------------------------------| +| Uso de la CPU (%) | > 90 % durante más de 5 minutos | +| Utilización de la RAM (%) | > 90 % durante más de 5 minutos | +| Utilización del disco raíz | > 90 % | +| Utilización de datos en el disco | > 90 % | + +### Métricas del validador {#validator-metrics} + +Los administradores deben configurar la recopilación de métricas de la API de Prometheus de Polygon Edge para poder +supervisar el rendimiento de la cadena de bloques. + +Consulta [las métricas de Prometheus](configuration/prometheus-metrics) para entender qué métricas se exponen y cómo configurar la recopilación de métricas de Prometheus. + + +Se les debe prestar especial atención a las siguientes métricas: +- ***Tiempo de producción de bloques***: si el tiempo de producción de bloques es superior al normal, existe un potencial problema en la red +- ***Número de rondas de consenso***: si hay más de una ronda, hay un problema potencial en el conjunto de validadores en la red +- ***Número de pares***: si el número de pares disminuye, hay un problema de conectividad en la red + +## Seguridad {#security} + +A continuación se presentan las mejores prácticas para asegurar un nodo validador en funcionamiento de una red de Polygon Edge. + +### Servicios de API {#api-services} + +- ***JSON-RPC*** - +Únicamente el servicio de API que debe ser expuesto al público (mediante el equilibrador de carga o directamente) . +Esta API debe ejecutarse en todas las interfaces o en una dirección IP específica ( ejemplo: `--json-rpc 0.0.0.0:8545`o `--json-prc 192.168.1.1:8545`). +:::info + +Como esta es una API de cara al público, se recomienda tener un equilibrador de carga o un proxy inverso delante de ella para dar seguridad y limitación de tarifas. + +::: + + +- ***LibP2P*** +Esta es la API de interconexión utilizada por los nodos para la comunicación entre pares. Debe ejecutarse en todas las interfaces o en una dirección IP específica +( `--libp2p 0.0.0.0:1478`o `--libp2p 192.168.1.1:1478` ). Esta API no debe estar expuesta públicamente, +pero debe ser accesible desde todos los demás nodos. +:::info + +Si se ejecuta en un anfitrión local (`--libp2p 127.0.0.1:1478`) no se podrán conectar otros nodos. + +::: + + +- ***GRPC*** - +Esta API es utilizada sólo para ejecutar comandos de operador y nada más. Como tal, debe ejecutarse exclusivamente en un anfitrión local (`--grpc-address 127.0.0.1:9632`). + +### Secretos de Polygon Edge {#polygon-edge-secrets} + +Los secretos de Polygon Edge ( claves `ibft` y `libp2p` ) no se deben almacenar en un sistema de archivos local. En su lugar, se debe utilizar un [administrador de secretos](configuration/secret-managers/set-up-aws-ssm) compatible. +El almacenamiento de secretos en el sistema de archivos local solo debe utilizarse en entornos que no sean de producción. + +## Actualización {#update} + +A continuación se encuentra el procedimiento de actualización deseado para los nodos validadores, descrito como instrucciones paso a paso. + +### Procedimiento de actualización {#update-procedure} + +- Descarga el binario de Polygon Edge más reciente de las [publicaciones](https://github.com/0xPolygon/polygon-edge/releases) oficiales de GitHub +- Detén el servicio de Polygon Edge ( ejemplo: `sudo systemctl stop polygon-edge.service` ) +- Sustituye el binario `polygon-edge`existente por el descargado ( ejemplo: `sudo mv polygon-edge /usr/local/bin/` ) +- Revisa si la versión correcta de `polygon-edge`está en su lugar ejecutando `polygon-edge version`. Debe corresponder a la versión publicada más reciente +- Revisa la documentación de la versión si hay algún paso de compatibilidad con versiones anteriores que deba surtirse antes de iniciar el servicio `polygon-edge` +- Inicia el servicio `polygon-edge` ( ejemplo: `sudo systemctl start polygon-edge.service` ) +- Por último, comprobar, revisar la salida de registro de y`polygon-edge` asegúrarse de que todo está funcionando sin ningún r`[ERROR]`egistro + +:::warning + +Cuando hay un lanzamiento de ruptura, este procedimiento de actualización debe realizarse en todos los nodos como +el binario que actualmente se ejecuta compatible no es compatible con la nueva versión. + +Esto significa que la cadena debe detenerse durante un breve período de tiempo ( hasta que se sustituyan los `polygon-edge`binarios y se reinicie el servicio ) +así que planifica en forma apropiada. + +Puedes utilizar herramientas como **[Ansible](https://www.ansible.com/)** o un script personalizado para realizar la actualización de manera eficiente y minimizar el tiempo de inactividad en la cadena +::: + +## Procedimiento de inicio {#startup-procedure} + +A continuación se muestra el flujo deseado del procedimiento de inicio para el validador de Polygon Edge + +- Leer a través de documentos listados en sección [de Base de Knowlege](#knowledge-base) +- Aplicar los últimos parches del SO en el nodo validador +- Descargar el último binario `polygon-edge` desde el GitHub oficial -r[eleases ](https://github.com/0xPolygon/polygon-edge/releases)y colócalo en la instancia local `PATH` +- Inicializar uno de los [administradores](/docs/category/secret-managers) soportados -- el comando `polygon-edge secrets generate`CLI +- Generar y almacenar secretos usando [el comando CLI](/docs/edge/get-started/cli-commands#secrets-init-flags)`polygon-edge secrets init` +- Tome nota de los `Public key (address)`valores `NodeID`y +- Generar el archivo`genesis.json` como se describe en [la configuración de la nube](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators) utilizando`polygon-edge genesis` [el comando CLI](/docs/edge/get-started/cli-commands#genesis-flags) +- Generar el archivo de configuración por defecto utilizando [el comando CLI](/docs/edge/configuration/sample-config)`polygon-edge server export` +- Editar `default-config.yaml`archivo para acomodar el entorno de nodo validador (rutas de archivo, etc.) +- Crear un servicio Polygon Edge ( `systemd`o similar) donde `polygon-edge`binario ejecutará el servidor desde un archivo `default-config.yaml` +- Inicia el servidor Polygon Edge iniciando el servicio ( ejemplo: `systemctl start polygon-edge`) +- Comprueba la salida del registro de `polygon-edge`y asegúrate de que los bloques se están generando y que no hay registros `[ERROR]` +- Comprueba la funcionalidad de la cadena llamando a un método JSON-RPC como [`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid) diff --git a/archive/edge/es-edge/working-with-node/backup-restore.md b/archive/edge/es-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..d24f7c3834 --- /dev/null +++ b/archive/edge/es-edge/working-with-node/backup-restore.md @@ -0,0 +1,93 @@ +--- +id: backup-restore +title: Copia de seguridad o restauración de la instancia de nodo +description: "Cómo hacer una copia de seguridad y restaurar una instancia de nodo de Polygon Edge." +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## Descripción general {#overview} + +La presente guía explica cómo hacer una copia de seguridad y restaurar una instancia de nodo de Polygon Edge. +Abarca las carpetas básicas, lo que contienen y qué archivos son críticos para hacer una copia de seguridad y restauración correctamente. + +## Carpetas básicas {#base-folders} + +Polygon Edge utiliza LevelDB como motor de almacenamiento. +Al iniciar un nodo de Polygon Edge, se crean las siguientes subcarpetas en el directorio de trabajo especificado: +* **blockchain** (cadena de bloques): almacena los datos de la cadena de bloques +* **tree** (árbol): almacena los árboles de Merkle (datos del estado mundial) +* **keystore** (almacén de claves): guarda las claves privadas para el cliente Eso incluye la clave privada de libp2p y la clave privada de sellado y validación. +* **consensus** (consenso): almacena cualquier información de consenso que el cliente pueda necesitar mientras trabaja. Por ahora, almacena la *clave de validación privada* del nodo + +Es esencial conservar esas carpetas para que la instancia de Polygon Edge se ejecute sin problemas. + +## Creación de una copia de seguridad de un nodo en ejecución y restauración para un nuevo nodo {#create-backup-from-a-running-node-and-restore-for-new-node} + +Esta sección te guía en la creación de datos de archivo de la cadena de bloques en un nodo en ejecución y su restauración en otra instancia. + +### Copia de seguridad {#backup} + +El comando `backup` trae los bloques de un nodo en ejecución mediante gRPC y genera una carpeta de archivo. Si `--from` y `--to` no se dan en el comando, este comando traerá los bloques desde el de génesis hasta el más reciente. + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### Restauración {#restore} + +Un servidor importa los bloques de un archivo al principio cuando se inicia con la indicación `--restore`. Cerciórate de que el nuevo nodo tenga clave. Para obtener más información sobre la importación o la generación de claves, visita la seción [Administradores de secretos](/docs/edge/configuration/secret-managers/set-up-aws-ssm) + +```bash +$ polygon-edge server --restore archive.dat +``` + +## Copia de seguridad o restauración de datos completos {#back-up-restore-whole-data} + +Esta sección te guía para hacer una copia de seguridad de los datos, incluyendo los datos de estado y la clave y hacer la restauración en la nueva instancia. + +### Paso 1: detén el cliente en ejecución {#step-1-stop-the-running-client} + +Dado que Polygon Edge utiliza **LevelDB** para el almacenamiento de datos, el nodo debe detenerse durante la ejecución de la copia de seguridad, +ya que **LevelDB** no permite el acceso simultáneo a sus archivos de base de datos. + +Por otro lado, Polygon Edge también hace descarga de datos al cerrarse. + +El primer paso consiste en detener el cliente en ejecución (mediante un administrador de servicios o algún otro mecanismo que le envíe una señal SIGINT al proceso), +para que pueda desencadenar 2 eventos al mismo tiempo que se desconecta gradualmente: +* Ejecución de la descarga de datos en el disco +* Liberación de los archivos de la base de datos bloqueados por LevelDB + +### Paso 2: haz una copia de seguridad del directorio {#step-2-backup-the-directory} + +Ahora que el cliente no se está ejecutando, se puede hacer una copia de seguridad del directorio de datos en otro medio. +Hay que recordar que los archivos con extensión `.key` contienen los datos de la clave privada que se pueden utilizar para suplantar al nodo actual +y, por lo tanto, nunca deben compartirse con un tercero o desconocido. + +:::info + +Haz una copia de seguridad y restaura el archivo `genesis` generado manualmente, para que el nodo restaurado funcione plenamente. + +::: + +## Restauración {#restore-1} + +### Paso 1: detén el cliente en ejecución {#step-1-stop-the-running-client-1} + +Si se está ejecutando alguna instancia de Polygon Edge, hay que detenerla para que el paso 2 pueda cumplirse. + +### Paso 2: copia el directorio de datos de la copia de seguridad en la carpeta deseada {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +Cuando el cliente no esté en ejecución, el directorio de datos del que se ha hecho copia de seguridad puede copiarse en la carpeta deseada. +Además, restaura el archivo `genesis` previamente copiado. + +### Paso 3: ejecuta el cliente de Polygon Edge especificando el directorio de datos correcto {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +Para que Polygon Edge utilice el directorio de datos restaurado, en el momento del inicio, el usuario debe especificar la ruta del +directorio de datos. Consulta la sección de [Comandos CLI](/docs/edge/get-started/cli-commands) para obtener información sobre la indicación `data-dir` diff --git a/archive/edge/es-edge/working-with-node/query-json-rpc.md b/archive/edge/es-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..84ff27bd95 --- /dev/null +++ b/archive/edge/es-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,93 @@ +--- +id: query-json-rpc +title: Terminales de consulta llamadas a procedimiento remoto (RPC) JSON +description: "Consulta los datos e inicia la cadena con una cuenta preminada." +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## Descripción general {#overview} + +La capa de RPC JSON de Polygon Edge les ofrece a los desarrolladores la funcionalidad de interactuar fácilmente con la cadena de bloques, +mediante solicitudes HTTP. + +Este ejemplo abarca el uso de herramientas como **curl** para consultar información, al igual que para iniciar la cadena con una cuenta preminada +y enviar una transacción. + +## Paso 1: Crea un archivo de génesis con una cuenta preminada. {#step-1-create-a-genesis-file-with-a-premined-account} + +Para generar un archivo de genesis, ejecuta el siguiente comando: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +La indicación de **preminar** establece la dirección que se debe incluir con saldo inicial en el archivo de **genesis.**
+En ese caso, la dirección `0x1010101010101010101010101010101010101010` tendrá un **saldo inicial por defecto** de `0xD3C21BCECCEDA1000000` +(1 millón de tokens de moneda nativa). + +Si quisiéramos especificar un saldo, podemos separar el saldo y la dirección con `:`, así: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +El saldo puede ser un valor `hex` o `uint256`. + +:::warning ¡Solo premina cuentas de las cuales tienes una clave privada! + +Si preminas cuentas de las que no tienes clave privada de acceso, el saldo preminado no será utilizable. + +::: + +## Paso 2: Inicia Polygon Edge en modo desarrollador. {#step-2-start-the-polygon-edge-in-dev-mode} + +Para iniciar Polygon Edge en modo de desarrollador, lo cual se explica en la sección de [Comandos CLI](/docs/edge/get-started/cli-commands), +ejecuta lo siguiente: +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## Paso 3: Consulta el saldo de la cuenta. {#step-3-query-the-account-balance} + +Ahora que el cliente está activado y ejecutándose en modo desarrollador, con el archivo de génesis generado en el **paso 1**, podemos usar una herramienta como +**curl** para consultar el saldo de la cuenta: +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +El comando debería arrojar el siguiente resultado: +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## Paso 4: Envía una transacción de transferencia. {#step-4-send-a-transfer-transaction} + +Ahora que confirmamos que la cuenta que configuramos como preminada tiene el saldo correcto, podemos transferir algunos ethers: + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/es-edge/working-with-node/query-operator-info.md b/archive/edge/es-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..72785d5343 --- /dev/null +++ b/archive/edge/es-edge/working-with-node/query-operator-info.md @@ -0,0 +1,85 @@ +--- +id: query-operator-info +title: Consulta la información del operador +description: "Cómo consultar la información del operador" +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## Prerrequisitos {#prerequisites} + +Esta guía asume que has seguido la [configuración local](/docs/edge/get-started/set-up-ibft-locally) o la [guía sobre cómo configurar un grupo IBFT en la nube](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +Se necesita un nodo que funcione para poder consultar cualquier tipo de información del operador. + +Con Polygon Edge, los operadores de los nodos tienen el control y están informados de qué hace el nodo que están operando.
+En todo momento, pueden utilizar la capa de información del nodo, construida sobre gRPC, y obtener información significativa, sin necesidad de filtrar los registros. + +:::note + +Si tu nodo no se está ejecutando en `127.0.0.1:8545` deberías añadirle una marca `--grpc-address `a los comandos que aparecen en este documento. + +::: + +## Información del par {#peer-information} + +### Lista de pares {#peers-list} + +Para obtener una lista completa de los pares conectados (incluyendo el propio nodo en ejecución), ejecuta el siguiente comando: +````bash +polygon-edge peers list +```` + +Eso mostrará una lista de direcciones libp2p que actualmente son pares del cliente en ejecución. + +### Estado del par {#peer-status} + +Para conocer el estado de un par específico, ejecuta: +````bash +polygon-edge peers status --peer-id
+```` +Donde el parámetro *address* (Dirección) es la dirección libp2p del par. + +## Información sobre tolerancia a fallas bizantinas de Estambul (IBFT) {#ibft-info} + +En muchas ocasiones, puede que un operador quiera conocer el estado del nodo en operación en el consenso IBFT. + +Afortunadamente, Polygon Edge ofrece una manera fácil de encontrar esa información. + +### Fotos instantáneas {#snapshots} + +La ejecución del siguiente comando muestra la foto instantánea más reciente. +````bash +polygon-edge ibft snapshot +```` +Para consultar la instantánea a una altura determinada (número de bloque), el operador puede ejecutar: +````bash +polygon-edge ibft snapshot --num +```` + +### Candidatos {#candidates} + +Para obtener la información más reciente sobre los candidatos, el operador puede ejecutar: +````bash +polygon-edge ibft candidates +```` +Este comando consulta el conjunto actual de candidatos propuestos, además de los candidatos que aún no han sido incluidos. + +### Estado {#status} + +El siguiente comando arroja la clave del validador actual del cliente IBFT en ejecución: +````bash +polygon-edge ibft status +```` + +## Grupo de transacciones {#transaction-pool} + +Para conocer el número actual de transacciones en el grupo de transacciones, el operador puede ejecutar: +````bash +polygon-edge txpool status +```` diff --git a/archive/edge/fr-edge/additional-features/blockscout.md b/archive/edge/fr-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..c38f4b7dd9 --- /dev/null +++ b/archive/edge/fr-edge/additional-features/blockscout.md @@ -0,0 +1,386 @@ +--- +id: blockscout +title: Blockscout +description: Comment configurer une instance de Blockscout pour travailler avec l'Edge de Polygon. +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## Aperçu {#overview} +Ce guide explique en détail comment compiler et déployer l'instance Blockscout pour travailler avec Polygon-Edge. +Blockscout a sa propre [documentation](https://docs.blockscout.com/for-developers/manual-deployment), mais ce guide se concentre sur des instructions simples mais détaillées, étape par étape, sur comment configurer une instance Blockscout. + +## Environnement {#environment} +* Système d'Exploitation: Ubuntu Server 20.04 LTS [lien de téléchargement](https://releases.ubuntu.com/20.04/) avec les autorisations de sudo +* Matériel Serveur: 8CPU / 16Go de RAM / 50Go de disque dur (LVM) +* Serveur de base de données : Serveur dédié avec 2 CPU / 4 Go de RAM / 100 Go de SSD / PostgreSQL 13.4 + +### Serveur DB {#db-server} +L'exigence pour suivre ce guide est d'avoir un serveur de base de données prêt, une base de données et un utilisateur de base de données configurées. Ce guide n'entrera pas dans les détails sur comment déployer et configurer le serveur PostgreSQL. Il existe actuellement de nombreux guides pour le faire, par exemple [le Guide de DigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart) + +:::info CLAUSE DE NON-RESPONSABILITÉ +Ce guide est uniquement destiné à vous aider à faire fonctionner Blockscout sur une seule instance, ce qui n'est pas une configuration de production idéale. +Pour la production, vous souhaiterez probablement introduire un proxy inverse, un équilibreur de charge, des options d'évolutivité, etc. dans l'architecture. +::: + +# Procédure de Déploiement de Blockscout {#blockscout-deployment-procedure} + +## Partie 1 - installez les dépendances {#part-1-install-dependencies} +Avant de commencer, nous devons nous assurer que nous avons installé tous les binaires dont dépend Blockscout. + +### Mettez à jour et améliorez le système {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### Ajoutez le référentiel d'erlang {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### Ajoutez le référentiel NodeJS {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### Installez Rust {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### Installez la version requise d'Erlang {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### Installez la version requise d'Elixir {#install-required-version-of-elixir} +La version d'Elixir doit être `1.13`. Si nous essayons d'installer cette version à partir du référentiel officiel, la `erlang` sera mise à jour en `Erlang/OTP 25` et nous ne le voulons pas. +Pour cette raison, nous devons installer la `elixir` version précompilée spécifique à partir de la page des versions de GitHub. + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +Nous devons maintenant configurer correctement `exlixir` les binaires du système. +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +Vérifiez si `elixir` et `erlang` sont correctement installés en exécutant `elixir -v`. +Cela devrait être la sortie: +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning +`Erlang/OTP` doit être la version `24` et `Elixir` doit être la version `1.13.*`. Si ce n'est pas le cas, vous rencontrerez des problèmes lors de la compilation et/ou de l'exécution de Blockscout. +::: +:::info +Consultez la page officielle ***[des exigences Blockscout](https://docs.blockscout.com/for-developers/information-and-settings/requirements)*** +::: + +### Installez NodeJS {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### Installez Cargo {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### Installez d'autres dépendances {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### Installez facultativement le client postgresql pour vérifier votre connexion de base de données {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## Partie 2 - définissez les variables d'environnement {#part-2-set-environment-variables} +Nous devons définir les variables d'environnement avant de commencer la compilation Blockscout. Dans ce guide, nous ne définirons que le minimum de l'essentiel pour le faire fonctionner. La liste complète des variables pouvant être définies est disponible [ici](https://docs.blockscout.com/for-developers/information-and-settings/env-variables) + +### Définissez la connexion de base de données comme variable d'environnement {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +Testez maintenant votre connexion de base de données avec les paramètres fournis. Puisque vous avez fourni des variables d'environnement PG, vous devriez pouvoir vous connecter à la base de données seulement en exécutant: +```bash +psql +``` + +Si la base de données est configurée correctement, vous devriez voir une psql apparaître: +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +Sinon, vous pourriez voir une erreur comme celle-ci: +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +Si tel est le cas, [ces documents](https://ubuntu.com/server/docs/databases-postgresql) pourraient vous aider. + +:::info Connexion de la base de données +Assurez-vous d'avoir résolu tous les problèmes de connexion à la base de données avant de passer à la partie suivante. +Vous devrez fournir des privilèges de superutilisateur à l'utilisateur blockscout. +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## Partie 3 - clonez et compilez Blockscout {#part-3-clone-and-compile-blockscout} +Maintenant, nous pouvons enfin démarrer l'installation de Blockscout. + +### Clonez le référentiel de Blockscout {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### Générez une base de clés secrètes pour protéger la version de production {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +À la toute dernière ligne, vous devriez voir une longue chaîne de caractères aléatoires. +Cela devrait être défini comme votre `SECRET_KEY_BASE` variable d'environnement, avant l'étape suivante. +Par exemple: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### Définissez le mode de production {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### Compilez {#compile} +Cd dans le répertoire clone et commencez à compiler + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info + +Si vous avez déjà déployé, supprimez les actifs de ressources statiques de la production précédente de ***mix phx.digest.clean***. + +::: + +### Migrez les bases de données {#migrate-databases} +:::info +Cette partie échouera si vous n'avez pas configuré correctement votre connexion de base de données, si vous n'avez pas fourni, ou si vous avez défini de mauvais paramètres dans la variable d'environnement DATABASE_URL. L'utilisateur de la base de données doit disposer de privilèges de superutilisateur. +::: +```bash +mix do ecto.create, ecto.migrate +``` + +Si vous devez d'abord supprimer la base de données, exécutez +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### Installez les dépendances npm et compilez les premiers actifs {#install-npm-dependencies-and-compile-frontend-assets} +Vous devez changer de répertoire dans le dossier qui contient les actifs frontaux. + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info Soyez patient +La compilation de ces actifs peut prendre quelques minutes et n'affichera aucune sortie. Il peut sembler que le processus est bloqué, mais soyez patient. Lorsque le processus de compilation est terminé, il devrait afficher quelque chose comme: `webpack 5.69.1 compiled with 3 warnings in 104942 ms` + +::: + +### Créez des actifs statiques {#build-static-assets} +Pour cette étape, vous devez revenir à la racine de votre dossier clone Blockscout. +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### Générez des certificats auto-signés {#generate-self-signed-certificates} +:::info +Vous pouvez ignorer cette étape si vous n'avez pas besoin`https`. +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## Partie 4 - créez et exécutez le service Blockscout {#part-4-create-and-run-blockscout-service} +Dans cette partie, nous devons configurer un service de système car nous voulons que Blockscout s'exécute en arrière-plan et persiste après le redémarrage du système. + +### Créez un dossier de service {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### Modifiez le fichier de service {#edit-service-file} +Utilisez votre éditeur de texte Linux préféré pour modifier ce fichier et configurez le service. +```bash +sudo vi /etc/systemd/system/explorer.service +``` +Le contenu du fichier explorer.service devrait ressembler à ceci: +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### Activez le démarrage du service au démarrage du système {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### Déplacez votre dossier clone Blockscout vers un emplacement à l'échelle du système {#move-your-blockscout-clone-folder-to-system-wide-location} +Le service Blockscout doit avoir accès au dossier que vous avez cloné à partir du référentiel Blockscout et de tous les actifs compilés. +```bash +sudo mv ~/blockscout /usr/local +``` + +### Créez un fichier env vars qui sera utilisé par le service Blockscout {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info +Utiliser ce que `SECRET_KEY_BASE`vous avez généré dans la Partie 3. +:::Enregistrez le fichier et quittez. + +### Enfin, démarrez le service Blockscout {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## Partie 5 - testez la fonctionnalité de votre instance Blockscout {#part-5-test-out-the-functionality-of-your-blockscout-instance} +Il ne reste plus qu'à vérifier si le service Blockscout est en cours d'exécution. Vérifiez l'état du service avec: +```bash +sudo systemctl status explorer.service +``` + +Pour vérifier la sortie du service: +```bash +sudo journalctl -u explorer.service -f +``` + +Vous pouvez vérifier s'il y a de nouveaux ports d'écoute: +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +Vous devriez obtenir une liste de ports d'écoute et sur la liste, il devrait y avoir quelque chose comme ceci: +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +Le service Web Blockscout exécute le port et le protocole définis dans le fichier env. Dans cet exemple, il s'exécute sur `4000`(http). Si tout va bien, vous devriez pouvoir accéder au portail Web Blockscout avec `http://:4000` + +## Considérations {#considerations} +Pour de meilleures performances, il est conseillé d'avoir un nœud non validateur d'archive `polygon-edge`complète dédié/local qui sera utilisé exclusivement pour les requêtes Blockscout. L'`json-rpc`API de ce nœud n'a pas besoin d'être exposée publiquement, car Blockscout exécute toutes les requêtes à partir du dorsal. + + +## Réflexions finales {#final-thoughts} +Nous venons de déployer une seule instance Blockscout, qui fonctionne bien, mais pour la production, vous devriez envisager de placer cette instance derrière un proxy inverse comme Nginx. Vous devez également penser à l'évolutivité de la base de données et de l'instance, en fonction de votre cas d'utilisation. + +Vous devriez certainement consulter la documentation officielle [de Blockscout](https://docs.blockscout.com/) car il y a beaucoup d'options de personnalisation. \ No newline at end of file diff --git a/archive/edge/fr-edge/additional-features/chainbridge/definitions.md b/archive/edge/fr-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..62ebf2ec04 --- /dev/null +++ b/archive/edge/fr-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,221 @@ +--- +id: definitions +title: Définitions Générales +description: Définitions Générales des termes utilisés dans chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## Relais {#relayer} +Chainbridge est un pont de type relais. Le rôle d'un relais est de voter pour l'exécution d'une requête (combien de jetons il faut brûler/lancer, par exemple). +Cela surveille les événements de chaque chaîne et vote pour une proposition dans le contrat Bridge de la chaîne de destination lorsqu'il reçoit un `Deposit` événement d'une chaîne. Un relais appelle une méthode dans le contrat Bridge pour exécuter la proposition après que le nombre requis de votes a été soumis. Le pont délègue l'exécution au contrat Gestionnaire. + + +## Types de contrats {#types-of-contracts} +Dans ChainBridge, il existe trois types de contrats sur chaque chaîne, appelés Bridge/Handler/Target. + +| **Type** | **Description** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Contrat Bridge | Un contrat Bridge qui gère les requêtes, les votes, les exécutions doit être déployé dans chaque chaîne. Les utilisateurs appelleront `deposit` dans Bridge pour démarrer un transfert, et Bridge délègue le processus au contrat Gestionnaire correspondant au contrat Cible. Une fois que le contrat Gestionnaire a réussi à appeler le contrat Cible, le contrat Bridge émet un `Deposit` événement pour notifier les relais. | +| Contrat Gestionnaire | Ce contrat interagit avec le contrat Target pour exécuter un dépôt ou une proposition. Cela valide la demande de l'utilisateur, appelle le contrat Cible et aide avec certains paramètres du contrat Cible. Il existe certains contrats Gestionnaires pour appeler chaque contrat Cible qui a une interface différente. Les appels indirects émis par le contrat Gestionnaire font le pont pour permettre le transfert de tout type d'actifs ou des données. Actuellement, il existe trois types de contrats Gestionnaires mis en œuvre par ChainBridge: ERC20Handler, ERC721Handler et GenericHandler. | +| Contrat Cible | Un contrat qui gère les actifs à échanger ou les messages qui sont transférés entre les chaînes. L'interaction avec ce contrat se fera de chaque côté du pont. | + +
+ +![Architecture de ChainBridge](/img/edge/chainbridge/architecture.svg) +*Architecture de ChainBridge* + +
+ +
+ +![Flux de travail du transfert de jeton ERC20](/img/edge/chainbridge/erc20-workflow.svg) +*ex. Flux de travail d'un transfert de jeton ERC20* + +
+ +## Types de comptes {#types-of-accounts} + +Veuillez vous assurer que les comptes disposent de suffisamment de jetons natifs pour créer des transactions avant de commencer. Dans Edge de Polygon, vous pouvez attribuer des soldes prédéfinis aux comptes lors de la production du bloc de genèse. + +| **Type** | **Description** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Administrateur | Ce compte se verra attribuer le rôle d'administrateur par défaut. | +| Utilisateur | Le compte expéditeur/destinataire qui envoie/reçoit des actifs. Le compte de l'expéditeur paie les frais de gaz lors de l'approbation des transferts de jetons et de l'appel du dépôt dans le contrat Bridge pour commencer un transfert. | + +:::info Le rôle d'administrateur + +Certaines actions ne peuvent être effectuées que par le compte disposant du rôle administrateur. Par défaut, le déployeur du contrat Bridge dispose du rôle d'administrateur. Vous trouverez ci-dessous comment attribuer le rôle d'administrateur à un autre compte ou le supprimer. + +### Ajouter un rôle d'administrateur {#add-admin-role} + +Ajoute un administrateur + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### Révoquer le rôle d'administrateur {#revoke-admin-role} + +Supprime un administrateur + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## Les opérations qui sont autorisées par le `admin` compte sont les suivantes. {#account-are-as-below} + +### Définir La Ressource {#set-resource} + +Enregistrez un Identifiant de ressource avec une adresse de contrat pour un gestionnaire. + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Rendre le contrat brûlant/monétisé {#make-contract-burnable-mintable} + +Définissez un contrat de jeton comme monétisé/brûlant dans un gestionnaire. + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Annuler la proposition {#cancel-proposal} + +Annuler la proposition d'exécution + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### Pause/Reprendre {#pause-unpause} + +Arrêter temporairement les dépôts, la création de propositions, le vote et les exécutions de dépôt. + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### Modifier Les Frais {#change-fee} + +Modifier les frais qui seront payés au Contrat Bridge + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### Ajouter/Supprimer un relais {#add-remove-a-relayer} + +Ajouter un compte en tant que nouveau relais ou supprimer un compte des relais + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### Modifier le niveau du relais {#change-relayer-threshold} + +Modifier le nombre de votes requis pour l'exécution d'une proposition + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## Identifiant de la chaîne {#chain-id} + +Le Chainbridge `chainId` est une valeur arbitraire utilisée dans le pont pour différencier entre les réseaux de la blockchain, et cela doit être dans la plage d'uint8. À ne pas confondre avec l'Identifiant de la chaîne du réseau, ce n'est pas la même chose. Cette valeur doit être unique, mais elle ne doit pas nécessairement être identique à l'Identifiant du réseau. + +Dans cet exemple, nous avons défini `99` dans `chainId`, car l'Identifiant de la chaîne du testnet de Mumbai est `80001`, ce qui ne peut pas être représenté par un uint8. + +## Identifiant de la Ressource {#resource-id} + +Un Identifiant de la ressource est une valeur unique de 32 octets dans un environnement inter-chaînes, associée à un certain actif (ressource) qui est transféré entre les réseaux. + +L'Identifiant de ressource est arbitraire, mais, par convention, le dernier octet contient généralement l'Identifiant de chaîne de la chaîne source (le réseau d'où provient cet actif). + +## URL JSON-RPC pour PoS de Polygon {#json-rpc-url-for-polygon-pos} + +Pour ce guide, nous utiliserons https://rpc-mumbai.matic.today, un URL JSON-RPC publique fourni par Polygon, qui peut avoir des limites de trafic ou de prix. Cela sera utilisé seulement pour se connecter au testnet de Polygon Mumbai. Nous vous conseillons d'obtenir votre URL JSON-RPC par un service externe comme Infura, car le déploiement de contrats enverra de nombreuses questions/requêtes au JSON-RPC. + +## Des façons de traiter le transfert de jetons {#ways-of-processing-the-transfer-of-tokens} +Lors du transfert de jetons ERC20 entre les chaînes, ils peuvent être traités selon deux modes différents: + +### Le mode verrouillage/déclenchement {#lock-release-mode} +Chaîne source: Les jetons que vous envoyez seront verrouillés dans le Contrat Gestionnaire
+Chaîne de destination: Le même nombre de jetons que vous avez envoyés dans la chaîne source serait déverrouillé et transféré du contrat Gestionnaire vers le compte destinataire dans la chaîne de destination. + +### Mode brûler/frapper {#burn-mint-mode} +Chaîne source: Les jetons que vous envoyez seront brûlés.
+Chaîne de destination: La même quantité de jetons que vous avez envoyés et brûlés sur la chaîne source sera frappée sur la chaîne de destination et envoyée au compte destinataire. + +Vous pouvez utiliser différents modes sur chaque chaîne. Cela signifie que vous pouvez verrouiller un jeton dans la chaîne principale tout en créant un jeton dans la sous-chaîne pour le transfert. Par exemple, cela peut être judicieux de verrouiller/déclencher les jetons si l'approvisionnement total ou le calendrier d'émission est contrôlé. Les jetons seraient frappés/brûlés si le contrat dans la sous-chaîne devait suivre l'approvisionnement dans la chaîne principale. + +Le mode par défaut est le mode verrouillage/déclenchement. Si vous voulez rendre les Jetons monétisés/brûlés, vous devez appeler `adminSetBurnable` la méthode. Si vous souhaitez créer des jetons lors de l'exécution, vous devrez attribuer `minter` un rôle au contrat Gestionnaire de ERC20. + + diff --git a/archive/edge/fr-edge/additional-features/chainbridge/overview.md b/archive/edge/fr-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..8ba922c5e1 --- /dev/null +++ b/archive/edge/fr-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Aperçu +description: Aperçu de ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Qu'est-ce que ChainBridge? {#what-is-chainbridge} + +ChainBridge est un pont de blockchain multidirectionnel modulaire prenant en charge les chaînes compatibles EVM et Substrate, construit par ChainSafe. Cela permet aux utilisateurs de transférer toutes sortes d'actifs ou des messages entre deux chaînes différentes. + +Pour en savoir plus sur ChainBridge, veuillez d'abord consulter les [documents officiels](https://chainbridge.chainsafe.io/) fournis par ses développeurs. + +Ce guide est destiné à faciliter l'intégration de Chainbridge à Polygon Edge. Cela décrit la configuration d'un pont entre un PoS de Polygon en cours d'exécution (testnet de Mumbai) et un réseau Edge de Polygon local. + +## Exigences {#requirements} + +Dans ce guide, vous exécuterez des nœuds Edge de Polygon, un relais de ChainBridge (plus d'informations [ici](/docs/edge/additional-features/chainbridge/definitions)) et l'outil cb-sol-cli, qui est un outil CLI pour déployer des contrats localement, enregistrer des ressources et modifier les paramètres du pont (vous pouvez vérifier [cela](https://chainbridge.chainsafe.io/cli-options/#cli-options) aussi). Les environnements suivants sont requis avant de commencer l'installation: + +* Go: >= 1.17 +* Node.js >= 16.13.0 +* Git + + +De plus, vous devrez cloner les référentiels suivants avec les versions pour exécuter certaines applications. + +* [Edge de Polygon](https://github.com/0xPolygon/polygon-edge): sur le `develop` domaine +* [ChainBridge](https://github.com/ChainSafe/ChainBridge): v1.1.5 +* [Outils de Déploiement de ChainBridge](https://github.com/ChainSafe/chainbridge-deploy): `f2aa093` sur le `main`domaine + + +Vous devez configurer un réseau Edge de Polygon avant de passer à la section suivante. Veuillez vérifier la [Configuration Locale](/docs/edge/get-started/set-up-ibft-locally) ou la [Configuration Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) pour plus de détails. \ No newline at end of file diff --git a/archive/edge/fr-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/fr-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..24f5a21193 --- /dev/null +++ b/archive/edge/fr-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,142 @@ +--- +id: setup-erc20-transfer +title: Transfert de Jeton ERC20 +description: Comment configurer le transfert de ERC-20 dans chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Jusqu'à présent, nous avons mis en place un pont pour échanger des actifs/données entre le PoS de Polygon et la chaîne Edge de Polygon. Cette section vous guidera pour mettre en place un pont ERC20 et envoyer des jetons entre différentes blockchains. + +## Étape 1: Enregistrez l'Identifiant de la ressource {#step-1-register-resource-id} + +D'abord, vous enregistrerez un identifiant de ressource qui associe des ressources dans un environnement de chaîne croisée. Un Identifiant de Ressource est une valeur de 32 octets qui doit être unique pour la ressource que nous transférons entre ces blockchains. Les Identifiants de Ressource sont arbitraires, mais ils peuvent avoir l'Identifiant de chaîne de la chaîne d'accueil dans le dernier octet, comme une convention (chaîne d'accueil faisant référence au réseau d'où proviennent ces ressources). + +Pour enregistrer l'Identifiant de ressource, vous pouvez utiliser la `cb-sol-cli bridge register-resource` commande. Vous devrez donner la clé privée du `admin` compte. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (Facultatif) Rendez les contrats monétisés/brûlés {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## Étape 2: Transférez le Jeton ERC20 {#step-2-transfer-erc20-token} + +Nous enverrons des Jetons ERC20 de la chaîne PoS de Polygon à la chaîne Edge de Polygon. + +Tout d'abord, vous obtiendrez des jetons en les frappant. Un compte avec le `minter` rôle peut créer de nouveaux jetons. Le compte qui a déployé le contrat ERC20 possède le `minter` rôle par défaut. Pour spécifier d'autres comptes en tant que membres du `minter` rôle, vous devez exécuter la `cb-sol-cli erc20 add-minter` commande. + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +Pour vérifier le solde actuel, vous pouvez utiliser la `cb-sol-cli erc20 balance` commande. + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +Ensuite, vous devez approuver le transfert des jetons ERC20 depuis le compte par le Gestionnaire de ERC20 + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +Pour transférer des jetons vers des chaînes Edge de Polygon, vous appellerez `deposit`. + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Une fois que la transaction de dépôt a été réussie, le relais recevra l'événement et votera pour la proposition. Cela exécute une transaction pour envoyer des jetons au compte destinataire dans la chaîne Edge de Polygon après que le nombre de votes requis est soumis. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Une fois que la transaction d'exécution a été réussie, vous obtiendrez des jetons dans la chaîne Edge de Polygon. + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/fr-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/fr-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..76ee019173 --- /dev/null +++ b/archive/edge/fr-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,134 @@ +--- +id: setup-erc721-transfer +title: Transfert de NFT ERC721 +description: Comment configurer le transfert de ERC721 dans chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Cette section vous guide dans la configuration d'un pont ERC721 et l'envoi de NFT entre les réseaux de blockchain. + +## Étape 1: Enregistrez l'identifiant de la ressource {#step-1-register-resource-id} + +Vous devrez d'abord enregistrer l'identifiant de la ressource pour le jeton ERC721 dans les contrats de Bridge sur les deux chaînes. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (Facultatif): Rendez les contrats monétisés/brûlés {#optional-make-contracts-mintable-burnable} + +Pour rendre les jetons monétisés/brûlés, vous devrez appeler les commandes suivantes: + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## Étape 2: Transfert de NFT {#step-2-transfer-nft} + +Tout d'abord, vous frapperez un NFT si vous en avez besoin. + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Pour vérifier le propriétaire du NFT, vous pouvez utiliser `cb-sol-cli erc721 owner` + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Ensuite, vous approuverez un transfert de NFT par le Gestionnaire de ERC721 + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Enfin, vous commencerez le transfert + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +Le relais obtiendra l'événement et votera pour la proposition. Il exécute une transaction pour envoyer des NFT au compte destinataire dans la chaîne Edge de Polygon, après que le nombre de votes requis a été soumis. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Vous pouvez vérifier le propriétaire du NFT sur le réseau Edge de Polygon après que l'exécution est terminée. + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/fr-edge/additional-features/chainbridge/setup.md b/archive/edge/fr-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..e1b019a3c8 --- /dev/null +++ b/archive/edge/fr-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,197 @@ +--- +id: setup +title: Configuration +description: Comment configurer ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Déploiement des contrats {#contracts-deployment} + +Dans cette section, vous allez déployer les contrats requis sur la chaîne PoS de Polygon et Edge de Polygon avec `cb-sol-cli`. + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +Tout d'abord, nous allons déployer des contrats sur la chaîne PoS de Polygon par `cb-sol-cli deploy` commande. `--all` l'option oblige la commande à déployer tous les contrats, y compris Bridge, le Gestionnaire de ERC20, le Gestionnaire de ERC721, le Gestionnaire Générique, le contrat de ERC20 et ERC721. De plus, il définira l'adresse du compte de relais par défaut et le niveau + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +En savoir plus sur chainID et l'URL JSON-RPC [ici](/docs/edge/additional-features/chainbridge/definitions) + +:::caution + +Le prix du gaz par défaut dans `cb-sol-cli` est `20000000` (`0.02 Gwei`). Pour définir le prix du gaz approprié dans une transaction, veuillez définir la valeur en utilisant `--gasPrice` l'argument. + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +Le contrat de Bridge nécessite environ 0x3f97b8 (4167608) de gaz pour se déployer. Veuillez vous assurer que les blocs générés ont une limite de gaz de bloc suffisante pour contenir la transaction de création de contrat. Pour en savoir plus sur la modification de la limite de gaz de bloc dans Edge de Polygon, veuillez visiter la [Configuration Locale](/docs/edge/get-started/set-up-ibft-locally) + +::: + +Une fois que les contrats sont déployés, vous obtiendrez le résultat suivant: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +Nous pouvons maintenant déployer les contrats sur la chaîne de Edge de Polygon. + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Enregistrez les sorties du terminal avec les adresses du contrat intelligent déployées car nous en aurons besoin pour la prochaine étape. + +## Configuration du relais {#relayer-setup} + +Dans cette section, vous allez démarrer un relais pour échanger des données entre 2 chaînes. + +Tout d'abord, nous devons cloner et construire le référentiel de ChainBridge. + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +Ensuite, Vous devez créer `config.json` et définir les URL JSON-RPC, l'adresse du relais, et l'adresse des contrats pour chaque chaîne. + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +Pour démarrer un relais, vous devez importer la clé privée correspondant à l'adresse du compte de relais. Vous devrez saisir le mot de passe lorsque vous importerez la clé privée. Une fois que l'importation a été réussie, la clé sera stockée sous `keys/
.key`. + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +Ensuite, vous pouvez démarrer le relais. Vous devrez entrer le même mot de passe que vous avez choisi pour stocker la clé au début. + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +Une fois que le relais a commencé, il commencera à surveiller de nouveaux blocs sur chaque chaîne. diff --git a/archive/edge/fr-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/fr-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..6f2fa70103 --- /dev/null +++ b/archive/edge/fr-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,255 @@ +--- +id: use-case-erc20-bridge +title: Cas d'utilisation - Pont ERC20 +description: Exemple pour le contrat de pont ERC20 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +Cette section vise à vous donner un flux de configuration du Pont ERC20 pour un cas d'utilisation pratique. + +Dans ce guide, vous utiliserez le testnet Mumbai de Polygon PoS et la chaîne locale Edge de Polygon. Veuillez vous assurer que vous disposez d'un point de terminaison JSON-RPC pour Mumbai et que vous avez configuré Edge de Polygon dans un environnement local. Veuillez vous référer à la [Configuration locale](/docs/edge/get-started/set-up-ibft-locally) ou [Configuration Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) pour plus de détails. + +## Scénario {#scenario} + +Ce scénario consiste à configurer un pont pour le jeton ERC20 qui a déjà été déployé dans la chaîne publique (Polygon PoS) afin de permettre un transfert à faible coût dans une chaîne privée (Polygon Edge) pour les utilisateurs dans un cas normal. Dans un tel cas, l'offre totale de jeton a été définie dans la chaîne publique et seul le montant du jeton qui a été transféré de la chaîne publique à la chaîne privée doit exister dans la chaîne privée. Pour cette raison, vous devrez utiliser le mode verrouillage/libération dans la chaîne publique et le mode brûlé/frappé dans la chaîne privée. + +Lors de l'envoi des jetons de la chaîne publique vers la chaîne privée, le jeton sera verrouillé dans le contrat Gestionnaire ERC20 de la chaîne publique et la même quantité de jetons sera frappée dans la chaîne privée. En revanche, en cas de transfert de la chaîne privée vers la chaîne publique, le jeton dans la chaîne privée sera brûlé et la même quantité de jeton sera libérée du contrat Gestionnaire ERC20 dans la chaîne publique. + +## Contrats {#contracts} + +Expliquer avec un simple contrat ERC20 au lieu du contrat développé par ChainBridge. Pour le mode brûlé/frappé, le contrat ERC20 doit avoir `mint`et `burnFrom`des méthodes en plus des méthodes pour ERC20 comme celles-ci: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +Tous les codes et scripts sont dans le Référentiel Github [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Étape1: Déployez les contrats Gestionnaire Bridge et ERC20 {#step1-deploy-bridge-and-erc20-handler-contracts} + +Tout d'abord, vous allez déployer les contrats Bridge et ERC20Handler en utilisant `cb-sol-cli`dans les deux chaînes. + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Vous obtiendrez des adresses de contrat Bridge et ERC20Handler comme celle-ci: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Étape 2: Déployez votre contrat ERC20 {#step2-deploy-your-erc20-contract} + +Vous déploierez votre contrat ERC20. Cet exemple vous guide avec le projet de casque [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Veuillez créer `.env`le fichier et définissez les valeurs suivantes. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Ensuite, vous déploierez le contrat ERC20 dans les deux chaînes. + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +Une fois le déploiement réussi, vous obtiendrez une adresse de contrat comme celle-ci: + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## Étape 3: Enregistrrz l'Identifiant de ressource dans le Pont {#step3-register-resource-id-in-bridge} + +Vous enregistrerez un Identifiant de ressource qui associe une ressource dans un environnement inter-chaînes. Vous devez définir le même Identifiant de ressource dans les deux chaînes. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## Étape 4: Définissez le mode Frappé/Brûlé dans le pont ERC20 du Edge {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +Le Pont s'attend à fonctionner en mode brûlé/frappé dans l'Edge de Polygon. Vous réglerez le mode brûlé/frappé à l'aide de `cb-sol-cli`. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +Et vous devez accorder un rôle de frappeur et de brûleur au contrat Gestionnaire ERC20. + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Étape 5: Frappez le Jeton {#step5-mint-token} + +Vous frapperez de nouveaux jetons ERC20 dans la chaîne de Mumbai. + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +Une fois la transaction réussie, le compte aura le jeton frappé. + +## Étape 6: Démarrez le transfert ERC20 {#step6-start-erc20-transfer} + +Avant de commencer cette étape, veuillez vous assurer que vous avez démarré un relais. Veuillez vérifier [la configuration](/docs/edge/additional-features/chainbridge/setup) pour plus de détails. + +Lors du transfert de jetons de Mumbai vers Edge, le contrat Gestionnaire ERC20 à Mumbai retire les jetons de votre compte. Vous appellerez approuvé avant le transfert. + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +Enfin, vous commencerez le transfert de jetons de Mumbai vers Edge en utilisant `cb-sol-cli`. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Une fois la transaction de dépôt réussie, le relais recevra l'événement et votera pour la proposition. Il exécute une transaction pour envoyer des jetons au compte destinataire dans la chaîne Edge de Polygon une fois que le nombre de votes requis a été soumis. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Une fois la transaction d'exécution réussie, vous obtiendrez des jetons dans la chaîne Edge de Polygon. diff --git a/archive/edge/fr-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/fr-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..c683cdbdfa --- /dev/null +++ b/archive/edge/fr-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,308 @@ +--- +id: use-case-erc721-bridge +title: Cas d'utilisation - Pont ERC721 +description: Exemple pour combler le contrat ERC721 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +Cette section vise à vous donner un flux de configuration du Pont ERC721 pour un cas d'utilisation pratique. + +Dans ce guide, vous utiliserez le testnet de Mumbai Polygon PoS et la chaîne locale Polygon Edge. Veuillez vous assurer que vous disposez d'un point de terminaison JSON-RPC pour Mumbai et que vous avez configuré Edge de Polygon dans un environnement local. Veuillez vous référer à la [Configuration locale](/docs/edge/get-started/set-up-ibft-locally) ou [Configuration Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) pour plus de détails. + +## Scénario {#scenario} + +Ce scénario consiste à configurer un Pont pour le NFT ERC721 qui a déjà été déployé dans la chaîne publique (Polygon PoS) afin de permettre un transfert à faible coût dans une chaîne privée (Edge de Polygon) pour les utilisateurs dans un cas régulier. Dans un tel cas, les métadonnées d'origine ont été définies dans la chaîne publique et les seuls NFT qui ont été transférés de la chaîne Publique peuvent exister dans la chaîne privée. Pour cette raison, vous devrez utiliser le mode verrouillage/déclenchement dans la chaîne publique et le mode de brûlure/mint dans la chaîne privée. + +Lors de l'envoi des NFT de la chaîne publique vers la chaîne privée, le NFT sera verrouillé dans le contrat Gestionnaire de ERC721 dans la chaîne publique et le même NFT sera frappé dans la chaîne privée. En revanche, en cas de transfert de la chaîne privée vers la chaîne publique, le NFT dans la chaîne privée sera brûlé et le même NFT sera libéré du contrat Gestionnaire de ERC721 dans la chaîne publique. + +## Contrats {#contracts} + +Explication avec un simple contrat ERC721 au lieu du contrat développé par ChainBridge. Pour le mode brûlé/frappé, le contrat ERC721 doit avoir des méthodes `mint` et `burn` en plus des méthodes définies dans ERC721 comme ceci: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +Tous les codes et les scénarios sont dans le Référentiel Github [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Étape 1: Déployez les contrats Bridge et Gestionnaire de ERC721 {#step1-deploy-bridge-and-erc721-handler-contracts} + +Tout d'abord, vous allez déployer les contrats Bridge et Gestionnaire de ERC721 en utilisant `cb-sol-cli` dans les deux chaînes. + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Vous obtiendrez des adresses de contrat Bridge et Gestionnaire de ERC721 comme celle-ci: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Étape 2: Déployez votre contrat ERC721 {#step2-deploy-your-erc721-contract} + +Vous déploierez votre contrat ERC721. Cet exemple vous guide avec le projet de casque [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Veuillez créer `.env` un fichier et définir les valeurs suivantes. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Ensuite, vous déploierez le contrat ERC721 dans les deux chaînes. + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +Après le déploiement réussi, vous obtiendrez l'adresse de contrat comme celle-ci: + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## Étape 3: Enregistrez l'Identifiant de ressource dans Bridge {#step3-register-resource-id-in-bridge} + +Vous enregistrerez un Identifiant de ressource qui associe des ressources dans un environnement inter-chaînes. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## Étape 4: Définir le mode Frappé/Brûlé dans le pont ERC721 de Edge {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +Bridge s'attend à fonctionner en mode brûlé/frappé dans Edge. Vous définirez le mode brûlé/frappé. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +Et vous devez accorder un rôle de monétisation et de brûlure au contrat Gestionnaire de ERC721. + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Étape 5: Frapper le NFT {#step5-mint-nft} + +Vous frapperez le nouveau NFT ERC721 dans la chaîne de Mumbai. + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +Une fois la transaction réussie, le compte aura le NFT frappé. + +## Étape 6: Démarrer le transfert de ERC721 {#step6-start-erc721-transfer} + +Avant de démarrer cette étape, veuillez vous assurer que vous avez enclenché le relais. Veuillez vérifier la [Configuration](/docs/edge/additional-features/chainbridge/setup) pour plus de détails. + +Pendant le transfert de NFT de Mumbai vers Edge, le contrat Gestionnaire de ERC721 dans Mumbai retire le NFT de votre compte. Vous appellerez approuver avant le transfert. + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +Enfin, vous commencerez le transfert de NFT de Mumbai vers Edge. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +Après la transaction de dépôt réussie, le relais recevra l'événement et votera pour la proposition. +Cela exécute une transaction pour envoyer le NFT au compte destinataire dans la chaîne Edge de Polygon après que le nombre requis de votes a été soumis. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Une fois la transaction d'exécution réussie, vous obtiendrez des NFT dans la chaîne Edge de Polygon. diff --git a/archive/edge/fr-edge/additional-features/permission-contract-deployment.md b/archive/edge/fr-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..1bfd63055b --- /dev/null +++ b/archive/edge/fr-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,85 @@ +--- +id: permission-contract-deployment +title: Autorisation du déploiement de contrat intelligent +description: Comment ajouter une autorisation pour le déploiement de contrat intelligent. +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## Aperçu {#overview} + +Ce guide explique en détail comment ajouter à la liste blanche des adresses pouvant déployer des contrats intelligents. Parfois, les opérateurs de réseau souhaitent empêcher les utilisateurs de déployer des contrats intelligents qui ne sont pas liés à l'objectif du réseau. Les opérateurs de réseau peuvent: + +1. Ajoutez à la liste blanche des adresses pour le déploiement de Contrat Intelligent +2. Supprimez des adresses de la liste blanche pour le déploiement de Contrat Intelligent + +## Présentation vidéo {#video-presentation} + +[![déploiement de contrat de permission - vidéo](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## Comment l'utiliser? {#how-to-use-it} + + +Vous pouvez trouver toutes les commandes cli liées à la liste blanche de déploiement sur la page des [Commandes CLI](/docs/edge/get-started/cli-commands#whitelist-commands). + +* `whitelist show`: Affiche les informations de la liste blanche +* `whitelist deployment --add`: Ajoute une nouvelle adresse à la liste blanche de déploiement du contrat +* `whitelist deployment --remove`: Supprime une nouvelle adresse de la liste blanche de déploiement du contrat + +#### Affichez toutes les adresses dans la liste blanche de déploiement {#show-all-addresses-in-the-deployment-whitelist} + +Il existe 2 façons de trouver des adresses à partir de la liste blanche de déploiement. +1. En regardant le `genesis.json` où les listes blanches sont enregistrées +2. Exécution `whitelist show`, ce qui imprime des informations pour toutes les listes blanches prises en charge par Edge de Polygon + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### Ajoutez une adresse à la liste blanche de déploiement {#add-an-address-to-the-deployment-whitelist} + +Pour ajouter une nouvelle adresse à la liste blanche de déploiement, exécutez la `whitelist deployment --add [ADDRESS]` commande CLI. Il n'y a pas de limite au nombre d'adresses présentes dans la liste blanche. Seules les adresses qui existent dans la liste blanche de déploiement de contrats peuvent déployer des contrats. Si la liste blanche est vide, n'importe quelle adresse peut effectuer le déploiement + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### Supprimez une adresse de la liste blanche de déploiement {#remove-an-address-from-the-deployment-whitelist} + +Pour supprimer une adresse de la liste blanche de déploiement, exécutez la `whitelist deployment --remove [ADDRESS]` commande CLI. Seules les adresses qui existent dans la liste blanche de déploiement de contrats peuvent déployer des contrats. Si la liste blanche est vide, n'importe quelle adresse peut effectuer le déploiement + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/fr-edge/architecture/modules/blockchain.md b/archive/edge/fr-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..53129d14ae --- /dev/null +++ b/archive/edge/fr-edge/architecture/modules/blockchain.md @@ -0,0 +1,158 @@ +--- +id: blockchain +title: Blockchain +description: Explication des modules de blockchain et d'état de Edge de Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## Aperçu {#overview} + +L'un des principaux modules de Polygon Edge sont **Blockchain** et **État**.
+ +**Blockchain** est la centrale électrique qui s'occupe des réorganisations de bloc. Cela signifie qu'il traite de toute la logique qui se produit lorsqu'un nouveau bloc est inclus dans la blockchain. + +**State** représente l'objet de *transition d'état*. Il traite de la façon dont l'état change lorsqu'un nouveau bloc est inclus.
**L'État** gère entre autres: +* Exécution des transactions +* Exécution de l'EVM +* Modification des essais de Merkle +* Beaucoup plus, qui est couvert dans la section **d'État** correspondante 🙂 + +La clé à retenir est que ces 2 parties sont très liées et qu'elles travaillent en étroite collaboration pour que le client fonctionne.
Par exemple, lorsque la couche de **Blockchain** reçoit un nouveau bloc (et qu'aucune réorganisation n'a eu lieu), elle appelle **l'État** pour effectuer une transition d'état. + +**Blockchain** doit également gérer certaines parties relatives au consensus (par exemple, *est-ce que ethHash est correct?*, *est-ce que ce PoW est correct?*).
En une phrase, **c'est le noyau principal de la logique à travers lequel tous les blocs sont inclus**. + +## *WriteBlocks* + +L'une des parties les plus importantes relatives à la couche de **Blockchain** est la méthode de *WriteBlocks*: + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +La méthode de *WriteBlocks* est le point d'entrée pour écrire des blocs dans blockchain. En tant que paramètre, cela prend un ensemble de blocs.
Dans un premier temps, les blocs sont validés. Après cela, ils sont écrits dans la chaîne. + +La *transition d'état* actuelle est effectuée en appelant la méthode *processBlock* dans *WriteBlocks*. + +Il convient de mentionner que, comme c'est le point d'entrée pour écrire des blocs dans la blockchain, d'autres modules (tels que le **Sealer**) utilisent cette méthode. + +## Abonnements sur Blockchain {#blockchain-subscriptions} + +Il doit y avoir un moyen de surveiller les changements liés à la blockchain.
C'est là que **Les Abonnements** entrent en jeu. + +Les Abonnements sont un moyen d'exploiter les flux d'événements de la blockchain et de recevoir instantanément des données significatives. + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +Les **Événements de Blockchain** contiennent des informations sur les modifications apportées à la chaîne actuelle. Cela inclut les réorganisations, ainsi que les nouveaux blocs: + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip Mis à Jour + +Vous souvenez vous que nous avons mentionné la commande ***monitor*** dans les [Commandes CLI](/docs/edge/get-started/cli-commands)? + +Les Événements de la Blockchain sont les événements originaux qui se produisent dans un Edge de Polygon, et ils sont ensuite cartographiés à un format de message Protocole de Protections pour un transfert facile. + +::: \ No newline at end of file diff --git a/archive/edge/fr-edge/architecture/modules/consensus.md b/archive/edge/fr-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..3cbbec47d3 --- /dev/null +++ b/archive/edge/fr-edge/architecture/modules/consensus.md @@ -0,0 +1,508 @@ +--- +id: consensus +title: Consensus +description: Explication du module de consensus de Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## Aperçu {#overview} + +Le module **Consensus** fournit une interface pour les mécanismes de consensus. + +Actuellement, les moteurs de consensus suivants sont disponibles: +* **IBFT PoA** +* **IBFT PoS** + +Le Polygon Edge veut maintenir un état de modularité et de connectivité.
+C'est la raison pour laquelle la logique de consensus de base a été rendue abstraite, de sorte que de nouveaux mécanismes de consensus peuvent être construits par-dessus, sans +compromettre l'utilité et la facilité d'utilisation. + + +## Interface du Consensus {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + +L'interface du ***Consensus*** est le noyau de l'abstraction mentionnée.
+* La méthode **VerifyHeader** représente une fonction d'aide que la couche du consensus expose à la couche de **blockchain** +Cela est présent pour gérer la vérification de l'en-tête +* La méthode de **Démarrage** lance simplement le processus de consensus, et tout ce qui y est associé. Cela inclut la synchronisation, +la fermeture, et tout ce qui doit être fait +* La méthode de **Fermeture** ferme la connexion du consensus + +## Configuration du Consensus {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +Il peut arriver que vous souhaitiez transmettre un emplacement personnalisé pour que le protocole de consensus stocke les données, ou peut-être + une carte clé de valeur personnalisée que vous voulez que le mécanisme de consensus utilise. Cela peut être réalisé par la structure de la ***Configuration***, +qui est lu lorsqu'un nouveau consensus est créé. + +## IBFT {#ibft} + +### ExtraData {#extradata} + +L'objet d'en-tête de la blockchain comporte, entre autres, un champ appelé **ExtraData**. + +L'IBFT utilise ce champ supplémentaire pour stocker des informations opérationnelles concernant le bloc, répondant ainsi à des questions comme celles-ci: +* "Qui a signé ce bloc?" +* "Qui sont les validateurs pour ce bloc?" + +Ces champs supplémentaires pour IBFT sont définis comme suit: +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### Des Données De Signature {#signing-data} + +Pour que le nœud puisse signer les informations dans IBFT, il utilise la méthode *signHash*: +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +Une autre méthode notable est la méthode *VerifyCommittedField*, qui vérifie que les sceaux validés proviennent des bons validateurs: +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### Photographie {#snapshots} + +Les photographies, comme leur nom l'indique, sont là pour fournir une *prise de photo*, ou *l'état* d'un système à n'importe quelle hauteur de bloc (nombre). + +Les photographies contiennent un ensemble de nœuds qui sont des validateurs, ainsi que des informations sur les votes (les validateurs peuvent voter pour d'autres validateurs). + Les validateurs incluent les informations de vote dans l'en-tête **Miner** et modifient la valeur du **nonce**: +* Le nonce est **tous les 1** si le noeud veut supprimer un validateur +* Nonce est **tous les 0** si le nœud veut ajouter un validateur + +Les photographies sont calculés à l'aide de la méthode ***processHeaders***: + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +Cette méthode est généralement appelée avec 1 en-tête, mais le flux est le même avec plusieurs en-têtes
. +Pour chaque en-tête transmis, IBFT doit vérifier que le proposant de l'en-tête est le validateur. Cela peut être fait facilement en saisissant la dernière photographie, et en vérifiant si le nœud se trouve dans l'ensemble de validateur. + +Ensuite, le nonce est vérifié. Le vote est inclus et compté - et s'il y a suffisamment de votes, un nœud est ajouté/supprimé de l'ensemble de validateur, après quoi la nouvelle photographie est enregistrée. + +#### Une Réserve De Photographie {#snapshot-store} + +Le service de photographie gère et met à jour une entité appelée **snapshotStore**, qui réserve la liste de toutes les photographies disponibles. +En l'utilisant, le service est capable de déterminer rapidement quelle photographie est associée à une hauteur de bloc déterminé. +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### Initialisation d'IBFT {#ibft-startup} + +Pour démarrer IBFT, le Polygon Edge doit d'abord configurer le transport IBFT: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +Cela crée essentiellement un nouveau sujet avec le proto IBFT, avec un nouveau message de protection de proto.
+Les messages sont destinés à être utilisés par les validateurs. Le Polygon Edge s'abonne ensuite au sujet et gère les messages en conséquence. + +#### MessageReq {#messagereq} + +Le message échangé par les validateurs: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +Le champ **View** dans **MessageReq** représente la position actuelle du nœud à l'intérieur de la chaîne. +Il a un attribut en *série* et un attribut de *séquence*. +* **série** représente le proposant de série pour la hauteur +* La **séquence** représente la hauteur de la blockchain + +Le fichier *msgQueue* déposé dans l'implémentation IBFT a pour but de stocker les demandes de message. Cela ordonne les messages par la *Vue* (d'abord par séquence, puis par série). L'implémentation IBFT possède également différentes files d'attente pour différents états dans le système. + +### Les États d'IBFT {#ibft-states} + +Une fois que le mécanisme de consensus est lancé à l'aide de la méthode **Start**, il s'exécute dans une boucle infinie qui simule une machine d'état: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### SyncState {#syncstate} + +Tous les nœuds démarrent initialement dans l'état **Sync**. + +En effet, de nouvelles données doivent être extraites de la blockchain. Le client doit savoir s'il s'agit du validateur, de trouver la photographie actuelle. Cet état résout tous les blocs en attente. + +Après que la synchronisation est terminée et que le client détermine qu'il s'agit bien d'un validateur, il doit être transféré vers **AcceptState**. +Si le client n'est **pas** un validateur, il continuera la synchronisation et restera dans **SyncState** + +#### AcceptState {#acceptstate} + +L'état d'**Accept** vérifie toujours la photographie et l'ensemble de validateur. Si le nœud actuel n'est pas dans l'ensemble des validateurs, +il revient à l'état de **Synchronisation**. + +En revanche, si le nœud **est** un validateur, il calcule le proposant. Il paraît que le nœud actuel est le proposant, il construit un bloc et envoie des préparations puis des messages de préparation. + +* Préparer les messages - les messages envoyés par les proposants aux validateurs, pour les informer sur la proposition +* Préparer les messages - les messages où les validateurs s'accordent sur une proposition. Tous les nœuds reçoivent tous les messages de préparation +* Les messages d'Engagement - les messages contenant des informations de validation pour la proposition + +Si le nœud actuel **n'est pas** un validateur, il utilise la méthode *getNextMessage* pour lire un message de la file d'attente affichée précédemment.
+Il attend les messages de préparation. Une fois que c'est confirmé que tout est correct, le nœud passe à l'état **Valider**. + +#### ValidateState {#validatestate} + +L'état **Valider** est plutôt simple - tous les nœuds dans cet état sont de lire les messages et de les ajouter à leur état de photographie locale. diff --git a/archive/edge/fr-edge/architecture/modules/json-rpc.md b/archive/edge/fr-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..0dba315a49 --- /dev/null +++ b/archive/edge/fr-edge/architecture/modules/json-rpc.md @@ -0,0 +1,175 @@ +--- +id: json-rpc +title: JSON RPC +description: Explication pour le module JSON RPC de Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## Aperçu {#overview} + +Le module **JSON RPC** implémente la **couche API JSON RPC**, ce truc que les développeurs d'App utilisent pour interagir avec blockchain. + +Cela inclut la prise en charge des **[points de terminaison json-rpc](https://eth.wiki/json-rpc/API)** standard, ainsi que du websocket points de terminaison. + +## Interface de Blockchain {#blockchain-interface} + +Polygon Edge utilise ***l'interface de blockchain*** pour définir toutes les méthodes que le module JSON RPC doit utiliser, dans commander pour livrer les points de terminaison. + +L'interface de blockchain est implémentée par le serveur **[Minimal](/docs/edge/architecture/modules/minimal)**. C'est la mise en oeuvre de base qui est passée dans la couche JSON RPC. + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## Les Points de Terminaison ETH {#eth-endpoints} + +Tous les points de terminaison JSON RPC standard sont implémentés dans: + +````bash +jsonrpc/eth_endpoint.go +```` + +## Gestionnaire de Filtre {#filter-manager} + +Le **Gestionnaire de Filtre** est un service qui s'exécute à côté du serveur JSON RPC. + +Cela fournit un support pour filtrer les blocs sur la blockchain.
Plus précisément, cela inclut à la fois un **journal** et un **bloc** de filtre de niveau. + +Le Gestionnaire de Filtre s'appuie fortement sur les Événements d'Abonnement, mentionnés dans La section de [Blockchain](blockchain#blockchain-subscriptions) + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +Les événements du Gestionnaire de Filtre sont envoyés dans la méthode *Exécuter* : + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## 📜 Ressources {#resources} +* **[Ethereum JSON-RPC](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/fr-edge/architecture/modules/minimal.md b/archive/edge/fr-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..6cbeeb0b8c --- /dev/null +++ b/archive/edge/fr-edge/architecture/modules/minimal.md @@ -0,0 +1,118 @@ +--- +id: minimal +title: Minimal +description: Explication du module minimal de Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## Aperçu {#overview} + +Comme mentionné précédemment, Polygon Edge est un ensemble de différents modules, tous connectés les uns aux autres.
La **Blockchain** est connectée à **l'État**, ou par exemple à la **Synchronisation**, qui dirige de nouveaux blocs vers la **Blockchain**. + +**Minimal** est la pierre angulaire de ces modules interconnectés.
+Il agit comme un hub central pour tous les services exécutés sur Polygon Edge. + +## La Magie de l'Initialisation {#startup-magic} + +Entre autres, Minimal est responsable pour: +* La configuration des répertoires de données +* La création d'un magasin de clés pour la communication libp2p +* La création de stockage +* La configuration d'un consensus +* La configuration de l'objet de blockchain avec GRPC, JSON RPC et la Synchronisation + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/fr-edge/architecture/modules/networking.md b/archive/edge/fr-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..b2ee45e4c3 --- /dev/null +++ b/archive/edge/fr-edge/architecture/modules/networking.md @@ -0,0 +1,80 @@ +--- +id: networking +title: Mise en réseau +description: Explication du module de mise en réseau de l'Edge de Polygon. +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## Aperçu {#overview} + +Un nœud doit communiquer avec d'autres nœuds du réseau, afin d'échanger des informations utiles.
+Pour accomplir cette tâche, l'Edge de Polygon s'appuie sur la structure **libp2p** testé au combat. + +Le choix d'aller avec **libp2p** est principalement axé sur les critères suivants : +* **Vitesse** - libp2p dispose d'une amélioration significative de performance par rapport à devp2p (utilisé dans GETH et d'autres clients) +* **Extensibilité** - il sert de base idéale pour d'autres fonctionnalités du système +* **Modularité** - libp2p est modulaire par nature, tout comme l'Edge de Polygon. Cela accorde une plus grande flexibilité, en particulier lorsque des parties de Polygon Edge doivent être interchangeables + +## GRPC {#grpc} + +En plus de **libp2p**, l'Edge de Polygon utilise le **protocole** GRPC.
+Techniquement, l'Edge de Polygon utilise plusieurs protocoles GRPC, qui seront abordés plus tard. + +La couche GRPC permet d'abstraire tous les protocoles de demande/réponse et simplifie les protocoles de diffusion nécessaires au fonctionnement de Polygon Edge. + +GRPC s'appuie sur **Protocol Buffers** pour définir les *services* et les *structures de message*.
+Les services et les structures sont définis dans des fichiers *.proto*, qui sont compilés et indépendants de la langue. + +Nous venoms de mentionner que Polygon Edge exploite plusieurs protocoles GRPC.
+Cela a été fait pour booster l'UX globale de l'opérateur du nœud, ce qui est souvent en retard avec des clients comme GETH et Parity. + +L'opérateur du nœud a une meilleure vue d'ensemble de ce qui se passe avec le système en appelant le service GRPC, au lieu de parcourir les registres pour trouver les informations qu'ils recherchent. + +### GRPC pour les Opérateurs de Nœud {#grpc-for-node-operators} + +La section suivante peut sembler familière, car elle a été brièvement abordée dans la section [Commandes CLI](/docs/edge/get-started/cli-commands). + +Le service GRPC destiné à être utilisé par les **opérateurs de nœuds** est défini ainsi : +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip + +Les commandes CLI appellent en fait les implémentations de ces méthodes de service. + +Ces méthodes sont implémentées dans ***minimal/system_service.go***. + +::: + +### GRPC pour les Autres Nœuds {#grpc-for-other-nodes} + +Polygon Edge implémente également plusieurs méthodes de service utilisées par d'autres nœuds du réseau.
+Le service mentionné est décrit dans la section **[Protocole](docs/edge/architecture/modules/consensus)**. + +## 📜 Ressources {#resources} +* **[Protocol Buffers](https://developers.google.com/protocol-buffers)** +* **[libp2p](https://libp2p.io/)** +* **[gRPC](https://grpc.io/)** diff --git a/archive/edge/fr-edge/architecture/modules/other-modules.md b/archive/edge/fr-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..1e9996c342 --- /dev/null +++ b/archive/edge/fr-edge/architecture/modules/other-modules.md @@ -0,0 +1,36 @@ +--- +id: other-modules +title: Autres modules +description: Explication pour les quelques modules de Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## Crypto {#crypto} + +Le module **Crypto** contient des fonctions d'utilitaires de crypto. + +## Chaîne {#chain} + +Le module **Chaîne** contient les paramètres de la chaîne (registres actifs, moteur de consensus, etc.) + +* **chaînes** - Configurations de chaînes prédéfinies (mainnet, goerli, ibft) + +## Assistant {#helper} + +Le module **Assistant** contient des packages d'assistance. + +* **Dao** - Utilitaires Dao +* **Enode** - Fonction d'encodage/décodage d'Enode +* **hex** - Fonctions d'encodage/décodage hex +* **ipc** - Fonction de connexion IPC +* **keccak** - Fonctions Keccak +* **rlputil** - Fonction d'aide à l'encodage/décodage Rlp + +## Commande {#command} + +Le module **Commande** contient des interfaces pour les commandes CLI. \ No newline at end of file diff --git a/archive/edge/fr-edge/architecture/modules/sealer.md b/archive/edge/fr-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..ccfd126e04 --- /dev/null +++ b/archive/edge/fr-edge/architecture/modules/sealer.md @@ -0,0 +1,70 @@ +--- +id: sealer +title: Scellant +description: Explication pour le module Scellant de Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## Aperçu {#overview} + +Le **Scellant** est une entité qui rassemble les transactions et crée un nouveau bloc.
Ensuite, bloc est envoyé au module **de consensus** pour le sceller. + +La logique de scellage finale est située dans le module **de consensus**. + +## Exécutez la Méthode {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution Travail en cours +Les **modules**et les **consensus** Scellants seront regroupés en une seule entité dans un futur proche. + +Le nouveau module intégrera une logique modulaire pour différents types de mécanismes de consensus, qui nécessitent différentes implémentations de scellage : +* **PoS** (Preuve d'Enjeu) +* **PoA** (Preuve d'Autorité) + +Actuellement, le **Scellant** et le **Consensus **fonctionnent avec PoW (Preuve de Travail). +::: \ No newline at end of file diff --git a/archive/edge/fr-edge/architecture/modules/state.md b/archive/edge/fr-edge/architecture/modules/state.md new file mode 100644 index 0000000000..8d75574483 --- /dev/null +++ b/archive/edge/fr-edge/architecture/modules/state.md @@ -0,0 +1,244 @@ +--- +id: state +title: État +description: Explication du module d'état de Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +Pour vraiment comprendre comment fonctionne l'**État**, vous devez comprendre certains concepts de base d'Ethereum.
+ +Nous vous recommandons vivement de lire le **[guide d'État dans Éthereum](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)**. + +## Aperçu {#overview} + +Maintenant que nous nous sommes familiarisés avec les concepts de base d'Ethereum, le prochain aperçu devrait être facile. + +Nous avons mentionné que le **World state trie** comprend tous les comptes Ethereum qui existent.
+Ces comptes sont les feuilles du trie de Merkle. Chaque feuille contient des informations codées sur **l'État du Compte**. + +Cela permet à Polygon Edge d'obtenir un trie de Merkle spécifique, pour un moment précis.
Par exemple, nous pouvons obtenir l'identifiant de l'état au bloc 10. + +Le trie de Merkle, à tout moment, est appelé une ***Photographie***. + +Nous pouvons avoir des ***photographies*** pour le **trie d'état** ou pour le **trie de stockage** - ils sont fondamentalement les mêmes.
+La seule différence est au niveau de ce que représentent les feuilles: + +* Dans le cas du trie de stockage, les feuilles contiennent un état arbitraire, que nous ne pouvons pas traiter ou savoir ce qui se trouve à l'intérieur +* Dans le cas de l'état trie, les feuilles représentent des comptes + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + +L'interface de la **Photographie** est définie comme suit: + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +Les informations pouvant être validées sont définies par la *structure de l'Objet*: + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +L'implémentation du trie de Merkle se trouve dans le dossier *state/immutable-trie*.
+*state/immutable-trie/state.go* implémente l'interface **d'État**. + +*state/immutable-trie/trie.go* est le principal objet du trie de Merkle. Il représente une version optimisée du trie de Merkle, +qui réutilise autant de mémoire que possible. + +## Exécuteur {#executor} + +*state/executor.go* inclut toutes les informations nécessaires pour que Polygon Edge décide comment un bloc modifie l'état actuel. L'implémentation de *ProcessBlock* se trouve ici. + +La méthode *apply* effectue la transition de l'état actuel. L'exécuteur appelle l'EVM. + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## Exécution {#runtime} + +Lorsqu'une transition d'état est exécutée, le module principal qui exécute la transition d'état est l'EVM (situé dans state/runtime/evm). + +La **table de répartition** fait une correspondance entre le **opcode** et l'instruction. + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +La logique de base qui alimente l'EVM est la boucle *Run*.
+ +C'est le point d'entrée principal de l'EVM. Il crée une boucle et vérifie l'opcode courant, récupère l'instruction, vérifie si elle peut être exécutée, consomme du gaz et exécute l'instruction jusqu'à ce qu'elle échoue ou s'arrête. + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/fr-edge/architecture/modules/storage.md b/archive/edge/fr-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..8d6dd8b6d5 --- /dev/null +++ b/archive/edge/fr-edge/architecture/modules/storage.md @@ -0,0 +1,117 @@ +--- +id: storage +title: Stockage +description: Explication pour le module de stockage de Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## Aperçu {#overview} + +Polygon Edge utilise actuellement **LevelDB** données stockage ainsi qu'un magasin données **en mémoire**. + +Tout au long du Polygon Edge quand les modules doivent interagir avec le stockage données sous-jacent, ils n'ont pas besoin de savoir à quel moteur DB ou service ils parlent. + +La couche DB est abstraite entre un module appelé **Stockage**, qui exporte des interfaces que les modules interrogent. + +Chaque couche de base de données, pour l'instant uniquement avec **LevelDB**, implémente ces méthodes séparément, en s'assurant qu'elles s'intègrent à leur implémentation. + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### Préfixes {#prefixes} + +Afin de rendre l'interrogation du stockage LevelDB déterministe, et d'éviter les conflits de stockage des clés, le Polygon Edge exploite les éléments suivants + les préfixes et les sous-préfixes lors du stockage des données + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## Plans Futurs {#future-plans} + +Dans un avenir proche, il est prévu d'ajouter certaines des solutions les plus populaires de DB, telles que: +* PostgreSQL +* MySQL + + +## 📜 Ressources {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/fr-edge/architecture/modules/syncer.md b/archive/edge/fr-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..3ce20a3103 --- /dev/null +++ b/archive/edge/fr-edge/architecture/modules/syncer.md @@ -0,0 +1,68 @@ +--- +id: syncer +title: Synchronisation +description: Explication du module de synchronisation de l'Edge de Polygon. +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## Aperçu {#overview} + +Ce module contient la logique du protocole de synchronisation. Il est utilisé pour synchroniser un nouveau nœud avec le réseau en cours, ou pour valider/insérer de nouveaux blocs pour les nœuds qui ne participent pas au consensus (non-validateurs). + +L'Edge de Polygon utilise **libp2p** comme couche de réseau, et en plus de cela démarre **gRPC**. + +L'Edge de Polygon comporte essentiellement 2 types de synchronisation: +* Synchronisation en masse  -  synchroniser un grand nombre de blocs à la fois +* Vérifier la Synchronisation - sous la base de synchronisation par bloc. + +### Synchronisation en Masse {#bulk-sync} + +Les étapes de la synchronisation en masse sont assez simples pour répondre à l'objectif de la synchronisation en masse, à savoir synchroniser autant de blocs (disponibles) que possible de l'autre pair pour compenser le retard, aussi rapidement que possible. + +Voici le flux du processus de Synchronisation en Masse: + +1. ** Déterminer si le nœud a besoin de Synchronisation en Masse ** - Dans cette étape, le nœud vérifie la carte des paires pour voir si quelqu'un possède un numéro de bloc plus grand que celui que le nœud possède localement +2. ** Trouver le meilleur pair (à l'aide de la carte des pairs de synchronisation) ** - Au cours de cette étape, le nœud trouve le meilleur pair avec lequel se synchroniser en fonction des critères mentionnés dans l'exemple ci-dessus. +3. ** Ouvrir un flux de synchronisation en masse ** - Au cours de cette étape, le nœud ouvre un flux gRPC au meilleur pair afin de synchroniser en masse les blocs à partir du numéro de bloc commun. +4. ** Le meilleur pair ferme le flux lorsqu'il a terminé l'envoi massif ** - Dans cette étape, le meilleur pair avec lequel le nœud est synchronisé fermera le flux dès qu'il aura envoyé tous les blocs disponibles qu'il détient +5. ** Lorsque la synchronisation en masse est terminée, vérifiez que le nœud est un validateur ** - Dans cette étape, le flux est fermé par le meilleur pair, et le nœud doit vérifier s'il est un validateur après la synchronisation en masse. + * S'ils le sont, ils sortent de l'état de synchronisation et commencent à participer au consensus + * S'ils ne le sont pas, ils continuent à ** Vérifier la Synchronisation ** + +### Vérifier la Synchronisation {#watch-sync} + +:::info + +L'étape de Vérifier la Synchronisation est exécutée uniquement si le nœud n'est pas un validateur, mais plutôt un nœud non validateur ordinaire dans le réseau qui ne fait que détecter les blocs qui arrivent. + +::: + +Le comportement de Vérifier la Synchronisation est assez simple, le nœud est déjà synchronisé avec le reste du réseau et a seulement besoin d'analyser les nouveaux blocs qui arrivent. + +Voici le déroulement du processus de Vérifier la Synchronisation: + +1. ** Ajoutez un nouveau bloc lorsque l'état d'un pair est mis à jour ** - Dans cette étape, les nœuds détectent les événements de nouveaux blocs. Lorsqu'ils ont un nouveau bloc, ils exécutent un appel de fonction gRPC, obtiennent le bloc et mettent à jour l'état local. +2. ** Vérifiez si le nœud est un validateur après avoir synchronisé le dernier bloc ** + * Si c'est le cas, il faut sortir de l'état de synchronisation + * Si ce n'est pas le cas, il faut continuer à détecter les nouveaux événements du bloc + +## Rapport sur la perfomance {#perfomance-report} + +:::info + +Les performances ont été mesurées sur une machine locale en synchronisant un ** million de blocs ** + +::: + +| Nom | Résultat | +|----------------------|----------------| +| Synchroniser 1M de blocs | ~ 25 min | +| Transférer 1M de blocs | ~ 1 min | +| Nombre d'appels GRPC | 2 | +| Capacité de test | ~ 93 % | \ No newline at end of file diff --git a/archive/edge/fr-edge/architecture/modules/txpool.md b/archive/edge/fr-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..bf97ef7673 --- /dev/null +++ b/archive/edge/fr-edge/architecture/modules/txpool.md @@ -0,0 +1,223 @@ +--- +id: txpool +title: TxPool +description: Explication du module TxPool de Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## Aperçu {#overview} + +Le module TxPool représente l'implémentation du pool de transactions, où les transactions sont ajoutées à partir de différentes parties du système. Le module expose également plusieurs fonctionnalités utiles pour les opérateurs de nœuds, qui sont décrites ci-dessous. + +## Les Commandes De L'Opérateur {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +Les opérateurs de nœud peuvent interroger ces points de terminaison GRPC, comme décrit dans la section des **[Commandes CLI](/docs/edge/get-started/cli-commands#transaction-pool-commands)**. + +## Traitement des Transactions {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +La méthode ***addImpl*** est la compatibilité du module de **TxPool**. C'est l'endroit central où les transactions sont ajoutées dans le système, étant appelées depuis le service GRPC, les points de terminaison JSON RPC, et chaque fois que le client reçoit une transaction via le protocole **gossip**. + +Cela prend comme argument le **ctx**, ce qui indique simplement le contexte à partir duquel les transactions sont ajoutées (GRPC, JSON RPC...).
L'autre paramètre est la liste des transactions à ajouter au pool. + +L'élément clé à noter ici est la vérification du champ **De** dans la transaction: +* Si le champ **De** est **vide**, il est considéré comme une transaction non chiffrée/non signée. Ces types de transactions ne sont qu' acceptées en mode de développement +* Si le champ **De** n'est **pas vide**, cela signifie qu'il s'agit d'une transaction signée, donc la vérification de la signature a lieu + +Après toutes ces validations, les transactions sont considérées comme valides. + +## Les Structures Des Données {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +Les champs de l'objet TxPool qui peuvent prêter à confusion sont la **file d'attente** et les listes **triées**. +* **file d'attente** - La grande implémentation d'une liste triée des transactions de compte (par nonce) +* **trié** - La liste triée de toutes les transactions promues en cours (toutes les transactions exécutables). Trié par le prix de gaz + +## Gestion des erreurs de la limite de gaz {#gas-limit-error-management} + +Chaque fois que vous soumettez une transaction, elle peut être traitée par le TxPool de trois manières. + +1. Toutes les transactions en attente peuvent contenir dans un bloc +2. Une ou plusieurs transactions en attente ne peuvent pas contenir dans un bloc +3. Une ou plusieurs transactions en attente ne contiendront jamais dans un bloc + +Ici, le mot **_fit_** signifie que la transaction a une limite de gaz inférieure au gaz restant dans le TxPool. + +Le premier scénario ne produit aucune erreur. + +### Deuxième scénario {#second-scenario} + +- Le gaz restant du TxPool est réglé sur la limite de gaz du dernier bloc, disons **5000** +- Une première transaction est traitée et consomme **3000** gaz du TxPool + - Le gaz restant du TxPool est maintenant de **2000** +- Une deuxième transaction, identique à la première et consommant toutes les deux 3000 unités de gaz, est soumise +- Le gaz restant du TxPool étant **inférieur** au gaz de transaction, elle ne peut pas être traitée dans le bloc actuel + - Cela est remise dans une file d'attente de transactions en attente afin qu'elle puisse être traitée dans le bloc suivant +- Le premier bloc est écrit, appelons-le **bloc n°1** +- Le gaz restant du TxPool est défini sur le bloc parent - la limite de gaz du **bloc n°1** +- La transaction qui a été remise dans la file d'attente des transactions en attente du TxPool est maintenant traitée et écrite dans le bloc + - Le gaz restant du TxPool est maintenant de **2000** +- Le deuxième bloc est écrit +- ... + +![Le Scénario d'erreur n°1 du TxPool](/img/edge/txpool-error-1.png) + +### Troisième scénario {#third-scenario} +- Le gaz restant du TxPool est réglé sur la limite de gaz du dernier bloc, disons **5000** +- Une première transaction est traitée et consomme **3000** gaz du TxPool + - Le gaz restant du TxPool est maintenant de **2000** +- Une deuxième transaction, avec un champ de gaz défini sur **6000** est soumise +- Étant donné que la limite de gaz du bloc est **inférieure** au gaz de transaction, cette transaction est rejetée + - Elle ne pourra jamais contenir dans un bloc +- Le premier bloc est écrit +- ... + + +![Le Scénario d'erreur n°2 du TxPool](/img/edge/txpool-error-2.png) + +> Cela se produit chaque fois que vous obtenez l'erreur suivante: +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## Cible de Gaz du Bloc {#block-gas-target} + +Il y a des situations où les nœuds veulent maintenir la limite de gaz de bloc en dessous ou à une certaine cible sur une chaîne en cours d'exécution. + +L'opérateur du nœud peut définir la limite de gaz cible sur un nœud spécifique, qui tentera d'appliquer cette limite aux blocs nouvellement créés. Si la majorité des autres nœuds ont également une limite de gaz cible similaire (ou identique), alors la limite de gaz du bloc passera toujours autour de cette cible de gaz du bloc, progressant lentement vers elle (au max `1/1024 * parent block gas limit`) à mesure que de nouveaux blocs sont créés. + +### Exemple de scénario {#example-scenario} + +* L'opérateur de nœud définit la limite de gaz du bloc pour qu'un seul nœud soit `5000` +* D'autres nœuds sont également configurés pour être `5000`, à l'exception d'un seul nœud qui est configuré pour être `7000` +* Lorsque les nœuds qui ont leur cible de gaz définie sur `5000` deviennent des proposants, ils vérifieront si la limite de gaz est déjà à la cible +* Si la limite de gaz n'est pas à la cible (elle est supérieure/inférieure), le nœud proposant définira la cible de gaz du bloc au maximum (1/1024 * limite de gaz parent) dans la direction de la cible + 1. Ex: `parentGasLimit = 4500` et `blockGasTarget = 5000`, le proposant calculera la limite de gaz pour le nouveau bloc comme `4504.39453125` (`4500/1024 + 4500`) + 2. Ex: `parentGasLimit = 5500` et `blockGasTarget = 5000`, le proposant calculera la limite de gaz pour le nouveau bloc comme `5494.62890625` (`5500 - 5500/1024`) +* Cela garantit que la limite de gaz du bloc dans la chaîne sera maintenue à la cible, car le seul proposant dont la cible est configurée sur `7000` ne peut pas avancer la limite énormément, et la majorité +des nœuds dont la cible est définie sur `5000` essaieront toujours de la conserver \ No newline at end of file diff --git a/archive/edge/fr-edge/architecture/modules/types.md b/archive/edge/fr-edge/architecture/modules/types.md new file mode 100644 index 0000000000..a54c48f7cf --- /dev/null +++ b/archive/edge/fr-edge/architecture/modules/types.md @@ -0,0 +1,43 @@ +--- +id: types +title: Types +description: Explication pour le module de types de Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## Aperçu {#overview} + +Le module **Types** implémente des types d'objet de base, tels que: + +* **Adresse** +* **Identifiant** +* **En-tête** +* beaucoup de fonctions d'aide + +## Encodage / Décodage RLP {#rlp-encoding-decoding} + +Contrairement aux clients tels que GETH, le Polygon Edge n'utilise pas la réflexion pour l'encodage.
+ Nous avons préféré ne pas utiliser la réflexion, car celle-ci introduit de nouveaux problèmes, tels que la détérioration + des performances, et une mise à l'échelle plus difficile. + +Le module **Types** offre une interface facile à utiliser pour la sérialisation et la désérialisation de RLP, en utilisant l'ensemble de FastRLP. + +La sérialisation est effectuée au moyen des méthodes *MarshalRLPWith* et *MarshalRLPTo*. Les méthodes analogues existent pour + la désérialisation. + +En définissant manuellement ces méthodes, le Polygon Edge n'a pas besoin d'utiliser la réflexion. Dans *rlp_marshal.go*, vous pouvez trouver + des méthodes de sérialisation: + +* **Corps** +* **Blocs** +* **En-têtes** +* **Reçus** +* **Registres** +* **Transactions** \ No newline at end of file diff --git a/archive/edge/fr-edge/architecture/overview.md b/archive/edge/fr-edge/architecture/overview.md new file mode 100644 index 0000000000..5c67251b86 --- /dev/null +++ b/archive/edge/fr-edge/architecture/overview.md @@ -0,0 +1,59 @@ +--- +id: overview +title: Présentation De L'Architecture +sidebar_label: Overview +description: Introduction à l'architecture de Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +Nous avons commencé avec l'idée de créer des logiciels *modulaires*. + +C'est un élément qui est présent dans presque toutes les composantes de Polygon Edge. Vous trouverez ci-dessous un bref aperçu de l'architecture développée et de sa stratification. + +## Stratification de Polygon Edge {#polygon-edge-layering} + +![Architecture de Polygon Edge](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +Tout commence au niveau de la couche du réseau de base, qui utilise **libp2p**. Nous avons opté pour cette technologie parce qu'elle correspond à la philosophie de conception de Polygon Edge. Libp2p est: + +- Modulaire +- Extensible +- Rapide + +Plus important encore, ce système constitue une excellente base pour des fonctionnalités plus avancées, que nous aborderons plus en avant. + + +## Synchronisation et Consensus {#synchronization-consensus} +La séparation des protocoles de synchronisation et de consensus permet la modularité et la mise en œuvre de mécanismes de synchronisation et de consensus **personnalisés**, en fonction de la façon dont le client est exécuté. + +Polygon Edge est conçu pour proposer des algorithmes de consensus prêts à l'emploi. + +La liste actuelle des algorithmes de consensus supportés: + +* IBFT PoA +* IBFT PoS + +## Blockchain {#blockchain} +La couche de Blockchain est la couche centrale qui coordonne tout dans le système de Polygon Edge. Elle est abordée en profondeur dans la section *Modules* correspondante. + +## État {#state} +La couche d'État interne contient la logique de transition d'état. Elle gère la façon dont l'état change lorsqu'un nouveau bloc est inclus. Elle est abordée en profondeur dans la section *Modules* correspondante. + +## JSON RPC {#json-rpc} +La couche JSON RPC est une couche d'API que les développeurs de dApps utilisent pour interagir avec la blockchain. Elle est abordée en profondeur dans la section *Modules* correspondante. + +## TxPool {#txpool} +La couche TxPool représente le pool de transactions, elle est étroitement liée aux autres modules du système car les transactions peuvent être introduites à partir de plusieurs points d'entrée. + +## grpc {#grpc} +gRPC, ou Google Remote Procedure Call, est un cadre open-source robuste RPC créé initialement pour construire des API évolutives et rapides. La couche GRPC est essentielle pour les interactions avec les opérateurs. Grâce à cette dernière, les opérateurs de nœuds peuvent facilement interagir avec le client, offrant ainsi une expérience utilisateur agréable. diff --git a/archive/edge/fr-edge/community/propose-new-feature.md b/archive/edge/fr-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..8279fce612 --- /dev/null +++ b/archive/edge/fr-edge/community/propose-new-feature.md @@ -0,0 +1,59 @@ +--- +id: propose-new-feature +title: Proposer une nouvelle fonctionnalité +description: "Un modèle de PR et des instructions pour proposer une nouvelle fonctionnalité." +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## Aperçu {#overview} + +Si vous souhaitez inclure un correctif ou simplement contribuer au code, nous vous encourageons vivement à contacter d'abord l'équipe.
Polygon Edge utilise un modèle de proposition de fonctionnalités relativement basique, concis et précis. + +## Modèle de PR {#pr-template} + +### Description {#description} + +Veuillez fournir une description détaillée de ce qui a été fait dans ce PR + +### Les modifications incluent les éléments suivants {#changes-include} + +- [ ] Bugfix (changement ininterrompu qui résout un problème) +- [ ] Hotfix (modification qui résout un problème urgent et nécessite une attention immédiate) +- [ ] Nouvelle fonctionnalité (changement ininterrompu qui ajoute des fonctionnalités) +- [ ] Changement avec rupture (changement qui n'est pas rétrocompatible et/ou modifie la fonctionnalité actuelle) + +### Les changements avec rupture {#breaking-changes} + +Veuillez terminer cette section si des changments importants ont été apportés, sinon supprimez-la + +### Liste De Contrôle {#checklist} + +- [ ] Je me suis attribué ce PR +- [ ] J'ai ajouté au moins 1 avis +- [ ] J'ai ajouté les étiquettes pertinentes +- [ ] J'ai mis à jour la documentation officielle +- [ ] J'ai ajouté suffisamment de documentation dans le code + +### Tests {#testing} + +- [ ] J'ai testé ce code avec la suite de tests officielle +- [ ] J'ai testé ce code manuellement + +## Tests manuels {#manual-tests} + +Veuillez terminer cette section si vous avez effectué des tests manuels pour cette fonctionnalité, sinon supprimez-la + +### Mise à jour de la documentation {#documentation-update} + +Veuillez lier le PR de mise à jour de la documentation dans cette section s'il est présent, sinon supprimez-le + +### Commentaires supplémentaires {#additional-comments} + +Veuillez poster des commentaires supplémentaires dans cette section si vous en avez, sinon supprimez-la \ No newline at end of file diff --git a/archive/edge/fr-edge/community/report-bug.md b/archive/edge/fr-edge/community/report-bug.md new file mode 100644 index 0000000000..dcaf2d4261 --- /dev/null +++ b/archive/edge/fr-edge/community/report-bug.md @@ -0,0 +1,55 @@ +--- +id: report-bug +title: Signaler un problème +description: Un modèle et des instructions pour signaler un problème avec Polygon Edge. +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## Aperçu {#overview} + +Parfois, des défaillances se produisent.
+ Il est préférable de faire part à l'équipe de tout problème que vous pourriez rencontrer.
+ Sur la page GitHub de Polygon Edge, vous pouvez soumettre un nouveau problème et commencer à en discuter avec l'équipe. + +## Modèle De Problème {#issue-template} + +## [Objet du problème] + +### Description {#description} + +Décrivez votre problème de la manière la plus détaillée possible ici + +### Votre environnement {#your-environment} + +* Le Système d'Exploitation et la version +* version de Polygon Edge +* branche qui provoque ce problème + +### Étapes pour reproduire {#steps-to-reproduce} + +* Dites-nous comment reproduire ce problème
+* Où est le problème, si vous le savez
+* Quelles commandes ont déclenché ce problème, le cas échéant + +### Comportement Prévu {#expected-behaviour} + +Dites-nous ce qui devrait se produire + +### Comportement réel {#actual-behaviour} + +Dites-nous ce qui se passe plutôt + +### Registres {#logs} + +Veuillez coller ici les journaux qui illustrent le problème, s'ils existent + +### une solution Proposée {#proposed-solution} + +Si vous avez une idée sur la façon de résoudre ce problème, veuillez l'écrire ici, afin que nous puissions commencer à en discuter \ No newline at end of file diff --git a/archive/edge/fr-edge/configuration/manage-private-keys.md b/archive/edge/fr-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..35a5f6f160 --- /dev/null +++ b/archive/edge/fr-edge/configuration/manage-private-keys.md @@ -0,0 +1,72 @@ +--- +id: manage-private-keys +title: Gérer les clés privées +description: "Comment gérer les clés privées et quels types de clés existent." +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## Aperçu {#overview} + +Polygon Edge dispose de deux types de clés privées qu'il gère directement: + +* **Clé privée utilisée pour le mécanisme de consensus** +* **Clé privée utilisée pour la mise en réseau par libp2p** +* **(Facultatif) Clé Privée de BLS utilisée pour le mécanisme de consensus afin d'agréger les signatures des validateurs** + +Actuellement, Polygon Edge n'offre pas de prise en charge de la gestion directe des comptes. + +Sur la base de la structure de répertoire décrite dans le [guide de Sauvegarde et de Restauration](/docs/edge/working-with-node/backup-restore), Polygon Edge stocke ces fichiers de clés mentionnés dans deux répertoires distincts - **consensus** et **keystore**. + +## Format de clé {#key-format} + +Les clés privées sont stockées au **format Base64** simple, elles peuvent donc être lisibles par l'homme et portables. + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info Type de Clé + +Tous les fichiers de clé privée générés et utilisés à l'intérieur de Polygon Edge reposent sur ECDSA avec la courbe [secp256k1](https://en.bitcoin.it/wiki/Secp256k1). + +Comme la courbe n'est pas standard, elle ne peut être encodée et stockée dans aucun format PEM standardisé. L'importation de clés non conformes à ce type de clé n'est pas prise en charge. +::: +## La Clé Privée du Consensus {#consensus-private-key} + +Le fichier de clé privée mentionné comme la *clé privée du consensus* est également la **clé privée du validateur**. Cette clé privée est utilisée lorsque le nœud agit en tant que validateur dans le réseau et doit signer de nouvelles données. + +Le fichier de clé privée se trouve dans `consensus/validator.key`, et respecte le [format de clé](/docs/edge/configuration/manage-private-keys#key-format) mentionné. + +:::warning + +La clé privée du validateur est unique pour chaque nœud de validateur. La même clé ne doit pas être partagée entre tous les validateurs, car cela pourrait compromettre la sécurité de votre chaîne. +::: + +## La Clé Privée De Mise En Réseau {#networking-private-key} + +Le fichier de clé privée mentionné pour la mise en réseau est utilisé par libp2p pour générer le PeerID correspondant, et cela permet au nœud de participer au réseau. + +Il se trouve dans `keystore/libp2p.key`, et respecte le [format de clé](/docs/edge/configuration/manage-private-keys#key-format) mentionné. + +## Clé Secrète De BLS {#bls-secret-key} + +Le fichier de clé secrète de BLS est utilisé pour agréger les sceaux validés dans la couche du consensus. La taille des sceaux validés agrégés par BLS est inférieure à celle des signatures ECDSA validées sérialisées. + +La fonction BLS est facultative et il est possible de choisir d'utiliser BLS ou non. Référez-vous à [BLS](/docs/edge/consensus/bls) pour plus de détails. + +## Importer / Exporter {#import-export} + +Comme les fichiers de clé sont stockés au format Base64 simple sur disque, ils peuvent être facilement sauvegardés ou importés. + +:::caution Modification des fichiers de clé + +Tout type de modification apportée aux fichiers de clés sur un réseau déjà configuré / en cours d'exécution peut entraîner de graves perturbations du réseau/consensus, étant donné que les mécanismes de consensus et de découverte par les pairs stockent les données dérivées de ces clés dans un stockage spécifique au nœud et s'appuient sur ces données pour initier des connexions et exécuter une logique de consensus + +::: \ No newline at end of file diff --git a/archive/edge/fr-edge/configuration/prometheus-metrics.md b/archive/edge/fr-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..dc4c5de58a --- /dev/null +++ b/archive/edge/fr-edge/configuration/prometheus-metrics.md @@ -0,0 +1,34 @@ +--- +id: prometheus-metrics +title: Les métriques Prometheus +description: "Comment activer les métriques Prometheus pour Polygon Edge." +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## Aperçu {#overview} + +Polygon Edge peut signaler et servir les métriques Prometheus, qui à leur tour peuvent être consommées en utilisant des collecteurs Prometheus. + +Les métriques Prometheus sont désactivées par défaut. Il peut être activé en spécifiant l'adresse de l'écouteur en utilisant un `--prometheus`indicateur ou `Telemetry.prometheus`un champ dans le fichier de configuration. Les métriques seront diffusées sur `/metrics` à l'adresse indiquée. + +## Les métriques disponibles {#available-metrics} + +Les métriques suivantes sont disponibles: + +| **Nom** | **Type** | **Description** | +|-----------------------------------------------|---------------|-------------------------------------------------| +| txpool_pending_transactions | Évaluer | Nombre de transactions en attente dans TxPool | +| consensus_validators | Évaluer | Nombre de Validateurs | +| consensus_rounds | Évaluer | Nombre de Tours | +| consensus_num_txs | Évaluer | Nombre de Transactions dans le dernier bloc | +| consensus_block_interval | Évaluer | Temps entre ce bloc et le dernier en secondes | +| network_peers | Évaluer | Nombre de pairs Connectés | +| network_outbound_connections_count | Évaluer | Nombre de connexions sortantes | +| network_inbound_connections_count | Évaluer | Nombre de connexions entrantes | +| network_pending_outbound_connections_count | Évaluer | Nombre de connexions sortantes en attente | +| network_pending_inbound_connections_count | Évaluer | Nombre de connexions entrantes en attente | \ No newline at end of file diff --git a/archive/edge/fr-edge/configuration/sample-config.md b/archive/edge/fr-edge/configuration/sample-config.md new file mode 100644 index 0000000000..d7d6f1fac7 --- /dev/null +++ b/archive/edge/fr-edge/configuration/sample-config.md @@ -0,0 +1,150 @@ +--- +id: sample-config +title: Fichier de Configuration du Serveur +description: "Démarrez le serveur de Polygon Edge à l'aide d'un fichier de configuration." +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# Fichier de configuration du serveur {#server-configuration-file} +Le démarrage du serveur avec diverses options de configuration peut être effectué à l'aide d'un fichier de configuration au lieu d'utiliser uniquement des indicateurs. La commande utilisée pour démarrer le serveur avec un fichier de configuration : `polygon-edge server --config ` + +## Exportez le fichier de configuration avec la configuration par défaut {#export-config-file-with-default-configuration} +La configuration avec les paramètres par défaut du serveur de Polygon Edge peut être exportée dans un fichier de configuration en n'importe quelle `yaml`ou `json`format de fichier. +Ce fichier peut être utilisé comme modèle pour exécuter le serveur à l'aide d'un fichier de configuration. + +### YAML {#yaml} +Pour générer le fichier de configuration au format `yaml` : +```bash +polygon-edge server export --type yaml +``` +ou simplement +```bash +polygon-edge server export +``` +le fichier de configuration nommé `default-config.yaml` sera créé dans le même répertoire que celui à partir duquel cette commande a été exécutée. + +Exemple de fichier: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +Pour générer le fichier de configuration au format `json` : +```bash +polygon-edge server export --type json +``` +le fichier de configuration nommé `default-config.json` sera créé dans le même répertoire que celui à partir duquel cette commande a été exécutée. + +Exemple de fichier: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +Consultez la section [Commandes CLI](/docs/edge/get-started/cli-commands) pour obtenir des informations sur l'utilisation de ces paramètres. + +### Schéma Typescript {#typescript-schema} + +Voici un exemple de format pour le fichier de configuration. Il est écrit en TypeScript pour exprimer les types de propriétés (`string`, `number`, `boolean`), vous pouvez en dériver votre configuration. Il convient de mentionner que le type `type-fest` de `PartialDeep` est utilisé pour exprimer que toutes les propriétés sont facultatives. + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/fr-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/fr-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..fc203d8711 --- /dev/null +++ b/archive/edge/fr-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,132 @@ +--- +id: set-up-aws-ssm +title: Configuration d’AWS SSM (Systems Manager) +description: "Configuration d’AWS SSM (Systems Manager) pour Polygon Edge." +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## Aperçu {#overview} + +Actuellement, Polygon Edge se préoccupe de garder 2 secrets d'exécution majeurs: +* La **clé privée du validateur** utilisée par le nœud, si le nœud est un validateur +* La **clé privée de mise en réseau** utilisée par libp2p, pour participer et communiquer avec d'autres pairs + +Pour plus d'informations, veuillez lire le [Guide de Gestion des Clés Privées](/docs/edge/configuration/manage-private-keys) + +Les modules du Polygon Edge **ne devraient pas avoir besoin de savoir garder des secrets**. En fin de compte, un module ne devrait pas se soucier du fait qu'un secret soit stocké sur un serveur distant ou localement sur le disque du nœud. + +Tout ce qu'un module doit savoir sur la conservation des secrets, c'est **savoir utiliser le secret**, **savoir quels secrets obtenir +ou enregistrer**. Les détails d'implémentation les plus fins de ces opérations sont délégués au `SecretsManager`, ce qui est bien sûr une abstraction. + +L'opérateur du nœud qui démarre le Polygon Edge peut désormais spécifier le gestionnaire des secrets qu'il souhaite utiliser, et dès que le bon gestionnaire de secrets est instancié, les modules traitent les secrets via l'interface mentionnée - sans se soucier de savoir si les secrets sont stockés sur un disque ou sur un serveur. + +Cet article détaille les étapes nécessaires afin de rendre le Polygon Edge opérationnel avec +[AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html). + +:::info guides précédents + +Il est **fortement recommandé** qu'avant de parcourir cet article, les articles sur [**Configuration locale**](/docs/edge/get-started/set-up-ibft-locally) +et [**Configuration cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud) soient lus. +::: + + +## Prérequis {#prerequisites} +### Politique IAM {#iam-policy} +L'utilisateur doit créer une politique IAM qui autorise les opérations de lecture et d'écriture pour AWS Systems Manager Parameter Store. + Après avoir correctement créé la politique IAM, l'utilisateur doit l'attacher à l'instance EC2 qui exécute le serveur de Polygon Edge. + La politique IAM doit ressembler à ceci : +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +Vous trouverez de plus amples informations sur les rôles IAM d'AWS SSM dans les [documents AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html). + +Informations requises avant de continuer : +* **Région** (la région dans laquelle Systems Manager et les nœuds réside) +* **Chemin de paramètre** (chemin arbitraire dans lequel le secret sera placé, par exemple `/polygon-edge/nodes`) + +## Étape 1 - Générez la configuration du gestionnaire de secrets {#step-1-generate-the-secrets-manager-configuration} + +Pour que Polygon Edge puisse communiquer de manière transparente avec AWS SSM, il doit analyser un +fichier de configuration déjà généré, qui contient toutes les informations nécessaires au stockage des secrets sur l'AWS SSM. + +Pour générer la configuration, exécutez la commande suivante : + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +Paramètres présents: +* `PATH` est le chemin vers lequel le fichier de configuration doit être exporté. `./secretsManagerConfig.json` Par défaut +* `NODE_NAME` est le nom du nœud actuel pour lequel la configuration AWS SSM est en cours de définition. Il peut s'agir d'une valeur arbitraire. `polygon-edge-node` Par défaut +* `REGION` est la région dans laquelle le SSM AWS réside dans le système. Il doit s'agir de la même région que le nœud utilisant AWS SSM. +* `SSM_PARAM_PATH` est le nom du chemin dans lequel le secret sera stocké. Par exemple, si `--name node1` et `ssm-parameter-path=/polygon-edge/nodes` +sont spécifiés, le secret sera stocké en tant que .`/polygon-edge/nodes/node1/` + +:::caution Noms de nœud + +Soyez prudent lorsque vous spécifiez les noms de nœud. + +Polygon Edge utilise le nom de nœud spécifié pour suivre les secrets qu'il génère et utilise sur AWS SSM. +Spécifier un nom de nœud existant peut avoir pour conséquence l'échec de l'écriture du secret dans AWS SSM. + +Les secrets sont stockés sur le chemin de base suivant : `SSM_PARAM_PATH/NODE_NAME` + +::: + +## Étape 2 - Initialiser les clés secrètes à l'aide de la configuration {#step-2-initialize-secret-keys-using-the-configuration} + +Maintenant que le fichier de configuration est présent, nous pouvons initialiser les clés secrètes requises avec le fichier de configuration le fichier est configuré à l'étape 1, à l'aide de `--config`: + +```bash +polygon-edge secrets init --config +``` + +Le paramètre `PATH` est l'emplacement du paramètre du gestionnaire de secrets généré précédemment à l'étape 1. + +:::info Politique IAM + +Cette étape échouera si la politique IAM qui autorise les opérations de lecture/écriture n'est pas configurée correctement ou n'est pas attachée à l'instance EC2 qui exécute cette commande. + +::: + +## Étape 3 - Générez le fichier de genèse {#step-3-generate-the-genesis-file} + +Le fichier de genèse doit être généré de la même manière que la [**Configuration Locale**](/docs/edge/get-started/set-up-ibft-locally) et les guides de [**Configuration du cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud), avec des modifications mineures. + +Étant donné qu’AWS SSM est utilisé à la place du système de fichiers local, les adresses de validateur doivent être ajoutées via l'`--ibft-validator`indicateur  : +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Étape 4 - Démarrez le client de Polygon Edge {#step-4-start-the-polygon-edge-client} + +Maintenant que les clés sont configurées et que le fichier de genèse est généré, la dernière étape de ce processus serait de démarrer le Polygon Edge avec la `server` commande. + +La `server` commande est utilisée de la même manière que dans les guides mentionnés précédemment, avec un ajout mineur - l'`--secrets-config`indicateur : +```bash +polygon-edge server --secrets-config ... +``` + +Le `PATH` param est l'emplacement du paramètre de gestionnaire des secrets généré précédemment à l'étape 1. \ No newline at end of file diff --git a/archive/edge/fr-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/fr-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..bb2268d8da --- /dev/null +++ b/archive/edge/fr-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,114 @@ +--- +id: set-up-gcp-secrets-manager +title: Configurez le Gestionnaire de Secrets GCP +description: "Configurez le Gestionnaire de Secrets GCP pour Polygon Edge." +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## Aperçu {#overview} + +Actuellement, Polygon Edge se préoccupe de garder 2 secrets d'exécution majeurs: +* La **clé privée du validateur** utilisée par le nœud, si le nœud est un validateur +* La **clé privée de mise en réseau** utilisée par libp2p, pour participer et communiquer avec d'autres pairs + +Pour plus d'informations, veuillez lire le [Guide de Gestion des Clés Privées](/docs/edge/configuration/manage-private-keys) + +Les modules du Polygon Edge **ne devraient pas avoir besoin de savoir garder des secrets**. En fin de compte, un module ne devrait pas se soucier du fait qu'un secret soit stocké sur un serveur distant ou localement sur le disque du nœud. + +Tout ce qu'un module doit savoir sur la conservation des secrets, c'est **savoir utiliser le secret**, **savoir quels secrets obtenir +ou enregistrer**. Les détails d'implémentation les plus fins de ces opérations sont délégués au `SecretsManager`, ce qui est bien sûr une abstraction. + +L'opérateur du nœud qui démarre le Polygon Edge peut désormais spécifier le gestionnaire des secrets qu'il souhaite utiliser, et dès que le bon gestionnaire de secrets est instancié, les modules traitent les secrets via l'interface mentionnée - sans se soucier de savoir si les secrets sont stockés sur un disque ou sur un serveur. + +Cet article détaille les étapes nécessaires pour que Polygon Edge soit opérationnel avec le [Gestionnaire de Secrets GCP](https://cloud.google.com/secret-manager). + +:::info guides précédents + +Il est **fortement recommandé** qu'avant de parcourir cet article, les articles sur [**Configuration locale**](/docs/edge/get-started/set-up-ibft-locally) +et [**Configuration cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud) soient lus. +::: + + +## Prérequis {#prerequisites} +### Compte de Facturation GCP {#gcp-billing-account} +Pour utiliser le Gestionnaire de Secrets GCP, l'utilisateur doit avoir activé le [Compte de facturation](https://console.cloud.google.com/) sur le portail GCP. +Les nouveaux comptes Google sur la plate-forme GCP reçoivent des fonds pour démarrer, en tant que roi de l'essai gratuit. +Plus d'informations sur la [documentation GCP](https://cloud.google.com/free) + +### API du Gestionnaire de Secrets {#secrets-manager-api} +L'utilisateur devra activer l'API du Gestionnaire de Secrets GCP avant de pouvoir l'utiliser. +Cela peut être fait via le [portail API du Gestionnaire de Secrets GCP](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com). +Plus d'informations : [Configuration du Gestionnaire de Secrets](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + +### Identifiant GCP {#gcp-credentials} +Enfin, l'utilisateur doit générer de nouvelles informations d'identification qui seront utilisées pour l'authentification. +Cela peut être fait en suivant les instructions affichées [ici](https://cloud.google.com/secret-manager/docs/reference/libraries). +Le fichier json généré contenant les informations d'identification doit être transféré à chaque nœud devant utiliser le Gestionnaire de Secrets GCP. + +Informations requises avant de continuer : +* **Identifiant du projet** (l'identifiant du projet défini sur la plate-forme GCP) +* **Emplacement du Fichier des Identifiants** (le chemin d'accès au fichier json contenant les informations d'identification) + +## Étape 1 - Générez la configuration du gestionnaire de secrets {#step-1-generate-the-secrets-manager-configuration} + +Pour que Polygon Edge puisse communiquer de manière transparente avec GCP SM, il doit analyser un +fichier de configuration déjà généré, qui contient toutes les informations nécessaires pour le stockage secret sur GCP SM. + +Pour générer la configuration, exécutez la commande suivante : + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +Paramètres présents: +* `PATH` est le chemin vers lequel le fichier de configuration doit être exporté. `./secretsManagerConfig.json` Par défaut +* `NODE_NAME` est le nom du nœud actuel pour lequel la configuration GCP SM est en cours de configuration. Il peut s'agir d'une valeur arbitraire. `polygon-edge-node` Par défaut +* `PROJECT_ID` est l'identifiant du projet que l'utilisateur a défini dans la console GCP lors de la configuration du compte et de l'activation de l'API du Gestionnaire de Secrets. +* `GCP_CREDS_FILE` est le chemin d'accès au fichier json contenant les informations d'identification qui permettront l'accès en lecture/écriture au Gestionnaire de Secrets. + +:::caution Noms de nœud + +Soyez prudent lorsque vous spécifiez les noms de nœud. + +Polygon Edge utilise le nom de nœud spécifié pour suivre les secrets qu'il génère et utilise sur le SM GCP. +La spécification d'un nom de nœud existant peut entraîner l'échec de l'écriture du secret dans GCP SM. + +Les secrets sont stockés sur le chemin de base suivant : `projects/PROJECT_ID/NODE_NAME` + +::: + +## Étape 2 - Initialiser les clés secrètes à l'aide de la configuration {#step-2-initialize-secret-keys-using-the-configuration} + +Maintenant que le fichier de configuration est présent, nous pouvons initialiser les clés secrètes requises avec le fichier de configuration le fichier est configuré à l'étape 1, à l'aide de `--config`: + +```bash +polygon-edge secrets init --config +``` + +Le `PATH` param est l'emplacement du paramètre de gestionnaire des secrets généré précédemment à l'étape 1. + +## Étape 3 - Générer le fichier de genèse {#step-3-generate-the-genesis-file} + +Le fichier de genèse doit être généré de la même manière que la [**Configuration Locale**](/docs/edge/get-started/set-up-ibft-locally) et les guides de [**Configuration du Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud), avec des modifications mineures. + +Étant donné que GCP SM est utilisé à la place du système de fichiers local, les adresses de validateur doivent être ajoutées via l'`--ibft-validator` indicateur: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Étape 4 - Démarrez le client de Polygon Edge {#step-4-start-the-polygon-edge-client} + +Maintenant que les clés sont configurées et que le fichier de genèse est généré, la dernière étape de ce processus serait de démarrer le Polygon Edge avec la `server` commande. + +La `server` commande est utilisée de la même manière que dans les guides mentionnés précédemment, avec un ajout mineur - l'`--secrets-config`indicateur : +```bash +polygon-edge server --secrets-config ... +``` + +Le `PATH` param est l'emplacement du paramètre de gestionnaire des secrets généré précédemment à l'étape 1. \ No newline at end of file diff --git a/archive/edge/fr-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/fr-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..d1906b8e66 --- /dev/null +++ b/archive/edge/fr-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,107 @@ +--- +id: set-up-hashicorp-vault +title: Configurer Hashicorp Vault +description: "Configurer le Hashicorp Vault pour Polygon Edge." +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## Aperçu {#overview} + +Actuellement, Polygon Edge se préoccupe de garder 2 secrets d'exécution majeurs: +* La **clé privée du validateur** utilisée par le nœud, si le nœud est un validateur +* La **clé privée de réseau** utilisée par libp2p, pour participer et communiquer avec d'autres pairs + +:::warning + +La clé privée du validateur est unique pour chaque nœud de validateur. La même clé ne doit pas être partagée entre tous les validateurs, car cela pourrait compromettre la sécurité de votre chaîne. +::: + +Pour plus d'informations, veuillez lire le [Guide de Gestion Des Clés Privées](/docs/edge/configuration/manage-private-keys) + +Les modules du Polygon Edge **ne devraient pas avoir besoin de savoir garder des secrets**. En fin de compte, un module ne devrait pas se soucier du fait qu'un secret soit stocké sur un serveur distant ou localement sur le disque du nœud. + +Tout ce qu'un module doit savoir sur la conservation des secrets, c'est **savoir utiliser le secret**, **savoir quels secrets obtenir +ou enregistrer**. Les détails d'implémentation les plus fins de ces opérations sont délégués au `SecretsManager`, ce qui est bien sûr une abstraction. + +L'opérateur du nœud qui démarre le Polygon Edge peut désormais spécifier le gestionnaire des secrets qu'il souhaite utiliser, et dès que le bon gestionnaire de secrets est instancié, les modules traitent les secrets via l'interface mentionnée - sans se soucier de savoir si les secrets sont stockés sur un disque ou sur un serveur. + +Cet article détaille les étapes nécessaires pour que le Polygon Edge soit opérationnel avec un serveur [Hashicorp Vault](https://www.vaultproject.io/). + +:::info guides précédents + +Il est **fortement recommandé** qu'avant de parcourir cet article, les articles sur [**Configuration locale**](/docs/edge/get-started/set-up-ibft-locally) +et [**Configuration cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud) soient lus. +::: + + +## Prérequis {#prerequisites} + +Cet article suppose qu'une instance de fonctionnement du serveur Hashicorp Vault **est déjà configurée**. + +De plus, il est nécessaire que le serveur Hashicorp Vault utilisé pour le Polygon Edge ait **activé le stockage KV**. + +Informations requises avant de continuer: +* **L'URL du serveur** (l'URL de l'API du serveur Hashicorp Vault) +* **Jeton** (jeton d'accès utilisé pour accéder au moteur de stockage KV) + +## Étape 1 - Générer la configuration du gestionnaire de secrets {#step-1-generate-the-secrets-manager-configuration} + +Pour que le Polygon Edge puisse communiquer de manière transparente avec le serveur Vault, il doit analyser un fichier de configuration déjà généré, qui contient toutes les informations nécessaires pour le stockage de secrets sur Vault. + +Pour générer la configuration, exécutez la commande suivante: + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +Paramètres présents: +* `PATH` est le chemin vers lequel le fichier de configuration doit être exporté. Par Défaut `./secretsManagerConfig.json` +* `TOKEN` est le jeton d'accès mentionné précédemment dans la [section des prérequis](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `SERVER_URL` est l'URL de l'API pour le serveur Vault, également mentionnée dans la [section des prérequis](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `NODE_NAME` est le nom du nœud actuel pour lequel la configuration Vault est installée. Il peut s'agir d'une valeur arbitraire. Par Défaut `polygon-edge-node` + +:::caution Les noms de nœud + +Soyez prudent lorsque vous spécifiez des noms de nœud. + +Le Polygon Edge utilise le nom de nœud spécifié pour suivre les secrets qu'il génère et utilise sur l'instance de Vault. La spécification d'un nom de nœud existant peut entraîner l'écrasement des données sur le serveur de Vault. + +Les secrets sont stockés sur le chemin de base suivant: `secrets/node_name` +::: + +## Étape 2 - Initialiser les clés secrètes à l'aide de la configuration {#step-2-initialize-secret-keys-using-the-configuration} + +Maintenant que le fichier de configuration est présent, nous pouvons initialiser les clés secrètes requises avec le fichier de configuration le fichier est configuré à l'étape 1, à l'aide de `--config`: + +```bash +polygon-edge secrets init --config +``` + +Le `PATH` param est l'emplacement du paramètre de gestionnaire des secrets généré précédemment à l'étape 1. + +## Étape 3 - Générer le fichier de genèse {#step-3-generate-the-genesis-file} + +Le fichier de genèse doit être généré de la même manière que la [**Configuration Locale**](/docs/edge/get-started/set-up-ibft-locally) et les guides de [**Configuration du Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud), avec des modifications mineures. + +Étant donné que Hashicorp Vault est utilisé à la place du système de fichiers local, les adresses de validateur doivent être ajoutées via `--ibft-validator` l'option: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Étape 4 - Démarrer le client de Polygon Edge {#step-4-start-the-polygon-edge-client} + +Maintenant que les clés sont configurées et que le fichier de genèse est généré, la dernière étape de ce processus serait de démarrer le Polygon Edge avec la `server` commande. + +La `server` commande est utilisée de la même manière que dans les guides mentionnés précédemment, avec un ajout mineur - l'`--secrets-config`indicateur : +```bash +polygon-edge server --secrets-config ... +``` + +Le `PATH` param est l'emplacement du paramètre de gestionnaire des secrets généré précédemment à l'étape 1. \ No newline at end of file diff --git a/archive/edge/fr-edge/consensus/bls.md b/archive/edge/fr-edge/consensus/bls.md new file mode 100644 index 0000000000..9ae65506da --- /dev/null +++ b/archive/edge/fr-edge/consensus/bls.md @@ -0,0 +1,144 @@ +--- +id: bls +title: BLS +description: "Explication et instructions concernant le mode BLS." +keywords: + - docs + - polygon + - edge + - bls +--- + +## Aperçu {#overview} + +BLS également connu sous le nom de Boneh–Lynn–Shacham (BLS)—is un schéma de signature cryptographique qui permet à un utilisateur de vérifier qu'un signataire est authentique. Il s'agit d'un schéma de signature qui peut agréger plusieurs signatures. Dans Polygon Edge, BLS est utilisé par défaut afin de fournir une plus grande sécurité dans le mode de consensus IBFT. BLS peut regrouper les signatures dans un seul tableau d'octets et réduire la taille de l'en-tête du bloc. Chaque chaîne a le choix d'utiliser ou non BLS. La clé ECDSA est utilisée, que le mode BLS soit activé ou non. + +## Présentation vidéo {#video-presentation} + +[![bls - vidéo](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## Comment configurer une nouvelle chaîne à l'aide de BLS {#how-to-setup-a-new-chain-using-bls} + +Référez-vous aux sections [Configuration Locale](/docs/edge/get-started/set-up-ibft-locally) / [Configuration du Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) pour obtenir des instructions de configuration détaillées. + +## Comment migrer d'une chaîne de PoA ECDSA existante vers une chaîne de PoA BLS {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +Cette section décrit comment utiliser le mode BLS dans une chaîne de PoA existante. + les étapes suivantes sont nécessaires afin d'activer BLS dans une chaîne de PoA. + +1. Arrêtez tous les nœuds +2. Générez les clés BLS pour les validateurs +3. Ajoutez un paramètre de fourche dans genesis.json +4. Redémarrez tous les nœuds + +### 1. Arrêtez tous les nœuds {#1-stop-all-nodes} + +Terminez tous les processus des validateurs en utilisant les touches Ctrl + c (Control + c). Veuillez mémoriser la dernière taille de bloc (le numéro de séquence le plus élevé dans le registre des blocs confirmés). + +### 2. Générez la clé BLS {#2-generate-the-bls-key} + +`secrets init` avec le `--bls` génère une clé BLS. `--ecdsa` et `--network` doivent être désactivés afin de conserver la clé ECDSA et la clé réseau existantes et d'ajouter une nouvelle clé BLS. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Ajoutez un paramètre de fourche {#3-add-fork-setting} + +`ibft switch`La commande ajoute un paramètre de fourche, qui active BLS dans la chaîne existante, dans `genesis.json`. + +Les validateurs doivent être indiqués dans la commande pour les réseaux de PoA. Tout comme pour la commande `genesis`, les indicateurs `--ibft-validators-prefix-path` ou `--ibft-validator` peuvent être utilisés pour spécifier le validateur. + +Spécifiez la taille à partir de laquelle la chaîne démarre en utilisant BLS avec`--from` l'indicateur. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. Redémarrez tous les nœuds {#4-restart-all-nodes} + +Redémarrez tous les nœuds avec la `server`commande. Après la création du bloc au `from` spécifié à l'étape précédente est créé, la chaîne active BLS et affiche les journaux comme ci-dessous : + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +Les registres indiquent également quel mode de vérification est utilisé pour générer chaque bloc après sa création. + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## Comment migrer d'une chaîne PdV ECDSA existante vers une chaîne PdV BLS {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +Cette section décrit comment utiliser le mode BLS dans une chaîne de PoS existante. + Les étapes suivantes sont requises afin d'activer BLS dans la chaîne de PoS. + +1. Arrêtez tous les nœuds +2. Générez les clés BLS pour les validateurs +3. Ajoutez un paramètre de fourche dans genesis.json +4. Appelez le contrat de staking pour enregistrer la Clé Publique de BLS +5. Redémarrez tous les nœuds + +### 1. Arrêtez tous les nœuds {#1-stop-all-nodes-1} + +Terminez tous les processus des validateurs en utilisant les touches Ctrl + c (Control + c). Veuillez mémoriser la dernière taille de bloc (le numéro de séquence le plus élevé dans le registre des blocs confirmés). + +### 2. Générez la clé BLS {#2-generate-the-bls-key-1} + +`secrets init` avec `--bls`l'indicateur génère la clé BLS. `--ecdsa` et `--network` doivent être désactivés afin de conserver les clés ECDSA et réseau existantes et d'ajouter une nouvelle clé BLS. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Ajoutez un paramètre de fourche {#3-add-fork-setting-1} + +`ibft switch`La commande ajoute un paramètre de fourche, qui active BLS à partir du milieu de la chaîne dans `genesis.json`. + +Spécifiez la taille à partir de laquelle la chaîne démarre en utilisant le mode BLS avec `from` l'indicateur , et la taille à laquelle le contrat est mis à jour avec `development` l'indicateur. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. Enregistrer la Clé Publique de BLS dans le contrat de staking {#4-register-bls-public-key-in-staking-contract} + +Après l'ajout de la fourche et le redémarrage des validateurs, chaque validateur doit appeler `registerBLSPublicKey` dans le contrat de staking pour enregistrer la Clé Publique de BLS. Ceci doit être fait après la taille spécifiée en `--deployment` avant la taille spécifiée en `--from`. + +Le scénario pour enregistrer la Clé Publique de BLS est défini dans le [référentiel du Contrat Intelligent de Staking](https://github.com/0xPolygon/staking-contracts). + +Définissez `BLS_PUBLIC_KEY` pour être enregistré dans `.env`le dossier. Voir [staker-déstaker-pos](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) pour plus de détails sur les autres paramètres. + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +La commande suivante enregistre la Clé Publique de BLS donnée dans `.env` au contrat. + +```bash +npm run register-blskey +``` + +:::warning Les validateurs doivent enregistrer manuellement la Clé Publique de BLS + +En mode BLS, les validateurs doivent disposer de leur propre adresse et de la clé publique de BLS. La couche de consensus ignore les validateurs qui n'ont pas enregistré la clé publique BLS dans le contrat lorsque le consensus récupère les informations sur les validateurs dans le contrat. + +::: + +### 5. Redémarrez tous les nœuds {#5-restart-all-nodes} + +Redémarrez tous les nœuds avec la `server`commande. La chaîne active le BLS après la création du bloc au `from` spécifié à l'étape précédente est créé. diff --git a/archive/edge/fr-edge/consensus/migration-to-pos.md b/archive/edge/fr-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..b6dfd82d9b --- /dev/null +++ b/archive/edge/fr-edge/consensus/migration-to-pos.md @@ -0,0 +1,40 @@ +--- +id: migration-to-pos +title: Migration de la PoA à la PoS +description: "Comment migrer de PoA au mode d'IBFT de la preuve de participation et vice versa." +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## Aperçu {#overview} + +Cette section vous explique comment passer du mode de PoA au mode d'IBFT de la preuve de participation, et vice versa, pour un groupe en fonctionnement, sans avoir à réinitialiser la blockchain. + +## Comment migrer vers PoS {#how-to-migrate-to-pos} + +Vous devrez arrêter tous les nœuds, ajouter la configuration de la fourche dans genesis.json par `ibft switch` la commande, et redémarrer les nœuds. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution Passer lors de l'utilisation ECDSA +Lors de l'utilisation ECDSA, `--ibft-validator-type`l'indicateur doit être ajouté au commutateur, en indiquant que ECDSA est utilisé. Si elle n'est pas incluse, Edge passera automatiquement vers BLS. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::Pour passer à PoS, vous devrez spécifier 2 hauteurs de bloc `deployment`: . `from`est `deployment`la hauteur pour déployer le contrat de staking et est `from`la hauteur du début de PoS. Le contrat de staking sera déployé à l'adresse `0x0000000000000000000000000000000000001001` au `deployment`, comme dans le cas du contrat pré-déployé. + +Veuillez consulter la [Preuve d'Enjeu](/docs/edge/consensus/pos-concepts) pour plus de détails sur le contrat de Staking. + +:::warning Les validateurs doivent être mis en place manuellement + +Chaque validateur doit miser après le déploiement du contrat à `deployment` et avant `from` afin de pouvoir être un validateur au début de la Preuve de Participation. Chaque validateur mettra à jour son propre ensemble de validateurs par l'ensemble dans le contrat de staking au début de la Preuve de Participation. + +Pour en savoir plus sur Staking, consultez la **[Configuration et utilisez la preuve de Stake](/docs/edge/consensus/pos-stake-unstake)**. +::: diff --git a/archive/edge/fr-edge/consensus/poa.md b/archive/edge/fr-edge/consensus/poa.md new file mode 100644 index 0000000000..bcad62bd1e --- /dev/null +++ b/archive/edge/fr-edge/consensus/poa.md @@ -0,0 +1,107 @@ +--- +id: poa +title: Preuve d'Autorité (PoA) +description: "Explication et les instructions concernant la Preuve d'Autorité." +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## Aperçu {#overview} + +La PoA d'IBFT est le mécanisme de consensus par défaut dans le Polygone Edge. Dans la PoA, les validateurs sont chargés de créer les blocs et de les ajouter en série à la blockchain. + +Tous les validateurs constituent un ensemble de validateur dynamique, dans lequel des validateurs peuvent être ajoutés ou retirés en utilisant un mécanisme de vote. Cela signifie que les validateurs peuvent être ajoutés ou retirés de l'ensemble des validateurs si la majorité (51%) des nœuds de validations vote pour ajouter ou retirer un certain validateur de l'ensemble. De cette façon, les validateurs malveillants peuvent être reconnus et écartés du réseau, tandis que de nouveaux validateurs de confiance peuvent être ajoutés au réseau. + +Tous les validateurs proposent à tour de rôle le bloc suivant (round-robin), et pour que le bloc soit validé ou inséré dans la blockchain, une supermajorité (plus de 2/3) des validateurs doit approuver bloc désigné. + +Outre les validateurs, certains non-validateurs ne participent pas dans la création du bloc mais participe au processus de validation du bloc. + +## Ajouter un validateur à l'ensemble des validateur {#adding-a-validator-to-the-validator-set} + +Ce guide décrit comment ajouter un nouveau nœud de validateur à un réseau IBFT actif avec 4 nœuds de validation. + Si vous avez besoin d'aide pour configurer le réseau, consultez les sections Configuration [locale](/edge/get-started/set-up-ibft-locally.md) / [Configuration du](/edge/get-started/set-up-ibft-on-the-cloud.md) Cloud. + +### Étape 1: Initialiser les dossiers de données pour IBFT et générer les clés de validation pour le nouveau nœud. {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +Afin de se lever et rendre IBFT opérationnel sur le nouveau nœud, vous devez d'abord initialiser les dossiers de données et générer les clés: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +Cette commande imprimera la clé de validation (adresse) et l'Identifiant du nœud. Vous aurez besoin de la clé de validation (adresse) pour l'étape suivante. + +### Étape 2: Proposer un nouveau candidat à partir d'autres nœuds de validation {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +Pour qu'un nouveau nœud devienne un validateur, au moins 51 % des validateurs doivent le proposer. + +Exemple sur la façon de proposer un nouveau validateur (`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`) à partir du noeud de validation existant sur l'adresse grpc: 127.0.0.1:10000: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +La structure des commandes IBFT est traitée dans la section des [Commandes CLI](/docs/edge/get-started/cli-commands). + +:::info Clé publique de BLS + +La clé publique de BLS est nécessaire uniquement si le réseau fonctionne avec le BLS, `--bls` c'est inutile pour le réseau qui ne fonctionne pas en mode de BLS +::: + +### Étape 3: Exécuter un nœud de client {#step-3-run-the-client-node} + +Étant donné que dans cet exemple, nous essayons de faire fonctionner le réseau dans lequel tous les nœuds sont sur la même machine, nous devons veiller à éviter les conflits de port. + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +Après avoir récupéré tous les blocs, vous remarquerez dans votre console qu'un nouveau nœud participe dans la validation + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info Promouvoir un non-validateur à un validateur + +Naturellement, un non-validateur peut devenir un validateur par le processus de vote, mais pour qu'il puisse être inclus dans l'ensemble des validateurs après le processus de vote, le nœud doit être redémarré avec `--seal` l'option. +::: + +## Supprimer un validateur de l'ensemble des validateur {#removing-a-validator-from-the-validator-set} + +Cette opération est assez simple. Pour supprimer un nœud de validation de l'ensemble des validateurs, cette commande doit être exécutée pour la majorité des nœuds de validation. + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info Clé publique de BLS + +La clé publique de BLS est nécessaire uniquement si le réseau fonctionne avec le BLS, `--bls` c'est inutile pour le réseau qui ne fonctionne pas en mode de BLS +::: + +Après l'exécution des commandes, on constate que le nombre de validateurs a diminué (dans cet exemple de protocole, de 4 à 3). + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/fr-edge/consensus/pos-concepts.md b/archive/edge/fr-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..06f4e9bc44 --- /dev/null +++ b/archive/edge/fr-edge/consensus/pos-concepts.md @@ -0,0 +1,121 @@ +--- +id: pos-concepts +title: Preuve d'Enjeu +description: "Explication et instructions concernant la Preuve d'Enjeu." +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## Aperçu {#overview} + +Cette section vise à donner un meilleur aperçu de certains concepts actuellement présents dans la Preuve d'Enjeu (PoS). + Mise en oeuvre du Polygon Edge. + +La mise en œuvre de la Preuve d'Enjeu (PoS) de Polygon Edge se veut une alternative à la mise en œuvre existante de la PoA IBFT, +donnant aux opérateurs de nœuds la possibilité de choisir facilement entre les deux au moment de démarrer une chaîne. + +## Caractéristiques de la Preuve d'Enjeu {#pos-features} + +La logique de base de la mise en œuvre de la Preuve d'Enjeu se trouve dans +le **[contrat intelligent Staking](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)** + +Ce contrat est pré-déployé chaque fois qu'un mécanisme de PoS de la chaîne de Polygon Edge est initialisé, et est disponible sur l'adresse +`0x0000000000000000000000000000000000001001` du bloc `0`. + +### Époques {#epochs} + +Les époques sont un concept introduit avec l'ajout de la PoS au Polygon Edge. + +Les époques sont considérées comme un cadre temporel spécial (en blocs) au cours duquel un certain ensemble de validateurs peut produire des blocs. + Leurs longueurs sont modifiables, ce qui signifie que les opérateurs de nœuds peuvent configurer la longueur d'une époque pendant la génération de la genèse. + +À la fin de chaque époque, un _bloc d'époque_ est créé, et après cet événement, une nouvelle époque commence. Pour en savoir plus sur +les blocs d'époques, consultez la section [Blocs d'époques](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Les ensembles de validateurs sont mis à jour à la fin de chaque époque. Les nœuds interrogent l'ensemble des validateurs du Contrat Intelligent de Staking +pendant la création du bloc d'époque et enregistrent les données obtenues dans le stockage local. Ce cycle de requête et de sauvegarde est +répété à la fin de chaque époque. + +Essentiellement, il garantit que le Contrat Intelligent de Staking a le contrôle total des adresses de l'ensemble de validateurs, et +ne laisse aux nœuds qu'une seule responsabilité : interroger le contrat une fois par époque pour obtenir les dernières informations +sur l'ensemble de validateurs. Cela permet de décharger les nœuds individuels de la responsabilité de s'occuper des ensembles de validateurs. + +### Staking {#staking} + +Les adresses peuvent faire le stake des fonds sur le Contrat Intelligent en invoquant la `stake` méthode , et en spécifiant une valeur pour +le montant en stake dans la transaction : + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +En faisant le stake des fonds sur le contrat Intelligent de Staking, les adresses peuvent entrer dans l'ensemble des validateurs et ainsi être en mesure de participer au +processus de production de blocs. + +:::info Limite pour le staking + +Actuellement, la limite minimum pour entrer dans l'ensemble des validateurs est le staking `1 ETH` + +::: + +### Défaire le stake {#unstaking} + +Les adresses possédant des fonds en stake ne peuvent **débloquer que la totalité de ces fonds en une seule fois**. + +On peut défaire le stake en invoquant la `unstake`méthode sur le Contrat Intelligent de Staking : + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +Après le déblocage de leurs fonds, les adresses sont retirées de l'ensemble des validateurs du Contrat Intelligent de Staking et ne seront pas +reconnues comme validateurs lors de la prochaine époque. + +## Blocs d'Époque {#epoch-blocks} + +**Les Blocs dÉpoque** sont un concept introduit dans la Preuve de Participation de la mise en oeuvre d'IBFT dans Polygon Edge. + +Essentiellement, les blocs d'époque sont des blocs spéciaux qui ne contiennent **aucune transaction** et n'apparaissent qu'à **la fin d'une époque**. + Par exemple, si la **taille** d'époque est définie sur des `50`blocs, les blocs d'époques seraient considérés comme des blocs , `50`, et ainsi `100``150`de suite. + +Ils sont utilisés pour exécuter une logique supplémentaire qui ne devrait pas se produire lors de la production de blocs ordinaires. + +Plus essentiellement, ils indiquent au nœud **qu'il doit aller chercher les dernières informations sur l'ensemble de validateurs** +dans le Contrat Intelligent de Staking. + +Après avoir mis à jour l'ensemble de validateurs au bloc d'époque, l'ensemble de validateurs (modifié ou inchangé) + est utilisé pour les `epochSize - 1` blocs suivants, jusqu'à ce qu'il soit à nouveau mis à jour en extrayant les dernières informations +le Contrat Intelligent de Staking. + +La longueur des époques (en blocs) est modifiable lors de la génération du fichier de genèse, en utilisant un indicateur spécial `--epoch-size` : + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +La taille par défaut d'une époque est de `100000` blocs dans le Polygon Edge. + +## Pré-déploiement du contrat {#contract-pre-deployment} + +Le Polygon Edge _pré-déploie_ +le [Contrat Intelligent de Staking](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol) +pendant **la génération de la genèse** à l'adresse `0x0000000000000000000000000000000000001001`. + +Pour ce faire, il n'est pas nécessaire de disposer d'une machine virtuelle Ethereum (EVM) en cours d'exécution, car il modifie directement l'état de la blockchain du Contrat Intelligent, en utilisant +les valeurs de configuration transmises à la commande de genèse. diff --git a/archive/edge/fr-edge/consensus/pos-stake-unstake.md b/archive/edge/fr-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..0ab3d1152e --- /dev/null +++ b/archive/edge/fr-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,154 @@ +--- +id: pos-stake-unstake +title: Configuration et utilisation de la Preuve d'Enjeu (PoS) +description: "Faire du Stake, défaire du stake et autres instructions relatives au staking." +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## Aperçu {#overview} + +Ce guide explique en détail comment mettre en place un réseau de Preuve d'Enjeu avec le Polygon Edge, comment faire du stake des fonds pour que les nœuds deviennent des validateurs et comment défaire du stake des fonds. + +Il est **fortement encouragé** à lire et à passer les sections de [Configuration Locale](/docs/edge/get-started/set-up-ibft-locally) et la [Configuration du Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) avant de suivre + ce guide de PoS. Ces sections décrivent les étapes nécessaires pour démarrer une groupe de Preuve d'Autorité (PoA) avec le Polygon Edge. + +Actuellement, le nombre de validateurs pouvant faire du stake des fonds sur le Contrat Intelligent de Staking n'est pas limité. + +## Contrat Intelligent de Staking {#staking-smart-contract} + +Le repo pour le Contrat Intelligent de Staking est situé [ici](https://github.com/0xPolygon/staking-contracts). + +Celui-ci contient les scénarios de test nécessaires, les fichiers ABI et, surtout, le Contrat Intelligent de Staking lui-même. + +## Configuration d'un groupe de nœuds de N {#setting-up-an-n-node-cluster} + +La configuration d'un réseau à l'aide du Polygon Edge est abordée dans les sections de [Configuration Locale](/docs/edge/get-started/set-up-ibft-locally) et la [Configuration du Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +La phase de génération de la genèse constitue la **seule différence** entre la configuration d'un groupe de PoS et de PoA. + +**Lors de la génération du fichier de genèse pour une groupe de PoS, un indicateur supplémentaire est nécessaire `--pos`**: + +```bash +polygon-edge genesis --pos ... +``` + +## Configuration de la longueur d'une époque {#setting-the-length-of-an-epoch} + +Les époques sont décrites en détail dans la section des [Blocs d'Époque](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Pour définir la taille d'une époque pour un groupe (en blocs), lors de la génération du fichier de genèse, un indicateur supplémentaire est spécifié `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +Cette valeur indique dans le fichier de genèse que la taille de l'époque doit être de `50` blocs. + +La valeur par défaut de la taille d'une époque (en blocs) est de `100000`. + +:::info Diminuer la longueur de l'époque + +Comme indiqué dans la section de [Blocs d'Époques](/docs/edge/consensus/pos-concepts#epoch-blocks), ces derniers sont utilisés pour mettre à jour les ensembles de validateur pour les nœuds. + +La durée par défaut de l'époque en blocs (`100000`) peut être longue afin de pouvoir effectuer les mises à jour de l'ensemble des validateurs. Si l'on considère que des nouveaux blocs sont ajoutés environ toutes les 2 secondes, il faudrait environ 55,5 heures pour que l'ensemble des validateur change éventuellement. + +Définir une valeur inférieure pour la durée de l'époque, permet d'assurer que l'ensemble de validateur est mis à jour plus fréquemment. + +::: + +## Utiliser les scénarios du Contrat Intelligent de Staking {#using-the-staking-smart-contract-scripts} + +### Prérequis {#prerequisites} + +Le repo du Contrat Intelligent de Staking est un projet Hardhat, qui nécessite NPM. + +Pour l'initialiser correctement, suivez les étapes suivantes dans le répertoire principal: + +```bash +npm install +```` + +### Configurer les scénarios d'assistant fournis {#setting-up-the-provided-helper-scripts} + +Les scénarios permettant d'interagir avec le Contrat Intelligent de Staking déployé se trouvent sur le [repo du Contrat Intelligent de Staking](https://github.com/0xPolygon/staking-contracts). + +Créez un `.env` fichier avec les paramètres suivants dans l'emplacement du repo des Contrats Intelligents: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +Où les paramètres se trouvent: + +* **JSONRPC_URL** - le point de terminaison JSON-RPC pour le nœud en cours +* **PRIVATE_KEYS** - les clés privées de l'adresse du staker. +* **STAKING_CONTRACT_ADDRESS** - l'adresse du contrat intelligent de staking ( par défaut `0x0000000000000000000000000000000000001001`) +* **BLS_PUBLIC_KEY** - la clé publique BLS du staker. Seulement nécessaire si le réseau fonctionne avec BLS + +### Des fonds de staking {#staking-funds} + +:::info Adresse de staking + +Le Contrat Intelligent de Staking est pré-déployé sur l'adresse `0x0000000000000000000000000000000000001001`. + +Tout type d'interaction avec le mécanisme de staking se fait par le biais du Contrat Intelligent de Staking à l'adresse spécifiée. + +Pour en savoir plus sur le Contrat Intelligent de Staking, veuillez consulter le **[contrat intelligent Staking](/docs/edge/consensus/pos-concepts#contract-pre-deployment)** . +::: + +Pour faire partie de l'ensemble des validateurs, une adresse doit faire du stake sur un montant donné de fonds au-dessus d'un certain niveau. + +Actuellement, le niveau par défaut pour faire partie de l'ensemble de validateur est de `1 ETH`. + +Le staking peut être initié en invoquant la `stake` méthode du Contrat Intelligent de Staking, et en spécifiant une valeur `>= 1 ETH`. + +Une fois que le `.env` fichier mentionné dans la [section précédente](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) a été configuré, et qu'une chaîne a été lancée en mode PoS, le staking peut être effectué avec la commande suivante dans le repo du Contrat Intelligent de Staking: + +```bash +npm run stake +``` + +Le `stake` scénario d'Hardhat fait du stake sur un montant par défaut de `1 ETH`, qui peut être changé en modifiant le `scripts/stake.ts`fichier. + +Si les fonds stakés sont `>= 1 ETH`, l'ensemble de validateurs du Contrat Intelligent de Staking est mis à jour et l'adresse fera partie de l'ensemble de validateur à partir de la prochaine époque. + +:::info Enregistrer les clés BLS + +Si le réseau fonctionne en mode BLS, les nœuds doivent enregistrer leurs clés publiques BLS après le staking, pour pouvoir devenir des validateurs + +Cela peut être effectué avec la commande suivante: + +```bash +npm run register-blskey +``` +::: + +### Défaire le stake sur des fonds {#unstaking-funds} + +Les adresses qui ont une participation peuvent **seulement défaire du stake de tous leurs fonds** en une seule fois seulement. + +Une fois que le `.env` fichier mentionné dans la [section précédente](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) a été configuré, et qu'une chaîne a été lancée dans le mode PoS, défaire du stake peut être effectué avec la commande suivante dans le repo du Contrat Intelligent de Staking: + +```bash +npm run unstake +``` + +### Récupérer la liste des stakers {#fetching-the-list-of-stakers} + +Toutes les adresses qui stakent des fonds sont enregistrées dans le Contrat Intelligent de Staking. + +Une fois que le `.env` fichier mentionné dans la [section précédente](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) a été configuré, et qu'une chaîne a été lancée dans le mode PoS, la récupération de la liste des validateurs peut être effectuée avec la commande suivante dans le repo du Contrat Intelligent de Staking: + +```bash +npm run info +``` diff --git a/archive/edge/fr-edge/faq/Contracts.md b/archive/edge/fr-edge/faq/Contracts.md new file mode 100644 index 0000000000..57afd4b307 --- /dev/null +++ b/archive/edge/fr-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: FAQ sur les Contrats Intelligents +description: "FAQ sur les Contrats Intelligents de Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## Le Polygon Edge prend-il en charge les Contrats Intelligents? {#does-polygon-edge-support-smart-contracts} + +Oui. Les réseaux de Polygon Edge sont des blockchains compatibles avec Ethereum, si bien que les Contrats Intelligents qui peuvent être déployés sur Ethereum le sont également sur les chaînes de Polygon Edge. + +## Pouvez-vous mettre à jour la logique du contrat de staking pour les PoS après le déploiement? {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +Pour l'instant, une fois que vous avez démarré le réseau de PoS, vous ne pouvez pas modifier la logique du contrat de staking, car elle fait partie du fichier de genèse. Par exemple, vous ne pouvez donc pas modifier le nombre minimum ou maximum de validateurs. Vous pouvez faire du stake ou défaire du stake, ajouter, ou encore retirer des validateurs. + + + diff --git a/archive/edge/fr-edge/faq/Gas.md b/archive/edge/fr-edge/faq/Gas.md new file mode 100644 index 0000000000..e689e73b46 --- /dev/null +++ b/archive/edge/fr-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: FAQ sur le Gaz +description: "FAQ sur le gaz pour Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Comment appliquer un prix de gaz minimum? {#how-to-enforce-a-minimum-gas-price} +Vous pouvez utiliser l'indicateur `--price-limit` fourni sur la commande du serveur. Cela obligera votre nœud à accepter uniquement les transactions dont le gaz est supérieur ou égal à la limite de prix que vous avez définie. Pour s'assurer qu'elle est appliquée sur l'ensemble du réseau, vous devez vous assurer que tous les nœuds ont la même limite de prix. + + +## Pouvez-vous avoir des transactions sans frais de gaz ? {#can-you-have-transactions-with-0-gas-fees} +Oui, c'est possible. La limite de prix par défaut que les nœuds appliquent est `0`, ce qui signifie que les nœuds accepteront les transactions dont le prix du gaz est fixé à `0`. + +## Comment définir la quantité totale d'approvisionnement du jeton de gaz (natif) ? {#how-to-set-the-gas-native-token-total-supply} + +Vous pouvez définir un solde prédéfini pour les comptes (adresses) en utilisant le `--premine flag`. Veuillez noter qu'il s'agit d'une configuration du fichier de genèse, et que celle-ci ne peut être modifiée ultérieurement. + +Exemple sur la façon d'utiliser le `--premine flag` : + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +Ceci établit un solde pré-miné de 1 000 ETH à l'adresse 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862 (le montant de l'argument est exprimé en wei). + +La quantité pré-minée du jeton de gaz constituera l'approvisionnement total. Aucune autre quantité de la monnaie native (jeton de gaz) ne peut être frappée ultérieurement. + +## Edge supporte-t-il l'ERC-20 comme jeton de gaz ? {#does-edge-support-erc-20-as-a-gas-token} + +Edge ne prend pas en charge le jeton ERC-20 comme jeton de gaz. Seule la monnaie native Edge est prise en charge pour le gaz. + +## Comment augmenter la limite de gaz? {#how-to-increase-the-gas-limit} + +Il existe deux options pour augmenter la limite de gaz dans Polygon Edge: +1. Essuyez la chaîne et augmentez `block-gas-limit`à la valeur uint64 maximale dans le fichier de genèse +2. Utilisez `--block-gas-target`l'indicateur avec une valeur élevée pour augmenter la limite de gaz de tous les nœuds. Cela nécessite un redémarrage de nœud . Explication détaillée [ici](/docs/edge/architecture/modules/txpool/#block-gas-target). \ No newline at end of file diff --git a/archive/edge/fr-edge/faq/Tokens.md b/archive/edge/fr-edge/faq/Tokens.md new file mode 100644 index 0000000000..b0d1bda690 --- /dev/null +++ b/archive/edge/fr-edge/faq/Tokens.md @@ -0,0 +1,23 @@ +--- +id: tokens +title: FAQ sur les Jetons +description: "FAQ sur les jetons de Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## Le Polygon Edge prend-il en charge la norme EIP-1559 ? {#does-polygon-edge-support-eip-1559} +Pour l'instant, le Polygon Edge ne prend pas en charge la norme EIP-1559. + +## Comment définir le symbole de la devise (jeton) ? {#how-to-set-the-currency-token-symbol} + +Le symbole du jeton n'est qu'un élément de l'Interface Utilisateur, il ne peut donc pas être configuré ou codé en dur sur le réseau. + Cependant, vous pouvez le modifier lorsque vous ajoutez le réseau à un portefeuille, comme Metamask, par exemple. + +## Qu'arrive-t-il aux transactions lorsqu'une chaîne s'arrête? {#what-happens-to-transactions-when-a-chain-halts} + +Toutes les transactions qui n'ont pas été traitées sont à l'intérieur de la file d'attente TxPool (enqueued ou promus). Si la chaîne s'arrête (tous les blocs de production s'arrêtent ), ces transactions ne seront jamais dans des blocs.
Ce n'est pas seulement le cas lorsque la chaîne s'arrête. Si les nœuds sont arrêtés ou redémarrés, toutes les transactions qui n'ont pas été exécutées et sont toujours dans TxPool, seront silencieusement supprimées.
La même chose arrivera aux transactions lorsqu'un changement de rupture est introduit, car il est nécessaire que les nœuds soient redémarrés. diff --git a/archive/edge/fr-edge/faq/Validators.md b/archive/edge/fr-edge/faq/Validators.md new file mode 100644 index 0000000000..a600973d1e --- /dev/null +++ b/archive/edge/fr-edge/faq/Validators.md @@ -0,0 +1,85 @@ +--- +id: validators +title: FAQ des validateurs +description: "FAQ pour les validateurs de Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Comment ajouter/supprimer un validateur ? {#how-to-add-remove-a-validator} + +### PoA {#poa} +L'ajout / la suppression de validateurs se fait par vote. Vous trouverez [ici](/docs/edge/consensus/poa) un guide complet à ce sujet. + +### Preuve de Participation {#pos} +Vous pouvez trouver un guide sur la façon de faire le stake des fonds [ici](/docs/edge/consensus/pos-stake-unstake), afin qu'un nœud puisse devenir un validateur, et comment défaire le stake (supprimer le validateur). + +Veuillez noter que : +- Vous pouvez utiliser l'indicateur de genèse `--max-validator-count` pour définir un nombre maximum de participants pouvant rejoindre l'ensemble de validateurs. +- Vous pouvez utiliser l'indicateur de genèse `--min-validator-count ` pour définir le nombre minimum de participants nécessaires pour rejoindre l'ensemble de validateurs (`1` par défaut). +- Lorsque le nombre maximum de validateurs est atteint, vous ne pouvez pas ajouter un autre validateur tant que vous n'en supprimez pas un existant de l'ensemble (peu importe si le montant en stake du nouveau est plus élevé). Si vous supprimez un validateur, le nombre de validateurs restants ne peut pas être inférieur à `--min-validator-count`. +- Il existe une limite par défaut `1` d'unité de devise du réseau natif (gaz) pour devenir un validateur. + + + +## Quelle quantité d'espace disque est recommandée pour un validateur? {#how-much-disk-space-is-recommended-for-a-validator} + +Nous vous recommandons de commencer avec 100G comme piste estimée de manière prudente et de vous assurer qu'il est possible de mettre le disque à l'échelle par la suite. + + +## Y a-t-il une limite au nombre de validateurs? {#is-there-a-limit-to-the-number-of-validators} + +Si nous parlons de limitations techniques, Polygon Edge n'a pas explicitement de plafond en ce qui concerne le nombre de nœuds que vous pouvez avoir dans un réseau. Vous pouvez définir des plafonds de connexion (nombre de connexions entrantes / sortantes) par nœud. + +Si nous parlons de limitations pratiques, vous allez voir une performance plus dégradée avec un cluster à 100 nœuds qu'avec un cluster à 10 nœuds. En augmentant le nombre de nœuds dans votre cluster, vous augmentez la complexité de la communication et donc la surcharge de mise en réseau en général. Tout dépend du type de réseau que vous utilisez et du type de topologie de réseau dont vous disposez. + +## Comment passer du PoA au PoS? {#how-to-switch-from-poa-to-pos} + +Le PoA est le mécanisme de consensus par défaut. Dans un nouveau cluster, pour passer en PoS, vous devrez ajouter l'indicateur `--pos` lors de la génération du fichier de genèse. Si vous avez un cluster en cours d'exécution, vous pouvez trouver [ici](/docs/edge/consensus/migration-to-pos) comment effectuer le changement. Toutes les informations dont vous avez besoin sur nos mécanismes de consensus et leur configuration se trouvent dans notre [section consensus](/docs/edge/consensus/poa). + +## Comment mettre à jour mes nœuds lorsqu'il y a un changement avec rupture? {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +Vous pouvez trouver un guide détaillé sur la façon d'entamer cette procédure [ici](/docs/edge/validator-hosting#update). + +## Le montant minimum de staking est-il configurable pour le PoS Edge? {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +Le montant minimum de staking par défaut est `1 ETH`, et il n'est pas configurable. + +## Pourquoi les commandes JSON RPC `eth_getBlockByNumber` et `eth_getBlockByHash` ne renvoient-elles pas l'adresse du mineur? {#not-return-the-miner-s-address} + +Le consensus utilisé actuellement dans Polygon Edge est IBFT 2.0, qui, à son tour, s'appuie sur le mécanisme de vote expliqué dans Clique PoA : [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225). + +En regardant l'EIP-225 (Clique PoA), c'est la partie pertinente qui explique à quoi sert le `miner` (aka `beneficiary`): + +
+Nous réaffectons les champs d'en-tête ethash ainsi: +
    +
  • bénéficiaire/mineur: Adresse avec laquelle vous proposez de modifier la liste des signataires autorisés.
  • +
      +
    • Devrait être rempli de zéros normalement, modifié uniquement lors du vote.
    • +
    • Les valeurs arbitraires sont néanmoins autorisées (même celles qui n'ont pas de sens telles que le vote contre les non-signataires) pour éviter une complexité supplémentaire dans les implémentations autour des mécanismes de vote.
    • +
    • Doit être rempli de zéros sur les blocs de point de contrôle (c'est-à-dire la transition d'époque).
    • +
    + +
+ +
+ +Ainsi, le `miner` champ est utilisé pour proposer un vote pour une certaine adresse, pas pour montrer le proposant du bloc. + +Les informations sur le proposant du bloc peuvent être trouvées en récupérant la clé publique à partir du champ Seal du champ de données supplémentaires Istanbul encodé RLP dans les en-têtes de bloc. + +## Quelles parties et quelles valeurs de Genèse peuvent être modifiées en toute sécurité? {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +Assurez-vous de créer une copie manuelle du fichier genesis.json existant avant de tenter de le modifier. Aussi, la chaîne entière doit être arrêtée avant de modifier le fichier genesis.json. Une fois que le fichier de genèse est modifié, la version la plus récente doit être distribuée sur tous les nœuds non validateurs et valdiator + +::: + +**Seule la section de nœuds de démarrage du fichier genèse peut être modifiée en toute sécurité**, où vous pouvez ajouter ou supprimer des nœuds de démarrage de la liste. \ No newline at end of file diff --git a/archive/edge/fr-edge/get-started/cli-commands.md b/archive/edge/fr-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..be1560c852 --- /dev/null +++ b/archive/edge/fr-edge/get-started/cli-commands.md @@ -0,0 +1,2208 @@ +--- +id: cli-commands +title: Les Commandes CLI +description: "La liste des commandes CLI et des indicateurs de commande pour Polygon Edge." +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +Cette section détaille les commandes actuelles, les indicateurs de commande dans Polygon Edge et leur utilisation. + +:::tip Prise en charge de la sortie JSON + +L'indicateur `--json` est pris en charge sur certaines commandes. Cet indicateur indique à la commande d'imprimer la sortie au format JSON + +::: + +## Les Commandes De Démarrage {#startup-commands} + +| **Commande** | **Description** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| serveur | La commande par défaut qui démarre le client de blockchain, en amorçant tous les modules ensemble | +| genèse | Génère un dossier *genesis.json*, qui est utilisé pour définir un état chaîne prédéfini avant de démarrer le client. La structure du fichier genesis est décrite ci-dessous | +| genèse predeploy | Prédéploiement un contrat intelligent pour les nouveaux réseaux | + +### indicateurs du serveur {#server-flags} + + +| **Tous les indicateurs de serveur** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [prometheus](/docs/edge/get-started/cli-commands#prometheus) | [block-gas-target](/docs/edge/get-started/cli-commands#block-gas-target) | +| [max-peers](/docs/edge/get-started/cli-commands#max-peers) | [max-inbound-peers](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [max-outbound-peers](/docs/edge/get-started/cli-commands#max-outbound-peers) | [max-enqueued](/docs/edge/get-started/cli-commands#max-enqueued) | +| [log-level](/docs/edge/get-started/cli-commands#log-level) | [log-to](/docs/edge/get-started/cli-commands#log-to) | +| [chaîne](/docs/edge/get-started/cli-commands#chain) | [rejoindre](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [limite de prix](/docs/edge/get-started/cli-commands#price-limit) | [max-slots](/docs/edge/get-started/cli-commands#max-slots) | +| [config](/docs/edge/get-started/cli-commands#config) | [secrets-config](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-interval](/docs/edge/get-started/cli-commands#dev-interval) | +| [no-discover](/docs/edge/get-started/cli-commands#no-discover) | [restaurer](/docs/edge/get-started/cli-commands#restore) | +| [block-time](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +Permet de spécifier le répertoire de données utilisé pour stocker les données du client de Polygon Edge. Par défau. .`./test-chain` + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +Définit l'adresse et le port du service JSON-RPC.`address:port` Si seul le port est défini `:10001` il se liera à toutes les interfaces.`0.0.0.0:10001` S'il est omis, le service sera lié à la valeur par défaut.`address:port` Adresse par défaut :.`0.0.0.0:8545` + +--- + +####

json-rpc-block-range-limit + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +Définit la plage de blocs maximale à prendre en compte lors de l'exécution de requêtes json-rpc qui incluent des valeurs fromBlock/toBlock (p.ex. eth_getLogs). Par défaut :`1000`. + +--- + +####

json-rpc-batch-request-limit + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +Définit la longueur maximale à prendre en compte lors du traitement des requêtes de lot json-rpc. Défaut:.`20` + +--- + +####

grpc + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +Définit l'adresse et le port du service gRPC.`address:port` Adresse par défaut :.`127.0.0.1:9632` + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +Définit l'adresse et le port du service libp2p.`address:port` Adresse par défaut :.`127.0.0.1:1478` + +--- + +####

prometheus + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +Définit l'adresse et le port du serveur prometheus.`address:port` Si seul le port est défini `:5001` le service se liera à toutes les interfaces.`0.0.0.0:5001` S'il est omis, le service ne sera pas démarré. + +--- + +####

block-gas-target + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +Définit la limite de gaz de bloc cible pour la chaîne. Défaut (non appliqué) :.`0` + +Une explication plus détaillée sur la cible de gaz de bloc se trouve dans la [section TxPool](/docs/edge/architecture/modules/txpool#block-gas-target). + +--- + +####

max-peers + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +Définit le nombre maximal d'homologues du client. Défaut:.`40` + +La limite d'homologues doit être spécifiée en utilisant `max-peers` ou `max-inbound/outbound-peers` l'indicateur. + +--- + +####

max-inbound-peers + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +Définit le nombre maximum d'homologues entrants du client. Si `max-peers` est défini, la limite max-inbound-peer est calculée à l'aide des formules suivantes. + +`max-inbound-peer = InboundRatio * max-peers`, où `InboundRatio` est.`0.8` + +--- + +####

max-outbound-peers + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +Définit le nombre maximal d'homologues sortants du client. Si `max-peers` est défini, le nombre max de pairs sortants est calculé à l'aide des formules suivantes. + +`max-outbound-peer = OutboundRatio * max-peers`, où `OutboundRatio` est.`0.2` + +--- + +####

max-enqueued + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +Définit le nombre maximum de transactions en attente par compte. Par défaut :`128`. + +--- + +####

log-level + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +Définit le niveau de registre pour la sortie de la console. Défaut:.`INFO` + +--- + +####

log-to + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +Définit le nom du fichier de registre qui contiendra toutes les sorties du registre de la commande du serveur. Par défaut, tous les registres du serveur seront sortis sur la console (stdout), mais si l'indicateur est défini, il n'y aura pas de sortie vers la console lors de l'exécution de la commande du serveur. + +--- + +####

chaîne + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +Spécifie le fichier de genèse utilisé pour démarrer la chaîne. Défaut:.`./genesis.json` + +--- + +####

rejoindre + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Spécifie l'adresse de l'homologue qui doit être rejoint. + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +Définit l'adresse IP externe sans le port, comme cela peut être vu par les pairs. + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +Définit l'adresse DNS de l'hôte. Ceci peut être utilisé pour annoncer un DNS externe. Prend en charge `dns`,`dns4`,`dns6`. + +--- + +####

limite de prix + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +Définit la limite de prix minimum du gaz à appliquer pour l'acceptation dans le pool. Défaut : `1`. + +--- + +####

max-slots + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +Définit les créneaux maximaux dans le pool. Défaut:.`4096` + +--- + +####

config + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +Spécifie le chemin d'accès à la configuration de CLI. Prend en charge.`.json` + +--- + +####

secrets-config + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +Définit le chemin d'accès au fichier de configuration. Utilisé pour Hashicorp Vault, AWS SSM et GCP Secrets Manager. S'il est omis, le gestionnaire FS secrets local est utilisé. + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +Définit le client en mode dev. Par défaut: `false`. Dans le mode dev, la découverte par les pairs est désactivée par défaut. + +--- + +####

dev-interval + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +Définit l'intervalle de notification de dev du client en secondes. Défaut:.`0` + +--- + +####

no-discover + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +Empêche le client de découvrir d'autres homologues. Défaut:.`false` + +--- + +####

restaurer + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +Restaurer les blocs à partir du fichier d'archive spécifié + +--- + +####

block-time + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +Définit le temps de production du bloc en secondes. Défaut : `2` + +--- + +####

access-control-allow-origins + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +Définit les domaines autorisés pour pouvoir partager les réponses des requêtes JSON-RPC. Ajoute plusieurs indicateurs `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"` pour autoriser plusieurs domaines. Si c'est omis, l'en-tête Access-Control-Allow-Origins sera défini sur `*` et tous les domaines seront autorisés. + +--- + +### indicateurs de genèse {#genesis-flags} +| **Tous les indicateurs de genèse** | +|---------------------------------------|---------------------------------------------| +| [dir](/docs/edge/get-started/cli-commands#dir) | [Nom](/docs/edge/get-started/cli-commands#name) | +| [pos](/docs/edge/get-started/cli-commands#pos) | [epoch-size](/docs/edge/get-started/cli-commands#epoch-size) | +| [premine](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [ibft-validator-type](/docs/edge/get-started/cli-commands#ibft-validator-type) | [ibft-validators-prefix-path](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [ibft-validator](/docs/edge/get-started/cli-commands#ibft-validator) | [block-gas-limit](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [consensus](/docs/edge/get-started/cli-commands#consensus) | [noeud de démarrage](/docs/edge/get-started/cli-commands#bootnode) | +| [max-validator-count](/docs/edge/get-started/cli-commands#max-validator-count) | [min-validator-count](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

dir + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +Définit le répertoire des données de genèse du Polygon Edge. Par défaut :.`./genesis.json` + +--- + +####

Nom + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +Définit le nom pour la chaîne. Défaut:.`polygon-edge` + +--- + +####

pos + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +Définit l'indicateur qui signifie que le client doit utiliser la Preuve d'Enjeu d'IBFT. Défaut de preuve d'autorité si l'indicateur n'est pas fourni ou.`false` + +--- + +####

epoch-size + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +Définit la taille d'époque pour la chaîne. Défaut.`100000` + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +Définit les comptes et les soldes prédominants dans le format.`address:amount` Le montant peut être en décimal ou en hexadécimal. +Solde prédominé par défaut : `0xD3C21BCECCEDA1000000`(1 million de jetons de monnaie native). + +--- + +####

chainid + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +Définit l'Identifiant de la chaîne. Défaut:.`100` + +--- + +####

ibft-validator-type + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +Spécifie le mode de validation des en-têtes de bloc. Valeurs possibles :.`[ecdsa, bls]` Défaut:.`bls` + +--- + +####

ibft-validators-prefix-path + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +Chemin de préfixe pour le répertoire du dossier du validateur. Doit être présent si l'indicateur `ibft-validator` est omis. + +--- + +####

ibft-validator + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Définit les adresses passées comme validateurs IBFT. Doit être présent si l'indicateur `ibft-validators-prefix-path` est omis. +1. Si le réseau fonctionne avec ECDSA, le format est.`--ibft-validator [ADDRESS]` +2. Si le réseau fonctionne avec BLS, le format est.`--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]` + +--- + +####

block-gas-limit + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +Désigne la quantité maximale de gaz utilisée par toutes les opérations d'un bloc. Défaut:.`5242880` + +--- + +####

consensus + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +Définit le protocole de consensus Défaut:.`pow` + +--- + +####

noeud de démarrage + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +URL Multiaddr pour le bootstrap de découverte de p2p. Cet indicateur peut être utilisé plusieurs fois. +Au lieu d'une adresse IP, l'adresse DNS du noeud de démarrage peut être fournie. + +--- + +####

max-validator-count + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +Le nombre maximum de joueurs de stake pouvant rejoindre le validateur défini dans un consensus de PoS. +Ce nombre ne peut pas dépasser la valeur de MAX_SAFE_INTEGER (2^53 - 2). + +--- + +####

min-validator-count + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +Le nombre minimum de joueurs de stake nécessaire pour rejoindre le validateur défini dans un consensus de PoS. +Ce nombre ne peut pas dépasser la valeur de max-validator-count. +Valeur par défaut : 1. + +--- + +### genèse predeploy des indicateurs {#genesis-predeploy-flags} + +

artifacts-path

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +Définit le chemin vers les artéfacts JSON du contrat qui contient le `abi`, `bytecode`et .`deployedBytecode` + +--- + +

chaîne

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +Définit le chemin d'accès au `genesis.json`fichier qui devrait être mis à jour. Défaut `./genesis.json`. + +--- + +

constructor-args

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +Définit les arguments constructeurs de contrats intelligents, le cas échéant. Pour un guide détaillé sur la façon à laquelle ces arguments devraient ressembler, veuillez consulter [l'article prédéploiement](/docs/edge/additional-features/predeployment). + +--- + +

predeploy-address

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +Définit l'adresse à predeploy Défaut `0x0000000000000000000000000000000000001100`. + +--- + + +## Les Commandes De L'Opérateur {#operator-commands} + +### Commandes des Pairs {#peer-commands} + +| **Commande** | **Description** | +|------------------------|-------------------------------------------------------------------------------------| +| ajout de pairs | Ajoute un nouveau pair en utilisant son adresse libp2p | +| liste de pairs | Répertorie tous les pairs auxquels le client est connecté via libp2p | +| statut des pairs | Renvoie le statut d'un pair spécifique de la liste des pairs, en utilisant l'adresse libp2p | + +

les pairs ajoutent des indicateurs

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Adresse libp2p du pair au format multiaddr. + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +Adresse de l'API gRPC. Défaut:.`127.0.0.1:9632` + +

indicateurs de la liste des pairs

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +Adresse de l'API gRPC. Défaut:.`127.0.0.1:9632` + +

indicateurs d'état des pairs

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Identifiant de nœud Libp2p d'un pair spécifique dans le réseau p2p. + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +Adresse de l'API gRPC. Défaut:.`127.0.0.1:9632` + +### Commandes IBFT {#ibft-commands} + +| **Commande** | **Description** | +|------------------------|-------------------------------------------------------------------------------------| +| instantané ibft | Renvoie l'instantané IBFT | +| candidats ibft | Cette requête interroge l'ensemble actuel de candidats proposés, ainsi que les candidats qui n'ont pas encore été inclus | +| proposition ibft | Propose un nouveau candidat à ajouter / supprimer de l'ensemble des validateurs | +| statut ibft | Renvoie l'état général du client IBFT | +| Changement d'ibft | Ajoutez des configurations de fourche dans le fichier genesis.json pour changer de type IBFT | +| quorum ibft | Spécifie le numéro de bloc après lequel la méthode de la taille du quorum optimale sera utilisée pour parvenir à un consensus | + + +

indicateurs d'instantané ibft

+ +

nombre

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +La hauteur de bloc (nombre) pour l'instantané. + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +Adresse de l'API gRPC. Défaut:.`127.0.0.1:9632` + +

indicateurs des candidats ibft

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Adresse de l'API gRPC. Défaut:.`127.0.0.1:9632` + +

indicateurs de proposition ibft

+ +

vote

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +Propose une modification de l'ensemble de validateurs. Valeurs possibles :.`[auth, drop]` + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +Adresse du compte pour lequel le vote doit avoir lieu. + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +Clé Publique BLS du compte faisant l'objet d'un vote, nécessaire uniquement en mode BLS. + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Adresse de l'API gRPC. Défaut:.`127.0.0.1:9632` + +

indicateurs du statut ibft

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +Adresse de l'API gRPC. Défaut:.`127.0.0.1:9632` + +

indicateurs de changement ibft

+ +

chaîne

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +Spécifie le fichier de genèse à mettre à jour. Défaut:.`./genesis.json` + +--- + +

Type

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +Spécifie le type IBFT à modifier. Valeurs possibles :.`[PoA, PoS]` + +--- + +

déploiement

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +Spécifie la hauteur de déploiement du contrat. Uniquement disponible avec PoS. + +--- + +

à partir de

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +Spécifie le mode de validation des en-têtes de bloc. Valeurs possibles :.`[ecdsa, bls]` Défaut:.`bls` + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +Chemin de préfixe pour les répertoires des nouveaux validateurs. Doit être présent si l'indicateur `ibft-validator` est omis. Disponible uniquement lorsque le mode IBFT est PoA (`--pos`l'indicateur est omis). + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Définit les adresses passées comme validateurs IBFT utilisés après la fourche. Doit être présent si l'indicateur `ibft-validators-prefix-path` est omis. Disponible uniquement en mode PoA. +1. Si le réseau fonctionne avec ECDSA, le format est.`--ibft-validator [ADDRESS]` +2. Si le réseau fonctionne avec BLS, le format est.`--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]` + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +Le nombre maximum de joueurs de stake pouvant rejoindre le validateur défini dans un consensus de PoS. +Ce nombre ne peut pas dépasser la valeur de MAX_SAFE_INTEGER (2^53 - 2). + +--- + +

min-validator-count

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +Le nombre minimum de joueurs de stake nécessaire pour rejoindre le validateur défini dans un consensus de PoS. +Ce nombre ne peut pas dépasser la valeur de max-validator-count. +Valeur par défaut : 1. + +Spécifie la hauteur de départ de la fourche. + +--- + +

indicateurs de quorum ibft

+ +

à partir de

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +La hauteur pour modifier le calcul du quorum sur QuorumOptimal, qui utilise la formule `(2/3 * N)`, `N` est le nombre de nœuds de validateur. Veuillez noter qu'il s'agit d'une compatibilité ancienne, c'est-à-dire uniquement pour les chaînes qui ont utilisé un calcul du Quorum jusqu'à une certaine hauteur de bloc. + +--- + +

chaîne

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +Spécifie le fichier de genèse à mettre à jour. Défaut:.`./genesis.json` + +### Commandes du Pool de Transactions {#transaction-pool-commands} + +| **Commande** | **Description** | +|------------------------|--------------------------------------------------------------------------------------| +| statut txpool | Renvoie le nombre de transactions dans le pool | +| abonnement txpool | S'abonne aux événements dans le pool de transactions | + +

indicateurs du statut txpool

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +Adresse de l'API gRPC. Défaut:.`127.0.0.1:9632` + +

indicateurs d'abonnement txpool

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +Adresse de l'API gRPC. Défaut:.`127.0.0.1:9632` + +--- + +

promu

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +S'abonne aux événements tx promus dans le TxPool. + +--- + +

supprimé

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +S'abonne aux événements tx supprimés dans le TxPool. + +--- + +

rétrogradé

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +S'abonne aux événements tx rétrogradés dans le TxPool. + +--- + +

ajouté

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +S'abonne aux événements tx ajoutés au TxPool. + +--- + +

placé dans la file d'attente

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +S'abonne aux événements tx en file d'attente dans les files d'attente du compte. + +--- + +### Les commandes de Blockchain {#blockchain-commands} + +| **Commande** | **Description** | +|------------------------|-------------------------------------------------------------------------------------| +| statut | Renvoie le statut du client. La réponse détaillée peut être trouvée ci-dessous | +| contrôler | S'abonne à un flux d'événements de blockchain. La réponse détaillée peut être trouvée ci-dessous | +| version | Renvoie la version actuelle du client | + +

indicateurs d'état

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +Adresse de l'API gRPC. Défaut:.`127.0.0.1:9632` + +

surveiller les indicateurs

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +Adresse de l'API gRPC. Défaut:.`127.0.0.1:9632` + +--- +

commande de version

+ + + + + + version + + + + +Affiche la version de version, la branche git, le hachage de commit et le temps de construction. + +## Les Commandes Secrets {#secrets-commands} + +| **Commande** | **Description** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| initialisation des secrets | Initialise les clés privées vers le gestionnaire des secrets correspondant | +| secrets générés | Génère un fichier de configuration de gestionnaire de secrets qui peut être analysé par Polygon Edge | +| sortie secrets | Imprimez l'adresse de clé publique BLS, l'adresse de clé publique validatrice et l'ID de nœud pour référence | + +### indicateurs d'initialisation de secrets {#secrets-init-flags} + +

config

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +Définit le chemin d'accès au fichier de configuration. Utilisé pour Hashicorp Vault. S'il est omis, le gestionnaire FS secrets local est utilisé. + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +Définit le répertoire des données de Polygon Edge si la FS locale est utilisée. + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +Définit l'indicateur précisant s'il faut générer une clé ECDSA. Défaut: `true`. + +--- + +

réseau

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +Définit l'indicateur précisant s'il faut générer une clé de Réseau Libp2p. Défaut: `true`. + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +Définit l'indicateur précisant s'il faut générer une clé de BLS. Défaut: `true`. + +### indicateurs de secrets générés {#secrets-generate-flags} + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +Définit le répertoire du fichier de configuration du gestionnaire de secrets par défaut : `./secretsManagerConfig.json` + +--- + +

Type

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +Spécifie le type du gestionnaire de secrets [`hashicorp-vault`]. Défaut : `hashicorp-vault` + +--- + +

jeton

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +Spécifie le jeton d'accès pour le service + +--- + +

url du serveur

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +Spécifie l'URL du serveur pour le service + +--- + +

nom

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +Spécifie le nom du nœud pour la conservation des enregistrements en service. Défaut : `polygon-edge-node` + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Spécifie l'espace de noms utilisé pour le gestionnaire de secrets Hashicorp Vault. Défaut : `admin` + +### secrets sorties flags {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +Définit l'indicateur indiquant s'il faut uniquement afficher la clé publique BLS. Défaut : `true` + +--- + +

config

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +Définit le chemin d'accès au fichier de configuration. S'il est omis, le gestionnaire FS secrets local est utilisé. + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +Définit le répertoire des données de Polygon Edge si la FS locale est utilisée. + +--- + +

node-id

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +Définit l'indicateur indiquant s'il faut uniquement produire l'ID de nœud réseau. Défaut : `true` + +--- + +

Validateur

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +Définit l'indicateur indiquant s'il faut uniquement afficher l'adresse validateur. Défaut : `true` + +--- + +## Réponses {#responses} + +### Réponse D'État {#status-response} + +L'objet de réponse est défini en utilisant les Protections de Protocole. +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### Surveiller La Réponse {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## Utilitaires {#utilities} + +### les commandes de liste blanche {#whitelist-commands} + +| **Commande** | **Description** | +|------------------------|-------------------------------------------------------------------------------------| +| afficher la liste blanche | Affiche les informations de la liste blanche | +| déploiement de la liste blanche | Met à jour la liste blanche de déploiement des contrats intelligents | + +

afficher la liste blanche

+ + + + + whitelist show + + + + +Affiche les informations de la liste blanche. + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +Spécifie le fichier de genèse à mettre à jour. Défaut: `./genesis.json`. + +--- + +

déploiement de la liste blanche

+ +

chaîne

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +Spécifie le fichier de genèse à mettre à jour. Défaut: `./genesis.json`. + +--- + +

ajouter

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Ajoute une nouvelle adresse à la liste blanche de déploiement du contrat Seules les adresses de la liste blanche de déploiement de contrats peuvent déployer des contrats. Si vide, n'importe quelle adresse peut exécuter le déploiement du contrat + +--- + +

supprimer

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Supprime une adresse de la liste blanche de déploiement du contrat. Seules les adresses de la liste blanche de déploiement de contrats peuvent déployer des contrats. Si vide, n'importe quelle adresse peut exécuter le déploiement du contrat + +--- + +### les indicateurs de sauvegarde {#backup-flags} + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +Adresse de l'API gRPC. Défaut: `127.0.0.1:9632`. + +--- + +

sortie

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +La trajectoire du fichier d'archive à sauvegarder. + +--- + +

à partir de

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +La hauteur du début des blocs dans l'archive. Défaut : 0. + +--- + +

vers

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +La hauteur de la fin des blocs dans l'archive. + +--- + +## Modèle de Genèse {#genesis-template} +Le fichier de genèse doit être utilisé pour définir l'état initial de la blockchain (par exemple si certains comptes doivent avoir un solde de départ). + +Le fichier *./genesis.json* suivant est généré : +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### Répertoire Des Données {#data-directory} + +Lors de l'exécution de l'indicateur *data-dir*, un dossier **test-chain** est généré. La structure des dossiers se compose des sous-dossiers suivants : +* **blockchain** - Enregistre le LevelDB pour les objets de blockchain +* **trie** - Enregistre le LevelDB pour les essais de Merkle +* **keystore** - Enregistre les clés privées du client. Cela inclut la clé privée de libp2p et la clé privée de scellement/validateur +* **consensus** - Enregistre toutes les informations du consensus dont le client pourrait avoir besoin pendant son travail. + +## Ressources {#resources} +* **[Protection du Protocole](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/fr-edge/get-started/installation.md b/archive/edge/fr-edge/get-started/installation.md new file mode 100644 index 0000000000..19569acdd7 --- /dev/null +++ b/archive/edge/fr-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: Installation +description: "Comment installer Polygon Edge" +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +Veuillez vous référer à la méthode d'installation qui est la plus applicable à votre cas. + +Nous vous recommandons d'utiliser les versions prédéfinies et de vérifier les sommes de contrôle fournies. + +## Versions pré-construites {#pre-built-releases} + +Veuillez vous référer à la page des [Versions de GitHub](https://github.com/0xPolygon/polygon-edge/releases) pour une liste des versions. + +Polygon Edge est livré avec des fichiers binaires AMD64/ARM64 compilés de manière croisée pour Darwin et Linux. + +--- + +## Image Docker {#docker-image} + +Les images Docker officielles sont hébergées sur le registre [hub.docker.com](https://hub.docker.com/r/0xpolygon/polygon-edge). + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## Construire à partir de la source {#building-from-source} + +Avant de l'utiliser, `go install` assurez-vous que Go `>=1.18` est installé et correctement configuré. + +La branche stable est la branche de la dernière version. + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## Utilisation de `go install` + +Avant de l'utiliser, `go install` assurez-vous que Go `>=1.17` est installé et correctement configuré. + +`go install github.com/0xPolygon/polygon-edge@release/` + +Le binaire sera disponible dans votre variable `GOBIN`d'environnement et inclura les modifications de la dernière version. Vous pouvez consulter [les versions GitHub](https://github.com/0xPolygon/polygon-edge/releases) pour savoir lequel est le plus récent. diff --git a/archive/edge/fr-edge/get-started/set-up-ibft-locally.md b/archive/edge/fr-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..aed15561cc --- /dev/null +++ b/archive/edge/fr-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,417 @@ +--- +id: set-up-ibft-locally +title: Configuration Locale +description: "Guide de configuration locale étape par étape." +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution Ce guide est uniquement à des fins de test + +Le guide ci-dessous vous explique comment configurer un réseau de Polygon Edge sur votre machine locale à des fins de test et de développement. +objectifs. + +La procédure diffère considérablement de la façon dont vous pourriez souhaiter configurer le réseau de Polygon Edge pour un scénario d'utilisation réel sur +un fournisseur de nuage: **[Configuration](/docs/edge/get-started/set-up-ibft-on-the-cloud)** du Cloud + +::: + + +## Exigences {#requirements} + +Référez-vous à la rubrique [Installation](/docs/edge/get-started/installation) pour installer Polygon Edge. + +## Aperçu {#overview} + +![Configuration Locale](/img/edge/ibft-setup/local.svg) + +Dans ce guide, notre objectif est d'établir un réseau de blockchain opérationnel `polygon-edge` fonctionnant avec le [Protocole de consensus IBFT](https://github.com/ethereum/EIPs/issues/650). +Le réseau blockchain sera composé de 4 nœuds qui sont tous les 4 des nœuds de validation, et en tant que tels sont éligibles à la fois pour la proposition et pour la validation des blocs provenant d'autres proposants. +Tous les 4 nœuds fonctionneront sur la même machine, car l'idée de ce guide est de vous donner un groupe IBFT entièrement fonctionnel dans le moins de temps possible. + +Pour y parvenir, nous vous guiderons à travers 4 étapes faciles : + +1. L'initialisation des répertoires de données générera les deux clés de validateur pour chacun des 4 nœuds, et initialisera les répertoires de données de blockchain vides. Les clés de validateur sont importantes car nous devons amorcer le bloc de genèse avec l'ensemble initial de validateurs à l'aide de ces clés. +2. La préparation de la chaîne de connexion pour le nœud de démarrage sera l'information vitale pour chaque nœud que nous exécuterons pour savoir à quel nœud se connecter au démarrage pour la première fois. +3. La génération du `genesis.json` fichier nécessitera comme entrée à la fois les clés de validateur générées à l'**étape 1** utilisées pour configurer les validateurs initiaux du réseau dans le bloc de genèse et la chaîne de connexion bootnode de l'**étape 2**. +4. Exécutez tous les nœuds est l'objectif final de ce guide et ce sera la dernière étape, nous allons indiquer aux nœuds quel répertoire de données utiliser et où trouver le `genesis.json` qui démarre l'état de réseau initial. + +Comme les quatre nœuds seront exécutés sur localhost, au cours du processus d'installation, il est prévu que tous les répertoires de données +pour chacun des noeuds se trouvent dans le même répertoire parent. + +:::info Nombre de validateurs + +Il n'y a pas de minimum pour le nombre de nœuds dans un groupe, ce qui signifie que des groupes avec seulement un nœud validateur sont possibles. Sachez qu'avec un cluster à nœud _unique_, il n'y a **pas de tolérance aux pannes** ni d**e garantie BFT**. + +Le nombre minimum de nœuds recommandé pour obtenir une garantie BFT est de 4 - puisque dans un groupe à 4 nœuds, la défaillance d'un nœud peut être tolérée, avec les 3 restants fonctionnant normalement. + +::: + +## Étape 1 : Initialisez les dossiers de données pour IBFT et générez des clés de validateur {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +Pour être opérationnel avec IBFT, vous devez initialiser les dossiers de données, +un pour chaque nœud : + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +Chacune de ces commandes imprimera la clé du validateur, la clé publique bls et [l'identifiant du nœud](https://docs.libp2p.io/concepts/peer-id/). Vous aurez besoin de l'identifiant de nœud du premier nœud pour l'étape suivante. + +### Secrets de Sortie {#outputting-secrets} +La sortie des secrets peut être récupérée à nouveau, si nécessaire. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## Étape 2 : Préparez la chaîne de connexion multiaddr pour le nœud de démarrage {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +`bootnode`Pour qu'un nœud réussisse à établir la connectivité, il doit savoir à quel serveur se connecter pour obtenir +les informations sur tous les nœuds restants sur le réseau. Le `bootnode` est parfois aussi connu sous le nom de serveur `rendezvous` dans le jargon p2p. + +`bootnode` n'est pas une instance spéciale du nœud polygon-edge. Chaque noeud polygon-edge peut servir de `bootnode`, mais +chaque noeud polygon-edge doit avoir un ensemble de noeuds récupérateurs spécifiés qui seront contactés pour fournir des informations sur la façon de se connecter avec +tous les nœuds restants dans le réseau. + +Pour créer la chaîne de connexion permettant de spécifier le nœud de démarrage, nous devrons nous conformer +au [format multiaddr](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +Dans ce guide, nous traiterons les premiers et deuxièmes nœuds comme des nœuds de démarrage pour tous les autres nœuds. Ce qui se passera dans ce scénario +est que les nœuds qui se connectent au `node 1` ou o `node 2`btiendront des informations sur la façon de se connecter les uns aux autres via le +nœud récupérateur mutuellement contacté. + +:::info Vous devez spécifier au moins un nœud de démarrage pour démarrer un nœud + +Au moins **un** nœud de démarrage est requis, afin que les autres nœuds du réseau puissent se découvrir. Plus de nœud de démarrage sont recommandés, étant donné qu'ils +assurent la résilience du réseau en cas de panne. Dans ce guide, nous énumérerons deux nœuds, mais cela peut être modifié à la volée, sans impact sur la validité du fichier `genesis.json` . + +::: + +Étant donné que nous fonctionnons sur localhost, on peut absolument assumer que le `` est `127.0.0.1`. + +Pour le ``, nous utiliserons `10001` puisque nous allons configurer le serveur libp2p pour `node 1` pour écouter ultérieurement sur ce port. + +Et enfin, nous avons besoin du `` que nous pouvons obtenir à partir de la sortie de la commande précédemment exécutée `polygon-edge secrets init --data-dir test-chain-1` (qui a été utilisée pour générer des clés et des répertoires de données pour le `node1`) + +Après l'assemblage, la chaîne de connexion multiaddr au `node 1` que nous utiliserons comme nœud de démarrage, ressemblera à ceci (seul le `` qui est à la fin devrait être différent) : +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +De même, nous construisons multiaddr pour le deuxième nœud de démarrage comme indiqué ci-dessous +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info Noms d'hôte NS au lieu d'ips + +Polygon Edge prend en charge l'utilisation des noms d'hôte DNS pour la configuration des nœuds. Il s'agit d'une fonctionnalité très utile pour les déploiements basés sur le cloud, car l'adresse IP du nœud peut changer pour diverses raisons. + +Le format multiaddr pour la chaîne de connexion lors de l'utilisation des noms d'hôte DNS est le suivant : +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## Étape 3 : Générez le fichier de genèse avec les 4 nœuds comme validateurs {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +Ce que fait cette commande : + +* Le `--ibft-validators-prefix-path` définit le chemin du dossier de préfixe sur celui spécifié que IBFT peut utiliser + +dans Polygon Edge. Ce répertoire est utilisé pour héberger le dossier `consensus/`, dans lequel la clé privée du validateur est conservée. La +clé publique du validateur est nécessaire pour construire le fichier de genèse - la liste initiale des nœuds de démarrage. +Cet indicateur n'a de sens que lors de la configuration du réseau sur localhost, car dans un scénario réel, nous ne pouvons pas nous attendre à ce que +tous les répertoires de données des nœuds se trouvent sur le même système de fichiers à partir duquel nous pouvons facilement lire leurs clés publiques. +* Le `--bootnode` définit l'adresse du nœud de démarrage qui permettra aux nœuds de se trouver. Nous utiliserons la chaîne multiaddr du `node 1`, comme mentionné à l'**étape 2**. + +Le résultat de cette commande est le fichier `genesis.json` qui contient le bloc genesis de notre nouvelle blockchain, avec le jeu de validateur prédéfini et la configuration pour savoir quel nœud contacter en premier afin d'établir la connectivité. + +:::info Passer à ECDSA + +BLS est le mode de validation par défaut des en-têtes de bloc. Si vous souhaitez que votre chaîne s'exécute en mode ECDSA, vous pouvez utiliser l'indicateur `—ibft-validator-type`, avec l'argument `ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info Soldes du compte de pré-exploitation + +Vous souhaiterez probablement configurer votre réseau de blockchain avec certaines adresses ayant des soldes « pré-exploités ». + +Pour cela, passez autant `--premine` d'indicateurs que vous le souhaitez par adresse que vous souhaitez initialiser avec un certain solde sur la blockchain. + +Par exemple, si nous souhaitons pré-exploiter 1000 ETH à l'adresse `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` dans notre bloc de genèse, nous aurions besoin de fournir l'argument suivant : + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Notez que le montant pré-exploité est en WEI, pas en ETH.** + +::: + +:::info Définir la limite de gaz du bloc + +La limite de gaz par défaut pour chaque bloc est `5242880`. Cette valeur est écrite dans le fichier de genèse, mais vous voudrez peut-être +l'augmenter / le diminuer. + +Pour cela, vous pouvez utiliser l'indicateur `--block-gas-limit` suivi de la valeur souhaitée comme indiqué ci-dessous : + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Définir la limite du descripteur de fichier à système + +La limite du descripteur de fichier par défaut ( nombre maximum de fichiers ouverts ) sur certains systèmes d'exploitation est assez petite. Si les nœuds doivent avoir un débit élevé, vous pouvez envisager d'augmenter cette limite au niveau du Système d'Exploitation. + +Pour la distribution Ubuntu, la procédure est la suivante ( si vous n'utilisez pas la distribution Ubuntu/Debian, consultez la documentation officielle de votre système d'exploitation ) : +- Vérifiez les limites actuelles du système d'exploitation ( fichiers ouverts ) +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- Augmenter la limite de fichiers ouverts + - Localement - n'affecte que la session en cours: + ```shell + ulimit -u 65535 + ``` + - Globalement ou par utilisateur ( ajoutez des limites à la fin du fichier /etc/security/limits.conf ) : + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +De manière facultative, modifiez les paramètres supplémentaires, enregistrez le fichier et redémarrez le système. Après le redémarrage, vérifiez à nouveau la limite du descripteur de fichier. +Il doit être défini sur la valeur que vous avez définie dans le fichier limits.conf. +::: + + +## Étape 4: Préparez tous les clients {#step-4-run-all-the-clients} + +Parce que nous essayons d'exécuter un réseau de Polygon Edge composé de 4 nœuds se trouvant tous sur la même machine, nous devons éviter les conflits de port. C'est pourquoi nous utiliserons le raisonnement suivant pour déterminer les ports d'écoute de chaque serveur d'un nœud: + +- `10000` pour le serveur gRPC de `node 1`, `20000` pour le serveur gRPC de `node 2`, etc. +- `10001` pour le serveur libp2p de `node 1`, `20001` pour le serveur libp2p de `node 2`, etc. +- `10002` pour le serveur JSON-RPC de `node 1`, `20002` pour le serveur JSON-RPC de `node 2`, etc. + +Pour exécuter le **premier** client (notez le port `10001` puisqu'il a été utilisé dans le cadre du multiaddr libp2p dans **l'étape 2** avec l'ID de nœud du nœud 1): + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +Pour exécuter le **deuxième** client: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +Pour préparer le **troisième** client: + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +Pour exécuter le **quatrième** client: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +Pour revenir brièvement sur ce qui a été fait jusqu'à présent: + +* Le répertoire des données client a été spécifié comme étant **./test-chain-\*** +* Les serveurs GRPC ont été démarrés sur les ports **10000**, **20000**, **30000** et **40000**, pour chaque nœud, respectivement +* Les serveurs de libp2p ont été démarrés sur les ports **10001**, **20001**, **30001** et **40001**, pour chaque nœud, respectivement. +* Les serveurs JSON-RPC ont été démarrés sur les ports **10002**, **20002**, **30002** et **40002**, pour chaque nœud, respectivement +* L'indicateur de *scellage* signifie que le noeud qui est en cours de démarrage va participer au scellage de bloc +* L'indicateur de *chaîne* spécifie quel fichier de Genèses doit être utilisé pour la configuration de la chaîne + +La structure du fichier de genèse est traitée dans la section des [Commandes CLI](/docs/edge/get-started/cli-commands) . + +Après avoir exécuté les commandes précédentes, vous avez configuré un réseau de Polygon Edge à 4 nœuds, capable de sceller les blocs et de se remettre de la défaillance du nœud. + +:::info Démarrez le client à l'aide du fichier de configuration + +Au lieu de spécifier tous les paramètres de configuration en tant qu'arguments de CLI, le client peut également être démarré à l'aide d'un fichier de configuration en exécutant la commande suivante: + +````bash +polygon-edge server --config +```` +Exemple : + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Actuellement, nous prenons en charge `yaml`et les fichiers de configuration basés sur la `json`base, exemples de fichiers de configuration peuvent être trouvés **[ici](/docs/edge/configuration/sample-config)** + +::: + +:::info Étapes pour exécuter un nœud non validateur + +Un non-validateur synchronisera toujours les derniers blocs reçus du nœud validateur, vous pouvez démarrer un nœud non-validateur en exécutant la commande suivante. + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +Par exemple, vous pouvez ajouter un **cinquième** client Non validateur en exécutant la commande suivante : + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info Spécifiez la limite de prix + +Un nœud de Polygon Edge peut être démarré avec une **limite de prix** définie pour les transactions entrantes. + +L'unité de la limite de prix est. `wei`. + +Fixer une limite de prix signifie que toute transaction traitée par le nœud actuel devra avoir un prix de gaz **plus élevé** que la limite de prix définie, sinon elle ne sera pas incluse dans un bloc. + +Le fait que la majorité des nœuds respectent une certaine limite de prix, cela applique la règle selon laquelle les transactions dans le réseau ne peuvent être inférieures à un certain niveau de prix. + +La valeur par défaut de la limite de prix est `0`, ce qui signifie qu'elle n'est pas appliquée du tout par défaut. + +Exemple d'utilisation de `--price-limit` l'indicateur : +````bash +polygon-edge server --price-limit 100000 ... +```` + +Il convient de noter que les limites de prix **ne sont appliquées que sur les transactions non locales**, ce qui signifie +que la limite de prix ne s'applique pas aux transactions ajoutées localement sur le nœud. + +::: + +:::info URL de WebSocket + +Par défaut, lorsque vous exécutez le Polygon Edge, il génère une URL de WebSocket basée sur l'emplacement de la chaîne. +Le schéma d'URL `wss://` est utilisé pour les liens HTTPS et `ws://` pour HTTP. + +URL de WebSocket de l'hôte local : +````bash +ws://localhost:10002/ws +```` +Veuillez noter que le numéro de port dépend du port JSON-RPC choisi pour le nœud. + +URL de WebSocket Edgenet: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## Étape 5 : Interagissez avec le réseau de polygon-edge {#step-5-interact-with-the-polygon-edge-network} + +Maintenant que vous avez configuré au moins un client en cours d'exécution, vous pouvez aller de l'avant et interagir avec la blockchain en utilisant le compte que vous avez exploité ci-dessus et en spécifiant l'URL JSON-RPC à l'un des 4 nœuds : +- Noeud 1 : `http://localhost:10002` +- Noeud 2 : `http://localhost:20002` +- Noeud 3 : `http://localhost:30002` +- Noeud 4 : `http://localhost:40002` + +Suivez ce guide pour envoyer des commandes d'opérateur au groupe nouvellement construit : [comment interroger les informations d'opérateur](/docs/edge/working-with-node/query-operator-info) (les ports GRPC pour le groupe que nous avons construit sont respectivement `10000`/`20000`/`30000`/`40000` pour chaque nœud) diff --git a/archive/edge/fr-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/fr-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..cb81af1a61 --- /dev/null +++ b/archive/edge/fr-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,439 @@ +--- +id: set-up-ibft-on-the-cloud +title: Configuration Cloud +description: "Guide détaillé de configuration cloud." +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info Ce guide concerne les configurations du mainnet ou du testnet + +Le guide ci-dessous vous expliquera comment configurer un réseau de Polygon Edge sur un fournisseur de cloud pour une configuration de production de votre testnet ou mainnet. + +Si vous souhaitez configurer un réseau de Polygon Edge localement pour tester rapidement le `polygon-edge` avant de procéder à une configuration de type production, veuillez vous référer à +**[Configuration locale](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## Exigences {#requirements} + +Référez-vous à la rubrique [Installation](/docs/edge/get-started/installation) pour installer Polygon Edge. + +### Configuration de la connectivité VM {#setting-up-the-vm-connectivity} + +Selon votre choix du fournisseur de cloud, vous pouvez rétablir une connectivité et des règles entre les VM à l'aide d'un pare-feu, +de groupes de sécurité ou des listes de contrôle d'accès. + +Comme la seule partie du `polygon-edge` qui doit être exposée à d'autres machines virtuelles est le serveur libp2p, permettre simplement +toutes les communications entre les VM sur le port libp2p par défaut `1478` est suffisant. + +## Aperçu {#overview} + +![Configuration Cloud](/img/edge/ibft-setup/cloud.svg) + +Dans ce guide, notre objectif est d'établir un réseau de blockchain opérationnel `polygon-edge` fonctionnant avec le [ Protocole de consensus IBFT](https://github.com/ethereum/EIPs/issues/650). +Le réseau de blockchain sera composé de 4 nœuds qui sont tous les 4 des nœuds de validation, et en tant que tels sont éligibles à la fois pour la proposition et pour la validation des blocs provenant d'autres proposants. +Chacun des 4 nœuds fonctionnera sur sa propre machine virtuelle, car l'idée de ce guide est de vous procurer un réseau de Polygon Edge entièrement fonctionnel tout en gardant les clés de validation privées pour assurer une configuration de réseau indépendant. + +Pour y parvenir, nous vous guiderons à travers 4 étapes faciles : + +0. Jetez un oeil sur la liste des **exigences** ci-dessus +1. Générez les clés privées pour chacun des validateurs, et initialisez le répertoire de données +2. Préparez la chaîne de connexion pour que le nœud de démarrage soit placé dans le système partagé `genesis.json` +3. Créez le `genesis.json` sur votre machine locale et envoyez/transférez-le vers chacun des nœuds +4. Démarrez tous les nœuds + +:::info Nombre de validateurs + +Il n'y a pas de minimum pour le nombre de nœuds dans un groupe, ce qui signifie que des groupes avec seulement un nœud validateur sont possibles. Sachez qu'avec un cluster à nœud _unique_, il n'y a **pas de tolérance aux pannes** ni d**e garantie BFT**. + +Le nombre minimum de nœuds recommandé pour obtenir une garantie BFT est de 4 - puisque dans un groupe à 4 nœuds, la défaillance d'un nœud peut être tolérée, avec les 3 restants fonctionnant normalement. + +::: + +## Étape 1 : Initialisez les dossiers de données et générez les clés de validation {#step-1-initialize-data-folders-and-generate-validator-keys} + +Pour rendre Polygon Edge opérationnel, vous devez initialiser les dossiers de données, sur chaque nœud : + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +Chacune de ces commandes imprimera la clé du validateur, la clé publique bls et [l'identifiant du nœud](https://docs.libp2p.io/concepts/peer-id/). Vous aurez besoin de l'identifiant de nœud du premier nœud pour l'étape suivante. + +### Secrets de Sortie {#outputting-secrets} +La sortie des secrets peut être récupérée à nouveau, si nécessaire. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning Gardez votre répertoire de données pour vous ! + +Les répertoires de données générés ci-dessus, en plus d'initialiser les répertoires pour conserver l'état de la blockchain, généreront également les clés privées de votre validateur. +**Cette clé doit être gardée secrète, car en cas de vol, elle rendrait quelqu'un capable de se faire passer pour vous, en tant que validateur du réseau !** + +::: + +## Étape 2 : Préparez la chaîne de connexion multiaddr pour le nœud de démarrage {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Pour qu'un nœud réussisse à établir la connectivité, il doit savoir à quel serveur `bootnode` se connecter pour obtenir +les informations sur tous les nœuds restants sur le réseau. Le `bootnode` est parfois aussi connu sous le nom de serveur `rendezvous`dans le jargon p2p. + +`bootnode` n'est pas une instance spéciale d'un nœud de Polygon Edge. Chaque nœud de Polygon Edge peut servir de `bootnode` et +chaque nœud de Polygon Edge doit avoir un ensemble de nœuds de démarrage spécifiés qui seront contactés pour fournir des informations sur la façon de se connecter à tous les nœuds restants dans le réseau. + +Pour créer la chaîne de connexion permettant de spécifier le nœud de démarrage, nous devrons nous conformer +au [format multiaddr](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +Dans ce guide, nous traiterons les premiers et deuxièmes nœuds comme des nœuds de démarrage pour tous les autres nœuds. Ce qui se passera dans ce scénario +est que les nœuds qui se connectent au `node 1` ou o `node 2`btiendront des informations sur la façon de se connecter les uns aux autres via le +nœud récupérateur mutuellement contacté. + +:::info Vous devez spécifier au moins un nœud de démarrage pour démarrer un nœud + +Au moins **un** nœud de démarrage est requis, afin que les autres nœuds du réseau puissent se découvrir. Plus de nœud de démarrage sont recommandés, étant donné qu'ils +assurent la résilience du réseau en cas de panne. Dans ce guide, nous énumérerons deux nœuds, mais cela peut être modifié à la volée, sans impact sur la validité du fichier `genesis.json`. + +::: + +Comme la première partie de la chaîne de connexion multiaddr est le``, ici, vous devrez entrer l'adresse IP accessible par d'autres nœuds, selon votre configuration, il peut s'agir d'une adresse IP privée ou publique, pas`127.0.0.1`. + +Pour le,`` nous utiliserons`1478`, puisqu'il s'agit du port libp2p par défaut. + +Et enfin, nous avons besoin du `` que nous pouvons obtenir à partir de la sortie de la commande précédemment `polygon-edge secrets init --data-dir data-dir` exécutée ( qui a été utilisée pour générer des clés et des répertoires de données pour le `node 1`) + +Après l'assemblage, la chaîne de connexion multiaddr au `node 1` que nous utiliserons comme nœud de démarrage, ressemblera à ceci (seul le `` qui est à la fin devrait être différent) : +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +De même, nous construisons multiaddr pour le deuxième nœud de démarrage comme indiqué ci-dessous +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info Noms d'hôte NS au lieu d'ips + +Polygon Edge prend en charge l'utilisation des noms d'hôte DNS pour la configuration des nœuds. Il s'agit d'une fonctionnalité très utile pour les déploiements basés sur le cloud, car l'adresse IP du nœud peut changer pour diverses raisons. + +Le format multiaddr pour la chaîne de connexion lors de l'utilisation des noms d'hôte DNS est le suivant : +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## Étape 3 : Générez le fichier de genèse avec les 4 nœuds comme validateurs {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +Cette étape peut être exécutée sur votre machine locale, mais vous aurez besoin des clés de validation publiques pour chacun des 4 validateurs. + +Les validateurs peuvent partager en toute sécurité le `Public key (address)` comme affiché ci-dessous dans la sortie de leurs `secrets init` commandes, de sorte que +vous puissiez générer en toute sécurité le fichier genesis.json avec ces validateurs dans l'ensemble initial de validateurs, identifiés par leurs clés publiques : + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +Étant donné que vous avez reçu les 4 clés publiques des validateurs, vous pouvez exécuter la commande suivante pour générer le `genesis.json` + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +Que fait cette commande : + +* Le `--ibft-validator` définit la clé publique du validateur qui doit être incluse dans le validateur initial défini dans le bloc de genèse. Il peut y avoir plusieurs validateurs initiaux. +* Le `--bootnode` définit l'adresse du nœud de démarrage qui permettra aux nœuds de se trouver. Nous utiliserons la chaîne multiaddr du `node 1`, comme mentionné à **l'étape 2**, bien que vous puissiez ajouter autant de nœuds de démarrage que vous le souhaitez, comme indiqué ci-dessus. + +:::info Passer à ECDSA + +BLS est le mode de validation par défaut des en-têtes de bloc. Si vous souhaitez que votre chaîne s'exécute en mode ECDSA, vous pouvez utiliser l'indicateur `—ibft-validator-type`, avec l'argument `ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info Soldes du compte de pré-exploitation + +Vous souhaiterez probablement configurer votre réseau de blockchain avec certaines adresses ayant des soldes « pré-exploités ». + +Pour cela, passez autant `--premine` d'indicateurs que vous le souhaitez par adresse que vous souhaitez initialiser avec un certain solde sur la blockchain. + +Par exemple, si nous souhaitons pré-exploiter 1000 ETH à l'adresse `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` dans notre bloc de genèse, nous aurions besoin de fournir l'argument suivant : + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Notez que le montant pré-exploité est en WEI, pas en ETH.** + +::: + +:::info Définir la limite de gaz du bloc + +La limite de gaz par défaut pour chaque bloc est `5242880`. Cette valeur est écrite dans le fichier de genèse, mais vous voudrez peut-être +l'augmenter / le diminuer. + +Pour cela, vous pouvez utiliser l'indicateur `--block-gas-limit` suivi de la valeur souhaitée comme indiqué ci-dessous : + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Définir la limite du descripteur de fichier à système + +La limite du descripteur de fichier par défaut ( nombre maximum de fichiers ouverts ) sur certains systèmes d'exploitation est assez petite. Si les nœuds doivent avoir un débit élevé, vous pouvez envisager d'augmenter cette limite au niveau du Système d'Exploitation. + +Pour la distribution Ubuntu, la procédure est la suivante ( si vous n'utilisez pas la distribution Ubuntu/Debian, consultez la documentation officielle de votre système d'exploitation ) : +- Vérifiez les limites actuelles du système d'exploitation ( fichiers ouverts ) +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- Augmenter la limite de fichiers ouverts + - Localement - n'affecte que la session en cours: + ```shell + ulimit -u 65535 + ``` + - Globalement ou par utilisateur ( ajoutez des limites à la fin du fichier /etc/security/limits.conf ) : + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +De manière facultative, modifiez les paramètres supplémentaires, enregistrez le fichier et redémarrez le système. Après le redémarrage, vérifiez à nouveau la limite du descripteur de fichier. +Il doit être défini sur la valeur que vous avez définie dans le fichier limits.conf. + +::: + +Après avoir précisé le : +1. Les clés publiques des validateurs à inclure dans le bloc de genèse en tant qu'ensemble de validateurs +2. Les chaînes de connexion multiaddr du nœud de démarrage +3. Les comptes et les soldes pré-exploités à inclure dans le bloc de genèse + +et en générant le `genesis.json`, vous devez le copier sur toutes les Machines Virtuelles dans le réseau. Selon votre configuration, vous pouvez +le copier/coller, l'envoyer à l'opérateur du nœud, ou simplement le SCP/FTP. + +La structure du fichier de genèse est traitée dans la section des [Commandes de CLI](/docs/edge/get-started/cli-commands). + +## Étape 4 : Préparez tous les clients {#step-4-run-all-the-clients} + +:::note Mise en réseau sur les fournisseurs de Cloud + +La plupart des fournisseurs de cloud n'exposent pas les adresses IP (en particulier les adresses publiques) en tant qu'interface de réseau directe sur votre Machine Virtuelle, mais configurent plutôt un proxy NAT invisible. + + +Pour permettre aux nœuds de se connecter les uns aux autres dans ce cas, vous devez les faire écouter sur `0.0.0.0` l'adresse IP pour vous lier à toutes les interfaces, mais vous devez toujours spécifier l'adresse IP ou l'adresse DNS que les autres nœuds peuvent utiliser pour se connecter à votre instance. Ceci est réalisé soit en utilisant l'argument `--nat` ou o `--dns`ù vous pouvez spécifier votre adresse IP externe ou DNS respectivement. + +#### Exemple {#example} + +L'adresse IP associée sur laquelle vous souhaitez écouter est `192.0.2.1`, mais elle n'est pas directement liée à aucune de vos interfaces réseau. + +Pour autoriser les nœuds à se connecter, vous devez passer les paramètres suivants : + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +Ou, si vous souhaitez spécifier une adresse DNS `dns/example.io`, passez les paramètres suivants : + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +Cela rendrait votre nœud capable d'etre écouté sur toutes les interfaces, mais lui ferait également savoir que les clients s'y connectent via l'adresse spécifiée `--nat` ou `--dns`. + +::: + +Pour exécuter le **premier** client : + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Pour exécuter le **deuxième** client : + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Pour préparer le **troisième** client: + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Pour exécuter le **quatrième** client : + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Après avoir exécuté les commandes précédentes, vous avez configuré un réseau de Polygon Edge à 4 nœuds, capable de sceller les blocs et de se remettre de la défaillance du nœud. + +:::info Démarrez le client à l'aide du fichier de configuration + +Au lieu de spécifier tous les paramètres de configuration en tant qu'arguments de CLI, le Client peut également être démarré à l'aide d'un fichier de configuration en exécutant la commande suivante : + +````bash +polygon-edge server --config +```` +Exemple : + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Actuellement, nous prenons en charge uniquement le fichier de configuration basé sur la `json`base, exemple de fichier de configuration peut être trouvé **[ici](/docs/edge/configuration/sample-config)** + +::: + +:::info Étapes pour exécuter un nœud non validateur + +Un non-validateur synchronisera toujours les derniers blocs reçus du nœud validateur, vous pouvez démarrer un nœud non-validateur en exécutant la commande suivante. + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +Par exemple, vous pouvez ajouter un **cinquième** client Non validateur en exécutant la commande suivante : + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info Spécifiez la limite de prix + +Un nœud de Polygon Edge peut être démarré avec une **limite de prix** définie pour les transactions entrantes. + +L'unité de la limite de prix est. `wei`. + +Fixer une limite de prix signifie que toute transaction traitée par le nœud actuel devra avoir un prix de gaz **plus élevé** +que la limite de prix fixée, sinon elle ne sera pas incluse dans un bloc. + +Le fait que la majorité des nœuds respectent une certaine limite de prix applique la règle selon laquelle les transactions dans le réseau +ne peuvent être inférieures à un certain niveau de prix. + +La valeur par défaut de la limite de prix est `0`, ce qui signifie qu'elle n'est pas appliquée du tout par défaut. + +Exemple d'utilisation de `--price-limit` l'indicateur : +````bash +polygon-edge server --price-limit 100000 ... +```` + +Il convient de noter que les limites de prix **ne sont appliquées que sur les transactions non locales**, ce qui signifie +que la limite de prix ne s'applique pas aux transactions ajoutées localement sur le nœud. + +::: + +:::info URL de WebSocket + +Par défaut, lorsque vous exécutez le Polygon Edge, il génère une URL de WebSocket basée sur l'emplacement de la chaîne. +Le schéma d'URL `wss://` est utilisé pour les liens HTTPS et `ws://` pour HTTP. + +URL de WebSocket de l'hôte local : +````bash +ws://localhost:10002/ws +```` +Veuillez noter que le numéro de port dépend du port JSON-RPC choisi pour le nœud. + +URL Edgenet de WebSocket : +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/fr-edge/get-started/terraform-aws-deployment.md b/archive/edge/fr-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..374bc58c28 --- /dev/null +++ b/archive/edge/fr-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,171 @@ +--- +id: terraform-aws-deployment +title: Déploiement d'AWS Terraform +description: "DéployeZ le réseau de Polygon Edge sur le fournisseur de cloud AWS à l'aide de Terraform" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info Guide de déploiement de la production + +Il s'agit du guide de déploiement AWS officiel, prêt pour la production et entièrement automatisé. + +Les déploiements manuels dans le ***[Cloud](set-up-ibft-on-the-cloud)*** ou ***[Local](set-up-ibft-locally)*** +sont recommandés pour les tests et/ou si votre fournisseur de cloud n'est pas AWS. +::: + +:::info + +Ce déploiement est uniquement compatible à PoA. +Si un mécanisme PoS est nécessaire, suivez simplement ce ***[guide](/docs/edge/consensus/migration-to-pos)*** maintenant pour passer du PoA au PoS. + +::: + +Ce guide décrira en détail le processus de déploiement d'un réseau blockchain de Polygon Edge sur le fournisseur de cloud AWS, qui est prêt pour la production, car les nœuds de validation sont répartis sur plusieurs zones de disponibilité. + +## Prérequis {#prerequisites} + +### Outils du système {#system-tools} +* [terraform](https://www.terraform.io/) +* [aws cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [Identifiant de clé d'accès aws et clé d'accès secrète](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Variables de Terraform {#terraform-variables} +Deux variables qui doivent être fournies, avant d'exécuter le déploiement: + +* `alb_ssl_certificate` - l'ARN du certificat provenant d'AWS Certificate Manager à utiliser par ALB pour le protocole https. + Le certificat doit être généré avant de commencer le déploiement, et il doit avoir le statut **Émis** +* `premine` - le compte qui recevra la devise native préminée. +La valeur doit suivre la spécification officielle de l'indicateur [CLI](/docs/edge/get-started/cli-commands#genesis-flags) + +## Informations de déploiement {#deployment-information} +### Ressources déployées {#deployed-resources} +Aperçu de haut niveau des ressources qui seront déployées : + +* VPC dédié +* 4 nœuds de validation (qui sont également des nœuds de démarrage) +* 4 passerelles NAT pour autoriser le trafic Internet sortant des nœuds +* Fonction lambda utilisée pour générer le premier bloc (genesis) et démarrer la chaîne +* Groupes de sécurité dédiés et rôles IAM +* Compartiment S3 utilisé pour stocker le fichier genesis.json +* Équilibreur de charge d'application utilisé pour exposer le point de terminaison JSON-RPC + +### Tolérance d'erreurs {#fault-tolerance} + +Seules les régions qui ont 4 zones de disponibilité sont requises pour ce déploiement. Chaque nœud est déployé dans une seule AZ (zone de disponibilité). + +En plaçant chaque nœud dans une seule zone de disponibilité, l'ensemble du cluster de la blockchain est tolérant aux erreurs en cas de défaillance d'un seul nœud (AZ), car Polygon Edge implémente le consensus IBFT +qui permet à un seul nœud d'échouer dans un cluster de 4 nœuds validateurs. + +### Accès à la ligne de commande {#command-line-access} + +Les nœuds de validation ne sont en aucun cas exposés à l'Internet public (JSON-PRC est accessible uniquement via ALB) et ils n'ont même pas d'adresses IP publiques qui leur sont attachées. +L'accès à la ligne de commande du nœud n'est possible que via [AWS Systems Manager - Session Manager](https://aws.amazon.com/systems-manager/features/). + +### Mise à niveau de l'AMI de base {#base-ami-upgrade} + +Ce déploiement utilise `ubuntu-focal-20.04-amd64-server` AWS AMI. Il **ne** déclenchera pas le *redéploiement* EC2 si l'AWS AMI est mise à jour. + +Si, pour une raison quelconque, l'AMI de base doit être mise à jour, cela peut être réalisé en exécutant la commande `terraform taint` pour chaque instance, avant que `terraform apply`. +des instances ne puissent être entachées en exécutant la commande +`terraform taint module.instances[].aws_instance.polygon_edge_instance`commande + +Exemple : +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info + +Dans un environnement de production, `terraform taint` doivent être exécutés un par un afin de maintenir le réseau blockchain opérationnel. + +::: + +## Procédure de déploiement {#deployment-procedure} + +### Étapes de pré-déploiement {#pre-deployment-steps} +* lisez le fichier readme [polygon-technology-edge](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) du registre terraform +* ajoutez le module `polygon-technology-edge` à votre fichier `main.tf` en utilisant les *instructions de mise à disposition* sur la page readme des modules +* exécutez la `terraform init`commande pour installer toutes les dépendances Terraform nécessaires +* fournissez un nouveau certificat dans [AWS Certificate Manager](https://aws.amazon.com/certificate-manager/) +* assurez-vous que le certificat fourni est dans l'état **Émis** et notez **l'ARN** du certificat +* configurez votre instruction de sortie afin d'obtenir la sortie des modules dans la cli + +#### `main.tf` exemple {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### `terraform.tfvars` exemple {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### Étapes de déploiement {#deployment-steps} +* créez le `terraform.tfvars`fichier +* définissez les variables terraform requises dans ce fichier (comme expliqué ci-dessus). +:::info +Il existe d'autres variables non obligatoires qui peuvent entièrement personnaliser ce déploiement. Vous pouvez remplacer les valeurs par défaut en ajoutant les vôtres au fichier `terraform.tfvars`. + + La spécification de toutes les variables disponibles peut être trouvée dans le ***[registre](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)*** Terraform des modules + +::: +* assurez-vous que vous avez correctement configuré une authentification aws cli en exécutant `aws s3 ls` - il ne devrait y avoir aucune erreur +* déployez l'infrastructure `terraform apply` + +### Étapes du post-déploiement {#post-deployment-steps} +* une fois le déploiement terminé, notez la valeur de la variable `json_rpc_dns_name` imprimée dans la cli +* créez un enregistrement DNS public cname pointant votre nom de domaine vers la valeur `json_rpc_dns_name` fournie. Par exemple : + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* une fois l'enregistrement cname propagé, vérifiez si la chaîne fonctionne correctement en appelant votre point de terminaison JSON-PRC. +À partir de l'exemple ci-dessus : + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## Détruisez la procédure {#destroy-procedure} +:::warning + +La procédure suivante supprimera définitivement l'ensemble de votre infrastructure déployée avec ces scripts terraform. +Assurez-vous que vous disposez de [sauvegardes de données de blockchain](docs/edge/working-with-node/backup-restore) appropriées et/ou que vous travaillez avec un environnement de test. + +::: + +Si vous devez supprimer toute l'infrastructure, exécutez la commande suivante `terraform destroy`. +De plus, vous devrez supprimer manuellement les secrets stockés dans [Parameter Store](https://aws.amazon.com/systems-manager/features/) d'AWS +pour la région où le déploiement a eu lieu. diff --git a/archive/edge/fr-edge/overview.md b/archive/edge/fr-edge/overview.md new file mode 100644 index 0000000000..ebceed13c8 --- /dev/null +++ b/archive/edge/fr-edge/overview.md @@ -0,0 +1,35 @@ +--- +id: overview +title: Polygon Edge +sidebar_label: What is Edge +description: "Une introduction à Polygon Edge." +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +Polygon Edge est un cadre modulaire et extensible permettant de créer des réseaux de blockchain, des chaînes latérales et des solutions de mise à l'échelle générales compatibles avec Ethereum. + +Son utilisation principale est de démarrer un nouveau réseau de blockchain tout en offrant une compatibilité totale avec les contrats intelligents et les transactions d'Ethereum. Il utilise le mécanisme de consensus IBFT (Istanbul Byzantine Fault Tolerant), pris en charge en deux versions comme [PoA (preuve d'autorité)](/docs/edge/consensus/poa) et [PoS (preuve d'enjeu)](/docs/edge/consensus/pos-stake-unstake). + +Polygon Edge prend également en charge la communication avec plusieurs réseaux de blockchain, permettant les transferts de jetons [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) et [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) en utilisant la [solution de pont centralisée](/docs/edge/additional-features/chainbridge/overview). + +Les portefeuilles standard de l'industrie peuvent être utilisés pour interagir avec Polygon Edge via les points de terminaison [JSON-RPC](/docs/edge/working-with-node/query-json-rpc) et les opérateurs de nœuds peuvent effectuer diverses actions sur les nœuds via le protocole [gRPC](/docs/edge/working-with-node/query-operator-info). + +Pour en savoir plus sur Polygon, visitez le [site officiel](https://polygon.technology). + +**[Répertoire GitHub](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +Il s'agit d'un travail en cours, donc des changements architecturaux peuvent se produire à l'avenir. Le code n'a pas été audité pour le moment, veuillez donc contacter l'équipe de Polygon si vous souhaitez l'utiliser en production. + +::: + + + +Pour démarrer en exécutant un `polygon-edge` réseau localement, veuillez lire: [Installation](/docs/edge/get-started/installation) et [Configuration Locale](/docs/edge/get-started/set-up-ibft-locally). diff --git a/archive/edge/fr-edge/performance-reports/overview.md b/archive/edge/fr-edge/performance-reports/overview.md new file mode 100644 index 0000000000..3ca890889e --- /dev/null +++ b/archive/edge/fr-edge/performance-reports/overview.md @@ -0,0 +1,29 @@ +--- +id: overview +title: Aperçu +description: "Introduction aux tests de Polygon Edge." +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +Veuillez noter que nos , `loadbot`qui ont été utilisés pour effectuer ces tests, sont maintenant dépréciés. +::: + +| Type | Valeur | Lien vers le test | +| ---- | ----- | ------------ | +| Transferts Réguliers | 1428 tps | [4 Juillet 2022](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| Transferts d'ERC-20 | 1111 tps | [4 Juillet 2022](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| Frappe de NFT | 714 tps | [4 Juillet 2022](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +Notre objectif est de créer un logiciel client de blockchain hautement performant, riche en fonctionnalités et facile à configurer et à entretenir. Tous les tests ont été effectués à l'aide du Polygon Edge Loadbot. Chaque rapport de performance que vous trouverez dans cette section est correctement daté, l'environnement clairement décrit et la méthode de test est clairement expliquée. + +L'objectif de ces tests de performance est de montrer une performance réelle du réseau de blockchain de Polygon Edge. N'importe qui devrait pouvoir obtenir les mêmes résultats que ceux publiés ici, sur le même environnement, en utilisant notre loadbot. + +Tous les tests de performance ont été menés sur la plateforme AWS sur une chaîne composée de nœuds d'instance EC2. \ No newline at end of file diff --git a/archive/edge/fr-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/fr-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..da02241164 --- /dev/null +++ b/archive/edge/fr-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,130 @@ +--- +id: test-2022-01-21 +title: 21 Janvier 2022 +description: "Test de performance à partir du 21 Janvier." +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## 21 Janvier 2022 {#january-21st-2022} + +### Sommaire {#summary} + +:::caution +Veuillez noter que nos , `loadbot`qui ont été utilisés pour effectuer ces tests, sont maintenant dépréciés. +::: + +Ce test a été effectué après le refacteur TxPool qui a significativement amélioré les performances (publié en [v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0)). + +L'objectif était de mettre en place un grand réseau composé de 30 validateurs participant activement afin de tester correctement le consensus et les rumeurs de transaction TxPool car toutes les transactions ont été envoyées au JSON-RPC d'un seul nœud. + +Notre objectif n'était pas d'atteindre un TPS maximal, car la taille du réseau a un impact négatif sur les performances, et puisque la limite de gaz de bloc et le temps de bloc sont définis sur des valeurs saines qui ne consomment pas beaucoup de ressources de système, cela permettrait un fonctionnement sur le matériel de base. + +### Résultats {#results} + +| Métrique | Valeur | +| ------ | ----- | +| Transactions par seconde | 344 | +| Transactions échouées | 0 | +| Transactions réussies | 10000 | +| Temps d'exécution total | 30s | + +### Environnement {#environment} + +
+ Configuration De L'Hôte +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fournisseur de CloudAWS
Taille de l'instancet2.xlarge
Mise En Réseausous-réseau privé
Système d"exploitationLinux Ubuntu 20.04 LTS - Focal Fossa
Limite du descripteur de dossier65535
Processus d'utilisateurs maximum65535
+
+
+
+
+ +
+ Configuration de la Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Version De Polygon EdgeValider 8377162281d1a2e4342ae27cd4e5367c4364aee2 sur la branche de développement
Nœuds de validation30
Nœuds de non validation0
ConsensusIBFT PoA
Temps de bloc2000 ms
Limite de gaz du bloc5242880
+
+
+
+
+ +
+ Configuration Du Loadbot +
+
+ + + + + + + + + + + + + +
Total Des Transactions10000
Transactions envoyées par seconde400
Type de transactionsTransferts EOA vers EOA
+
+
+
+
diff --git a/archive/edge/fr-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/fr-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..855cf61dd4 --- /dev/null +++ b/archive/edge/fr-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,390 @@ +--- +id: test-2022-03-02 +title: 2 Mars 2022 +description: "Test de performance à partir du 2 Mars." +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### Sommaire {#summary} + +:::caution +Veuillez noter que nos , `loadbot`qui ont été utilisés pour effectuer ces tests, sont maintenant dépréciés. +::: + +Ce test a été effectué pour mesurer les transferts de jetons SC ERC20 et la fonctionnalité de frappe de jetons SC ERC721 avec des charges lourdes et la vitesse des transactions. + +L'objectif était de vérifier si tout fonctionne comme prévu pendant les charges lourdes. C'est également la raison pour laquelle nous avons introduit des mesures de gaz dans la sortie du loadbot, qui nous montrent si les blocs sont correctement remplis de transactions. + +Toutes les transactions ont été envoyées au nœud unique via l'API GRPC et les reçus ont été réceptionnés via l'API JSON-RPC. Une fois toutes les transactions effectuées, les informations sur le gaz ont été lues à partir de chaque bloc, à l'aide de la méthode eth_getBlockByNumber JSON-RPC. + +Notre objectif n'était pas d'atteindre un TPS maximal possible, +puisque la limite de gaz de bloc et le temps de bloc sont définis sur des valeurs saines qui ne consomment pas beaucoup de ressources de système, et qui permettrait un fonctionnement sur le matériel de base. + +### Résultats ERC20 {#results-erc20} + +| Métrique | Valeur | +| ------ | ----- | +| Type de transaction | ERC20 | +| Transactions par seconde | 65 | +| Transactions échouées | 0 | +| Transactions réussies | 5000 | +| Temps d'exécution des transactions ERC20 | 76 681690 s | +| Temps de Déploiement SC | 4 048250 s | + +### Résultats ERC721 {#results-erc721} + +| Métrique | Valeur | +| ------ | ----- | +| Type de transaction | ERC721 | +| Transactions par seconde | 20 | +| Transactions échouées | 0 | +| Transactions réussies | 2000 | +| Temps d'exécution des transactions ERC721 | 97 239920 s | +| Temps de Déploiement SC | 3 048970 s | + +### Environnement ERC20 {#environment-erc20} + +
+ Configuration de l'Hôte +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fournisseur de CloudAWS
Taille de l'instancet2.micro
Mise en réseausous-réseau privé
Système d"exploitationLinux Ubuntu 20.04 LTS - Focal Fossa
Limite du descripteur de dossier65535
Processus d'utilisateurs maximum65535
+
+
+
+
+ +
+ Configuration de la Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Version de Polygon EdgeValidez 8a033aa1afb191abdac04636d318f83f32511f3c sur la branche de développement
Nœuds de validation6
Nœuds de non validation0
ConsensusIBFT PoA
Temps du bloc2 s
Limite de gaz du bloc5242880
Utilisation moyenne des blocs95 %
+
+
+
+
+ +
+ Configuration du Loadbot +
+
+ + + + + + + + + + + + + +
Total des Transactions5000
Transactions envoyées par seconde200
Type de transactionsTransferts ERC20 vers ERC20
+
+
+
+
+ +
+ Registres du Loadbot + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### Environnement ERC721 {#environment-erc721} + +
+ Configuration de l'Hôte +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fournisseur de CloudAWS
Taille de l'instancet2.micro
Mise en réseausous-réseau privé
Système d"exploitationLinux Ubuntu 20.04 LTS - Focal Fossa
Limite du descripteur de dossier65535
Processus d'utilisateurs maximum65535
+
+
+
+
+ +
+ Configuration de la Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Version de Polygon EdgeValidez 8a033aa1afb191abdac04636d318f83f32511f3c sur la branche de développement
Nœuds de validation6
Nœuds de non validation0
ConsensusIBFT PoA
Temps du bloc2 s
Limite de gaz du bloc5242880
Utilisation moyenne des blocs94 %
+
+
+
+
+ +
+ Configuration du Loadbot +
+
+ + + + + + + + + + + + + +
Total des Transactions2000
Transactions envoyées par seconde200
Type de transactionsFrappe de jetons ERC721
+
+
+
+
+ +
+ Registres du Loadbot + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/fr-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/fr-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..c0af09a9f8 --- /dev/null +++ b/archive/edge/fr-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,957 @@ +--- +id: test-2022-03-23 +title: 23 Mars 2022 +description: "Test de performance du 23 Mars." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### Sommaire {#summary} + +:::caution +Veuillez noter que nos , `loadbot`qui ont été utilisés pour effectuer ces tests, sont maintenant dépréciés. +::: + +Ce test a été effectué pour mesurer les transferts de jetons SC ERC20, la frappe de jetons SC ERC721 et la fonctionnalité des transactions EOA à EOA avec de lourdes charges et une vitesse de transactions sur les nœuds avec des ressources matérielles plus élevées. + +L'objectif était de vérifier si tout fonctionne comme prévu pendant les charges lourdes. C'est également la raison pour laquelle nous avons introduit des mesures de gaz dans la sortie du loadbot, qui nous montrent si les blocs sont correctement remplis de transactions. + +Toutes les transactions ont été envoyées au nœud unique via l'API GRPC et les reçus ont été réceptionnés via l'API JSON-RPC. Une fois toutes les transactions effectuées, les informations sur le gaz ont été lues à partir de chaque bloc, à l'aide de la méthode eth_getBlockByNumber JSON-RPC. + +Notre objectif était de nous efforcer d'atteindre un maximum de TPS possible sur les ressources de matérielles disponibles. Pour y parvenir, nous avons modifié les paramètres de la limite de gaz du bloc et celles du temps du bloc, pour nous donner les meilleurs résultats TPS possibles et maintenir l'intégrité et la stabilité du système. + +:::info Limite de Gaz de Bloc + +La limite de gaz de bloc peut être augmentée à un nombre relativement élevé si les transactions utilisent beaucoup de gaz à exécuter. +Dans l'exemple ci-dessous, la frappe de jeton ERC721 a fonctionné beaucoup plus rapidement avec une limite de gaz de bloc fixée à 80 000 000 (au lieu de 20 millions), mais avec des transferts de jeton ERC20 avec une limite de gaz de bloc de 80 millions, le serveur s'est effondré. + +::: + +:::info Environnements de Production + +Lors de la configuration d'un environnement de production, vous devez être prudent si vous essayez d'obtenir des performances élevées de la chaîne. Si le paramètre de limite de gaz du bloc est défini sur une valeur élevée, et le temps de bloc est défini sur 1 s, et qu'il y a une charge de transaction élevée sur un seul nœud, ce nœud consommera beaucoup (voire toute la RAM disponible) et peut provoquer un effondrement du serveur. +Utilisez le loadbot pour tout tester en profondeur, surveiller l'utilisation des ressources du système et définir vos paramètres de configuration en conséquence. +::: + +:::info Erreurs de Mémoire Insuffisante + +Certaines distros linux vont automatiquement tuer le processus qui a une très grande utilisation de la RAM (erreur OOM), afin de préserver la stabilité du système. +Le résultat du registres de cette erreur OOM ressemble à ceci (voir ci-dessous). +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### Résultats des transferts EOA à EOA {#results-of-eoa-to-eoa-transfers} +| Métrique | Valeur | +| ------ | ----- | +| Type de transaction | EOA à EOA | +| Transactions par seconde | 689 | +| Transactions échouées | 0 | +| Transactions réussies | 20000 | +| Total des blocs utilisés | 25 | +| Temps d'exécution total | 29.921110 s | + +### Résultats des transferts de jetons ERC20 {#results-of-erc20-token-transfers} + +| Métrique | Valeur | +| ------ | ----- | +| Type de transaction | ERC20 | +| Transactions par seconde | 500 | +| Transactions échouées | 0 | +| Transactions réussies | 20000 | +| Total des blocs utilisés | 33 | +| Temps d'exécution des transactions ERC20 | 40.402900 s | +| Temps de Déploiement SC | 2.004140 s | + +### Résultats de la frappe de jetons ERC721 {#results-of-erc721-token-minting} + +| Métrique | Valeur | +| ------ | ----- | +| Type de transaction | ERC721 | +| Transactions par seconde | 157 | +| Transactions échouées | 0 | +| Transactions réussies | 20000 | +| Total des blocs utilisés | 124 | +| Temps d'exécution des transactions ERC721 | 127.537340 s | +| Temps de Déploiement SC | 2.004420 s | + + +### Résultats de la frappe du jeton ERC721 avec une limite de gaz de bloc très élevée (80 mil.) {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| Métrique | Valeur | +| ------ | ----- | +| Type de transaction | ERC721 | +| Transactions par seconde | 487 | +| Transactions échouées | 0 | +| Transactions réussies | 20000 | +| Total des blocs utilisés | 34 | +| Temps d'exécution des transactions ERC721 | 41 098410 s | +| Temps de Déploiement SC | 2.004300 s | + + +### Environnement EOA à EOA {#environment-eoa-to-eoa} +
+ Configuration de l'Hôte +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fournisseur de CloudAWS
Taille de l'instancec5.2xlarge
Mise en réseausous-réseau privé
Système d'exploitationAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite du descripteur de dossier65535
Processus d'utilisateurs maximum65535
+
+
+
+
+ +
+ Configuration de la Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Version de Polygon EdgeValidez 06e11eac8da98c79c938fc53dda2da3318cfbe04 sur la branche de développement
Nœuds de validation4
Nœuds de non validation0
ConsensusIBFT PoA
Temps du bloc1 s
Limite de gaz du bloc20000000
Emplacements maximum1 000 000
Utilisation moyenne des blocs84,00 %
+
+
+
+
+ +
+ Configuration du Loadbot +
+
+ + + + + + + + + + + + + +
Total des Transactions20000
Transactions envoyées par seconde689
Type de transactionsTransferts EOA à EOA
+
+
+
+
+ +
+ Registres du Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### Environnement ERC20 {#environment-erc20} +
+ Configuration de l'Hôte +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fournisseur de CloudAWS
Taille de l'instancec5.2xlarge
Mise en réseausous-réseau privé
Système d'exploitationAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite du descripteur de dossier65535
Processus d'utilisateurs maximum65535
+
+
+
+
+ +
+ Configuration de la Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Version de Polygon EdgeValidez 06e11eac8da98c79c938fc53dda2da3318cfbe04 sur la branche de développement
Nœuds de validation4
Nœuds de non validation0
ConsensusIBFT PoA
Temps du bloc1 s
Limite de gaz du bloc20000000
Emplacements maximum1 000 000
Utilisation moyenne des blocs88,38 %
+
+
+
+
+ +
+ Configuration du Loadbot +
+
+ + + + + + + + + + + + + +
Total des Transactions20000
Transactions envoyées par seconde500
Type de transactionsTransferts ERC20 vers ERC20
+
+
+
+
+ +
+ Registres du Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### Environnement ERC721 {#environment-erc721} +
+ Configuration de l'Hôte +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fournisseur de CloudAWS
Taille de l'instancec5.2xlarge
Mise en réseausous-réseau privé
Système d'exploitationAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite du descripteur de dossier65535
Processus d'utilisateurs maximum65535
+
+
+
+
+ +
+ Configuration de la Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Version de Polygon EdgeValidez 06e11eac8da98c79c938fc53dda2da3318cfbe04 sur la branche de développement
Nœuds de validation4
Nœuds de non validation0
ConsensusIBFT PoA
Temps du bloc1 s
Limite de gaz du bloc20000000
Emplacements maximum1 000 000
Utilisation moyenne des blocs92,90 %
+
+
+
+
+ +
+ Configuration du Loadbot +
+
+ + + + + + + + + + + + + +
Total des Transactions20000
Transactions envoyées par seconde157
Type de transactionsFrappe de jetons ERC721
+
+
+
+
+ +
+ Registres du Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### Environnement ERC20 - limite de gaz de bloc très élevée {#environment-erc20-very-high-block-gas-limit} +
+ Configuration de l'Hôte +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fournisseur de CloudAWS
Taille de l'instancec5.2xlarge
Mise en réseausous-réseau privé
Système d'exploitationAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite du descripteur de dossier65535
Processus d'utilisateurs maximum65535
+
+
+
+
+ +
+ Configuration de la Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Version de Polygon EdgeValidez 06e11eac8da98c79c938fc53dda2da3318cfbe04 sur la branche de développement
Nœuds de validation4
Nœuds de non validation0
ConsensusIBFT PoA
Temps du bloc1 s
Limite de gaz du bloc80000000
Emplacements maximum1 000 000
Utilisation moyenne des blocs---
+
+
+
+
+ +
+ Configuration du Loadbot +
+
+ + + + + + + + + + + + + +
Total des Transactions20000
Transactions envoyées par seconde---
Type de transactionsTransferts ERC20 vers ERC20
+
+
+
+
+ +
+ Erreur du registre OOM + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### Environnement ERC721 - limite de gaz de bloc très élevée {#environment-erc721-very-high-block-gas-limit} +
+ Configuration de l'Hôte +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fournisseur de CloudAWS
Taille de l'instancec5.2xlarge
Mise en réseausous-réseau privé
Système d'exploitationAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite du descripteur de dossier65535
Processus d'utilisateurs maximum65535
+
+
+
+
+ +
+ Configuration de la Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Version de Polygon EdgeValidez 06e11eac8da98c79c938fc53dda2da3318cfbe04 sur la branche de développement
Nœuds de validation4
Nœuds de non validation0
ConsensusIBFT PoA
Temps du bloc1 s
Limite de gaz du bloc80000000
Emplacements maximum1 000 000
Utilisation moyenne des blocs84,68%
+
+
+
+
+ +
+ Configuration du Loadbot +
+
+ + + + + + + + + + + + + +
Total des Transactions20000
Transactions envoyées par seconde487
Type de transactionsFrappe de jetons ERC721
+
+
+
+
+ +
+ Registres du Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/fr-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/fr-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..02be0d0ce9 --- /dev/null +++ b/archive/edge/fr-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,565 @@ +--- +id: test-2022-07-04 +title: 4 juillet 2022 +description: "Test de performance du 4 juillet." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### Sommaire {#summary} + +:::caution +Veuillez noter que nos , `loadbot`qui ont été utilisés pour effectuer ces tests, sont maintenant dépréciés. +::: + +Ce test a été effectué pour mesurer les transferts de jetons SC ERC20, la frappe de jetons SC ERC721 et la fonctionnalité des transactions EOA à EOA avec de lourdes charges et une vitesse de transactions sur les nœuds avec des ressources matérielles plus élevées. + +L'objectif était de vérifier si tout fonctionne comme prévu pendant les charges lourdes. C'est également la raison pour laquelle nous avons introduit des mesures de gaz dans la sortie du loadbot, qui nous montrent si les blocs sont correctement remplis de transactions. + +Toutes les transactions ont été envoyées au nœud unique via l'API GRPC et les reçus ont été réceptionnés via l'API JSON-RPC. Une fois toutes les transactions effectuées, les informations sur le gaz ont été lues à partir de chaque bloc, à l'aide de la méthode eth_getBlockByNumber JSON-RPC. + +Notre objectif était de nous efforcer d'atteindre un maximum de TPS possible sur les ressources de matérielles disponibles. Pour y parvenir, nous avons modifié les paramètres de la limite de gaz du bloc et celles du temps du bloc, pour nous donner les meilleurs résultats TPS possibles et maintenir l'intégrité et la stabilité du système. + + +:::info Environnements de production + +Lors de la configuration d'un environnement de production, vous devez être prudent si vous essayez d'obtenir des performances élevées de la chaîne. Si le paramètre de limite de gaz du bloc est défini sur une valeur élevée, et le temps de bloc est défini sur 1 s, et qu'il y a une charge de transaction élevée sur un seul nœud, ce nœud consommera beaucoup (voire toute la RAM disponible) et peut provoquer un effondrement du serveur. +Utilisez le loadbot pour tout tester en profondeur, surveiller l'utilisation des ressources du système et définir vos paramètres de configuration en conséquence. +::: + + + +### Résultats des transferts EOA à EOA {#results-of-eoa-to-eoa-transfers} +| Métrique | Valeur | +| ------ | ----- | +| Type de transaction | EOA à EOA | +| Transactions par seconde | 1428 | +| Transactions échouées | 0 | +| Transactions réussies | 30 000 | +| Total des blocs utilisés | 15 | +| Temps d'exécution total | 21.374620 s | + +### Résultats des transferts de jetons ERC20 {#results-of-erc20-token-transfers} + +| Métrique | Valeur | +| ------ | ----- | +| Type de transaction | ERC20 | +| Transactions par seconde | 1 111 | +| Transactions échouées | 0 | +| Transactions réussies | 50 000 | +| Total des blocs utilisés | 38 | +| Temps d'exécution des transactions ERC20 | 45,906450 s | +| Temps de déploiement SC | 2,006580 s | + +### Résultats du monnayage de jetons ERC721 {#results-of-erc721-token-minting} + +| Métrique | Valeur | +| ------ | ----- | +| Type de transaction | ERC721 | +| Transactions par seconde | 714 | +| Transactions échouées | 0 | +| Transactions réussies | 30 000 | +| Total des blocs utilisés | 39 | +| Temps d'exécution des transactions ERC721 | 42,864140 s | +| Temps de déploiement SC | 2,005500 s | + + + + +### Environnement EOA à EOA {#environment-eoa-to-eoa} +
+ Configuration de l'Hôte +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fournisseur de cloudAWS EC2
Taille de l'instancec6a.48xlarge
Mise en réseausous-réseau privé
Système d"exploitationLinux Ubuntu 20.04 LTS - Focal Fossa
Limite du descripteur de dossier65535
Processus d'utilisateurs maximum65535
+
+
+
+
+ +
+ Configuration de la Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Version Polygon EdgeVersion v0.4.1
Nœuds de validation4
Nœuds de non validation0
ConsensusIBFT PoA
Temps du bloc1 s
Limite de gaz du bloc70778880
Emplacements maximum276480
Utilisation moyenne des blocs59,34 %
+
+
+
+
+ +
+ Configuration du loadbot +
+
+ + + + + + + + + + + + + +
Total des transactions30 000
Transactions envoyées par seconde1428
Type de transactionsTransferts EOA à EOA
+
+
+
+
+ +
+ Registres du Loadbot + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### Environnement ERC20 {#environment-erc20} +
+ Configuration de l'Hôte +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fournisseur de cloudAWS EC2
Taille de l'instancec6a.48xlarge
Mise en réseausous-réseau privé
Système d"exploitationLinux Ubuntu 20.04 LTS - Focal Fossa
Limite du descripteur de dossier65535
Processus d'utilisateurs maximum65535
+
+
+
+
+ +
+ Configuration de la Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Version Polygon EdgeVersion v0.4.1
Nœuds de validation4
Nœuds de non validation0
ConsensusIBFT PoA
Temps du bloc1 s
Limite de gaz du bloc47185920
Emplacements maximum184320
Utilisation moyenne des blocs81,29 %
+
+
+
+
+ +
+ Configuration du loadbot +
+
+ + + + + + + + + + + + + +
Total des transactions50 000
Transactions envoyées par seconde1 111
Type de transactionsTransferts ERC20 vers ERC20
+
+
+
+
+ +
+ Registres du Loadbot + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### Environnement ERC721 {#environment-erc721} +
+ Configuration de l'Hôte +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fournisseur de cloudAWS EC2
Taille de l'instancec6a.48xlarge
Mise en réseausous-réseau privé
Système d"exploitationLinux Ubuntu 20.04 LTS - Focal Fossa
Limite du descripteur de dossier65535
Processus d'utilisateurs maximum65535
+
+
+
+
+ +
+ Configuration de la Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Version Polygon EdgeVersion v0.4.1
Nœuds de validation4
Nœuds de non validation0
ConsensusIBFT PoA
Temps du bloc1 s
Limite de gaz du bloc94371840
Emplacements maximum1 000 000
Utilisation moyenne des blocs93,88 %
+
+
+
+
+ +
+ Configuration du loadbot +
+
+ + + + + + + + + + + + + +
Total des transactions30 000
Transactions envoyées par seconde714
Type de transactionsFrappe de jetons ERC721
+
+
+
+
+ +
+ Registres du Loadbot + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/fr-edge/troubleshooting.md b/archive/edge/fr-edge/troubleshooting.md new file mode 100644 index 0000000000..548061be7e --- /dev/null +++ b/archive/edge/fr-edge/troubleshooting.md @@ -0,0 +1,70 @@ +--- +id: troubleshooting +title: Dépannage +description: "Section de dépannage pour Polygon Edge" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# Dépannage {#troubleshooting} + +## `method=eth_call err="invalid signature"` erreur {#error} + +Lorsque vous utilisez un portefeuille pour effectuer une transaction avec Polygon Edge, assurez-vous que c'est dans la configuration du réseau local de votre portefeuille: + +1. Le `chainID` est le bon. La défaillance `chainID` pour Edge est `100`, mais elle peut être personnalisée en utilisant l'indicateur de genèse `--chain-id`. + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. Assurez-vous que dans le champ « URL RPC », vous utilisez le port RPC JSON du nœud auquel vous vous connectez. + + +## Comment obtenir une URL WebSocket {#how-to-get-a-websocket-url} + +Par défaut, lorsque vous exploitez le Polygon Edge, il génère un point de terminaison WebSocket basé sur l'emplacement de la chaîne. Le schéma d'URL `wss://` est utilisé pour les liens HTTPS, et `ws://` HTTP. + +URL de WebSocket de l'hôte local : +````bash +ws://:/ws +```` +Veuillez noter que le numéro de port dépend du port JSON-RPC choisi pour le nœud. + +URL Edgenet WebSocket: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## `insufficient funds` erreur lors du déploiement d'un contrat {#error-when-trying-to-deploy-a-contract} + +Si vous obtenez cette erreur, veuillez vous assurer que vous avez suffisamment de fonds sur l'adresse souhaitée, et que l'adresse utilisée est la bonne.
+Pour définir l'équilibre prédominé, vous pouvez utiliser l'indicateur de genèse `genesis [--premine ADDRESS:VALUE]` lors de la génération du fichier de genèse. +Exemple d'utilisation de cet indicateur: +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +Cela permet de préminer 1000000000000000000000 WEI à 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862. + + +## Jetons ERC20 non libérés lors de l'utilisation de Chainbridge {#erc20-tokens-not-released-while-using-chainbridge} + +Si vous essayez de transférer des jetons ERC20 entre POS de Polygon et un réseau Edge local, et que vos jetons ERC20 sont déposés, la proposition est également exécutée au relayer, mais les jetons ne sont pas libérés dans votre réseau Edge. Veuillez vous assurer que le gestionnaire ERC20 dans la chaîne de Polygon Edge a suffisamment de jetons à libérer.
+Le contrat du gestionnaire dans la chaîne de destination doit avoir suffisamment de jetons pour être libéré pour le mode de déverrouillage. Si vous n'avez pas de jetons ERC20 dans le Gestionnaire ERC20 de votre réseau Edge local, veuillez créer de nouveaux jetons et les transférer au Gestionnaire ERC20. + +## `Incorrect fee supplied` erreur lors de l'utilisation de Chainbridge {#error-when-using-chainbridge} + +Vous pouvez obtenir cette erreur lorsque vous essayez de transférer des jetons ERC20 entre la chaîne POS de Polygon Mumbai et une configuration locale de Polygon Edge. Cette erreur apparaît lorsque vous définissez les frais de déploiement à l'aide de l'`--fee`indicateur, mais ne définissez pas la même valeur dans la transaction de dépôt. +Vous pouvez utiliser la commande ci-dessous pour modifier les frais: +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +Vous pouvez trouver plus d'informations sur ce drapeau [ici](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md). + + + + + diff --git a/archive/edge/fr-edge/validator-hosting.md b/archive/edge/fr-edge/validator-hosting.md new file mode 100644 index 0000000000..1f29dcaf65 --- /dev/null +++ b/archive/edge/fr-edge/validator-hosting.md @@ -0,0 +1,257 @@ +--- +id: validator-hosting +title: Hébergement du Validateur +description: "Exigences d'hébergement pour Polygon Edge" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +Vous trouverez ci-dessous les suggestions pour héberger correctement un nœud de validation dans un réseau Polygon Edge. Veuillez porter une attention particulière à tous les éléments énumérés ci-dessous pour vous assurer que votre configuration de validateur est correctement configurée pour être sécurisée, stable et performante. + +## Base de connaissances {#knowledge-base} + +Avant d'essayer d'exécuter le nœud de validation, veuillez lire attentivement ce document. +Les documents supplémentaires qui pourraient être utiles sont : + +- [Installation](get-started/installation) +- [Configuration Cloud](get-started/set-up-ibft-on-the-cloud) +- [Commandes CLI](get-started/cli-commands) +- [Fichier de configuration du serveur](configuration/sample-config) +- [Clés privées](configuration/manage-private-keys) +- [Mesures Prometheus](configuration/prometheus-metrics) +- [Gestionnaires de secrets](/docs/category/secret-managers) +- [Sauvegarde/Restauration](working-with-node/backup-restore) + +## Recommandation minimum du système {#minimum-system-requirements} + +| Type | Valeur | Influencée par | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 2 centres |
  • Nombre de requêtes JSON-RPC
  • Taille de l'état de la blockchain
  • Limite de gaz du bloc
  • Temps de bloc
| +| RAM | 2 Go |
  • Nombre de requêtes JSON-RPC
  • Taille de l'état de la blockchain
  • Limite de gaz du bloc
| +| Disque |
  • Partition de root de 10 Go
  • Partition de root de 30 Go avec LVM pour l'extension de disque
|
  • Taille de l'état de la blockchain
| + + +## Configuration de service {#service-configuration} + +`polygon-edge` binaire doit s'exécuter automatiquement en tant que service de système lors de l'établissement de la connectivité du réseau et avoir des fonctionnalités de démarrage / arrêt / redémarrage +. Nous vous recommandons d'utiliser un gestionnaire de service comme `systemd.` + +Exemple `systemd` de fichier de configuration du système: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### Binaire {#binary} + +Dans les charges de travail de production, `polygon-edge` le binaire doit être seulement déployé à partir des binaires de version GitHub pré-construits - et non par compilation manuelle. +:::info + +En compilant manuellement `develop` la branche de GitHub, vous pouvez introduire des modifications radicales dans votre environnement. Pour cette raison, il est recommandé de déployer le binaire de Polygon Edge exclusivement à partir des versions, car il contiendra des informations sur les changements avec rupture et sur la façon de les surmonter. +::: + +Veuillez vous référer à [Installation](/docs/edge/get-started/installation) pour un aperçu complet de la méthode d'installation. + +### Stockage de données {#data-storage} + +Le dossier `data/` contenant l'état complet de la blockchain doit être monté sur un disque / volume dédié permettant de faire les sauvegardes de disque automatiques, l'extension de volume et éventuellement le montage de disque / volume sur une autre instance en cas de panne. + + +### Le registre des Fichiers {#log-files} + +Le registre des fichiers doivent être tournés quotidiennement (avec un outil comme `logrotate`). +:::warning +S'ils sont configurés sans rotation des journaux, le registre des fichiers peuvent utiliser tout l'espace de disque disponible, ce qui peut perturber la disponibilité du validateur. +::: + +Exemple de `logrotate`configuration: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +Reportez-vous à la section de [Registre](#logging) ci-dessous pour obtenir des recommandations sur le stockage des registres. + +### Dépendances supplémentaires {#additional-dependencies} + +`polygon-edge` est compilé statiquement, ne nécessitant aucune dépendance supplémentaire du système d'exploitation hôte. + +## Maintenance {#maintenance} + +Vous trouverez ci-dessous les meilleures pratiques pour maintenir un nœud de validation en cours d'exécution d'un réseau de Polygon Edge. + +### Sauvegarde {#backup} + +Il existe deux types de procédures de sauvegarde recommandées pour les nœuds de Polygon Edge. + +La suggestion est d'utiliser les deux, dans la mesure du possible, avec la sauvegarde de Polygon Edge étant une option toujours disponible. + +* ***Sauvegarde du volume***: + Sauvegarde incrémentale quotidienne du `data/` volume du nœud de Polygon Edge, ou de la VM complète si possible. + + +* ***Sauvegarde de Polygon Edge***: + Un travail CRON quotidien qui effectue des sauvegardes régulières de Polygon Edge et qui déplace les fichiers `.dat` vers un emplacement hors site ou vers un stockage d'objets cloud sécurisé est recommandé. + +La sauvegarde de Polygon Edge ne devrait idéalement pas dupliquer la sauvegarde de Volume décrite ci-dessus. + +Référez-vous à [l'instance du nœud de Sauvegarde/restauration](working-with-node/backup-restore) pour obtenir des instructions sur la façon d'effectuer des sauvegardes de Polygon Edge. + +### Registre {#logging} + +Les registres générés par les nœuds de Polygon Edge doivent: +- être envoyés à un magasin de données externe avec des capacités d'indexation et de recherche +- ayant une période de rétention du registre de 30 jours + +Si c'est la première fois que vous configurez un validateur de Polygon Edge, nous vous recommandons de démarrer le nœud +avec la possibilité `--log-level=DEBUG` de déboguer rapidement tous les problèmes que vous pourriez rencontrer. + +:::info + +Le `--log-level=DEBUG` rendra la sortie du registre de nœud aussi détaillée que possible. +Les registres de débogage augmenteront considérablement la taille du fichier de registre qui doit être pris en compte lors de la configuration +de la solution de rotation de registre. + +::: +### Les pièces de sécurité du Système d'Exploitation {#os-security-patches} + +Les administrateurs doivent s'assurer que le Système d'Exploitation de l'instance du validateur est toujours mis à jour avec les derniers correctifs au moins une fois par mois. + +## Métriques {#metrics} + +### Les métriques du système {#system-metrics} + +Les administrateurs doivent configurer une sorte de moniteur des métriques du système (par exemple, Telegraf + InfluxDB + Grafana ou un SaaS tiers). + +Les métriques qui doivent être surveillées et être configurées pour les notifications d'alarme: + +| Nom de la métrique | Niveau d'alarme | +|-----------------------|-------------------------------| +| Utilisation du processeur (%) | > 90% pendant plus de 5 minutes | +| Utilisation de RAM (%) | > 90% pendant plus de 5 minutes | +| Utilisation du disque de root | > 90% | +| Utilisation du disque de données | > 90% | + +### Les métriques du validateur {#validator-metrics} + +Les administrateurs doivent configurer la collection de métriques à partir de l'API Prometheus de Polygon Edge pour être capable de surveiller les performances de la blockchain. + +Référez-vous à des [métriques Prometheus](configuration/prometheus-metrics) pour comprendre quelles métriques sont exposées et comment configurer la collection des métriques Prometheus. + + +Une attention particulière doit être accordée aux mesures suivantes: +- ***Le temps de production de bloc*** - si le temps de production de bloc est supérieur à la normale, il y a un problème potentiel avec le réseau +- ***Nombre de tours de consensus*** - s'il y a plus d'1 tour, il y aura un problème potentiel avec le validateur défini dans le réseau +- ***Nombre de pairs*** - si le nombre de pairs chute, il y a un problème de connectivité dans le réseau + +## Securité {#security} + +Vous trouverez ci-dessous les meilleures pratiques pour sécuriser un nœud de validation en cours d'exécution d'un réseau de Polygon Edge. + +### Services d'API {#api-services} + +- ***JSON-RPC*** - +Seuls les service d'API doivent être exposés au public (via un équilibreur de charge ou directement). +Cette API doit s'exécuter sur toutes les interfaces ou sur une adresse IP spécifique (exemple: `--json-rpc 0.0.0.0:8545` ou `--json-prc 192.168.1.1:8545`). +:::info + +Comme il s'agit d'une API publique, il est recommandé d'avoir un équilibreur de charge ou un proxy inverse devant lui, pour assurer la sécurité et la limitation du débit. + +::: + + +- ***LibP2P*** - +Il s'agit de l'API de mise en réseau utilisée par les nœuds pour la communication entre pairs. Il doit fonctionner sur toutes les interfaces ou sur une adresse IP spécifique +( `--libp2p 0.0.0.0:1478` ou `--libp2p 192.168.1.1:1478` ). Cette API ne doit pas être exposée au publique, +mais elle doit être accessible depuis tous les autres nœuds. +:::info + +S'il est exécuté sur localhost, (`--libp2p 127.0.0.1:1478`) les autres nœuds ne pourront pas se connecter. + +::: + + +- ***GRPC*** - +Cette API est utilisée uniquement pour exécuter des commandes d'opérateur et rien d'autres. En tant que tel, elle doit s'exécuter exclusivement sur localhost ( `--grpc-address 127.0.0.1:9632` ). + +### Les secrets de Polygone Edge {#polygon-edge-secrets} + +Les secrets de Polygon Edge ( `ibft` et des `libp2p` clés ) ne doivent pas être stockés sur un système de fichiers local. +Au lieu de cela, un [Gestionnaire de Secret](configuration/secret-managers/set-up-aws-ssm) pris en charge doit être utilisé. +Le stockage des secrets dans le système de fichiers local doit être seulement utilisé dans des environnements de non-production. + +## Mise À Jour {#update} + +Vous trouverez ci-dessous la procédure de mise à jour souhaitée pour les nœuds de validation, décrite sous forme d'instructions détaillées. + +### Procédure de mise à jour {#update-procedure} + +- Téléchargez le dernier binaire de Polygon Edge à partir des [versions](https://github.com/0xPolygon/polygon-edge/releases) officielles du GitHub +- Arrêtez le service de Polygon Edge ( exemple: `sudo systemctl stop polygon-edge.service` ) +- Remplacez le `polygon-edge` binaire existant par celui téléchargé ( par exemple: `sudo mv polygon-edge /usr/local/bin/` ) +- Vérifiez si la `polygon-edge` version correcte est en place en exécutant `polygon-edge version` - elle doit correspondre à la version publiée +- Vérifiez la documentation de la version s'il y a des étapes de rétrocompatibilité à effectuer avant de démarrer le `polygon-edge` service +- Démarrez `polygon-edge` le service ( exemple: `sudo systemctl start polygon-edge.service` ) +- Enfin, vérifiez la sortie du registre `polygon-edge` et assurez-vous que tout fonctionne sans aucun registre `[ERROR]` + +:::warning + +Lorsqu'il y a une version de rupture, cette procédure de mise à jour doit être effectuée sur tous les nœuds, car +le binaire en cours d'exécution n'est pas compatible avec la nouvelle version. + +Cela signifie que la chaîne doit être arrêtée pendant une courte période ( jusqu'à ce que les `polygon-edge` binaires soient remplacés et que le service redémarre ) +alors plannifiez en conséquence. + +Vous pouvez utiliser des outils comme **[Ansible](https://www.ansible.com/)** ou un scénario personnalisé pour effectuer la mise à jour efficacement +et minimiser les temps d'arrêt de la chaîne. + +::: + +## Procédure de démarrage {#startup-procedure} + +Voici le flux souhaité de la procédure de démarrage pour le validateur de Polygon Edge + +- Lisez les documents répertoriés dans la section de [Base Des Connaissances](#knowledge-base) +- Appliquez les derniers correctifs du Système d'Exploitation sur le nœud du validateur +- Téléchargez le dernier `polygon-edge` fichier binaire à partir des [versions](https://github.com/0xPolygon/polygon-edge/releases) officielles du GitHub et placez-le dans une instance locale `PATH` +- Initialisez l'un des [gestionnaires de secrets](/docs/category/secret-managers) pris en charge en utilisant `polygon-edge secrets generate` la commande CLI +- Générez et stockez des secrets en utilisant la `polygon-edge secrets init` [commande CLI](/docs/edge/get-started/cli-commands#secrets-init-flags) +- Prendre note de `Public key (address)` et `NodeID` des valeurs +- Générez `genesis.json` le fichier comme décrit dans la [configuration de cloud](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators) en utilisant la `polygon-edge genesis` [commande CLI](/docs/edge/get-started/cli-commands#genesis-flags) +- Générer le fichier de configuration par défaut en utilisant la `polygon-edge server export` [commande CLI](/docs/edge/configuration/sample-config) +- Modifier `default-config.yaml` le fichier pour s'adapter à l'environnement du nœud de validation local ( les trajectoires de fichiers, etc. ) +- Créez un service de Polygon Edge (`systemd` ou similaire) où le fichier binaire `polygon-edge` dirigera le serveur à partir d'un `default-config.yaml` fichier +- Démarrez le serveur de Polygon Edge en démarrant le service ( exemple: `systemctl start polygon-edge` ) +- Vérifiez la sortie du registre `polygon-edge` et assurez-vous que les blocs sont générés et qu'il n'y a pas de `[ERROR]` registres +- Vérifiez la fonctionnalité de la chaîne en appelant une méthode JSON-RPC comme [`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid) diff --git a/archive/edge/fr-edge/working-with-node/backup-restore.md b/archive/edge/fr-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..40a29653b4 --- /dev/null +++ b/archive/edge/fr-edge/working-with-node/backup-restore.md @@ -0,0 +1,87 @@ +--- +id: backup-restore +title: Instance de nœud de sauvegarde/restauration +description: "Comment sauvegarder et restaurer une instance de nœud de Polygon Edge." +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## Aperçu {#overview} + +Ce guide explique en détail comment sauvegarder et restaurer une instance de nœud Polygon Edge. +Il couvre les dossiers de base et ce qu'ils contiennent, ainsi que les fichiers essentiels pour effectuer une sauvegarde et une restauration réussies. + +## Dossiers de base {#base-folders} + +Polygon Edge utilise LevelDB comme moteur de stockage. +Lors du démarrage d'un nœud Polygon Edge, les sous-dossiers suivants sont créés dans le répertoire de travail spécifié : +* **blockchain** - Stocke les données de la blockchain +* **trie** - Stocke les tries de Merkle (données sur l'état mondial) +* **keystore** - Stocke les clés privées du client. Cela inclut la clé privée libp2p et la clé privée de scellement/validateur +* **consensus** - Stocke toutes les informations de consensus dont le client pourrait avoir besoin pendant son travail. Pour l'instant, il stocke la *clé de validation privée* du nœud + +Il est essentiel que ces dossiers soient conservés pour que l'instance Polygon Edge fonctionne correctement. + +## Créez une sauvegarde à partir d'un nœud en cours d'exécution et faîtes une restauration pour un nouveau nœud {#create-backup-from-a-running-node-and-restore-for-new-node} + +Cette section vous guide dans la création de données d'archive de la blockchain dans un nœud en cours d'exécution et dans sa restauration dans une autre instance. + +### Sauvegarde {#backup} + +`backup` La commande récupère les blocs d'un nœud en cours d'exécution par gRPC et génère un fichier d'archive. Si `--from` et `--to` ne sont pas donnés dans la commande, cette commande récupérera les blocs de la genèse au plus récent. + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### Restaurez {#restore} + +Un serveur importe des blocs d'une archive au démarrage lorsqu'il démarre avec l'indicateur `--restore`. Assurez-vous qu'il existe une clé pour le nouveau nœud. Pour en savoir plus sur l'importation ou la génération de clés, visitez la [section Gestionnaires de secrets](/docs/edge/configuration/secret-managers/set-up-aws-ssm). + +```bash +$ polygon-edge server --restore archive.dat +``` + +## Sauvegardez/restaurez des données Complètes {#back-up-restore-whole-data} + +Cette section vous guide dans la sauvegarde des données, y compris les données d'état et la clé, puis la restauration dans la nouvelle instance. + +### Étape 1 : Arrêtez le client en cours d'exécution {#step-1-stop-the-running-client} + +Étant donné que Polygon Edge utilise **LevelDB** pour le stockage des données, le nœud doit être arrêté pendant la durée de la sauvegarde, +car **LevelDB** n'autorise pas l'accès simultané à ses fichiers de base de données. + +De plus, Polygon Edge effectue également le vidage des données à la fermeture. + +La première étape consiste à arrêter le client en cours d'exécution (soit via un gestionnaire de services, soit via un autre mécanisme qui envoie un signal SIGINT au processus), +cela peut donc déclencher 2 événements tout en s'arrêtant gracieusement : +* Exécution du vidage des données sur le disque +* Libération du verrouillage des fichiers DB par LevelDB + +### Étape 2 : sauvegardez le répertoire {#step-2-backup-the-directory} + +Maintenant que le client n'est pas en cours d'exécution, le répertoire de données peut être sauvegardé sur un autre support. Gardez à l'esprit que les fichiers avec une extension `.key` contiennent les données de clé privée qui peuvent être utilisées pour emprunter l'identité du nœud actuel, et ils ne doivent jamais être partagés avec un tiers/inconnu. + +:::info +Veuillez sauvegarder et restaurer manuellement le fichier `genesis` généré, afin que le nœud restauré soit pleinement opérationnel. +::: + +## Restaurez {#restore-1} + +### Étape 1 : Arrêtez le client en cours d'exécution {#step-1-stop-the-running-client-1} + +Si une instance de Polygon Edge est en cours d'exécution, elle doit être arrêtée pour que l'étape 2 réussisse. + +### Étape 2 : Copiez le répertoire de données sauvegardées dans le dossier souhaité {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +Une fois que le client n'est pas en cours d'exécution, le répertoire de données précédemment sauvegardé peut être copié dans le dossier souhaité. De plus, restaurez le fichier `genesis` précédemment copié. + +### Étape 3 : Exécutez le client de Polygon Edge tout en spécifiant le répertoire de données correct {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +Pour que Polygon Edge utilise le répertoire de données restauré, au lancement, l'utilisateur doit spécifier le chemin d'accès au répertoire de données. Veuillez consulter la section [Commandes CLI](/docs/edge/get-started/cli-commands) pour plus d'informations sur l'indicateur `data-dir`. diff --git a/archive/edge/fr-edge/working-with-node/query-json-rpc.md b/archive/edge/fr-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..206b4d9ed6 --- /dev/null +++ b/archive/edge/fr-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,94 @@ +--- +id: query-json-rpc +title: Requête des points de terminaison JSON RPC +description: "Interrogez les données et démarrez la chaîne avec un compte prédominé." +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## Aperçu {#overview} + +La couche JSON-RPC de Polygon Edge offre aux développeurs la fonctionnalité d'interagir facilement avec la blockchain, +via des requêtes HTTP. + +Cet exemple couvre l'utilisation d'outils tels que le **curl** pour interroger des informations, ainsi que le démarrage de la chaîne avec un compte prédominé, +et l'envoi d'une transaction. + +## Étape 1 : Créez un fichier de genèse avec un compte prédominé {#step-1-create-a-genesis-file-with-a-premined-account} + +Pour générer un fichier de genèse, exécutez la commande suivante : +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +L'indicateur **préminé** définit l'adresse qui doit être incluse avec un solde de départ dans le fichier **genèse**.
+Dans ce cas, l'adresse `0x1010101010101010101010101010101010101010` aura un **solde par défaut** de départ de +`0xD3C21BCECCEDA1000000`(1 million de jetons de monnaie native). + +Si nous souhaitons spécifier un solde, nous pouvons séparer le solde et indiquer un `:`, comme ceci : +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +Le solde peut être soit une valeur `hex`, soit une valeur `uint256`. + +:::warning Faîtes seulement le premine des comptes pour lesquels vous disposez d'une clé privée! + +Si vous préminez des comptes et que vous n'avez pas de clé privée pour y accéder, votre solde préminé ne sera pas utilisable + +::: + +## Étape 2 : Démarrez Polygon Edge en mode dev {#step-2-start-the-polygon-edge-in-dev-mode} + +Pour démarrer Polygon Edge en mode de développement, ce qui est expliqué dans la section [CLI Commands](/docs/edge/get-started/cli-commands), +exécutez les opérations suivantes : +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## Étape 3 : Interrogez le solde du compte {#step-3-query-the-account-balance} + +Maintenant que le client est opérationnel en mode dev, en utilisant le fichier de genèse généré à l'**étape 1**, nous pouvons utiliser un outil tel que + +**curl** pour interroger le solde du compte : +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +La commande doit renvoyer le résultat suivant : +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## Étape 4 : Envoyez une transaction de transfert {#step-4-send-a-transfer-transaction} + +Maintenant que nous avons confirmé que le compte que nous avons configuré pour préminer a le bon solde, nous pouvons transférer un peu d'éther : + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/fr-edge/working-with-node/query-operator-info.md b/archive/edge/fr-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..3e2958117e --- /dev/null +++ b/archive/edge/fr-edge/working-with-node/query-operator-info.md @@ -0,0 +1,85 @@ +--- +id: query-operator-info +title: Interrogez les informations de l'opérateur. +description: "Comment interroger les informations de l'opérateur." +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## Prérequis {#prerequisites} + +Ce guide suppose que vous avez suivi la [Configuration Locale](/docs/edge/get-started/set-up-ibft-locally) ou le [guide sur la configuration d'un cluster IBFT sur le cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +Un nœud fonctionnel est nécessaire pour interroger tout type d'informations sur l'opérateur. + +Avec Polygon Edge, les opérateurs de nœuds ont le contrôle et sont informés de ce que fait le nœud qu'ils exploitent.
+À tout moment, ils peuvent utiliser la couche d'informations de nœud, construite au-dessus de gRPC, et obtenir des informations significatives - aucun filtrage des journaux n'est requis. + +:::note + +Si votre nœud n'est pas en cours d'exécution sur `127.0.0.1:8545` vous devez ajouter un indicateur `--grpc-address ` aux commandes répertoriées dans ce document. + +::: + +## Informations sur les pairs {#peer-information} + +### Liste des pairs {#peers-list} + +Pour obtenir une liste complète des pairs connectés (y compris le nœud en cours d'exécution lui-même), exécutez la commande suivante : +````bash +polygon-edge peers list +```` + +Cela renverra une liste d'adresses libp2p qui sont actuellement des pairs du client en cours d'exécution. + +### Statut des pairs {#peer-status} + +Pour connaître l'état d'un pair spécifique, exécutez : +````bash +polygon-edge peers status --peer-id
+```` +Le paramètre *d'adresse* étant l'adresse libp2p du pair. + +## Informations sur les IBFT {#ibft-info} + +Souvent, un opérateur peut vouloir connaître l'état du nœud d'exploitation dans le consensus IBFT. + +Heureusement, Polygon Edge fournit un moyen facile de trouver ces informations. + +### Prise de photos {#snapshots} + +L'exécution de la commande suivante renvoie l'instantané le plus récent. +````bash +polygon-edge ibft snapshot +```` +Pour interroger l'instantané à une hauteur spécifique (numéro de bloc), l'opérateur peut exécuter : +````bash +polygon-edge ibft snapshot --num +```` + +### Candidats {#candidates} + +Pour obtenir les informations les plus récentes sur les candidats, l'opérateur peut exécuter : +````bash +polygon-edge ibft candidates +```` +Cette commande interroge l'ensemble actuel de candidats proposés, ainsi que les candidats qui n'ont pas encore été inclus + +### Statut {#status} + +La commande suivante renvoie la clé de validation actuelle du client IBFT en cours d'exécution : +````bash +polygon-edge ibft status +```` + +## Pool de transactions {#transaction-pool} + +Pour trouver le nombre actuel de transactions dans le pool de transactions, l'opérateur peut exécuter : +````bash +polygon-edge txpool status +```` diff --git a/archive/edge/hi-edge/additional-features/blockscout.md b/archive/edge/hi-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..3e39607faf --- /dev/null +++ b/archive/edge/hi-edge/additional-features/blockscout.md @@ -0,0 +1,379 @@ +--- +id: blockscout +title: ब्लॉक स्काउट +description: पॉलीगॉन एज के साथ काम करने के लिए एक ब्लॉक स्काउट इंस्टैंस कैसे सेट किया जाए. +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## ओवरव्यू {#overview} +यह गाइड, पॉलीगॉन-एज के साथ काम करने के लिए ब्लॉक स्काउट इंस्टैंस कम्पाइल और डिप्लॉय कैसे किया जाए उसका विवरण देता है. ब्लॉक स्काउट का अपना [डॉक्यूमेंटेशन](https://docs.blockscout.com/for-developers/manual-deployment) होता है, लेकिन यह गाइड, ब्लॉक स्काउट इंस्टैंस को कैसे सेटअप किया जाए उस पर सरल लेकिन विस्तृत स्टेप-बाय-स्टेप निर्देशों पर ध्यान केंद्रित करता है. + +## वातावरण {#environment} +* ऑपरेटिंग सिस्टम: सूडो अनुमतियों के साथ Ubuntu सर्वर 20. 04 LTS [डाउनलोड लिंक](https://releases.ubuntu.com/20.04/) +* सर्वर हार्डवेयर : 8CPU / 16GB रैम / 50GB HDD (LVM) +* डेटाबेस सर्वर: 2 CPU / 4GB रैम / 100GB SSD / PostgreSQL 13.4 + +### DB सर्वर {#db-server} +इस गाइड को फॉलो करने के लिए एक डेटाबेस सर्वर रेडी, डेटाबेस और db यूज़र कॉन्फ़िगर होना चाहिए. यह गाइड, पोस्टग्रेएसक्यूएल सर्वर को डिप्लॉय और कॉन्फ़िगर कैसे किया जाए उसका विवरण नहीं देगा. इसे करने के लिए अब बहुत सारे गाइड हैं, उदाहरण के लिए [DigitalOcean गाइड](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart) + +:::info डिस्क्लेमर +यह गाइड सिर्फ ब्लॉक स्काउट पाने और सिंगल इंस्टैंस पर रन करने में सहायता करने के लिए है जो आदर्श उत्पादन सेटअप नहीं है . उत्पादन के लिए, आप शायद आर्किटेक्चर में रिवर्स प्रोक्सी, लोड बैलेंसर, स्केल करने की क्षमता, इत्यादि को पेश करना चाहते हैं. +::: + +# ब्लॉक स्काउट डिप्लॉयमेंट प्रक्रिया {#blockscout-deployment-procedure} + +## भाग 1 - निर्भरता इंस्टॉल करें {#part-1-install-dependencies} +शुरू करने से पहले हमें यह सुनिश्चित करने की जरूरत है कि हमने उन सभी बाइनरी को इंस्टॉल कर लिया है जिन पर ब्लॉक स्काउट निर्भर है. + +### अपडेट और अपग्रेड सिस्टम {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### एरलैंग रेपोस जोड़ें {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### NodeJS रेपो जोड़ें {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### रस्ट इंस्टॉल करें {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### एरलैंग का आवश्यक वर्जन इंस्टॉल करें {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### एलिक्सिर का आवश्यक वर्जन इंस्टॉल करें {#install-required-version-of-elixir} +एलिक्सिर का वर्जन `1.13` होना चाहिए. अगर हम आधिकारिक रेपो से इस वर्जन को इंस्टॉल इंस्टॉल करने की कोशिश करते हैं, तो `erlang` में `Erlang/OTP 25` अपडेट हो जाएगा और हम ऐसा नहीं चाहते हैं. इस वजह से, हमें गिटहब रिलीज पेज से विशिष्ट प्रीकम्पाइल्ड `elixir`वर्जन इंस्टॉल करने की जरूरत है. + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +अब हमें `exlixir`सिस्टम बायनरी को ठीक से सेट करने की जरूरत है. +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +`elixir -v`को रन करके जाँचें कि `erlang`और `elixir` ठीक से इंस्टॉल हुए हैं या नहीं. आउटपुट यही होना चाहिए: +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning +`Erlang/OTP` वर्जन `24` होना चाहिए और `Elixir` वर्जन `1.13.*` होना चाहिए. अगर ऐसा नहीं होता है, तो आपको ब्लॉक स्काउट को कम्पाइल और / या रन करने में समस्या होगी. +::: +:::info +आधिकारिक ***[ब्लॉक स्काउट आवश्यकताएं पेज](https://docs.blockscout.com/for-developers/information-and-settings/requirements)*** जाँचें +::: + +### NodeJS इंस्टॉल करें {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### कार्गो इंस्टॉल करें {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### अन्य निर्भरताएँ इंस्टॉल करें {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### अपना db कनेक्शन जाँचने के लिए वैकल्पिक रूप से postgresql क्लाइंट इंस्टॉल करें {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## भाग 2 - वातावरण वेरिएबल्स सेट करें {#part-2-set-environment-variables} +ब्लॉक स्काउट कम्पाइलेशन शुरू करने से पहले हमें वातावरण वेरिएबल्स सेट करने होंगे. इस गाइड में हम इससे काम कराने के लिए केवल बुनियादी न्यूनतम सेट करेंगे. सेट किए जा सकने वाले वेरिएबल्स की पूरी सूची आपको [यहाँ](https://docs.blockscout.com/for-developers/information-and-settings/env-variables) मिल सकती है + +### वातावरण वेरिएबल के रूप में डेटाबेस कनेक्शन सेट करें {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +अब दिए गए पैरामीटरों के साथ अपने DB कनेक्शन को टेस्ट करें. चूंकि आपने PG env vars प्रदान किया है, तो आपको सिर्फ निम्नलिखित को रन करके डेटाबेस से कनेक्ट होने में सक्षम होना चाहिए: +```bash +psql +``` + +अगर डेटाबेस को सही तरीके से कॉन्फ़िगर किया गया है, तो आपको एक psql प्रांप्ट दिखाई देना चाहिए: +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +अन्यथा, आपको इस तरह की त्रुटि दिखाई दे सकती है: +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +अगर ऐसी बात है तो [ये डॉक्यूमेंट](https://ubuntu.com/server/docs/databases-postgresql) आपकी सहायता कर सकते हैं. + +:::info DB कनेक्शन + +अगले भाग की तरफ बढ़ने से पहले सुनिश्चित करें कि आपने सभी db कनेक्शन समस्याओं को सुलझा लिया है. +आपको ब्लॉक स्काउट यूज़र को सुपर यूज़र विशेषाधिकार प्रदान करने होंगे. + +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## भाग 3 - ब्लॉक स्काउट को क्लोन और कम्पाइल करें {#part-3-clone-and-compile-blockscout} +अब हम आख़िरकार ब्लॉक स्काउट इंस्टॉलेशन शुरू करते हैं. + +### ब्लॉक स्काउट रेपो क्लोन करें {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### उत्पादन निर्माण को बचाने के लिए सीक्रेट की आधार तैयार करें {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +बहुत आखिरी लाइन में, आपको यादृच्छिक अक्षरों का एक लम्बा स्ट्रिंग दिखाई देना चाहिए. अगले स्टेप से पहले इसे आपके `SECRET_KEY_BASE`वातावरण वेरिएबल के रूप में सेट किया जाना चाहिए. उदाहरण के लिए: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### उत्पादन मोड सेट करें {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### कम्पाइल करें {#compile} +क्लोन निर्देशिका में Cd करें और कम्पाइलिंग शुरू करें + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info +अगर आपने पिछली बार डिप्लॉय किया है, तो पिछले बिल्ड ***मिक्स phx.digest.clean*** से स्टेटिक एसेट्स को हटा दें. +::: + +### डेटाबेस को माइग्रेट करें {#migrate-databases} +:::info +यह भाग विफल हो जाएगा यदि आपने अपने DB कनेक्शन को ठीक से सेट नहीं किया है, तो आपने प्रदान नहीं किया है, या आपने DATABASE_URL वातावरण वेरिएबल पर गलत पैरामीटर्स को परिभाषित किया है. डेटाबेस यूज़र के पास सुपरयूज़र विशेषाधिकार होना चाहिए. +::: +```bash +mix do ecto.create, ecto.migrate +``` + +अगर आपको पहले डेटाबेस को ड्रॉप करने की जरूरत है, तो रन करें +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### npm निर्भरता इंस्टॉल करें और फ्रंटएंड एसेट्स को कम्पाइल करें {#install-npm-dependencies-and-compile-frontend-assets} +आपको डायरेक्टरी को फ़ोल्डर में बदलना होगा जिसमें फ्रंटएंड एसेट्स है. + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info धैर्य रखें +इन एसेट्स के कम्पाइलेशन में कुछ मिनट लग सकता है, और यह कोई आउटपुट नहीं दिखाएगा. ऐसा लग सकता है कि प्रक्रिया अटक गई है, लेकिन बस धैर्य रखें. कम्पाइल प्रक्रिया समाप्त होने पर इसका आउटपुट कुछ ऐसा होना चाहिए: `webpack 5.69.1 compiled with 3 warnings in 104942 ms` +::: + +### स्टेटिक एसेट्स बनाएँ {#build-static-assets} +इस स्टेप के लिए आपको अपने ब्लॉक स्काउट क्लोन फ़ोल्डर के रुट में लौटना होगा. +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### स्व-हस्ताक्षरित प्रमाणपत्र बनाएँ {#generate-self-signed-certificates} +:::info +यदि आप `https` इस्तेमाल नहीं करेंगे तो आप यह स्टेप छोड़ सकते हैं. +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## भाग 4 - ब्लॉक स्काउट सेवा बनाएँ और रन करें {#part-4-create-and-run-blockscout-service} +इस भाग में हमें सिस्टम सेवा सेट करनी होगी क्योंकि हम चाहते हैं कि ब्लॉक स्काउट, पृष्ठभूमि में रन करे और सिस्टम रीबूट के बाद कायम रहे. + +### सेवा फ़ाइल बनाएँ {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### सेवा फ़ाइल एडिट करें {#edit-service-file} +इस फ़ाइल को एडिट करने और सेवा को कॉन्फ़िगर करने के लिए अपने पसंदीदा लिनक्स टेक्स्ट एडिटर का इस्तेमाल करें +```bash +sudo vi /etc/systemd/system/explorer.service +``` +explorer.service फ़ाइल की सामग्री ऐसी दिखनी चाहिए: +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### सिस्टम बूट पर शुरूआती सेवा चालू करें {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### अपने ब्लॉक स्काउट क्लोन फ़ोल्डर को सिस्टम व्यापी स्थान में ले जाएँ {#move-your-blockscout-clone-folder-to-system-wide-location} +ब्लॉक स्काउट सेवा के पास उस फ़ोल्डर का एक्सेस होना चाहिए जिसे आपने ब्लॉक स्काउट रेपो से क्लोन किया है और सभी एसेट्स को कम्पाइल किया है. +```bash +sudo mv ~/blockscout /usr/local +``` + +### env vars फ़ाइल बनाएँ जिसका इस्तेमाल ब्लॉक स्काउट सेवा द्वारा किया जाएगा {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info +`SECRET_KEY_BASE` का इस्तेमाल करें जिसे आपने भाग 3 में बनाया है. +:::फ़ाइल सहेजकर बाहर निकलें. + +### अंत में, ब्लॉक सेवा शुरू करें {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## भाग 5 - अपने ब्लॉक स्काउट इंस्टैंस की कार्यक्षमता टेस्ट करें {#part-5-test-out-the-functionality-of-your-blockscout-instance} +अब सिर्फ यह जाँचना बाकी है कि ब्लॉक स्काउट सेवा रन हो रही या नहीं. के साथ सेवा स्थिति जाँचें +```bash +sudo systemctl status explorer.service +``` + +सेवा आउटपुट जाँचने के लिए: +```bash +sudo journalctl -u explorer.service -f +``` + +आप जाँच सकते हैं कि कोई नया लिसनिंग पोर्ट है या नहीं: +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +आपको लिसनिंग पोर्ट्स की सूची प्राप्त प्राप्त होनी चाहिए और सूची कुछ ऐसी होनी चाहिए: +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +ब्लॉक स्काउट वेब सेवा, env फ़ाइल में परिभाषित पोर्ट और प्रोटोकॉल रन करती है. इस उदाहरण में यह `4000`(http) पर रन होता है. अगर सब कुछ ठीक है, तो आपको `http://:4000` के साथ ब्लॉक स्काउट वेब पोर्टल को एक्सेस करने में सक्षम होना चाहिए. + +## विचार {#considerations} +सर्वश्रेष्ठ प्रदर्शन के लिए, एक समर्पित / स्थानीय`polygon-edge` पूरा आर्काइव नॉन-वैलिडेटर नोड प्राप्त करना बेहतर होता है जिसका इस्तेमाल विशेष रूप से ब्लॉक स्काउट प्रश्नों के लिए किया जाएगा. इस नोड के `json-rpc`API को सार्वजनिक रूप से उजागर करने की जरूरत नहीं है क्योंकि ब्लॉक स्काउट, सभी प्रश्नों को बैकएंड से रन करता है. + + +## अंतिम विचार {#final-thoughts} +हमने अभी-अभी एक सिंगल ब्लॉक स्काउट इंस्टैंस डिप्लॉय किया है, जो ठीक काम करता है, लेकिन उत्पादन के लिए आपको इस इंस्टैंस को Nginx जैसे रिवर्स प्रॉक्सी के पीछे रखने पर विचार करना चाहिए. आपको अपने इस्तेमाल मामले के आधार पर, डेटाबेस और इंस्टैंस स्केल करने की क्षमता के बारे में भी सोचना चाहिए. + +आपको आधिकारिक [ब्लॉक स्काउट डॉक्यूमेंटेशन ](https://docs.blockscout.com/)को जरूर जाँचना चाहिए क्योंकि इसमें बहुत सारे कस्टमाइजेशन विकल्प होते हैं. \ No newline at end of file diff --git a/archive/edge/hi-edge/additional-features/chainbridge/definitions.md b/archive/edge/hi-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..3a1a52a8d5 --- /dev/null +++ b/archive/edge/hi-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,219 @@ +--- +id: definitions +title: सामान्य परिभाषाएँ +description: चेनब्रिज में इस्तेमाल किए गए शब्दों की सामान्य परिभाषाएँ +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## रिलेयर {#relayer} +चेनब्रिज एक रिलेयर प्रकार का ब्रिज है. एक रिलेयर का काम अनुरोध के एग्जीक्यूशन के लिए वोट करना है (उदाहरण के लिए, कितने टोकन बर्न/रिलीज़ करना है). +यह प्रत्येक चेन से इवेंट को मॉनिटर करता है, और जब इसे एक चेन से `Deposit` इवेंट प्राप्त होता है तो गंतव्य चेन के ब्रिज कॉन्ट्रैक्ट में प्रस्ताव के लिए वोट करता है. ज़रूरी वोट जमा करने के बाद, रिलेयर प्रस्ताव को एग्जीक्यूट करने के लिए ब्रिज कॉन्ट्रैक्ट में एक रिलेयर को कॉल करता है. ब्रिज हैंडलर कॉन्ट्रैक्ट के एग्जीक्यूशन को डेलीगेट करता है. + + +## कॉन्ट्रैक्ट के प्रकार {#types-of-contracts} +चैनब्रिज में, प्रत्येक चेन पर तीन प्रकार के कॉन्ट्रैक्ट होते हैं, जिन्हें ब्रिज/हैंडलर/टार्गेट कहा जाता है. + +| **प्रकार** | **वर्णन** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| ब्रिज कॉन्ट्रैक्ट | ब्रिज कॉन्ट्रैक्ट अनुरोध, वोट, हर चेन में डिप्लॉय करने के लिए ज़रूरी एग्जीक्यूशन को मैनेज करता है. यूज़र ट्रांसफ़र शुरू करने के लिए ब्रिज में `deposit` को कॉल करेंगे, और ब्रिज टार्गेट कॉन्ट्रैक्ट के अनुरूप प्रक्रिया को हैंडलर कॉन्ट्रैक्ट को डेलिगेट देगा. हैंडलर कॉन्ट्रैक्ट एक बार टार्गेट कॉन्ट्रैक्ट को कॉल करने में सफल होने के बाद, ब्रिज कॉन्ट्रैक्ट रिलेयर्स को सूचित करने के लिए एक `Deposit` इवेंट का एमिट करता है. | +| हैंडलर कॉन्ट्रैक्ट | यह कॉन्ट्रैक्ट डिपॉज़िट या प्रस्ताव का एग्जीक्यूशन करने के लिए टार्गेट कॉन्ट्रैक्ट के साथ इंटरैक्ट करता है. यह यूज़र के कॉन्ट्रैक्ट को वैलिडेट करता है, टार्गेट कॉन्ट्रैक्ट को कॉल करता है और टार्गेट कॉन्ट्रैक्ट की सेटिंग्स में मदद करता है. प्रत्येक टार्गेट कॉन्ट्रैक्ट को कॉल करने के लिए कुछ ख़ास हैंडलर कॉन्ट्रैक्ट होते हैं जिनका एक अलग इंटरफ़ेस होता है. हैंडलर कॉन्ट्रैक्ट द्वारा की गई अप्रत्यक्ष कॉल किसी भी प्रकार की असेट या डेटा का ट्रांसफ़र करने के लिए ब्रिज बनाते हैं. वर्तमान में, चैनब्रिज द्वारा कार्यान्वित तीन प्रकार के हैंडलर कॉन्ट्रैक्ट हैं: ERC20Handler, ERC721Handler, और GenericHandler. | +| टार्गेट कॉन्ट्रैक्ट | ऐसा कॉन्ट्रैक्ट जो एक्सचेंज की जाने वाली असेट या चेन के बीच ट्रांसफ़र किए जाने वाले मैसेज को मैनेज करता है. इस कॉन्ट्रैक्ट के साथ इंटरैक्शन ब्रिज के हर साइड से की जाएगी. | + +
+ +![चैनब्रिज आर्किटेक्चर](/img/edge/chainbridge/architecture.svg) +*चैनब्रिज आर्किटेक्चर* + +
+ +
+ +![erc20 टोकन ट्रांसफ़र का वर्कफ्लो](/img/edge/chainbridge/erc20-workflow.svg) *जैसे एक erc20 टोकन ट्रांसफ़र का वर्कफ्लो* + +
+ +## अकाउंट के प्रकार {#types-of-accounts} + +कृपया शुरू करने से पहले यह सुनिश्चित करें कि ट्रांज़ैक्शन करने के लिए अकाउंट में पर्याप्त नेटिव टोकन हैं. पॉलीगॉन एज में, आप जेनेसिस ब्लॉक जनरेट करते समय, अकाउंट में premined बैलेंस को असाइन कर सकते हैं. + +| **प्रकार** | **विवरण** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| एडमिन | इस अकाउंट को डिफ़ॉल्ट रूप से एडमिन के रूप में इस्तेमाल किया जाएगा. | +| यूज़र | प्रेषक/प्राप्तकर्ता अकाउंट जो असेट भेजता/प्राप्त करता है. प्रेषक अकाउंट टोकन ट्रांसफ़र की मंजूरी देने और ट्रांसफ़र शुरू करने के लिए ब्रिज कॉन्ट्रैक्ट में डिपॉज़िट करने के लिए गैस फ़ीस का भुगतान करता है. | + +:::info एडमिन की भूमिका +कुछ कार्रवाईयाँ सिर्फ़ एडमिन अकाउंट से की जा सकती है. डिफ़ॉल्ट रूप से, कॉन्ट्रैक्ट के डिप्लॉयर में एडमिन की भूमिका होती है. आप नीचे किसी अन्य अकाउंट को एडमिन की भूमिका प्रदान करने या उसे हटाने के तरीके जानेंगे. + +### एडमिन की भूमिका जोड़ना {#add-admin-role} + +एक एडमिन को जोड़ना + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### एडमिन की भूमिका रद्द करना {#revoke-admin-role} + +एडमिन को हटाना + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## `admin` अकाउंट द्वारा अनुमत ऑपरेशन्स नीचे दिए गए हैं. {#account-are-as-below} + +### रिसोर्स सेट करें {#set-resource} + +हैंडलर के लिए कॉन्ट्रैक्ट पते के साथ रिसोर्स ID रजिस्टर करें. + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### कॉन्ट्रैक्ट को मिन्टेबल/बर्नेबल बनाएँ {#make-contract-burnable-mintable} + +हैंडलर में टोकन कॉन्ट्रैक्ट को मिन्टेबल/बर्नेबल सेट करें. + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### प्रस्ताव रद्द करें {#cancel-proposal} + +एग्जीक्यूशन का प्रस्ताव रद्द करें + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### पॉज़/अनपॉज़ {#pause-unpause} + +डिपॉज़िट, प्रस्ताव निर्माण, वोटिंग और डिपॉज़िट एग्जीक्यूशन को अस्थायी रूप से रोकें. + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### फ़ीस बदलें {#change-fee} + +ब्रिज कॉन्ट्रैक्ट पर भुगतान की गई फ़ीस बदलें + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### रिलेयर को जोड़ें/हटाएँ {#add-remove-a-relayer} + +एक अकाउंट को नए रिलेयर के रूप में जोड़ें या रिलेयर से एक अकाउंट हटाएँ + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### रिलेयर की सीमा बदलें {#change-relayer-threshold} + +प्रस्ताव के एग्जीक्यूशन के लिए आवश्यक वोटों की संख्या बदलें + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## चेन ID {#chain-id} + +चैनब्रिज `chainId`एक आर्बिट्रेरी वैल्यू है जिसका इस्तेमाल ब्रिज में ब्लॉकचेन नेटवर्क के बीच अंतर करने के लिए किया जाता है, और इसे uint8 की सीमा में होना चाहिए. नेटवर्क की चेन ID से भ्रमित न होने के लिए, वे एक से नहीं होते. वैल्यू यूनिक होनी चाहिए, लेकिन ये नेटवर्क की ID की जैसी नहीं होनी चाहिए. + +इस उदाहरण में, हम `99`को `chainId`में सेट करते हैं, क्योंकि मुंबई टेस्टनेट की चेन ID `80001`है, जिसे uint8 के साथ प्रस्तुत नहीं किया जा सकता है. + +## रिसोर्स ID {#resource-id} + +रिसोर्स ID एक क्रॉस-चेन वातावरण में एक यूनिक 32-बाइट वैल्यू है, जो एक निश्चित असेट (रिसोर्स) से जुड़ी होती है जिसे नेटवर्क के बीच ट्रांसफ़र किया जाता है. + +रिसोर्स ID आर्बिट्रेरी होती है, लेकिन, एक कन्वेशन के रूप में, आमतौर पर अंतिम बाइट में स्रोत चेन की चेन ID होती है (जिस नेटवर्क से यह असेट उत्पन्न हुई है). + +## पॉलीगॉन PoS के लिए JSON-RPC URL {#json-rpc-url-for-polygon-pos} + +इस गाइड के लिए, हम पॉलीगॉन द्वारा प्रदान किए गए सार्वजनिक JSON-RPC URL https://rpc-mumbai.matic.today, का इस्तेमाल करेंगे, जिसमें ट्रैफिक या रेट-लिमिट. हो सकती है. इसका इस्तेमाल सिर्फ़ पॉलीगॉन मुंबई टेस्टनेट से जुड़ने के लिए किया जाएगा. हम आपको बाहरी सेवा जैसे Infura से अपना JSON-RPC URL प्राप्त करने की सलाह देते हैं क्योंकि कॉन्ट्रैक्ट को लागू करने से JSON-RPC को कई क्वेरीज़/अनुरोध भेजे जाएँगे. + +## टोकन ट्रांसफ़र करने की प्रक्रिया के तरीके {#ways-of-processing-the-transfer-of-tokens} +चेन के बीच erc20 टोकन ट्रांसफ़र दो अलग-अलग मोड में किए जा सकते हैं: + +### लॉक/रिलीज मोड {#lock-release-mode} +सोर्स चेन: आपके द्वारा भेजे जा रहे टोकन हैंडलर अनुबंध में लॉक कर दिए जाएंगे.
+गंतव्य चेन: आपके द्वारा स्रोत चेन में भेजे गए टोकन की समान मात्रा को अनलॉक किया जाएगा और हैंडलर कॉन्ट्रैक्ट से गंतव्य चेन में प्राप्तकर्ता के अकाउंट में ट्रांसफ़र किया जाएगा. + +### बर्न/मिंट मोड {#burn-mint-mode} +स्रोत चेन: आपके द्वारा भेजे जा रहे टोकन को बर्न कर दिया जाएगा.
+गंतव्य चेन: गंतव्य चेन के लिए आपने स्रोत चेन पर भेजे और बर्न किए गए टोकन की रकम गंतव्य चेन पर मिंट कर अकाउंट को भेजा जाएगा और प्राप्तकर्ता के अकाउंट में भेजी जाएगी. + +आप सभी चेन पर विभिन्न मोड का इस्तेमाल कर सकते हैं. इसका मतलब है कि आप ट्रांसफर करने के लिए सबचैन में टोकन को मिंट करते हुए टोकन को मेन चेन में लॉक कर सकते हैं. उदाहरण के लिए, अगर कुल सप्लाई या मिंट शेड्यूल नियंत्रित है, तो टोकन को लॉक/रिलीज़ करना काम आ सकता है. अगर सबचेन में अनुबंध को मेन चेन में सप्लाई को फ़ॉलो पालन करना है तो, टोकन को मिंट/बर्न किया जाएगा. + +डिफ़ॉल्ट मोड लॉक/रिलीज मोड होता है. अगर आप टोकन को मिन्टेबल/बर्नेबल बनाना चाहते हैं, तो आपको इस तरीके का `adminSetBurnable`इस्तेमाल करना होगा. अगर आप एग्जीक्यूशन पर टोकन मिंट करना चाहते हैं, तो आपको erc20 हैंडलर अनुबंध को `minter`प्रदान करना होगा. + + diff --git a/archive/edge/hi-edge/additional-features/chainbridge/overview.md b/archive/edge/hi-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..e032f97a10 --- /dev/null +++ b/archive/edge/hi-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: अवलोकन +description: चेनब्रिज का अवलोकन +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## चैनब्रिज क्या है? {#what-is-chainbridge} + +चैनब्रिज एक मॉड्यूलर मल्टी-डायरेक्शनल ब्लॉकचेन ब्रिज है जो ईवीएम और सबस्ट्रेट कॉम्पैटिबल चेन को सपोर्ट करता है, जिसे चैनसेफ द्वारा बनाया गया है. यह उपयोगकर्ताओं को सभी प्रकार की संपत्तियों या संदेशों को दो अलग-अलग श्रृंखलाओं के बीच ट्रांसफ़र करने की अनुमति देता है. + +चैनब्रिज के बारे में और पता लगाने के लिए, कृपया पहले अपने डेवलपर्स द्वारा उपलब्ध किए गए [ऑफिसियल डॉक्यूमेंट](https://chainbridge.chainsafe.io/)का दौरा करें. + +इस गाइड का उद्देश्य चैनब्रिज को पॉलीगॉन एज से जोड़ने में सहायता करना है. यह पॉलीगॉन पॉस (मुंबई टेस्टनेट ) और एक स्थानीय पॉलीगॉन एज नेटवर्क के बीच ब्रिज के सेटअप के माध्यम से चलता है. + +## आवश्यकताएँ {#requirements} + +इस गाइड में, आप पॉलीगॉन एज नोड्स, एक चैनब्रिज रिलेयर (इसके बारे में [यहां](/docs/edge/additional-features/chainbridge/definitions) अधिक), और सीबी-सोल-क्ली टूल चलाएंगे, जो स्थानीय रूप से अनुबंधों को तैनात करने, संसाधन दर्ज करने और पुल के लिए सेटिंग बदलने के लिए एक सीएलआई उपकरण है ( आप [इसे](https://chainbridge.chainsafe.io/cli-options/#cli-options)भी चेक कर सकते हैं). सेटअप शुरू करने से पहले निम्नलिखित वातावरण की आवश्यकता होती है: + +* जाओ: >= 1.17 +* नोड.जेएस >= 16.13.0 +* गिट + + +इसके अलावा, आपको कुछ एप्लिकेशन रन करने के लिए संस्करण के साथ निम्नलिखित रिपोजिटरी को क्लोन करने की जरूरत होगी. + +* [पॉलीगॉन एज](https://github.com/0xPolygon/polygon-edge): : शाखा `develop` पर +* [चैनब्रिज](https://github.com/ChainSafe/ChainBridge): v1.1.5 +* [चैनब्रिज डिप्लॉय टूल](https://github.com/ChainSafe/chainbridge-deploy): `f2aa093`शाखा `main` पर + + +आपको अगले सेक्शन में आगे बढ़ने से पहले पॉलीगॉन एज नेटवर्क स्थापित करने की जरूरत है. अधिक विवरण के लिए [स्थानीय सेटअप](/docs/edge/get-started/set-up-ibft-locally) या [क्लाउड सेटअप](/docs/edge/get-started/set-up-ibft-on-the-cloud)जाँचें. \ No newline at end of file diff --git a/archive/edge/hi-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/hi-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..3a1ea4c106 --- /dev/null +++ b/archive/edge/hi-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,142 @@ +--- +id: setup-erc20-transfer +title: ERC20 टोकन ट्रांसफ़र +description: चेनब्रिज में ERC-20 ट्रांसफ़र को सेटअप कैसे करें +keywords: + - docs + - polygon + - edge + - Bridge +--- + +अब तक, हमने पॉलीगॉन पॉस पॉलीगॉन एज चेन के पॉलीगॉन पॉस और असेट्स/डाटा एक्सचेंज करने के लिए ब्रिज बनाया है. यह सेक्शन आपको ERC20 ब्रिज स्थापित करने और विभिन्न ब्लॉकचेन के बीच टोकन भेजने के लिए गाइड करेगा. + +## स्टेप 1: संसाधन आईडी रजिस्टर करें {#step-1-register-resource-id} + +सबसे पहले, आप एक संसाधन आईडी पंजीकृत करेंगे जो संसाधनों को एक क्रॉस-चेन वातावरण में संबद्ध करता है. एक संसाधन आईडी एक 32-बाइट मान है जो उस संसाधन के लिए अद्वितीय होना चाहिए जिसे हम इन ब्लॉकचेन के बीच स्थानांतरित कर रहे हैं. संसाधन आईडी मनमाना हैं, लेकिन उनके पास अंतिम बाइट में होम चेन की चेन आईडी हो सकती है, एक कन्वेंशन के रूप में (होम चेन उस नेटवर्क का जिक्र है जिस पर ये संसाधन उत्पन्न हुए हैं). + +संसाधन आईडी को रजिस्टर करने के लिए, आप `cb-sol-cli bridge register-resource`कमांड का इस्तेमाल कर सकते हैं. आपको `admin`अकाउंट की निजी की देने की जरूरत होगी. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (वैकल्पिक) कान्ट्रैक्टस को मिन्टेबल/बर्नेबल बनाएं {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## स्टेप 2: ट्रांसफ़र erc20 टोकन {#step-2-transfer-erc20-token} + +हम पॉलीगॉन पॉस चेन से पॉलीगॉन एज चेन को ERC20 टोकन भेजेंगे. + +सबसे पहले, आपको मिंटिंग करनेसे टोकेन्स मिलेंगे. `minter`भूमिका वाला अकाउंट नए टोकन को मिंट कर सकता है. ERC20 अनुबंध को लागू करने वाले अकाउंट में डिफ़ॉल्ट रूप से `minter`भूमिका होती है. `minter`भूमिका के सदस्यों के रूप में अन्य खातों को निर्दिष्ट करने के लिए, आपको `cb-sol-cli erc20 add-minter`कमांड चलाने की आवश्यकता है. + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +करंट बैलेंस चेक करने के लिए आप `cb-sol-cli erc20 balance`कमांड का इस्तेमाल कर सकते हैं. + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +इसके बाद, आपको ERC20 हैंडलर द्वारा अकाउंट से ERC20 टोकन ट्रांसफ़र को स्वीकृत करने की आवश्यकता है + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +पॉलीगॉन एज चेन में टोकन ट्रांसफर करने के लिए, आप `deposit`को कॉल करेंगे. + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +डिपॉजिट ट्रांजैक्शन सफल होने के बाद, रिलेयर को इवेंट मिलेगा और प्रस्ताव के लिए वोट करेगा. वोटों की आवश्यक संख्या जमा करने के बाद, पॉलीगॉन एज चेन में प्राप्तकर्ता अकाउंट में टोकन्स भेजने के लिए यह ट्रांज़ैक्शन निष्पादित करता है. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +एक बार एग्जीक्यूशन ट्रांज़ैक्शन सफल हो जाने के बाद, आपको पॉलीगॉन एज चेन में टोकन प्राप्त होंगे. + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/hi-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/hi-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..32b89233cc --- /dev/null +++ b/archive/edge/hi-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,134 @@ +--- +id: setup-erc721-transfer +title: erc721 NFT ट्रांसफ़र +description: चेनब्रिज में erc721 ट्रांफर कैसे सेटअप करें +keywords: + - docs + - polygon + - edge + - Bridge +--- + +यह सेक्शन आपको ERC721 ब्रिज स्थापित करने और ब्लॉकचेन नेटवर्क के बीच NFTs भेजने के माध्यम से मार्गदर्शन करता है. + +## स्टेप 1: संसाधन आईडी रजिस्टर करें {#step-1-register-resource-id} + +आपको सबसे पहले ब्रिज कॉन्ट्रैक्ट में erc721 टोकन के लिए आईडी को दोनों चेन पर रजिस्टर करने होंगे. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (वैकल्पिक): कान्ट्रैक्टस को मिन्टेबल/बर्नेबल बनाएं {#optional-make-contracts-mintable-burnable} + +टोकन को मिन्टेबल/बर्नेबल बनाने के लिए, आपको निम्नलिखित कमांड्स को कॉल करने की आवश्यकता होगी: + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## स्टेप 2: ट्रांसफ़र NFT {#step-2-transfer-nft} + +यदि आपको इसकी आवश्यकता है तो सबसे पहले, आप एक NFT का मिंट करेंगे. + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +TNFT मालिक को जाँज ने केलिए, आप`cb-sol-cli erc721 owner`इस्तेमाल कर सकते हैं. + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +फिर, आप ERC721 हैंडलर द्वारा NFT के ट्रांसफ़र को स्वीकृति देंगे + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +अंत में, आप ट्रांसफ़र शुरू कर देंगे + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +रिलेयर इवेंट प्राप्त करेगा और प्रस्ताव के लिए वोट करेगा. वोटों की आवश्यक संख्या जमा करने के बाद, पॉलीगॉन एज श्रृंखला में प्राप्तकर्ता अकाउंट में NFT भेजने के लिए यह ट्रांज़ैक्शन निष्पादित करता है. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +एग्जीक्यूशन पूरा होने के बाद आप पॉलीगॉन एज नेटवर्क पर NFT के मालिक की जांच कर सकते हैं. + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/hi-edge/additional-features/chainbridge/setup.md b/archive/edge/hi-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..a5b2abac7f --- /dev/null +++ b/archive/edge/hi-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,198 @@ +--- +id: setup +title: सेटअप +description: चेनब्रिज को कैसे सेटअप करें +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## कॉन्ट्रैक्ट्स का डिप्लॉयमेंट {#contracts-deployment} + +इस सेक्शन में, आप `cb-sol-cli` के साथ पॉलीगॉन PoS और पॉलीगॉन एज चेन के लिए ज़रूरी कॉन्ट्रैक्ट डिप्लॉय करेंगे. + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +सबसे पहले, हम `cb-sol-cli deploy` कमांड द्वारा पॉलीगॉन PoS चेन में कॉन्ट्रैक्ट को डिप्लॉय करेंगे. `--all` फ्लैग कमांड को ब्रिज, ERC20 हैंडलर, ERC721 हैंडलर, जेनेरिक हैंडलर, ERC20 और ERC721 कॉन्ट्रैक्ट्स सहित सभी कॉन्ट्रैक्ट्स को डिप्लॉय करता है. इसके अलावा, यह डिफ़ॉल्ट रिलेयर अकाउंट पता और थ्रेशोल्ड सेट करेगा + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +[यहाँ](/docs/edge/additional-features/chainbridge/definitions) पर चेनID और JSON-RPC URL के बारे में अधिक जानें + +:::caution + +`cb-sol-cli` में डिफ़ॉल्ट गैस की कीमत `20000000` (`0.02 Gwei`) है. ट्रांज़ैक्शन में उचित गैस की कीमत निर्धारित करने के लिए, कृपया `--gasPrice` आर्गुमेंट का इस्तेमाल करके वैल्यू निर्धारित करें. + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +ब्रिज कॉन्ट्रैक्ट डिप्लॉय करने के लिए लगभग 0x3f97b8 (4167608) गैस लेता है. कृपया सुनिश्चित करें कि जो ब्लॉक जनरेट किए जा रहे हैं उनमें कॉन्ट्रैक्ट क्रिएशन ट्रांज़ैक्शन को शामिल करने के लिए पर्याप्त ब्लॉक गैस सीमा है. पॉलीगॉन एज में ब्लॉक गैस सीमा को बदलने के बारे में अधिक जानकारी के लिए, कृपया जाएँ +[स्थानीय सेटअप](/docs/edge/get-started/set-up-ibft-locally) + +::: + +एक बार कॉन्ट्रैक्ट्स के डिप्लॉय होने पर, आपको निम्नलिखित परिणाम मिलेंगे: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +अब हम पॉलीगॉन एज चेन में कॉन्ट्रैक्ट्स को डिप्लॉय कर सकते हैं. + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +डिप्लॉय किए गए स्मार्ट कॉन्ट्रैक्ट एड्रेस के साथ टर्मिनल आउटपुट को सेव करें, क्योंकि हमें अगले स्टेप में उनकी ज़रूरत होगी. + +## रिलेयर सेटअप {#relayer-setup} + +इस सेक्शन में, आप 2 चेन के बीच डेटा का एक्सचेंज करने के लिए रिलेयर शुरू करेंगे. + +सबसे पहले, हमें क्लोन करने और चेनब्रिज रिपॉज़िटरी बनाने की ज़रूरत है. + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +इसके बाद, आप JSON-RPC URL, रिलेयर पता और सभी चेन के कॉन्ट्रैक्ट्स के पता को सेट करें और `config.json` बनाएँ. + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +रिलेयर शुरू करने के लिए, आपको रिलेयर अकाउंट एड्रेस के अनुरूप निजी की इम्पोर्ट करनी होगी. निजी की इंपोर्ट करने के लिए, आपको पासवर्ड डालना होगा. इंपोर्ट सफल होने के बाद, की `keys/
.key` पर स्टोर हो जाएगी. + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +फिर, आप रिलेयर शुरू कर सकते हैं. आपको वही पासवर्ड डालना होगा जो आपने शुरुआत में की को स्टोर करने के लिए चुना था. + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +एक रिलेयर शुरू होने के बाद, यह हर चेन पर नए ब्लॉक देखना शुरू कर देगा. diff --git a/archive/edge/hi-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/hi-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..0929445c3f --- /dev/null +++ b/archive/edge/hi-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,255 @@ +--- +id: use-case-erc20-bridge +title: ERC20 ब्रिज - केस का इस्तेमाल करें +description: ERC20 कॉन्ट्रैक्ट ब्रिज के लिए उदाहरण +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +इस सेक्शन का उद्देश्य आपको प्रैक्टिकल इस्तेमाल के मामले में, ERC20 ब्रिज का एक सेटअप फ़्लो देना है. + +इस गाइड में, आप मुंबई पॉलीगॉन PoS टेस्टनेट और पॉलीगॉन एज स्थानीय चेन का इस्तेमाल करेंगे. कृपया सुनिश्चित करें कि आपके पास मुंबई के लिए JSON-RPC एंडपॉइंट हो और आपने स्थानीय वातावरण में पॉलीगॉन एज को सेट अप किया हो. अधिक विवरण के लिए [स्थानीय सेटअप](/docs/edge/get-started/set-up-ibft-locally) या [क्लाउड सेटअप](/docs/edge/get-started/set-up-ibft-on-the-cloud) का संदर्भ लें. + +## परिदृश्य {#scenario} + +यह परिदृश्य, ERC20 टोकन के लिए एक ब्रिज को सेटअप करता है जिसे पहले से ही सार्वजनिक चेन (पॉलीगॉन PoS) में पहले से ही डिप्लॉय किया गया है, ताकि एक आम मामले में यूज़र्स एक निजी चेन (पॉलीगॉन एज) में कम लागत में ट्रांसफ़र करना सक्षम कर सकें. ऐसे मामले में, टोकन की कुल आपूर्ति को सार्वजनिक चेन में निर्धारित किया जाता है और सिर्फ़ टोकन की रकम की उस मात्रा को जिसे सार्वजनिक चेन से निजी चेन में ट्रांसफ़र किया जा रहा है, उसे ही निजी चेन में मौजूद होना चाहिए. इसी वजह से, आपको सार्वजनिक चेन में लॉक/रिलीज़ मोड को और निजी चेन में बर्न/मिंट मोड को इस्तेमाल करना होगा. + +जब टोकनों को सार्वजनिक चेन से निजी चेन में भेजा जाता है, तो टोकन सार्वजनिक चेन के ERC20 हैंडलर कॉन्ट्रैक्ट में लॉक हो जाएँगे और उतनी ही रकम के टोकन निजी चेन में मिंट हो जाएँगे. दूसरी ओर, निजी चेन से सार्वजनिक चेन में ट्रांसफ़र करने पर, निजी चेन के टोकन बर्न हो जाएँगे और उतनी ही रकम के टोकन ERC20 हैंडलर के कॉन्ट्रैक्ट से सार्वजनिक चेन में रिलीज़ कर दिए जाएँगे. + +## कॉन्ट्रैक्ट {#contracts} + +चेनब्रिज द्वारा तैयार कॉन्ट्रैक्ट के बजाय एक साधारण ERC20 कॉन्ट्रैक्ट के साथ समझाएँ. बर्न/मिंट मोड के लिए, ERC20 कॉन्ट्रैक्ट में अवश्य ही `mint` और `burnFrom` तरीकों के अलावा और भी तरीके होने चाहिए: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +सभी कोड और स्क्रिप्ट Github रेपो [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example) में हैं. + +## स्टेप1: ब्रिज और ERC20 हैंडलर कॉन्ट्रैक्ट को डिप्लॉय करें {#step1-deploy-bridge-and-erc20-handler-contracts} + +सबसे पहले, आप दोनों चेन में `cb-sol-cli` का इस्तेमाल करते हुए ब्रिज और ERC20हैंडलर कॉन्ट्रैक्ट को डिप्लॉय करेंगे. + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +आपको ब्रिज और ERC20हैंडलर कॉन्ट्रैक्ट का पता इस प्रकार मिलेंगे: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## स्टेप2: अपने ERC20 कॉन्ट्रैक्ट को डिप्लॉय करें {#step2-deploy-your-erc20-contract} + +आप अपने ERC20 कॉन्ट्रैक्ट को डिप्लॉय करेंगे. यह उदाहरण आपको हार्डहैट प्रोजेक्ट [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example) के साथ गाइड करता है. + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +कृपया `.env` फ़ाइल बनाएँ और नीचे दी गई वैल्यू को सेट करें. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +इसके बाद, आप दोनों चेन में ERC20 कॉन्ट्रैक्ट को डिप्लॉय करेंगे. + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +डिप्लॉयमेंट सफल होने के बाद, आपको इस प्रकार कॉन्ट्रैक्ट का पता प्राप्त होगा: + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## स्टेप3: ब्रिज में रिसोर्स आईडी रजिस्टर करें {#step3-register-resource-id-in-bridge} + +सबसे पहले, आप एक रिसोर्स आईडी रजिस्टर करेंगे, जो रिसोर्स को एक क्रॉस-चेन वातावरण में जोड़ती है. आपको दोनों चेन में एक ही रिसोर्स आईडी को सेट करना होगा. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## स्टेप4: एज के ERC20 ब्रिज में मिंट/बर्न मोड सेट करें {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +ब्रिज, पॉलीगॉन एज में बर्न/मिंट मोड के रूप में काम करने की उम्मीद करता है. आप `cb-sol-cli` का इस्तेमाल करके बर्न/मिंट मोड सेट करेंगे . + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +और आपको ERC20 हैंडलर कॉन्ट्रैक्ट को मिंट करने वाले और बर्न करने वाले की भूमिका प्रदान करने की ज़रूरत होगी. + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## स्टेप5: टोकन मिंट करें {#step5-mint-token} + +आप मुंबई चेन में ERC20 के नए टोकन मिंट करेंगे. + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +ट्रांज़ैक्शन सफल होने के बाद, अकाउंट में मिंट किए गए टोकन होंगे. + +## स्टेप6: ERC20 ट्रांसफ़र शुरू करें {#step6-start-erc20-transfer} + +यह स्टेप शुरू करने से पहले, कृपया सुनिश्चित करें कि आपने एक रिलेयर को शुरू किया है. अधिक विवरण के लिए कृपया [सेटअप](/docs/edge/additional-features/chainbridge/setup) देखें. + +मुंबई से एज में टोकन ट्रांसफ़र के दौरान, मुंबई में ERC20 हैंडलर कॉन्ट्रैक्ट आपके अकाउंट से टोकन निकाल लेता है. ट्रांसफ़र करने से पहले आप अनुमोदन के लिए कॉल करेंगे. + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +अंत में, आप `cb-sol-cli` को इस्तेमाल करके मुंबई से एज में टोकन ट्रांसफ़र करना शुरू करेंगे . + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +डिपॉज़िट ट्रांज़ैक्शन के सफल होने के बाद, रिलेयर को प्रस्ताव के लिए इवेंट और वोट मिलेगा. वोट्स की आवश्यक संख्या जमा हो जाने के बाद, यह पॉलीगॉन एज चेन में प्राप्तकर्ता अकाउंट में टोकन्स भेजने के लिए ट्रांज़ैक्शन को एग्जीक्यूट करता है. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +एक बार ट्रांज़ैक्शन का एग्जीक्यूशन सफल होने के बाद, आपको पॉलीगॉन एज चेन में टोकन मिल जाएँगे. diff --git a/archive/edge/hi-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/hi-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..9fb3957c19 --- /dev/null +++ b/archive/edge/hi-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,308 @@ +--- +id: use-case-erc721-bridge +title: केस का इस्तेमाल करें - erc721 ब्रिज +description: erc721 कॉन्ट्रैक्ट ब्रिज करने के लिए उदाहरण +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +इस सेक्शन का उद्देश्य आपको प्रैक्टिकल यूज़ केस के लिए, erc721 ब्रिज का एक सेटअप फ़्लो देना है. + +इस गाइड में, आप मुंबई पॉलीगॉन PoS टेस्टनेट और पॉलीगॉन एज स्थानीय चेन का इस्तेमाल करेंगे. कृपया सुनिश्चित करें कि आपके पास मुंबई के लिए JSON-RPC एंडपॉइंट हो और आपने स्थानीय वातावरण में पॉलीगॉन एज को सेट अप किया हो. अधिक विवरण के लिए [स्थानीय सेटअप](/docs/edge/get-started/set-up-ibft-locally) या [क्लाउड सेटअप](/docs/edge/get-started/set-up-ibft-on-the-cloud) का संदर्भ लें. + +## परिदृश्य {#scenario} + +यह परिदृश्य ERC721 NFT के लिए एक ब्रिज सेटअप करने के लिए है जिसे पहले से ही पब्लिक चेन (पॉलीगॉन PoS) में डिप्लॉय किया गया है ताकि एक नियमित तौर पर यूज़र के लिए एक निजी चेन (Polygon Edge) में कम लागत वाले ट्रांसफ़र किए जा सकें. ऐसे मामले में, पब्लिक चेन में ओरिजनल मेटाडेटा को डिफ़ाइन किया गया है और सिर्फ़ पब्लिक चेन से ट्रांसफ़र किए गए NFT ही निजी चेन में हो सकते हैं. इसीलिए, आपको पब्लिक चेन में लॉक/रिलीज़ मोड का इस्तेमाल करना होगा और निजी चेन में बर्न/मिंट मोड. + +NFT को पब्लिक चेन से निजी चेन में भेजने के बाद, NFT पब्लिक चेन में erc721 हैंडलर कॉन्ट्रैक्ट में लॉक हो जाएगी और वही NFT निजी चेन में भी मिंट हो जाएगी. दूसरी ओर, पब्लिक चेन से निजी चेन में ट्रांसफ़र करने पर, NFT को निजी चेन में बर्न जाएगा और वही NFT पब्लिक चेन में erc721 हैंडलर कॉन्ट्रैक्ट से रिलीज़ की जाएगी. + +## कॉन्ट्रैक्ट {#contracts} + +चेनब्रिज द्वारा तैयार कॉन्ट्रैक्ट के बजाय एक साधारण erc721 कॉन्ट्रैक्ट के साथ समझाएँ. बर्न/मिंट मोड के लिए, ERC721 में डिफ़ाइन तरीकों के अलावा, ERC721 कॉन्ट्रैक्ट `mint` और `burn` तरीकों में होना चाहिए: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +सभी कोड और स्क्रिप्ट Github रेपो [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example) में हैं. + +## स्टेप1: ब्रिज डिप्लॉय करें और erc721 हैंडलर कॉन्ट्रैक्ट {#step1-deploy-bridge-and-erc721-handler-contracts} + +सबसे पहले, आप दोनों चेन में `cb-sol-cli` का इस्तेमाल करते हुए ब्रिज और erc721 हैंडलर कॉन्ट्रैक्ट को डिप्लॉय करेंगे. + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +आपको ब्रिज और erc721हैंडलर कॉन्ट्रैक्ट पता इस प्रकार से मिलेंगे: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## स्टेप2: अपने erc721 कॉन्ट्रैक्ट को डिप्लॉय करें {#step2-deploy-your-erc721-contract} + +आप अपना erc721 कॉन्ट्रैक्ट डिप्लॉय करेंगे. यह उदाहरण आपको हार्डहैट प्रोजेक्ट [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). के साथ गाइड करता है. + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +`.env` फ़ाइल बनाएँ और नीचे दी गई वैल्यू सेट करें. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +इसके बाद, आप दोनों चेन में erc721 कॉन्ट्रैक्ट डिप्लॉय करेंगे. + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +डिप्लॉय सफल होने के बाद, आपको इस प्रकार कॉन्ट्रैक्ट पता प्राप्त होगा: + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## स्टेप3: ब्रिज में रिसोर्स ID रजिस्टर करें {#step3-register-resource-id-in-bridge} + +सबसे पहले, आप एक रिसोर्स ID रजिस्टर करेंगे जो रिसोर्स को एक क्रॉस-चेन वातावरण में जोड़ती है. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## स्टेप4: एज के erc721 ब्रिज में मिंट/बर्न मोड सेट करें {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +ब्रिज एज में बर्न/मिंट मोड के रूप में काम करने की उम्मीद करता है. आप बर्न/मिंट मोड सेट करेंगे. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +और आपको erc721 हैंडलर कॉन्ट्रैक्ट में एक मिंटर और बर्नर की भूमिका प्रदान करने की ज़रूरत है. + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## स्टेप5: NFT मिंट करें {#step5-mint-nft} + +आप मुंबई चेन में नए erc721 NFT मिंट करेंगे. + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +ट्रांज़ैक्शन सफल होने के बाद, अकाउंट में मिंट किए गए NFT होंगे. + +## स्टेप6: ERC721 ट्रांसफ़र शुरू करें {#step6-start-erc721-transfer} + +यह स्टेप शुरू करने से पहले, कृपया अपना रिलेयर शुरू करें. अधिक विवरण के लिए कृपया [सेटअप](/docs/edge/additional-features/chainbridge/setup) देखें. + +मुंबई से एज में NFT ट्रांसफ़र के दौरान, मुंबई में ERC721 हैंडलर कॉन्ट्रैक्ट आपके अकाउंट से NFT को निकाल लेता है. ट्रांसफ़र करने से पहले आप अनुमोदन के लिए कॉल करेंगे. + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +अंत में, आप मुंबई से एज में NFT ट्रांसफ़र शुरू करेंगे. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +डिपॉज़िट ट्रांज़ैक्शन सफल होने के बाद, रिलेयर को इवेंट मिलेगा और प्रस्ताव के लिए वोट करेगा. + आवश्यक वोट जमा किए जाने के बाद, यह पॉलीगॉन एज चेन में प्राप्तकर्ता के अकाउंट में NFT भेजने के लिए ट्रांज़ैक्शन को एग्जीक्यूट करता है. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +एक बार ट्रांज़ैक्शन का एग्जीक्यूशन सफल होने के बाद, आपको पॉलीगॉन एज चेन में NFT मिलेगा. diff --git a/archive/edge/hi-edge/additional-features/permission-contract-deployment.md b/archive/edge/hi-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..6c42a16355 --- /dev/null +++ b/archive/edge/hi-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,86 @@ +--- +id: permission-contract-deployment +title: स्मार्ट कॉन्ट्रैक्ट डिप्लॉयमेंट में अनुमति +description: स्मार्ट कॉन्ट्रैक्ट डिप्लॉयमेंट में अनुमति कैसे जोडें. +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## ओवरव्यू {#overview} + +यह गाइड एड्रेस को वाइटलिस्ट में करने के बारे में विस्तार से जानकारी प्रदान करती है ताकि स्मार्ट कॉन्ट्रैक्ट डिप्लॉय किया जा सके. +कभी-कभी नेटवर्क ऑपरेटर्स यूज़र को नेटवर्क के उद्देश्य के अनुरूप ना होने वाले स्मार्ट कॉन्ट्रैक्ट डिप्लॉय करने से रोकना चाहते हैं. नेटवर्क ऑपरेटर्स कर सकते हैं: + +1. स्मार्ट कॉन्ट्रैक्ट डिप्लॉयमेंट के लिए वाइटलिस्ट पता +2. स्मार्ट कॉन्ट्रैक्ट डिप्लॉयमेंट के लिए वाइटलिस्ट से पता हटाएँ + +## वीडियो प्रेजेंटेशन {#video-presentation} + +[![कॉन्ट्रैक्ट डिप्लॉयमेंट की अनुमति - वीडियो](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## इसका इस्तेमाल कैसे करें? {#how-to-use-it} + + +आप [CLI कमांड](/docs/edge/get-started/cli-commands#whitelist-commands) पेज में डिप्लॉयमेंट वाइटलिस्ट से जुड़े सभी cli कमांड ढूँढ सकते हैं. + +* `whitelist show`: वाइटलिस्ट की जानकारी को प्रदर्शित करता है +* `whitelist deployment --add`: कॉन्ट्रैक्ट डिप्लॉयमेंट वाइटलिस्ट में एक नया पता जोड़ता है +* `whitelist deployment --remove`: कॉन्ट्रैक्ट डिप्लॉयमेंट वाइटलिस्ट से एक नया पता हटाता है + +#### डिप्लॉयमेंट वाइटलिस्ट में सभी पते दिखाएँ {#show-all-addresses-in-the-deployment-whitelist} + +डिप्लॉयमेंट वाइटलिस्ट में सभी पते खोजने के 2 तरीके हैं. +1. जहाँ वाइटलिस्ट को सेव किया गया है, `genesis.json` देखें +2. `whitelist show` एग्जीक्यूट करना, जो पॉलीगॉन एज द्वारा समर्थित सभी वाइटलिस्ट के लिए जानकारी को प्रिंट करता है + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### डिप्लॉयमेंट वाइटलिस्ट में एक पता जोड़ें {#add-an-address-to-the-deployment-whitelist} + +वाइटलिस्ट डिप्लॉयमेंट में एक नया पता जोड़ने के लिए, `whitelist deployment --add [ADDRESS]` CLI कमांड एक्जीक्यूट करें. वाइटलिस्ट में पतों की संख्या की सीमा नहीं है. सिर्फ़ कॉन्ट्रैक्ट डिप्लॉयमेंट वाइटलिस्ट में मौजूद पता ही कॉन्ट्रैक्ट डिप्लॉय कर सकता है. अगर वाइटलिस्ट खाली है, तो कोई भी पता डिप्लॉयमेंट कर सकता है + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### डिप्लॉयमेंट वाइटलिस्ट से पता हटाएँ {#remove-an-address-from-the-deployment-whitelist} + +डिप्लॉयमेंट वाइटलिस्ट से एक पता हटाने के लिए `whitelist deployment --remove [ADDRESS]` CLI कमांड एग्जीक्यूट करें. सिर्फ़ कॉन्ट्रैक्ट डिप्लॉयमेंट वाइटलिस्ट में मौजूद पता ही कॉन्ट्रैक्ट डिप्लॉय कर सकता है. अगर वाइटलिस्ट खाली है, तो कोई भी पता डिप्लॉयमेंट कर सकता है + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/hi-edge/architecture/modules/blockchain.md b/archive/edge/hi-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..871c3a983b --- /dev/null +++ b/archive/edge/hi-edge/architecture/modules/blockchain.md @@ -0,0 +1,159 @@ +--- +id: blockchain +title: ब्लॉकचेन +description: पॉलीगॉन एज की ब्लॉकचेन स्टेट और स्टेट मॉड्यूल के लिए स्पष्टीकरण. +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## ओवरव्यू {#overview} + +पॉलीगॉन एज के प्रमुख मॉड्यूल **ब्लॉकचेन** और **स्टेट** हैं.
+ +**ब्लॉकचेन** वह पावरहाउस है जो ब्लॉक के पुनर्निर्माण से संबंधित होता है. इसका मतलब है कि यह सभी उन लॉजिक से संबंधित होता है जो ब्लॉकचेन में ब्लॉक को जोड़ते समय होते हैं. + +**स्टेट** *ऑब्जेक्ट* का प्रतिनिधित्व करता है. यह इसके बारे में है कि नए ब्लॉक को शामिल करने पर स्टेट कैसे बदल जाता है.
अन्य बातों के साथ, **स्टेट** हैंडल्स: +* ट्रांजैक्शन को एक्जीक्यूट कर रहा है +* EVM को एक्जीक्यूट कर रहा है +* Merkle tries को बदल रहा +* अधिकतर, संबंधित **स्टेट** सेक्शन में कवर होता है 🙂 + +मुख्य टेकअवे यह है कि इन 2 भागों को ठीक से कनेक्ट कर दिया गया है और ये क्लाइंट के फ़ंक्शन के लिए एक साथ काम करते हैं.
उदाहरण के लिए, जब **ब्लॉकचेन** लेयर को ब्लॉक (और कोई पुनर्गठन नहीं हुआ) प्राप्त होता है, तो यह **स्टेट** को स्टेट ट्रांजिशन करने के लिए कहता है. + +**ब्लॉकचेन** को सहमति से संबंधित कुछ हिस्सों से भी निपटना पड़ता है (जैसे * क्या यह सही ethHash है?* *क्या यह सही PoW है?*).
एक वाक्य में, **यह लॉजिक का मुख्य कोर है जिसके माध्यम से सभी ब्लॉक को जोड़ा जाता है**. + +## *WriteBlocks* + +**ब्लॉकचेन** लेयर से संबंधित सबसे महत्वपूर्ण भाग *WriteBlocks* तरीका है: + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +*WriteBlocks* तरीका ब्लॉकचेन में ब्लॉक को लिखने का एंट्री पॉइंट है. पैरामीटर के रूप में, यह कई रेंज के ब्लॉक लेता है.
+सबसे पहले, ब्लॉक को वैलिडेट किया जाता है. इसके बाद, इन्हें चेन को लिखा जाता है. + +*WriteBlocks* के भीतर *processBlock* विधि को कॉल करके वास्तविक *स्टेट ट्रांजिशन* किया जाता है. + +यह ध्यान देने लायक है क्योंकि, यह ब्लॉकचैन को ब्लॉक लिखने का एंट्री प्वाइंट है, अन्य मॉड्यूल (जैसे कि **सीलर**) इस तरीके का इस्तेमाल करते हैं. + +## ब्लॉकचेन सबस्क्रिप्शन {#blockchain-subscriptions} + +ब्लॉकचेन-रिलेटेड बदलावों को मॉनिटर करने का एक तरीका होना चाहिए.
+यहाँ पर **सबस्क्रिप्शन** आते हैं. + +सबस्क्रिप्शन ब्लॉकचेन इवेंट स्ट्रीम में टैप करने का एक तरीका होते हैं जहाँ पर तुरंत डेटा प्राप्त होता है. + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +**ब्लॉकचेन इवेंट्स** में वास्तविक चेन में किए गए किसी भी बदलाव की जानकारी होती है. इसमें पुनर्निर्माण के साथ साथ नए ब्लॉक होते हैं: + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip रिफ्रेशर +क्या आपको याद है कि हमने [CLI कमांड्स](/docs/edge/get-started/cli-commands) में ***मॉनिटर*** कमांड का उल्लेख कब किया था? + +ब्लॉकचैन इवेंट्स ऐसे मूल इवेंट्स हैं जो पॉलीगॉन एज में होते हैं, और उन्हें बाद में आसानी से ट्रांसफ़र करने के लिए एक प्रोटोकॉल बफ़र संदेश फ़ॉर्मेट में मैप किया जाता है. + +::: \ No newline at end of file diff --git a/archive/edge/hi-edge/architecture/modules/consensus.md b/archive/edge/hi-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..162f440d6c --- /dev/null +++ b/archive/edge/hi-edge/architecture/modules/consensus.md @@ -0,0 +1,499 @@ +--- +id: consensus +title: सहमति +description: पॉलीगॉन एज के सहमति मॉड्यूल के लिए स्पष्टीकरण. +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## ओवरव्यू {#overview} + +**सहमति** का मॉड्यूल सहमति मैकेनिज्म के लिए एक इंटरफेस प्रदान करता है. + +फ़िलहाल, निम्नलिखित सहमति इंजन उपलब्ध हैं: +* **IBFT PoA** +* **IBFT PoS** + +पॉलीगॉन एज मॉड्युलैरिटी एवं प्लगबिलिटी की स्थिति को बनाए रखना चाहता है.
+यही कारण है कि कोर सहमति तर्क को अलग कर दिया गया है, ताकि प्रयोज्यता और आसानी से उपयोग में समझौता किए बिना नए सहमति मैकेनिज्म का निर्माण सबसे ऊपर किया जा सकें. + +## सहमति इंटरफ़ेस {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + +***सहमति*** इंटरफ़ेस उल्लेखित अमूर्तता का मूल है.
+* **VerifyHeader** तरीका एक सहायक फ़ंक्शन का प्रतिनिधित्व करता है जिसे सहमति लेयर **ब्लॉकचेन** लेयर में उजागर करता है यह हेडर वेरिफिकेशन को संभालने के लिए है +* **स्टार्ट** तरीका केवल सहमति की प्रक्रिया और इससे जुड़ी हर चीज को शुरू करता है. इसमें शामिल है, सिंक्रनाइज़ेशन, +सीलिंग और सब कुछ जो किया जाना चाहिए +* **बंद** तरीका सहमति कनेक्शन को बंद करता है + +## सहमति कॉन्फ़िगरेशन {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +ऐसा समय हो सकता है जब आप डेटा को स्टोर करने के लिए सहमति प्रोटोकॉल के लिए कस्टम स्थान में जाना चाहते हैं या शायद कस्टम की-वैल्यू मैप, जिसके बारे में आप चाहते हैं कि वह सहमति मैकेनिज्म द्वारा उपयोग किया जाएं. यह ***कॉन्फ़िगरेशन*** के जरिए हासिल किया जा सकता है, जिसे पढ़ा जाता है जब कोई सहमति का मिसाल बनता है. + +## IBFT {#ibft} + +### एक्स्ट्राडेटा {#extradata} + +ब्लॉकचेन हैडर ऑब्जेक्ट के पास, अन्य क्षेत्रों के साथ, एक दूसरा फ़ील्ड भी है, जिसे **एक्स्ट्रा डेटा** कहते है. + +IBFT इस अतिरिक्त फील्ड का इस्तेमाल ब्लॉक के बारे में जानकारी को स्टोर करने के लिए करता है, जिसमें सवालों का जवाब दिया गया है, जैसे: +* "इस ब्लॉक को किसने साइन किया?" +* "इस ब्लॉक के लिए वैलिडेटर कौन हैं?" + +IBFT के लिए ये अतिरिक्त फील्ड इस प्रकार निर्दिष्ट किए गए हैं: +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### साइनिंग डेटा {#signing-data} + +IBFT में जानकारी साइन करने के लिए, यह *signHash* तरीके का फायदा उठाता है: +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +एक और ध्यान देने योग्य तरीका *VerifyCommittedFields* मेथड है, जो यह सत्यापित करता है कि प्रतिबद्ध सील वैध वैलिडेटर्स से हैं: +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### स्नैपशॉट्स {#snapshots} + +स्नैपशॉट्स जैसे नाम से स्पष्ट होता है, किसी भी ब्लॉक ऊँचाई (संख्या) पर एक*स्नैपशॉट्स*, या सिस्टम का *स्टेट *उपलब्ध कराने के लिए हैं. + +स्नैपशॉट्स में नोड्स का एक समूह होता है जो वैलिडेटर के साथ-साथ वोटिंग इनफार्मेशन (वैलिडेटर अन्य वैलिडेटर्स के लिए वोट कर सकते हैं). वैलिडेटर्स में फाइल किए गए **माइनर** हेडर में वोटिंग जानकारी शामिल होती है और **नान्स**के मान को बदलते हैं: +* नान्स **सभी 1s** है अगर नोड वैलिडेटर को हटाना चाहता है +* नान्स **सभी 0s** है अगर नोड वैलिडेटर पता जोड़ना चाहता है + +स्नैपशॉट की गणना ***प्रोसेसहेडर्स*** तरीके से की जाती है: + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +यह तरीका आमतौर पर 1 हेडर के साथ कहा जाता है, लेकिन यह प्रवाह मल्टिपल/कई हेडर के साथ भी समान ही होता है.
+प्रत्येक पास पास-इन हेडर के लिए, IBFT को यह सत्यापित करने की जरूरत है कि हेडर का प्रपोज़र ही वैलिडेटर है. यह नवीनतम स्नैपशॉट को कैप्चर करके और वैलिडेटर सेट में नोड है या नहीं, इसकी जांच करके आसानी से किया जा सकता है. + +इसके बाद, नान्स की जाँच की जाती है. वोट को शामिल और मिलान किया गया है - और यदि पर्याप्त वोट हैं तो वैलिडेटर सेट से एक नोड जोड़ा/हटा दिया जाता है, जिसके बाद नए स्नैपशॉट को सहेजा जाता है. + +#### स्नैपशॉट स्टोर {#snapshot-store} + +स्नैपशॉट सेवा एक निकाय का प्रबंधन और अद्यतन करता है जिसे **स्नैपशॉट स्टोर**कहते है, जो सभी उपलब्ध स्नैपशॉट की सूची को स्टोर करता है. इसका इस्तेमाल करके, सेवा जल्दी से पता लगाने में सक्षम है कि कौन सा स्नैपशॉट किस ब्लॉक ऊँचाई से जुड़ा है. +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### IBFT स्टार्टअप {#ibft-startup} + +IBFT को शुरू करने के लिए, पॉलीगॉन एज को पहले शुरू करने के लिए IBFT ट्रांसपोर्ट को स्थापित करने की जरूरत है: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +एक नए प्रोटो बफ्फ़ मैसेज के साथ, यह अनिवार्य रूप से IBFT प्रोटो के साथ एक नया विषय बनाता है.
+संदेशों का इस्तेमाल वैलिडेटर्स द्वारा किया जाना चाहिए. पॉलीगॉन एज तब विषय को स्वीकार करता है और तदनुसार मैसेज को संभालता है. + +#### मैसेज रिक्वाइअर {#messagereq} + +वैलिडेटर्स द्वारा आदान-प्रदान किया गया मैसेज: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +**मैसेज रिक्वाइअर** में **दृश्य **क्षेत्र चेन के अंदर नोड की स्थिति का प्रतिनिधित्व करता है. इसमें एक *राउंड*, और एक *अनुक्रम* एट्रीब्यूट है. +* **राउंड** ऊँचाई के लिए प्रपोज़र राउंड का प्रतिनिधित्व करता है +* **अनुक्रम** ब्लॉकचेन की ऊँचाई का प्रतिनिधित्व करता है + +IBFT इम्प्लिमेन्टेशन में *msgQueue* फ़ील्ड का उद्देश्य मैसेज अनुरोध को स्टोर करना है. यह मैसेज को *दृश्य* द्वारा ऑर्डर करता है (पहले अनुक्रम से, फिर राउंड से). IBFT इम्प्लिमेन्टेशन सिस्टम में विभिन्न स्थितियों के लिए अलग अलग कतारें भी होती हैं. + +### IBFT स्टेट्स {#ibft-states} + +एक बार **स्टार्ट** तरीके की मदद से सहमति मैकेनिज्म को शुरू करने के बाद, यह एक अनंत लूप में चलता है जो स्टेट मशीन को सिमुलेट करता है: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### सिंक्रोनाइज़ेशन स्टेट {#syncstate} + +सभी नोड आरंभ में **सिंक्रोनाइज़ेशन** स्टेट में शुरू होता है. + +ऐसा इसलिए होता है क्योंकि ब्लॉकचेन से ताजा डेटा को प्राप्त करने की जरूरत होती है. क्लाइंट को पता लगाने की जरूरत है कि अगर यह वैलिडेटर है तो, मौजूदा स्नैपशॉट का पता लगाएं. यह स्टेट किसी भी लंबित ब्लॉक का समाधान करता है. + +सिंक्रोनाइज़ेशन के पूरा होने के बाद, क्लाइंट निर्धारित करता है कि यह वास्तव में एक वैलिडेटर है, तो इसे**AcceptState** में ट्रांसफ़र करने की जरूरत है. +अगर क्लाइंट एक वैलिडेटर **नहीं **है, यह सिंक्रोनाइजिंग जारी रखेगा और स**िंक्रोनाइज़ेशन स्टेट **में ही रहेगा + +#### एक्सेप्ट स्टेट {#acceptstate} + +यह **एक्सेप्ट** एक्सेप्ट स्टेट हमेशा स्नैपशॉट और वैलिडेटर सेट की जाँच करता है. अगर हालिया नोड वैलिडेटर्स सेट में नहीं है, +यह **सिंक्रोनाइज़ेशन** स्टेट में वापस चला जाता है. + +दूसरी ओर, अगर नोड **एक** एक वैलिडेटर है, तो यह प्रपोज़र की गणना करता है. अगर यह पता चलता है कि हालिया नोड ही प्रपोज़र है, तो यह ब्लॉक बनाता है और preprepare भेजता है और फिर मैसेज तैयार करता है. + +* Preprepare मैसेज - यह प्रपोज़र द्वारा वैलिडेटर्स को भेजा जाने वाला मैसेज है, ताकि उन्हें प्रस्ताव के बारे में सूचित किया जा सकें +* प्रिपेयर मैसेज - मैसेज जहां एक वैलिडेटर किसी प्रस्ताव पर सहमत होता है. सभी नोड सभी प्रिपेयर मैसेज प्राप्त करते हैं +* कमिट मैसेज - इसमें प्रस्ताव के लिए प्रतिबद्ध जानकारी शामिल होती है + +अगर हालिया नोड एक वैलिडेटर **नहीं है**, तो यह *getNextMessage* तरीके का उपयोग पहले से कतार में दिखाए गए मैसेज को पढ़ने के लिए करता है.
यह preprepare मैसेज का इंतजार करता है. एक बार जब यह पुष्टि हो जाती है कि सब कुछ सही है, तो नोड **वैलिडेट** स्टेट में चला जाता है. + +#### ValidateState {#validatestate} + +यह **वैलिडेट** स्टेट बहुत ही सरल है - इस स्टेट में सभी नोड ही मैसेज पढ़ता है और उन्हें अपने स्थानीय स्नैपशॉट स्टेट में जोड़ देता है. diff --git a/archive/edge/hi-edge/architecture/modules/json-rpc.md b/archive/edge/hi-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..bd7d58e426 --- /dev/null +++ b/archive/edge/hi-edge/architecture/modules/json-rpc.md @@ -0,0 +1,181 @@ +--- +id: json-rpc +title: JSON RPC +description: पॉलीगॉन एज के JSON RPC मॉड्यूल के लिए स्पष्टीकरण. +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## ओवरव्यू {#overview} + +**JSON RPC** मॉड्यूल **JSON RPC API लेयर** को लागू करता है, जो dapp डेवलपर्स ब्लॉकचेन के साथ इंटरैक्ट करने के लिए +करते हैं. + +इसमें वेबसॉकेट एंडपॉइंट सहित मानक **[json-rpc एंडपॉइंट](https://eth.wiki/json-rpc/API)** के लिए सहायता भी शामिल +होती है. + +## ब्लॉकचेन इंटरफ़ेस {#blockchain-interface} + +पॉलीगॉन एज JSON RPC मॉड्यूल द्वारा इस्तेमाल किए जाने वाले सभी तरीकों को डिफ़ाइन करने के लिए ***ब्लॉकचेन इंटरफ़ेस*** का इस्तेमाल करता है, +ताकि इसके एंडपॉइंट को ऑर्डर किया जा सके. + +ब्लॉकचेन इंटरफ़ेस **[मिनिमल](/docs/edge/architecture/modules/minimal)** सर्वर द्वारा लागू होता है. यह बेस इम्प्लीमेंटेशन होता है +जिसे JSON RPC लेयर में पास किया जाता है. + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## ETH एंडपॉइंट्स {#eth-endpoints} + +सभी मानक JSON RPC एंडपॉइंट को लागू किया जाता है: + +````bash +jsonrpc/eth_endpoint.go +```` + +## फ़िल्टर मैनेजर में {#filter-manager} + +**फिल्टर मैनेजर** वह सेवा है जो JSON RPC सर्वर के साथ रन होती है. + +यह ब्लॉकचेन पर फ़िल्टरिंग ब्लॉक को सहायता प्रदान करता है.
+विशेष रूप से, इसमें दोनों **लॉग** और **ब्लॉक** लेवल के फिल्टर होते हैं. + +फिल्टर मैनेजर सब्सक्रिप्शन इवेंट्स पर काफी हद तक निर्भर करता है +[जिसका उल्लेख ब्लॉकचेन](blockchain#blockchain-subscriptions) सेक्शन में किया गया है + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +फ़िल्टर मैनेजर इवेंट *रन* करने के तरीकों में भेजे जाते हैं: + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## 📜 संसाधन {#resources} +* **[Ethereum JSON-RPC](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/hi-edge/architecture/modules/minimal.md b/archive/edge/hi-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..86b45ecf84 --- /dev/null +++ b/archive/edge/hi-edge/architecture/modules/minimal.md @@ -0,0 +1,119 @@ +--- +id: minimal +title: मिनिमल +description: पॉलीगॉन एज के मिनिमल मॉड्यूल के लिए स्पष्टीकरण. +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## ओवरव्यू {#overview} + +जैसा कि पहले बताया गया है, पॉलीगॉन एज विभिन्न मॉड्यूल का सेट होता है जो सभी एक दूसरे से जुड़े होते हैं.
+**ब्लॉकचेन** **स्टेट** से जुड़ा होता है, या उदाहरण के लिए, **सिंक्रनाइज़ेशन** जो **ब्लॉकचेन** में नए ब्लॉक को पाइप करता है. + +**मिनिमल** इन इंटर-कनेक्टेड मॉड्यूल के लिए कॉर्नरस्टोन होता है.
+यह पॉलीगॉन एज पर रन करने वाली सभी सेवाओं के लिए एक सेंट्रल हब के रूप में काम करता है. + +## स्टार्टअप मैजिक {#startup-magic} + +अन्य बातों के अलावा, मिनिमल इसके लिए जिम्मेदार है: +* डेटा डायरेक्टरी सेट अप करने के लिए +* libp2p कम्युनिकेशन के लिए कीस्टोर बनाने के लिए +* स्टोरेज बनाने के लिए +* सहमति सेट करने के लिए +* GRPC, JSON RPC, और सिंक्रनाइज़ेशन के साथ ब्लॉकचेन ऑब्जेक्ट सेट अप करने के लिए + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/hi-edge/architecture/modules/networking.md b/archive/edge/hi-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..d871c63dd5 --- /dev/null +++ b/archive/edge/hi-edge/architecture/modules/networking.md @@ -0,0 +1,77 @@ +--- +id: networking +title: नेटवर्किंग +description: पॉलीगॉन एज के नेटवर्किंग मॉड्यूल के लिए स्पष्टीकरण. +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## अवलोकन {#overview} + +उपयोगी सूचनाओं के एक्सचेंज के लिए एक नोड को नेटवर्क पर अन्य नोड्स के साथ संवाद करना पड़ता है.
इस कार्य को पूरा करने के लिए, पॉलीगॉन एज युद्ध-परीक्षण किए गए **libp2p**ढांचे का लाभ उठाता है. + + **libp2p** के साथ जाने का विकल्प मुख्य रूप से इस पर केंद्रित है: +* **स्पीड** - libp2p में devp2p (GET और अन्य क्लाइंट्स में प्रयुक्त) की तुलना में महत्वपूर्ण प्रदर्शन सुधार है +* **एक्स्टेंसिबिलिटी**- यह सिस्टम की अन्य विशेषताओं के लिए एक महान आधार के रूप में कार्य करता है +* **मॉड्यूलरिटी** - libp2p पॉलीगॉन एज की तरह ही स्वभाव से मॉड्यूलर है. यह अधिक लचीलापन देता है, खासकर जब पॉलीगॉन एज के कुछ हिस्सों को स्वैप करने की आवश्यकता होती है. + +## GRPC {#grpc} + +**libp2p** के ऊपर, पॉलीगॉन एज **GRPC** प्रोटोकॉल का उपयोग करता है.
+तकनीकी रूप से, पॉलीगॉन एज कई जीआरपीसी प्रोटोकॉल का उपयोग करता है, जिसे बाद में कवर किया जाएगा. + +जीआरपीसी लेयर सभी अनुरोध/उत्तर प्रोटोकॉल को अमूर्त करने में मदद करती है और पॉलीगॉन एज के फ़ंक्शन करने के लिए आवश्यक स्ट्रीमिंग प्रोटोकॉल को सरल बनाती है. + +जीआरपीसी *सेवाओं*और *मैसेज संरचनाओं*को परिभाषित करने के लिए **प्रोटोकॉल बफ़र्स**पर निर्भर करता है.
सेवाओं और संरचनाओं को *प्रोटो*फाइलों में परिभाषित किया गया है, जो संकलित हैं और भाषा-अज्ञेयवादी हैं. + +इससे पहले, हमने उल्लेख किया था कि पॉलीगॉन एज कई जीआरपीसी प्रोटोकॉल का लाभ उठाता है.
+यह नोड ऑपरेटर के लिए समग्र UX को बढ़ावा देने के लिए किया गया था, कुछ ऐसा जो अक्सर GETH और Parity जैसे ग्राहकों के साथ होता है. + +वे जिस जानकारी की तलाश कर रहे हैं, उसे खोजने के लिए लॉग के माध्यम से छानने के बजाय नोड ऑपरेटर के पास जीआरपीसी सेवा को कॉल करके सिस्टम के साथ क्या हो रहा है, इसका बेहतर अवलोकन है. + +### नोड ऑपरेटरों के लिए जीआरपीसी {#grpc-for-node-operators} + +निम्नलिखित सेक्शन परिचित लग सकता है क्योंकि यह संक्षेप में [सीएलआई कमांड्स](/docs/edge/get-started/cli-commands)अनुभाग में शामिल किया गया था. + +**नोड ऑपरेटरों** द्वारा उपयोग की जाने वाली GRPC सेवा को इस प्रकार परिभाषित किया गया है: +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip +सीएलआई आदेश वास्तव में इन सेवा विधियों के कार्यान्वयन को कहते हैं. + +इन विधियों को में लागू किया गया है ***न्यूनतम/system_service.go***. + +::: + +### अन्य नोड के लिए जीआरपीसी {#grpc-for-other-nodes} + +पॉलीगॉन एज नेटवर्क पर अन्य नोड्स द्वारा उपयोग की जाने वाली कई सेवा विधियों को भी लागू करता है.
+उल्लिखित सेवा **[प्रोटोकॉल](docs/edge/architecture/modules/consensus)**अनुभाग में वर्णित है. + +## 📜 संसाधन {#resources} +* **[प्रोटोकॉल बफ़र्स](https://developers.google.com/protocol-buffers)** +* **[libp2p](https://libp2p.io/)** +* **[gRPC](https://grpc.io/)** diff --git a/archive/edge/hi-edge/architecture/modules/other-modules.md b/archive/edge/hi-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..24869f0e4b --- /dev/null +++ b/archive/edge/hi-edge/architecture/modules/other-modules.md @@ -0,0 +1,36 @@ +--- +id: other-modules +title: अन्य मॉड्यूल +description: पॉलीगॉन एज के कुछ मॉड्यूल के लिए स्पष्टीकरण. +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## क्रिप्टो {#crypto} + +**Crypto** मॉड्यूल में क्रिप्टो यूटिलिटी फ़ंक्शन होते हैं. + +## चेन {#chain} + +**चेन** मॉड्यूल में चेन पैरामीटर (एक्टिव फोर्क्स, सहमति इंजन आदि) होते हैं + +* **चेन** - पहले से डिफ़ाइन चेन कॉन्फ़िगरेशन (मेननेट, गोएर्ली, ibft) + +## हेल्पर {#helper} + +**हेल्पर** मॉड्यूल में हेल्पर पैकेज होते हैं. + +* **dao** - dao utils +* **enode** - एनकोड एनकोडिंग/डिकोडिंग फ़ंक्शन +* **hex** Hex एनकोडिंग/डिकोडिंग फ़ंक्शन्स +* **ipc** - IPC कनेक्शन फ़ंक्शन्स +* **keccak** - keccak फ़ंक्शन्स +* **rlputil** - Rlp एनकोडिंग/डिकोडिंग हेल्पर फ़ंक्शन + +## कमांड {#command} + +**कमांड** मॉड्यूल में CLI कमांड्स के लिए इंटरफ़ोस होते हैं. \ No newline at end of file diff --git a/archive/edge/hi-edge/architecture/modules/sealer.md b/archive/edge/hi-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..d8ade564c3 --- /dev/null +++ b/archive/edge/hi-edge/architecture/modules/sealer.md @@ -0,0 +1,71 @@ +--- +id: sealer +title: सीलर +description: पॉलीगॉन एज के सीलर मॉड्यूल के लिए स्पष्टीकरण. +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## ओवरव्यू {#overview} + +**सीलर** एक इकाई है जो लेनदेन को इकट्ठा करती है और एक नया ब्लॉक बनाती है.
फिर, उस ब्लॉक को सील करने के लिए **सहमति** मॉड्यूल में भेजा जाता है. + +अंतिम सीलिंग तर्क आम **सहमति** मॉड्यूल के भीतर स्थित है. + +## रन तरीका {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution कार्य प्रगति पर है + +**सीलर**और आम**सहमति** मॉड्यूल निकट भविष्य में एक इकाई में संयुक्त हो जाएंगे. + +नया मॉड्यूल विभिन्न प्रकार सहमति तंत्र के लिए मॉड्यूलर लॉजिक मॉडुलर लॉजिक शामिल करेगा, जिसमें विभिन्न सीलिंग इम्प्लीमेंट की ज़रूरत होती है: +* **पॉस** (भागीदारी का सबूत) +* **PoA** (प्रूफ अथॉरिटी) + +वर्तमान में, **सीलर** और **सहमति**मॉड्यूल पीओडब्ल्यू (प्रूफ ऑफ वर्क) के साथ काम करते हैं. +::: \ No newline at end of file diff --git a/archive/edge/hi-edge/architecture/modules/state.md b/archive/edge/hi-edge/architecture/modules/state.md new file mode 100644 index 0000000000..b8cace84e0 --- /dev/null +++ b/archive/edge/hi-edge/architecture/modules/state.md @@ -0,0 +1,241 @@ +--- +id: state +title: स्टेट +description: पॉलीगॉन एज के स्टेट मॉड्यूल का स्पष्टीकरण. +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +वास्तव में यह समझने के लिए **स्टेट** कैसे काम करता है, आपको कुछ बुनियादी एथेरेयम अवधारणाओं को समझना चाहिए.
+ +हम **[एथेरेयम गाइड में स्टेट](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)** को पढ़ने की बहुत सिफारिश करते हैं. + +## ओवरव्यू {#overview} + +अब जबकि हम एथेरेयम अवधारणाओं से परिचित हो गए हैं, अगला ओवरव्यू आसान होना चाहिए. + +हमने उल्लेख किया है कि **वर्ल्ड स्टेट ट्री** में ऐसे सभी एथेरेयम अकाउंट जो मौजूद हैं.
ये एकाउंट, मर्कल ट्री के लीव्स हैं. प्रत्येक लीफ में कूटबद्ध **अकाउंट स्टेट** जानकारी होती है. + +यह पॉलीगॉन एज को किसी विशिष्ट समय के लिए, एक विशिष्ट मर्कल ट्री प्राप्त करने में सक्षम बनाता है.
उदाहरण के लिए, हम ब्लॉक 10 में स्टेट का हैश प्राप्त कर सकते हैं. + +मर्कल ट्री को किसी भी समय पर, ***स्नैपशॉट*** कहा जाता है. + +हम **स्टेट ट्री** के लिए, या **स्टोरेज ट्री** के लिए ***स्नैपशॉट*** प्राप्त कर सकते हैं - ये मूल रूप से एक ही हैं
. केवल उसमें अंतर है जिसमें लीव्स प्रतिनिधित्व करते हैं: + +* स्टोरेज ट्री के मामले में, पत्तियों में एक आर्बिट्रेरी स्टेट होता है, जिसे हम प्रोसेस नहीं कर सकते या नहीं जानते कि उसमें क्या है +* स्टेट ट्री के मामले में, लीव्स, एकाउंट का प्रतिनिधित्व करते हैं + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + +**स्नैपशॉट** इंटरफ़ेस को इस प्रकार परिभाषित किया गया है: + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +जिस जानकारी को प्रतिबद्ध किया जा सकता है *उसे ऑब्जेक्ट स्ट्रक्ट* द्वारा परिभाषित किया जाता है: + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +मर्कल ट्री का इम्प्लीमेंटेशन, *स्टेट / इम्यूटेबल ट्री* फ़ोल्डर में है.
*state/immutable-trie/state.go* **स्टेट** इंटरफ़ेस को लागू करता है. + +*state/immutable-trie/trie.go*, मुख्य मर्कल ट्री ऑब्जेक्ट है. यह मर्कल ट्री के ऑप्टिमाइज्ड वर्जन का प्रतिनिधित्व करता है, जो फिर से ज़्यादा से ज़्यादा मेमोरी का इस्तेमाल करता है. + +## एग्जीक्यूटर {#executor} + +*state/executor.go* यह तय करने के लिए पॉलीगॉन एज के लिए आवश्यक सभी जानकारी होती है कि ब्लॉक मौजूदा +स्टेट को कैसे बदलता है. *प्रोसेस ब्लॉक* का इम्प्लीमेंटेशन यहाँ स्थित है. + +*लागू करने* का तरीका वास्तविक स्टेट ट्रांजिशन करता है. एग्जीक्यूटर EVM को कॉल करता है. + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## रनटाइम {#runtime} + +जब स्टेट ट्रांजिशन एग्जीक्यूट होता है तब स्टेट ट्रांजिशन को एग्जीक्यूट करने वाला मुख्य मॉड्यूल EVM होता है (जो state/runtime/evm में स्थित होता है). + +**डिस्पैच टेबल**, **opcode** और निर्देश के बीच मिलान करता है. + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +EVM को पॉवर देने वाला कोर लॉजिक, *रन* लूप होता है.
+ +यह EVM का मुख्य प्रवेश स्थान है. यह एक लूप करता है और वर्तमान opcode को जाँचता है, निर्देश लाता है, जाँचता है कि इसे एग्जिक्यूट किया जा सकता है या नहीं, गैस का सेवन करता है और निर्देश को एग्जिक्यूट करता है जब तक यह विफल या बंद नहीं होता है. + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/hi-edge/architecture/modules/storage.md b/archive/edge/hi-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..74873ac0d6 --- /dev/null +++ b/archive/edge/hi-edge/architecture/modules/storage.md @@ -0,0 +1,116 @@ +--- +id: storage +title: स्टॉरिज +description: पॉलीगॉन एज के स्टोरेज मॉड्यूल के लिए स्पष्टीकरण. +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## अवलोकन {#overview} + +पॉलीगॉन एज वर्तमान में डेटा स्टोरेज के लिए **लेवल डीबी** का इस्तेमाल करता है, साथ ही **ईन इन मेमोरी**डेटा स्टोर भी उपलब्ध है. + +पॉलीगॉन एज के दौरान, जब मॉड्यूल डेटा स्टोर के साथ इंटरैक्ट करें, उन्हें यह जानने की आवश्यकता नहीं है कि वे किस DB इंजन या सेवा से बात कर रहे हैं. + +डीबी लेयर को **स्टोरेज**नामक मॉड्यूल के बीच अलग कर दिया जाता है, जो उस मॉड्यूल क्वेरी को इंटरफेस निर्यात करता है. + +प्रत्येक DB लेयर, अभी के लिए केवल **LevelDB**, इन विधियों को अलग से लागू करती है, यह सुनिश्चित करते हुए कि वे उनके लागू करना के साथ फिट हैं. + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### उपसर्गों {#prefixes} + +LevelDB स्टोरेज को निर्धारित करने वाली क्वेरी करने के लिए, और की स्टोरेज क्लैशिंग से बचने के लिए, पॉलीगॉन एज लीवरेज करता है डेटा संग्रहीत करते समय उपसर्ग और उप-उपसर्ग + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## भविष्य की योजना {#future-plans} + +निकट भविष्य के लिए योजनाओं में कुछ सबसे लोकप्रिय डीबी सॉल्यूशंस शामिल हैं, जैसे: +* PostgreSQL +* MySQL + + +## 📜 संसाधन {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/hi-edge/architecture/modules/syncer.md b/archive/edge/hi-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..aa264d95e7 --- /dev/null +++ b/archive/edge/hi-edge/architecture/modules/syncer.md @@ -0,0 +1,68 @@ +--- +id: syncer +title: सिंक्रोनाइज़ेशन +description: पॉलीगॉन एज के सिंक्रोनाइज़ेशन मॉड्यूल के लिए व्याख्या. +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## ओवरव्यू {#overview} + +इस मॉड्यूल में सिंक्रोनाइज़ेशन प्रोटोकॉल के लिए लॉजिक शामिल है. इसका इस्तेमाल रन कर रहे नेटवर्क के साथ एक नोड को सिंक करने या जो नोड्स सहमति (नॉन वैलिडेटर) में भाग नहीं लेते उनके लिए नए ब्लॉक को वैलिडेट/इंसर्ट करने के लिए किया जाता है. + +पॉलीगॉन एज नेटवर्किंग लेयर के रूप में **libp2p** का इस्तेमाल करता है, और उस पर **gRPC** को रन करता है. + +पॉलीगॉन एज में अनिवार्य रूप से 2 सिंक प्रकार हैं: +* बल्क सिंक - एक बार में ब्लॉक की एक बड़ी रेंज को सिंक करता है +* वॉच सिंक - ब्लॉक को एक-एक करके सिंक करता है + +### बल्क सिंक {#bulk-sync} + +बल्क सिंकिंग के लिए स्टेप्स, एक साथ बल्क में सिंक करने के लक्ष्य को पाने के लिए काफ़ी सीधे-सरल होते हैं - इसमें बराबर आने के लिए जितना संभव हो (उपलब्ध हों) उतने ही ब्लॉक को पियर से जितना जल्दी हो, लेना होता है. + +यह बल्क में सिंक करने की प्रक्रिया का फ़्लो है: + +1. ** निर्धारित करें कि नोड को बल्क में सिंक कराने की ज़रूरत है ** - इस स्टेप में, नोड पियर के मैप को जाँचता है कि क्या कोई ऐसा है जिसके पास नोड के स्थानीय नंबर से बड़ा ब्लॉक नंबर है +2. ** सर्वश्रेष्ठ पियर का पता लगाएँ (सिंक के मैप का इस्तेमाल करके) ** - इस स्टेप में नोड, ऊपर दिए गए उदाहरण में बताए गए मानदंडों के आधार पर सिंक करने के लिए सबसे अच्छे पियर का पता लगाता है. +3. ** एक बल्क सिंक स्ट्रीम खोलें ** - इस स्टेप में नोड ब्लॉक को सामान्य ब्लॉक नंबर से बल्क में सिंक करने के लिए सबसे अच्छे पियर के लिए एक gRPC स्ट्रीम खोलता है +4. ** सबसे अच्छा पियर जब बल्क में भेज देता है तो वह स्ट्रीम बंद कर देता है ** - इस स्टेप में सबसे अच्छा पियर जैसे ही अपने पास के सारे ब्लॉक भेज देता है, वैसे ही नोड का सिंक होना स्ट्रीम बंद होने के साथ ही बंद हो जाएगा +5. ** जब बल्क में सिंक किया जा रहा हो, तो जाँचें कि नोड एक वैलिडेटर है ** - इस स्टेप में, को सबसे अच्छे पियर द्वारा बंद कर दिया जाता है, और नोड को चेक करने की ज़रूरत होती है कि वे बल्क में सिंक होने के बाद एक वैलिडेटर हैं. + * अगर वे हैं, तो वे सिंक स्टेट से बाहर निकल जाते हैं और सहमति में भाग लेना शुरू कर दें + * अगर वे ऐसा नहीं करते, तो वे ** वॉच सिंक ** में जारी रहते हैं + +### वॉच सिंक {#watch-sync} + +:::info + +वॉच सिंकिंग के लिए स्टेप को केवल तब एक्ज़ीक्यूट किया जाता है, जब नोड एक वैलिडेटर नहीं होता, लेकिन नेटवर्क में एक नियमित नॉन-वैलिडेटर नोड होता है जो सिर्फ़ आने वाले ब्लॉक को ही सुनता है. + +::: + +वॉच सिंक का व्यवहार बहुत सीधा-सरल होता है, नोड पहले से ही बाकी के नेटवर्क के साथ सिंक किया जाता है और इसमें सिर्फ़ नए आने वाले ब्लॉक को ही पार्स कराने की ज़रूरत होती है. + +यह वॉच सिंक की प्रक्रिया का फ़्लो है: + +1. ** जब एक पियर का स्टेटस अपडेट किया जाता है तब एक नया ब्लॉक जोड़ें ** - इस स्टेप में नोड नए ब्लॉक इवेंट को सुनते हैं जब इसमें एक नया ब्लॉक होता है तो यह एक gRPC फंक्शन को कॉल करता है ब्लॉक लेता है और स्थानीय स्टेट को अपडेट करता है. +2. ** जाँचें कि नए ब्लॉक को सिंक करने के बाद नोड एक वैलिडेटर है या नहीं ** + * अगर यह है, तो सिंक स्टेट से बाहर आ जाएँ + * अगर यह नहीं है, तो नए ब्लॉक इवेंट को सुनना जारी रखें + +## प्रदर्शन रिपोर्ट {#perfomance-report} + +:::info + +प्रदर्शन को एक स्थानीय मशीन पर एक ** मिलियन ब्लॉक ** को सिंक करके मापा गया था + +::: + +| नाम | परिणाम | +|----------------------|----------------| +| 1मिलियन ब्लॉक को सिंक करना | ~25 मिनट | +| 1मिलियन ब्लॉक को ट्रांसफ़र करना | ~1 मिनट | +| GRPC कॉल की संख्या | 2 | +| टेस्ट कवरेज | ~ 93% | \ No newline at end of file diff --git a/archive/edge/hi-edge/architecture/modules/txpool.md b/archive/edge/hi-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..9d9ccfb6fa --- /dev/null +++ b/archive/edge/hi-edge/architecture/modules/txpool.md @@ -0,0 +1,231 @@ +--- +id: txpool +title: TxPool +description: पॉलीगॉन एज के TxPool मॉड्यूल के लिए स्पष्टीकरण. +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## ओवरव्यू {#overview} + +TxPool मॉड्यूल ट्रांज़ैक्शन पूल लागू करने का प्रतिनिधित्व करता है, जहाँ सिस्टम के विभिन्न भागों से ट्रांज़ैक्शन +जोड़े जाते हैं. यह मॉड्यूल नोड ऑपरेटर्स के लिए कई उपयोगी सुविधाओं को भी सार्वजनिक करता है, जो नीचे दी गई हैं. + +## ऑपरेटर कमांड्स {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +नोड ऑपरेटर इन GRPC एंडपॉइंट्स से क्वेरी कर सकते हैं, जो **[CLI कमांड्स](/docs/edge/get-started/cli-commands#transaction-pool-commands)** सेक्शन में दिए गए हैं. + +## ट्रांज़ैक्शन प्रोसेस हो रहा {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +***addImpl*** तरीका **TxPool** मॉड्यूल की सबसे मुख्य ज़रूरत है. +यह वह मुख्य स्थान है जहाँ सिस्टम में ट्रांज़ैक्शन जोड़े जाते हैं, GRPC सेवा, JSON RPC एंडपॉइंट्स से कॉल किया जाता है, +और क्लाइंट **gossip** प्रोटोकॉल के माध्यम से ट्रांज़ैक्शन प्राप्त करता है. + +यह एक आर्ग्युमेंट **ctx**, के रूप में लेता है, जो सिर्फ़ उस संदर्भ को दर्शाता है जिससे ट्रांज़ैक्शन जोड़े जा रहे हैं (GRPC, JSON RPC...).
+अन्य पैरामीटर पूल में जोड़े जाने वाले ट्रांज़ैक्शन की सूची है. + +यहाँ ध्यान देने लायक मुख्य बात यह है कि ट्रांज़ैक्शन के भीतर **फ़्रॉम** फील्ड के लिए चेक करें: +* अगर **फ़्रॉम** फील्ड **खाली** है, तो इसे एक अन-एनक्रिप्टेड/अन-साइन किया गया ट्रांज़ैक्शन माना जाता है. इन प्रकार के ट्रांज़ैक्शन सिर्फ़ +डेवलपमेंट मोड में स्वीकार होते हैं +* अगर **फ्रॉम** फील्ड खाली नहीं है, तो इसका मतलब है कि यह एक **साइन किया हुआ ट्रांज़ैक्शन** है, इसलिए सिग्नेचर वेरीफ़िकेशन होता है + +इन सभी वेलिडेशन्स के बाद, ट्रांज़ैक्शन्स को वैलिड माना जाता है. + +## डेटा स्ट्रक्चर {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +Txpool ऑब्जेक्ट में फील्ड जो कन्फ़्युशन पैदा कर सकते हैं, वे **क्यू** और **सॉर्टेड** सूचियाँ हैं. +* **क्यू** - अकाउंट ट्रांज़ैक्शन की एक सॉर्टेड सूची का हीप इम्प्लीमेंटेशन (अस्थायी रूप से) +* **सॉर्टेड** - सभी मौजूदा प्रमोटेड ट्रांज़ैक्शन के लिए सॉर्टेड लिस्ट (सभी एक्जीक्यूटेबल ट्रांज़ैक्शन). गैस प्राइस के आधार पर सोर्टेड + +## गैस लिमिट गड़बड़ी मैनेजमेंट {#gas-limit-error-management} + +जब आप कोई ट्रांज़ैक्शन करते हैं, तो TxPool द्वारा ये तीन तरीकों से किया जा सकता है. + +1. सभी पेंडिंग ट्रांज़ैक्शन एक ब्लॉक में हो सकते हैं +2. एक या अधिक पेंडिंग ट्रांज़ैक्शन एक ब्लॉक में फिट नहीं हो सकते +3. एक या अधिक पेंडिंग ट्रांज़ैक्शन एक ब्लॉक में कभी भी फिट नहीं हो पाएंगे + +यहाँ, **_फिट_** शब्द का मतलब हर ट्रांज़ैक्शन की गैस सीमा से है, जो TxPool की शेष गैस की तुलना में कम होती है. + +पहला सिनेरियों से कोई गड़बड़ी नहीं होती है. + +### द्वितीय सिनेरियों {#second-scenario} + +- TxPool शेष गैस को अंतिम ब्लॉक की गैस लिमिट पर सेट किया गया है, जो **5000** है +- पहला ट्रांज़ैक्शन होता है और TxPool की **3000** गैस की खपत होती है + - TxPool की शेष गैस अब **2000** है +- दूसरा ट्रांज़ैक्शन, जो पहले के ही समान है - दोनों 3000 यूनिट गैस की खपत करते हैं, सबमिट किए जाते हैं +- चूंकि TxPool की शेष गैस ट्रांज़ैक्शन की तुलना में **कम** है, इसलिए इसे अभी मौजूदा ब्लॉक में प्रोसेस नहीं किया +जा सकता है + - इसे दोबारा पेंडिंग ट्रांज़ैक्शन की क्यू में डाल दिया जाता है ताकि इसे अगले ब्लॉक में प्रोसेस किया जा सके +- पहले ब्लॉक को **ब्लॉक #1** कहा जाता है +- TxPool शेष गैस को पैरेंट ब्लॉक में सेट किया जाता है - **ब्लॉक #1** की गैस लिमिट +- ऐसा ट्रांज़ैक्शन जो TxPool पेंडिंग ट्रांज़ैक्शन क्यू में वापस रखा गया था, उसे अब प्रोसेस और ब्लॉक में लिखा गया है + - TxPool शेष गैस अब **2000** है +- दूसरे ब्लॉक को लिखा गया है +- ... + +![TxPool गड़बड़ी का सिनेरियों #1](/img/edge/txpool-error-1.png) + +### तीसरा सिनेरियों {#third-scenario} +- TxPool शेष गैस को अंतिम ब्लॉक की गैस लिमिट पर सेट किया गया है, जो **5000** है +- पहला ट्रांज़ैक्शन होता है और TxPool की **3000** गैस की खपत होती है + - TxPool की शेष गैस अब **2000** है +- दूसरे ट्रांज़ैक्शन को **6000** पर सेट गैस फ़ील्ड के साथ सबमिट किया जाता है +- चूंकि ब्लॉक गैस लिमिट ट्रांज़ैक्शन गैस की तुलना में **कम** है, इसलिए इस ट्रांज़ैक्शन को डिस्कार्ड किया जाता है + - यह कभी भी एक ब्लॉक में फिट नहीं हो पाएगा +- पहला ब्लॉक पहले लिखा है +- ... + + +![TxPool गड़बड़ी का सिनेरियों #2](/img/edge/txpool-error-2.png) + +> ये तभी होता है जब आपको ये नीचे दी गई गड़बड़ी मिलती है: +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## ब्लॉक गैस टारगेट {#block-gas-target} + +कुछ ऐसी स्थितियाँ होती हैं जब नोड्स ब्लॉक गैस लिमिट को एक रनिंग चेन पर या नीचे एक निश्चित लक्ष्य पर रखना चाहते हैं. + +नोड ऑपरेटर टार्गेट गैस लिमिट को किसी ख़ास नोड पर सेट कर सकते हैं, जो इस सीमा को नए बनाए गए ब्लॉक पर लागू करने की कोशिश करेगा. +यदि अधिकांश अन्य नोड्स में भी एक समान (या समान) लक्ष्य गैस लिमिट निर्धारित है, तो ब्लॉक गैस सीमा हमेशा उस ब्लॉक गैस लक्ष्य के आसपास मंडराती रहेगी, +धीरे-धीरे इसकी ओर बढ़ती जाएगी (अधिकतम `1/1024 * parent block gas limit`पर) क्योंकि नए ब्लॉक बनाए जाते हैं. + +### उदाहरण के लिए सिनेरियों {#example-scenario} + +* नोड ऑपरेटर `5000`होने के लिए सिंगल नोड के लिए ब्लॉक गैस लिमिट को सेट करता है +* अन्य नोड को `5000` के रूप में भी कॉन्फ़िगर किया जाता है, के अलावा सिंगल नोड को `7000` होने के लिए कॉन्फ़िगर किया जाता है +* जब `5000`के लिए निर्धारित गैस टार्गेट वाले नोड प्रस्तावित करने वाले बन जाते हैं, तो वे यह जाँच करेंगे कि गैस लिमिट पहले से ही टार्गेट पर है या नहीं +* अगर गैस लिमिट टार्गेट पर नहीं है (अधिक/कम है), तो प्रस्तावित करने वाला नोड ब्लॉक गैस टार्गेट को टार्गेट की दिशा में अधिकतम (1/1024 * पैरेंट गैस सीमा) पर सेट करेगा + 1. जैसे: `parentGasLimit = 4500` और `blockGasTarget = 5000`, प्रस्तावित करने वाला नए ब्लॉक के लिए गैस लिमिट की गणना `4504.39453125` के रूप में करेगा (`4500/1024 + 4500`) + 2. जैसे: `parentGasLimit = 5500` और `blockGasTarget = 5000`, प्रस्तावित करने वाला नए ब्लॉक के लिए गैस लिमिट की गणना `5494.62890625` के रूप में करेगा (`5500 - 5500/1024`) +* यह सुनिश्चित करता है कि चेन में ब्लॉक गैस की सीमा को टार्गेट पर रखा जाएगा, क्योंकि सिंगल प्रपोज़ करने वाला जिसके पास `7000`के लिए कॉन्फ़िगर किया गया टार्गेट है, वह सीमा को बहुत आगे नहीं बढ़ा सकता है, और +`5000`में सेट किए गए अधिकांश नोड्स हमेशा बनाए रखने का प्रयास करेंगे \ No newline at end of file diff --git a/archive/edge/hi-edge/architecture/modules/types.md b/archive/edge/hi-edge/architecture/modules/types.md new file mode 100644 index 0000000000..b38e666835 --- /dev/null +++ b/archive/edge/hi-edge/architecture/modules/types.md @@ -0,0 +1,40 @@ +--- +id: types +title: प्रकार +description: पॉलीगॉन एज के प्रकार के मॉड्यूल के लिए स्पष्टीकरण. +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## ओवरव्यू {#overview} + +**प्रकार**के मॉड्यूल ऑब्जेक्ट के प्रकार को लागू करता है करता है, जैसे: + +* **पता** +* **हैश** +* **हेडर** +* बहुत सारे सहायक कार्य + +## RLP एनकोडिंग / डिकोडिंग {#rlp-encoding-decoding} + +GETH जैसे ग्राहकों के विपरीत, Polygon Edge एन्कोडिंग के लिए प्रतिबिंब का उपयोग नहीं करता है
. +वरीयता प्रतिबिंब का उपयोग नहीं करना था क्योंकि यह प्रदर्शन जैसी नई समस्याओं का परिचय देता है. गिरावट, और कठिन स्केलिंग. + +**प्रकार**मॉड्यूल फास्ट आरएलपी पैकेज का उपयोग करते हुए आरएलपी मार्शलिंग और अनमर्सॉलिंग के लिए उपयोग में आसान इंटरफ़ेस प्रदान करता है. + +*मार्शल RLP* और *मार्शल RLPTo*विधि के माध्यम से मार्शलिंग की जाती है. अनमर्सलिंग के लिए समान तरीके मौजूद हैं. + +इन तरीकों को मैन्युअल रूप से परिभाषित करने के द्वारा, पॉलीगॉन एज को प्रतिबिंबित करने की जरूरत नहीं है. *Rlp_marshal.go* में आप पा सकते हैं मार्शल करने के लिए तरीका: + +* **बॉडी** +* **ब्लोक्क्स** +* **हेयडर्स** +* **प्राप्तियां** +* **लॉग** +* **ट्रांज़ैक्शनस** \ No newline at end of file diff --git a/archive/edge/hi-edge/architecture/overview.md b/archive/edge/hi-edge/architecture/overview.md new file mode 100644 index 0000000000..36bf0dac77 --- /dev/null +++ b/archive/edge/hi-edge/architecture/overview.md @@ -0,0 +1,61 @@ +--- +id: overview +title: आर्किटेक्चर ओवरव्यू +sidebar_label: Overview +description: पॉलीगॉन एज के आर्किटेक्चर का परिचय. +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +हमने *मॉडुलर* सॉफ्टवेयर बनाने के आइडिया पर काम करना शुरू कर दिया है. + +इसमें ऐसा कुछ है जो पॉलीगॉन एज के लगभग सभी पार्ट में मौजूद है. नीचे आप बिल्ट आर्किटेक्चर और इसकी लेयरिंग +के बारे संक्षिप्त जानकारी प्राप्त करेंगे. + +## पॉलीगॉन एज लेयरिंग {#polygon-edge-layering} + +![पॉलीगॉन एज आर्किटेक्चर](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +यह बेस नेटवर्किंग लेयर पर शुरू होता है, जो **libp2p** का इस्तेमाल करता है. हमने इस टेक्नोलॉजी का इस्तेमाल करने का फैसला किया क्योंकि +यह पॉलीगॉन एज के डिजाइनिंग फ़िलॉसफ़ीज़ में फिट बैठती है. Libp2p है: + +- मॉडुलर +- एक्सटेंसिबल +- फास्ट + +सबसे महत्वपूर्ण कि यह अधिक एडवांस फ़ीचर के लिए एक अच्छी शुरूआत प्रदान करता है, जो हम बाद में कवर करेंगे. + + +## सिंक्रनाइज़ेशन और सहमति {#synchronization-consensus} +सिंक्रनाइज़ेशन और सहमति प्रोटोकॉल को अलग करने से **कस्टम** सिंक और सहमति मैकेनिज्म के मॉड्यूलैरिटी और इम्प्लीमेंटेशन की अनुमति मिलती है - यह इस बात पर निर्भर करता है कि क्लाइंट कैसे रन किया जा रहा है. + +पॉलीगॉन एज को ऑफ़-द-शेल्फ़ प्लगेबल सहमति अल्गोरिथम को ऑफ़र करने के लिए डिज़ाइन किया गया है. + +समर्थित सहमति अल्गोरिथम की मौजूदा सूची: + +* IBFT PoA +* IBFT PoS + +## ब्लॉकचेन {#blockchain} +ब्लॉकचेन लेयर वह मुख्य लेयर है जो पॉलीगॉन एज सिस्टम में हर चीज का समन्वय करता है. इसे संबंधित *मॉड्यूल* सेक्शन में ठीक से कवर किया गया है. + +## स्टेट {#state} +स्टेट इनर लेयर में स्टेट ट्रांजिशन लॉजिक होते हैं. यह इस बारे में है कि एक नया ब्लॉक शामिल करने से स्टेट कैसे बदल जाता है. इसे संबंधित *मॉड्यूल* सेक्शन में ठीक से कवर किया गया है. + +## JSON RPC {#json-rpc} +JSON RPC लेयर एक API लेयर होती है जिसका इस्तमाल dapp डेवलपर्स ब्लॉकचेन के साथ इंटरैक्ट करने के लिए करते हैं. इसे संबंधित *मॉड्यूल* सेक्शन में ठीक से कवर किया गया है. + +## TxPool {#txpool} +TxPool लेयर ट्रांज़ैक्शन पूल का प्रतिनिधित्व करती है और यह सिस्टम के अन्य मॉड्यूल के साथ ठीक से लिंक होती है, क्योंकि ट्रांज़ैक्शन को कई एंट्री पॉइंट से जोड़ा जा सकता है. + +## GRPC {#grpc} +gRPC, या Google रिमोट प्रोसेस कॉल एक मजबूत ओपन-सोर्स RPC फ्रेमवर्क है जो गूगल ने शुरू में स्केलेबल और फास्ट API बनाने के लिए बनाई थी. GRPC लेयर ऑपरेटर इंटरैक्शन के लिए बहुत महत्वपूर्ण है. इसके माध्यम से, नोड ऑपरेटर एक आनंददायक UX प्रदान करके, क्लाइंट के साथ आसानी से इंटरैक्ट कर सकते हैं. diff --git a/archive/edge/hi-edge/community/propose-new-feature.md b/archive/edge/hi-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..4dfc3457c3 --- /dev/null +++ b/archive/edge/hi-edge/community/propose-new-feature.md @@ -0,0 +1,60 @@ +--- +id: propose-new-feature +title: नए फ़ीचर को प्रस्तावित करें +description: "नए फ़ीचर को प्रस्तावित करने के लिए PR टेम्पलेट और निर्देश." +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## ओवरव्यू {#overview} + +अगर आप कुछ सुधार करना चाहते हैं, या सिर्फ़ कोड में योगदान करना चाहते हैं, तो सबसे पहले आपको अपनी टीम से बात करना होगा.
+पॉलीगॉन एज एक अपेक्षाकृत बेसिक फ़ीचर प्रस्ताव टेम्पलेट का इस्तेमाल करता है, जो कि संक्षिप्त और प्रासंगिक होता है. + +## PR टेम्पलेट {#pr-template} + +### वर्णन {#description} + +कृपया इस PR में किए गए कार्यों का विस्तृत विवरण प्रदान करें + +### परिवर्तनों में शामिल हैं {#changes-include} + +- [ ]Bugfix (नॉन-ब्रेकिंग परिवर्तन जो समस्या को हल करता हैं) +- [ ] Hotfix (ऐसे परिवर्तन जो समस्या को हल करते हैं, और जिन्हें तुरंत ठीक करने की ज़रुरत होती है) +- [ ] नया फ़ीचर (नॉन-ब्रेकिंग परिवर्तन जो फ़ंक्शनैलिटी को बढ़ाते हैं) +- [ ]ब्रेकिंग परिवर्तन (ऐसे परिवर्तन जो बैकवर्ड-कॉम्पैटिबल नहीं हैं और/या मौजूदा फ़ंक्शनैलिटी को परिवर्तित नहीं करते हैं) + +### ब्रेकिंग परिवर्तन {#breaking-changes} + +अगर कोई ब्रेकिंग परिवर्तन किए गए हैं, तो कृपया इस सेक्शन को पूरा करें, अन्यथा इसे डिलीट कर दें + +### चेकलिस्ट {#checklist} + +- [ ] मैंने यह PR को खुद असाइन किया है +- [ ] मैंने कम से कम 1 रिव्यूअर जोड़ा है +- [ ] मैंने संबंधित लेबल्स जोड़ें हैं +- [ ] मैंने आधिकारिक डॉक्यूमेंटेशन अपडेट किया है +- [ ] मैंने कोड में पर्याप्त डॉक्यूमेंटेशन जोड़ा है + +### टेस्टिंग {#testing} + +- [ ] मैंने इस टेस्ट कोड को आधिकारिक टेस्ट सूट के साथ किया है +- [ ] मैंने इस कोड को मैन्युअल रूप से टेस्ट किया है + +## मैनुअल टेस्ट {#manual-tests} + +अगर आप इस फ़ंक्शनैलिटी के लिए मैनुअल टेस्ट रन किए हैं, तो कृपया इस सेक्शन को पूरा करें, अन्यथा इसे डिलीट कर दें + +### डॉक्यूमेंटेशन अपडेट {#documentation-update} + +अगर यह मौजूद है, तो डॉक्यूमेंटेशन अपडेट PR सेक्शन को लिंक करें, अन्यथा इसे डिलीट कर दें + +### अतिरिक्त टिप्पणियाँ {#additional-comments} + +अगर आपके वे पास है, तो इस सेक्शन में अतिरिक्त टिप्पणियाँ पोस्ट करें, अन्यथा इसे डिलीट कर दें \ No newline at end of file diff --git a/archive/edge/hi-edge/community/report-bug.md b/archive/edge/hi-edge/community/report-bug.md new file mode 100644 index 0000000000..80f20bb79a --- /dev/null +++ b/archive/edge/hi-edge/community/report-bug.md @@ -0,0 +1,55 @@ +--- +id: report-bug +title: समस्या की रिपोर्ट करें +description: पॉलीगॉन समस्या की रिपोर्ट करने के लिए टेम्पलेट और निर्देश. +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## ओवरव्यू {#overview} + +कभी-कभी चीजें ब्रेक हो जाती हैं.
+अपनी किसी भी समस्या के बारे में टीम को बताना हमेशा बेहतर होता है.
+पॉलीगॉन एज GitHub पेज पर, आप समस्या फ़ाइल कर सकते हैं और टीम के साथ इसके बारे में चर्चा कर सकते हैं. + +## समस्या टेम्पलेट {#issue-template} + +## [समस्या का विषय] + +### वर्णन {#description} + +अपनी समस्या जितना हो सके विस्तार में यहाँ पर बताएँ + +### आपका क्षेत्र {#your-environment} + +* OS और वर्जन +* पॉलीगॉन एज का वर्जन +* ऐसी ब्रांच जो ये समस्या पैदा करती है + +### रिप्रोड्यूस करने के स्टेप्स {#steps-to-reproduce} + +* हमें बताएँ कि ये समस्या दोबारा कैसे रिप्रोड्यूस की जाए
+* अगर
आप जानते हैं, तो समस्या कहाँ है +* किस कमांड में समस्या आ रही है, अगर कोई हो तो + +### अपेक्षित व्यवहार {#expected-behaviour} + +हमें बताएँ कि क्या होना चाहिए + +### वास्तविक व्यवहार {#actual-behaviour} + +हमें बताएँ कि इसके बदले क्या होता है + +### लॉग {#logs} + +कृपया यहाँ पर कोई भी लॉग पेस्ट करें जिसमें वो समस्या दिखाई गई है, अगर हो तो + +### प्रस्तावित सोल्यूशन {#proposed-solution} + +अगर समस्या को ठीक करने के बारे में जानते हैं, तो कृपया यहाँ लिखें, तो हम इसके बारे पर चर्चा शुरू कर सकते हैं \ No newline at end of file diff --git a/archive/edge/hi-edge/configuration/manage-private-keys.md b/archive/edge/hi-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..38acda48ea --- /dev/null +++ b/archive/edge/hi-edge/configuration/manage-private-keys.md @@ -0,0 +1,69 @@ +--- +id: manage-private-keys +title: निजी कुंजी को प्रबंधित करें +description: "निजी कुंजी का प्रबंधन कैसे करें और वहाँ किस प्रकार की कुंजियाँ हैं." +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## ओवरव्यू {#overview} + +पॉलीगॉन एज में दो प्रकार की निजी कुंजियाँ होती हैं जिन्हें वह सीधे प्रबंधित करता है: + +* **सहमति मैकेनिज्म के लिए इस्तेमाल की गई निजी कुंजी** +* **निजी कुंजी का उपयोग libp2p द्वारा नेटवर्किंग के लिए किया गया** +* **वैलिडेटर्स के हस्ताक्षर को संयुक्त करने के लिए सहमति मैकेनिज्म के लिए (ऐच्छिक) BLS निजी कुंजी** + +वर्तमान में, पॉलीगॉन एज प्रत्यक्ष अकाउंट मैनेजमेंट के लिए सहायता नहीं देता है. + +[बैकअप & रिस्टोर गाइड](/docs/edge/working-with-node/backup-restore) में उल्लिखित निर्देशिका संरचना के आधार पर, पॉलीगॉन एज इन की/कुंजी फ़ाइलों को दो अलग निर्देशिकाओं - **सहमति** और **कीस्टोर** में स्टोर करता है. + +## की/मुख्य फॉर्मेट {#key-format} + +निजी कुंजी को सरल **बेस64 प्रारूप** में संग्रहित किया जाता है, इसलिए वे मानव-पठनीय और पोर्टेबल हो सकते हैं. + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info की/कुंजी का प्रकार +पॉलीगॉन एज के अंदर उत्पन्न और इस्तेमाल किए गए सभी निजी की/कुंजी फ़ाइल वक्र[secp256k1](https://en.bitcoin.it/wiki/Secp256k1) के साथ ECDSA पर निर्भर हैं. + +चूंकि वक्र गैर-मानक है, इसे एनकोडिंग और किसी भी मानकीकृत PEM प्रारूप में संग्रहित नहीं किया जा सकता है. इम्पोर्ट की जाने वाली कुंजियाँ, जो इस कुंजी प्रकार के अनुरूप नहीं है, समर्थित नहीं है. +::: +## सहमति निजी की/कुंजी {#consensus-private-key} + +निजी की/कुंजी फाइल, जिसका उल्लेख *सहमति निजी कुंजी* के रूप में किया गया है, उसे **वैलिडेटर निजी कुंजी** के रूप में भी संदर्भित किया जाता है. निजी की/कुंजी का इस्तेमाल तब किया जाता है जब नोड नेटवर्क में एक वैलिडेटर के रूप में काम करता है और उसे नए डेटा को साइन करने की जरूरत होती है. + +निजी की/कुंजी फाइल `consensus/validator.key`में स्थित है और उल्लेखित की/कुंजी [प्रारूप](/docs/edge/configuration/manage-private-keys#key-format) का पालन करता है. + +:::warning +वैलिडेटर निजी की/कुंजी हर एक वैलिडेटर नोड के लिए अलग होती है. एक ही की/कुंजी को सभी वैलिडेटर के बीच साझा नहीं किया जाना चाहिए, क्योंकि ऐसा करना आपकी चेन की सुरक्षा को जोखिम में डाल सकता है. + +::: + +## नेटवर्किंग निजी की/कुंजी {#networking-private-key} + +नेटवर्किंग के लिए उल्लेख निजी की/कुंजी फाइल का इस्तेमाल libp2p द्वारा संबंधित PeerID उत्पन्न करने के लिए किया जाता है और यह नोड को नेटवर्क में भाग लेने की सुविधा देता है. + +यह `keystore/libp2p.key`में स्थित है और उल्लेखित [कुंजी प्रारूप](/docs/edge/configuration/manage-private-keys#key-format) का पालन करता है. + +## BLS गुप्त की/कुंजी {#bls-secret-key} + +BLS की गुप्त कुंजी फाइल लेयर का इस्तेमाल सामान्य सहमति परत में प्रतिबद्ध सील को शामिल करने के लिए किया जाता है. BLS द्वारा संकलित प्रतिबद्ध सील का आकार गंभीर रूप से प्रतिबद्ध ECDSA हस्ताक्षर से कम है. + +BLS फ़ीचर वैकल्पिक है और यह चयन करना संभव है कि BLS का इस्तेमाल करें या नहीं. अधिक विवरण के लिए [BLS](/docs/edge/consensus/bls) को देखें. + +## इम्पोर्ट / एक्सपोर्ट {#import-export} + +चूँकि की/कुंजी फ़ाइल को डिस्क पर सरल बेस64 में संग्रहित किया जाता है, उन्हें आसानी से बैकअप या इम्पोर्ट किया जा सकता है. + +:::caution की/कुंजी फ़ाइल को बदलना +पहले से ही स्थापित / संचालित हो रहे नेटवर्क पर की/कुंजी फ़ाइलों में किए गए किसी भी बदलाव के फलस्वरूप गंभीर नेटवर्क/सहमति व्यवधान उत्पन्न हो सकता है, चूंकि सहमति और सहकर्मी डिस्कवरी मैकेनिज्म इन की/कुंजी में नोड वाले विशेष भंडारण से निकाले गए डेटा को संग्रहित करता है और इस डेटा पर कनेक्शन शुरू करने और सहमति तर्क को पूरा करने के लिए निर्भर करता है +::: \ No newline at end of file diff --git a/archive/edge/hi-edge/configuration/prometheus-metrics.md b/archive/edge/hi-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..feeb159fc8 --- /dev/null +++ b/archive/edge/hi-edge/configuration/prometheus-metrics.md @@ -0,0 +1,35 @@ +--- +id: prometheus-metrics +title: प्रोमेथियस मैट्रिक्स +description: "पॉलीगॉन एज के लिए प्रोमेथियस मैट्रिक्स कैसे चालू करें." +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## ओवरव्यू {#overview} + +पॉलीगॉन एज प्रोमेथियस मेट्रिक्स को रिपोर्ट और सर्व कर सकता है, जिसे प्रोमेथियस कलेक्टर्स का इस्तेमाल करके इस्तेमाल किया जा सकता है. + +प्रोमेथियस मैट्रिक्स डिफ़ॉल्ट रूप से निष्क्रिय कर दिए गए हैं. कॉन्फ़िगरेशन फ़ाइल में `--prometheus` फ़्लैग या `Telemetry.prometheus` फ़ील्ड का इस्तेमाल करके श्रोता के पता निर्दिष्ट करके इसे चालू किया जा सकता है. +किसी ख़ास पते पर मेट्रिक्स को `/metrics` के तहत सर्व किया जाएगा. + +## उपलब्ध मैट्रिक्स {#available-metrics} + +निम्नलिखित मैट्रिक्स उपलब्ध हैं: + +| **नाम** | **प्रकार** | **वर्णन** | +|-----------------------------------------------|---------------|-------------------------------------------------| +| txpool_pending_transactions | गेज | TxPool में पेंडिंग ट्रांज़ैक्शन्स की संख्या | +| consensus_validators | गेज | वैलिडेटर्स की संख्या | +| consensus_rounds | गेज | राउंड्स की संख्या | +| consensus_num_txs | गेज | नए ब्लॉक में ट्रांज़ैक्शन्स की संख्या | +| consensus_block_interval | गेज | इस और आख़िरी ब्लॉक के बीच का समय (सेकंड में) | +| network_peers | गेज | कनेक्टेड पीयर्स की संख्या | +| network_outbound_connections_count | गेज | आउटबाउंड कनेक्शन्स की संख्या | +| network_inbound_connections_count | गेज | इनबाउंड कनेक्शन्स की संख्या | +| network_pending_outbound_connections_count | गेज | पेंडिंग आउटबाउंड कनेक्शन्स की संख्या | +| network_pending_inbound_connections_count | गेज | पेंडिंग इनबाउंड कनेक्शन्स की संख्या | \ No newline at end of file diff --git a/archive/edge/hi-edge/configuration/sample-config.md b/archive/edge/hi-edge/configuration/sample-config.md new file mode 100644 index 0000000000..96e05a462e --- /dev/null +++ b/archive/edge/hi-edge/configuration/sample-config.md @@ -0,0 +1,149 @@ +--- +id: sample-config +title: सर्वर कन्फिग्यरैशन फाइल +description: "कन्फिग्यरैशन फ़ाइल का इस्तेमाल करके पॉलीगॉन एज सर्वर शुरू करें." +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# सर्वर कन्फिग्यरैशन फ़ाइल {#server-configuration-file} +सर्वर को विभिन्न कॉन्फ़िगरेशन विकल्पों के साथ शुरू करने के लिए केवल झंडे का उपयोग करने के बजाय कॉन्फ़िगरेशन फ़ाइल का उपयोग किया जा सकता है. सर्वर को कॉन्फ़िगरेशन फ़ाइल के साथ शुरू करने के लिए उपयोग की जाने वाली कमांड: `polygon-edge server --config ` + +## डिफ़ॉल्ट कॉन्फ़िगरेशन के साथ कॉन्फ़िगरेशन फ़ाइल निर्यात करें {#export-config-file-with-default-configuration} +पॉलीगॉन एज सर्वर के लिए डिफ़ॉल्ट सेटिंग्स के साथ कॉन्फ़िगरेशन को `yaml`या `json`फ़ाइल प्रारूप में कॉन्फ़िग फ़ाइल में निर्यात किया जा सकता है. कॉन्फ़िगरेशन फ़ाइल का उपयोग करके सर्वर को चलाने के लिए इस फ़ाइल का उपयोग टेम्पलेट के रूप में किया जा सकता है. + +### YAML {#yaml} +To generate the config file in format कॉन्फ़िगरेशन फ़ाइल को `yaml`प्रारूप में सृजित करने के लिए: +```bash +polygon-edge server export --type yaml +``` +या सिर्फ +```bash +polygon-edge server export +``` +`default-config.yaml`नाम की कॉन्फ़िगरेशन फ़ाइल उसी डायरेक्टरी में बनाई जाएगी जिससे यह कमांड चलाया गया है. + +फ़ाइल उदाहरण: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +To generate the config file in format कॉन्फ़िगरेशन फ़ाइल को `json`प्रारूप में सृजित करने के लिए: +```bash +polygon-edge server export --type json +``` +`default-config.json`नाम की कॉन्फ़िगरेशन फ़ाइल उसी डायरेक्टरी में बनाई जाएगी जिससे यह कमांड चलाया गया है. + +फ़ाइल उदाहरण: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +इन मापदंडों का उपयोग कैसे करें, इस बारे में जानकारी प्राप्त करने के लिए [सीएलआई कमांड](/docs/edge/get-started/cli-commands) सेक्शन देखें. + +### टीपेसक्रीटप स्कीमा {#typescript-schema} + +कॉन्फ़िगरेशन फ़ाइल के लिए नमूना स्वरूप निम्न है. यह टाइपस्क्रिप्ट में गुण प्रकारों (`string`, `number`, `boolean`) को व्यक्त करने के लिए लिखा गया है, जिससे आप अपना कॉन्फ़िगरेशन प्राप्त कर सकते हैं. यह उल्लेखनीय है कि `type-fest` से `PartialDeep` प्रकार का उपयोग यह व्यक्त करने के लिए किया जाता है कि सभी गुण वैकल्पिक हैं. + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/hi-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/hi-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..feb5441bf9 --- /dev/null +++ b/archive/edge/hi-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,124 @@ +--- +id: set-up-aws-ssm +title: AWS SSM (सिस्टम मैनेजर) सेटअप करें +description: "पॉलीगॉन एज के लिए AWS SSM (सिस्टम मैनेजर) सेटअप करें." +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## ओवरव्यू {#overview} + +मौजूदा समय में, पॉलीगॉन एज का संबंध 2 प्रमुख रनटाइम सीक्रेट्स को रखने से है: +* **वैलिडेटर की निजी की नोड** द्वारा इस्तेमाल की जाती है, अगर नोड एक वैलिडेटर है तो +* अन्य पीअर्स के साथ हिस्सा लेने और कम्युनिकेशन करने के लिए, libp2p द्वारा इस्तेमाल की जाने वाली **नेटवर्किंग निजी की** + +अतिरिक्त जानकारी के लिए, कृपया [मैनेजिंग निजी की गाइड](/docs/edge/configuration/manage-private-keys) पढ़ें + +पॉलीगॉन एज के मॉड्यूल **को यह जानने की ज़रूरत नहीं होनी चाहिए कि सीक्रेट्स कैसे रखे जाते** हैं. आखिरकार, एक मॉड्यूल को परवाह नहीं करनी चाहिए कि एक दूर के सर्वर पर या स्थानीय रूप से नोड की डिस्क पर कोई सीक्रेट्स स्टोर है या नहीं. + +सीक्रेट रखने के बारे में एक मॉड्यूल को जो कुछ जानने की ज़रूरत है, वह **सीक्रेट का इस्तेमाल करना जानना** है,**, यह जानना कि कौन से सीक्रेट +प्राप्त या सेव** करने हैं. इन ऑपरेशन के बेहतर कार्यान्वयन विवरण को को डेलिगेट किया गया है,`SecretsManager` जो निश्चित रूप से एक एब्स्ट्रेक्शन है. + +पॉलीगॉन एज शुरू करने वाला नोड ऑपरेटर अब निर्दिष्ट कर सकता है कि वे किस सीक्रेट मैनेजर का इस्तेमाल करना चाहते हैं, और जैसे ही सही सीक्रेट मैनेजर शुरू हो जाता है, मॉड्यूल उल्लिखित इंटरफ़ेस के माध्यम से सीक्रेट्स से निपटते हैं, भले ही सीक्रेट डिस्क पर स्टोर हों या एक सर्वर पर. + +यह लेख, पॉलीगॉन एज को ऊपर लाने और [AWS सिस्टम मैनेजर पैरामीटर स्टोर के साथ रन करने के लिए ज़रूरी स्टेप का विवरण](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) देता है. + +:::info पिछली गाइड + +**यह सख़्त सुझाव दिया ज**ाता है कि इस लेख को पढ़ने से पहले, स्[**थानीय सेटअप और**](/docs/edge/get-started/set-up-ibft-locally) [**क्लाउड सेटअप**](/docs/edge/get-started/set-up-ibft-on-the-cloud) पर लेख पढ़े जाएँ. + +::: + + +## आवश्यक शर्तें {#prerequisites} +### IAM पॉलिसी {#iam-policy} +यूज़र को एक IAM पॉलिसी बनाने की जरूरत है जो AWS सिस्टम मैनेजर पैरामीटर स्टोर के लिए रीड/राइट ऑपरेशन की अनुमति देता है. सफलतापूर्वक IAM पॉलिसी बनाने के बाद, यूज़र को उसे पॉलीगॉन एज सर्वर को रन करने वाले EC2 इंस्टैंस में संलग्न करने की जरूरत है. IAM पॉलिसी कुछ इस तरह दिखनी चाहिए: +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +AWS SSM IAM भूमिकाओं के बारे में अधिक जानकारी [AWS डॉक्यूमेंट](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html) में मिल सकती है. + +जारी रखने से पहले आवश्यक जानकारी: +* **क्षेत्र** (वह क्षेत्र जिसमें सिस्टम मैनेजर और नोड्स होते हैं) +* **पैरामीटर पाथ** (आर्बिट्रेरी पाथ जिसमें सीक्रेट को रखा जाएगा, उदाहरण के लिए`/polygon-edge/nodes`) + +## स्टेप 1 - सीक्रेट्स मैनेजर कॉन्फ़िगरेशन जनरेट करें {#step-1-generate-the-secrets-manager-configuration} + +पॉलीगॉन एज को AWS SSM के साथ निर्बाध रूप से संचार करने में सक्षम होने के लिए, पहले से जनरेटेड कॉन्फिग फ़ाइल को पार्स करने की जरूरत है, जिसमें AWS SSM पर सीक्रेट स्टोरेज के लिए सभी आवश्यक जानकारी होती है. + +कॉन्फ़िगरेशन जनरेट करने के लिए, नीचे दिया कमांड रन करें: + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +मौजूद पैरामीटर: +* `PATH` वह पाथ है जिस पर कॉन्फ़िगरेशन फ़ाइल एक्स्पोर्ट की जानी चाहिए. डिफ़ॉल्ट `./secretsManagerConfig.json` +* `NODE_NAME`वर्तमान नोड का नाम है जिसके लिए AWS SSM कॉन्फ़िगरेशन को सेटअप किया जा रहा है. यह एक मनमानी वैल्यू हो सकती है. डिफ़ॉल्ट `polygon-edge-node` +* `REGION`वह क्षेत्र है जिसमें AWS SSM रहता है. यह वही क्षेत्र होना चाहिए जो AWS SSM का इस्तेमाल करने वाले नोड का है. +* `SSM_PARAM_PATH`उस पाथ का नाम है जिसे सीक्रेट को स्टोर किया जाएगा. उदाहरण के लिए अगर `--name node1`और `ssm-parameter-path=/polygon-edge/nodes`निर्दिष्ट किए गए हैं, तो सीक्रेट को `/polygon-edge/nodes/node1/`के रूप में स्टोर किया जाएगा + +:::caution नोड के नाम +नोड के नाम निर्दिष्ट करते समय सावधान रहें. + +पॉलीगॉन एज, निर्दिष्ट नोड नाम का इस्तेमाल, उन सीक्रेट्स को ट्रैक करने के लिए करता है जिसे यह AWS SSM पर जनरेट और इस्तेमाल करता है. पहले से मौजूद नोड नाम को निर्दिष्ट करने पर AWS SSM में सीक्रेट लिखने में विफलता का सामना करना पड़ सकता है. + +सीक्रेट्स नीचे दिए गए बेस पाथ पर स्टोर किए गए हैं`SSM_PARAM_PATH/NODE_NAME`: + +::: + +## स्टेप 2 - कॉन्फ़िगरेशन का इस्तेमाल करके सीक्रेट की शुरू करें {#step-2-initialize-secret-keys-using-the-configuration} + +अब जबकि कॉन्फ़िगरेशन फ़ाइल मौजूद है, हम का इस्तेमाल करके स्टेप 1 में कॉन्फ़िगरेशन फ़ाइल के साथ आवश्यक सीक्रेट की को शुरू कर सकते हैं`--config`: + +```bash +polygon-edge secrets init --config +``` + + `PATH`परम स्टेप 1 से पहले जनरेट किए गए सीक्रेट्स मैनेजर परम की लोकेशन है. + +:::info IAM पॉलिसी +स्टेप विफल हो जाएगा अगर रीड/राइट ऑपरेशन की अनुमति देने वाली IAM पॉलिसी, सही ढंग से कॉन्फ़िगर नहीं होती है और / या इस कमांड को रन करने वाले EC2 इंस्टैंस से संलग्न नहीं है. +::: + +## स्टेप 3 - जेनेसिस फ़ाइल जनरेट करें {#step-3-generate-the-genesis-file} + +जेनेसिस फ़ाइल [**को स्थानीय सेटअप**](/docs/edge/get-started/set-up-ibft-locally) +और [**क्लाउड सेटअप**](/docs/edge/get-started/set-up-ibft-on-the-cloud), मामूली बदलावों के साथ गाइड करता है. + +चूँकि स्थानीय फ़ाइल सिस्टम के बजाय AWS SSM का इस्तेमाल किया जा रहा है, इसलिए वैलिडेटर पते को `--ibft-validator`फ़्लैग के माध्यम से जोड़ा जाना चाहिए: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## स्टेप 4 - पॉलीगॉन एज क्लाइंट शुरू करें {#step-4-start-the-polygon-edge-client} + +अब जब की सेट अप हो गई हैं, और जेनेसिस फ़ाइल जनरेट हो गई है, तो इस प्रक्रिया का आखिरी स्टेप पॉलीगॉन एज को क`server`मांड के साथ शुरू करना होगा. + + `server`कमांड का इस्तेमाल उसी तरीके से किया जाता है जैसे कि पहले बताए गई गाइडों में, मामूली जोड़ के साथ - फ़्लैग`--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + + `PATH`परम स्टेप 1 से पहले जनरेट किए गए सीक्रेट्स मैनेजर परम की लोकेशन है. \ No newline at end of file diff --git a/archive/edge/hi-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/hi-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..ea85259f90 --- /dev/null +++ b/archive/edge/hi-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,110 @@ +--- +id: set-up-gcp-secrets-manager +title: GCP सीक्रेट मैनेजर सेट अप करें +description: "पॉलीगॉन एज के लिए GCP सीक्रेट मैनेजर सेट अप करें." +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## ओवरव्यू {#overview} + +मौजूदा समय में, पॉलीगॉन एज का संबंध 2 प्रमुख रनटाइम सीक्रेट्स को रखने से है: +* **वैलिडेटर की निजी की नोड** द्वारा इस्तेमाल की जाती है, अगर नोड एक वैलिडेटर है तो +* अन्य पीअर्स के साथ हिस्सा लेने और कम्युनिकेशन करने के लिए, libp2p द्वारा इस्तेमाल की जाने वाली **नेटवर्किंग निजी की** + +अतिरिक्त जानकारी के लिए, कृपया [मैनेजिंग निजी की गाइड](/docs/edge/configuration/manage-private-keys) पढ़ें + +पॉलीगॉन एज के मॉड्यूल **को यह जानने की ज़रूरत नहीं होनी चाहिए कि सीक्रेट्स कैसे रखे जाते** हैं. आखिरकार, एक मॉड्यूल को परवाह नहीं करनी चाहिए कि एक दूर के सर्वर पर या स्थानीय रूप से नोड की डिस्क पर कोई सीक्रेट्स स्टोर है या नहीं. + +सीक्रेट रखने के बारे में एक मॉड्यूल को जो कुछ जानने की ज़रूरत है, वह **सीक्रेट का इस्तेमाल करना जानना** है,**, यह जानना कि कौन से सीक्रेट +प्राप्त या सेव** करने हैं. इन ऑपरेशन के बेहतर कार्यान्वयन विवरण को को डेलिगेट किया गया है,`SecretsManager` जो निश्चित रूप से एक एब्स्ट्रेक्शन है. + +पॉलीगॉन एज शुरू करने वाला नोड ऑपरेटर अब निर्दिष्ट कर सकता है कि वे किस सीक्रेट मैनेजर का इस्तेमाल करना चाहते हैं, और जैसे ही सही सीक्रेट मैनेजर शुरू हो जाता है, मॉड्यूल उल्लिखित इंटरफ़ेस के माध्यम से सीक्रेट्स से निपटते हैं, भले ही सीक्रेट डिस्क पर स्टोर हों या एक सर्वर पर. + +यह लेख पॉलीगॉन एज को ऊपर लाने और [GCP सीक्रेट मैनेजर](https://cloud.google.com/secret-manager) के साथ रन करने के लिए ज़रूरी स्टेप का विवरण देता है. + +:::info पिछली गाइड + +**यह सख़्त सुझाव दिया ज**ाता है कि इस लेख को पढ़ने से पहले, स्[**थानीय सेटअप और**](/docs/edge/get-started/set-up-ibft-locally) [**क्लाउड सेटअप**](/docs/edge/get-started/set-up-ibft-on-the-cloud) पर लेख पढ़े जाएँ. + +::: + + +## आवश्यक शर्तें {#prerequisites} +### GCP बिलिंग अकाउंट {#gcp-billing-account} +GCP सीक्रेट्स मैनेजर का इस्तेमाल करने के लिए, यूज़र के पास GCP पोर्टल पर [बिलिंग अकाउंट](https://console.cloud.google.com/) सक्षम होना चाहिए. +फ़्री ट्रायल के बादशाह के रूप में, GCP प्लेटफ़ॉर्म पर नए Google अकाउंट को चालू करने के लिए कुछ फ़ंड दिए जाते है. [GCP डॉक्यूमेंट](https://cloud.google.com/free) की जानकारी अधिक + +### सीक्रेट्स मैनेजर API {#secrets-manager-api} +यूज़र को GCP सीक्रेट मैनेजर API का इस्तेमाल करने से पहले उसे सक्षम करना होगा. +ऐसा [सीक्रेट्स मैनेजर API पोर्टल](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com) के ज़रिए किया जा सकता है. +अधिक जानकारी: [सीक्रेट मैनेजर कॉन्फ़िगर करना](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + +### GCP क्रेडेंशियल्स {#gcp-credentials} +अंत में, यूज़र को प्रमाणीकरण के लिए इस्तेमाल किए जाने वाले नए क्रेडेंशियल्स जनरेट करने की ज़रूरत होती है. [यहाँ ](https://cloud.google.com/secret-manager/docs/reference/libraries)पोस्ट किए गए निर्देशों का पालन करके ऐसा किया जा सकता है. +जनरेट की गई json फ़ाइल जिसमें क्रेडेंशियल्स हैं, को हर एक नोड में ट्रांसफ़र किया जाना चाहिए जिसे GCP सीक्रेट मैनेजर का इस्तेमाल करने की आवश्यकता है. + +जारी रखने से पहले आवश्यक जानकारी: +* **प्रोजेक्ट ID** (प्रोजेक्ट को GCP प्लेटफ़ॉर्म पर परिभाषित किया गया है) +* **क्रेडेंशियल फ़ाइल लोकेशन** (क्रेडेंशियल युक्त json फ़ाइल का पाथ) + +## स्टेप 1 - सीक्रेट्स मैनेजर कॉन्फ़िगरेशन जनरेट करें {#step-1-generate-the-secrets-manager-configuration} + +पॉलीगॉन एज GCP SM के साथ निर्बाध रूप से संचार करने में सक्षम होने के लिए, इसे पहले से जेनरेट की गई कॉन्फ़िगरेशन फ़ाइल को पार्स करने की आवश्यकता है, जिसमें GCP SM पर सीक्रेट स्टोरेज के लिए सभी आवश्यक जानकारी शामिल है. + +कॉन्फ़िगरेशन जनरेट करने के लिए, नीचे दिया कमांड रन करें: + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +मौजूद पैरामीटर: +* `PATH` वह पाथ है जिस पर कॉन्फ़िगरेशन फ़ाइल एक्स्पोर्ट की जानी चाहिए. डिफ़ॉल्ट `./secretsManagerConfig.json` +* `NODE_NAME` मौजूदा नोड का नाम है जिसके लिए GCP SM कॉन्फ़िगरेशन को सेट किया जा रहा है. यह एक मनमानी वैल्यू हो सकती है. डिफ़ॉल्ट `polygon-edge-node` +* `PROJECT_ID` उस प्रोजेक्ट की ID है जिसे यूज़र ने अकाउंट सेटअप और सीक्रेट्स मैनेजर API एक्टिवेशन के दौरान GCP कंसोल में स्पष्ट किया है. +* `GCP_CREDS_FILE` json फ़ाइल का पाथ है जिसमें क्रेडेंशियल्स हैं जो सीक्रेट मैनेजर को पढ़ने/लिखने की अनुमति देगा. + +:::caution नोड के नाम +नोड के नाम निर्दिष्ट करते समय सावधान रहें. + +पॉलीगॉन एज निर्दिष्ट नोड नाम का इस्तेमाल उन सीक्रेट्स को ट्रैक करने के लिए करता है जिसे यह GCP SM पर जनरेट और इस्तेमाल करता है. किसी मौजूदा नोड नाम को निर्दिष्ट करने से GCP SM को सीक्रेट रूप से लिखने में विफल होने जैसे परिणाम हो सकते हैं. + +सीक्रेट्स नीचे दिए गए बेस पाथ पर स्टोर किए गए हैं: `projects/PROJECT_ID/NODE_NAME` + +::: + +## स्टेप 2 - कॉन्फ़िगरेशन का इस्तेमाल करके सीक्रेट की शुरू करें {#step-2-initialize-secret-keys-using-the-configuration} + +अब जबकि कॉन्फ़िगरेशन फ़ाइल मौजूद है, हम का इस्तेमाल करके स्टेप 1 में कॉन्फ़िगरेशन फ़ाइल के साथ आवश्यक सीक्रेट की को शुरू कर सकते हैं`--config`: + +```bash +polygon-edge secrets init --config +``` + +`PATH`परम स्टेप 1 से पहले जनरेट किए गए सीक्रेट्स मैनेजर परम की लोकेशन है. + +## स्टेप 3 - जेनेसिस फ़ाइल जनरेट करें {#step-3-generate-the-genesis-file} + +जेनेसिस फ़ाइल [**को स्थानीय सेटअप**](/docs/edge/get-started/set-up-ibft-locally) +और [**क्लाउड सेटअप**](/docs/edge/get-started/set-up-ibft-on-the-cloud) गाइड के समान मामूली बदलावों के साथ जनरेट किया जाना चाहिए. + +चूँकि स्थानीय फ़ाइल सिस्टम के बजाय GCP SM को इस्तेमाल किया जा रहा है, वैलिडेटर पते को `--ibft-validator` फ़्लैग के माध्यम से जोड़ा जाना चाहिए: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## स्टेप 4 - पॉलीगॉन एज क्लाइंट शुरू करें {#step-4-start-the-polygon-edge-client} + +अब जब की सेट अप हो गई हैं, और जेनेसिस फ़ाइल जनरेट हो गई है, तो इस प्रक्रिया का आखिरी स्टेप पॉलीगॉन एज को क`server`मांड के साथ शुरू करना होगा. + + `server`कमांड का इस्तेमाल उसी तरीके से किया जाता है जैसे कि पहले बताए गई गाइडों में, मामूली जोड़ के साथ - फ़्लैग`--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + + `PATH`परम स्टेप 1 से पहले जनरेट किए गए सीक्रेट्स मैनेजर परम की लोकेशन है. \ No newline at end of file diff --git a/archive/edge/hi-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/hi-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..7ece9a0a01 --- /dev/null +++ b/archive/edge/hi-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,108 @@ +--- +id: set-up-hashicorp-vault +title: Hashicorp वॉल्ट सेट अप करें +description: "पॉलीगॉन एज के लिए Hashicorp वॉल्ट सेट अप करें." +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## ओवरव्यू {#overview} + +मौजूदा समय में, पॉलीगॉन एज का संबंध 2 प्रमुख रनटाइम सीक्रेट्स को रखने से है: +* **वैलिडेटर की निजी की नोड** द्वारा इस्तेमाल की जाती है, अगर नोड एक वैलिडेटर है तो +* अन्य पीअर्स के साथ हिस्सा लेने और कम्युनिकेशन करने के लिए, libp2p द्वारा इस्तेमाल की जाने वाली **नेटवर्किंग निजी की** + +:::warning +वैलिडेटर निजी की हर एक वैलिडेटर नोड के लिए अलग होती है. एक ही की को सभी वैलिडेटर के बीच साझा नहीं किया जाना चाहिए, क्योंकि ऐसा करना आपकी चेन की सुरक्षा से समझौता हो सकता है. + +::: + +अतिरिक्त जानकारी के लिए, कृपया [मैनेजिंग निजी की गाइड](/docs/edge/configuration/manage-private-keys) पढ़ें + +पॉलीगॉन एज के मॉड्यूल **को यह जानने की ज़रूरत नहीं होनी चाहिए कि सीक्रेट्स कैसे रखे जाते** हैं. आखिरकार, एक मॉड्यूल को परवाह नहीं करनी चाहिए कि एक दूर के सर्वर पर या स्थानीय रूप से नोड की डिस्क पर कोई सीक्रेट्स स्टोर है या नहीं. + +सीक्रेट रखने के बारे में एक मॉड्यूल को जो कुछ जानने की ज़रूरत है, वह **सीक्रेट का इस्तेमाल करना जानना** है,**, यह जानना कि कौन से सीक्रेट +प्राप्त या सेव** करने हैं. इन ऑपरेशन के बेहतर कार्यान्वयन विवरण को को डेलिगेट किया गया है,`SecretsManager` जो निश्चित रूप से एक एब्स्ट्रेक्शन है. + +पॉलीगॉन एज शुरू करने वाला नोड ऑपरेटर अब निर्दिष्ट कर सकता है कि वे किस सीक्रेट मैनेजर का इस्तेमाल करना चाहते हैं, और जैसे ही सही सीक्रेट मैनेजर शुरू हो जाता है, मॉड्यूल उल्लिखित इंटरफ़ेस के माध्यम से सीक्रेट्स से निपटते हैं, भले ही सीक्रेट डिस्क पर स्टोर हों या एक सर्वर पर. + +यह लेख पॉलीगॉन एज को ऊपर लाने और [Hashicorp वॉल्ट](https://www.vaultproject.io/) सर्वर के साथ रन करने के लिए ज़रूरी स्टेप का विवरण देता है. + +:::info पिछली गाइड + +**यह सख़्त सुझाव दिया ज**ाता है कि इस लेख को पढ़ने से पहले, स्[**थानीय सेटअप और**](/docs/edge/get-started/set-up-ibft-locally) [**क्लाउड सेटअप**](/docs/edge/get-started/set-up-ibft-on-the-cloud) पर लेख पढ़े जाएँ. + +::: + + +## आवश्यक शर्तें {#prerequisites} + +यह लेख मानता है कि Hashicorp वॉल्ट सर्वर का कार्यशील उदाहरण **पहले से ही सेट अप है**. + +इसके अलावा, यह आवश्यक है कि पॉलीगॉन एज के लिए इस्तेमाल किए जा रहे Hashicorp वॉल्ट सर्वर में **KV स्टोरेज को सक्षम किया जाना चाहिए**. + +जारी रखने से पहले आवश्यक जानकारी: +* **सर्वर URL** (Hashicorp Vault सर्वर का API URL) +* **टोकन** (KV स्टोरेज इंजन के एक्सेस के लिए इस्तेमाल किया जाने वाला एक्सेस टोकन) + +## स्टेप 1 - सीक्रेट्स मैनेजर कॉन्फ़िगरेशन जनरेट करें {#step-1-generate-the-secrets-manager-configuration} + +पॉलीगॉन एज के लिए वॉल्ट सर्वर के साथ निर्बाध रूप से कम्युनिकेट करने में सक्षम होने के लिए, इसे पहले से जनरेट की गई कॉन्फ़िगरेशन फ़ाइल को पार्स करने की ज़रूरत होती है, जिसमें वॉल्ट पर सीक्रेट स्टोरेज के लिए सभी आवश्यक जानकारी होती है. + +कॉन्फ़िगरेशन जनरेट करने के लिए, नीचे दिया कमांड रन करें: + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +मौजूद पैरामीटर: +* `PATH` वह पाथ है जिस पर कॉन्फ़िगरेशन फ़ाइल एक्स्पोर्ट की जानी चाहिए. डिफ़ॉल्ट `./secretsManagerConfig.json` +* `TOKEN` [आवश्यक शर्तें सेक्शन](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) में पहले से बताया गया एक्सेस टोकन है +* `SERVER_URL` वॉल्ट सर्वर के लिए API का URL है, जिसका उल्लेख [आवश्यक शर्तें सेक्शन में भी किया गया है](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `NODE_NAME` उस मौजूदा नोड का नाम है जिसके लिए वॉल्ट कॉन्फ़िगरेशन को सेट अप किया जा रहा है. यह एक मनमानी वैल्यू हो सकती है. डिफ़ॉल्ट `polygon-edge-node` + +:::caution नोड के नाम +नोड के नाम निर्दिष्ट करते समय सावधान रहें. + +पॉलीगॉन एज निर्दिष्ट नोड नाम का इस्तेमाल उन सीक्रेट्स को ट्रैक करने के लिए करता है जिसे यह वॉल्ट इंस्टेंस पर जनरेट और इस्तेमाल करता है. मौजूदा नोड नाम निर्दिष्ट करने से वॉल्ट सर्वर पर डेटा ओवरराइट होनें जैसा परिणाम हो सकता है. + +सीक्रेट्स नीचे दिए गए बेस पाथ पर स्टोर किए गए हैं: `secrets/node_name` + +::: + +## स्टेप 2 - कॉन्फ़िगरेशन का इस्तेमाल करके सीक्रेट की शुरू करें {#step-2-initialize-secret-keys-using-the-configuration} + +अब जबकि कॉन्फ़िगरेशन फ़ाइल मौजूद है, हम का इस्तेमाल करके स्टेप 1 में कॉन्फ़िगरेशन फ़ाइल के साथ आवश्यक सीक्रेट की को शुरू कर सकते हैं`--config`: + +```bash +polygon-edge secrets init --config +``` + +`PATH`परम स्टेप 1 से पहले जनरेट किए गए सीक्रेट्स मैनेजर परम की लोकेशन है. + +## स्टेप 3 - जेनेसिस फ़ाइल जनरेट करें {#step-3-generate-the-genesis-file} + +जेनेसिस फ़ाइल [**को स्थानीय सेटअप**](/docs/edge/get-started/set-up-ibft-locally) +और [**क्लाउड सेटअप**](/docs/edge/get-started/set-up-ibft-on-the-cloud) गाइड के समान मामूली बदलावों के साथ जनरेट किया जाना चाहिए. + +चूँकि स्थानीय फ़ाइल सिस्टम के बजाय Hashicorp वॉल्ट को इस्तेमाल किया जा रहा है, वैलिडेटर पते को `--ibft-validator` फ़्लैग के माध्यम से जोड़ा जाना चाहिए: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## स्टेप 4 - पॉलीगॉन एज क्लाइंट शुरू करें {#step-4-start-the-polygon-edge-client} + +अब जब की सेट अप हो गई हैं, और जेनेसिस फ़ाइल जनरेट हो गई है, तो इस प्रक्रिया का आखिरी स्टेप पॉलीगॉन एज को क`server`मांड के साथ शुरू करना होगा. + + `server`कमांड का इस्तेमाल उसी तरीके से किया जाता है जैसे कि पहले बताए गई गाइडों में, मामूली जोड़ के साथ - फ़्लैग`--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + + `PATH`परम स्टेप 1 से पहले जनरेट किए गए सीक्रेट्स मैनेजर परम की लोकेशन है. \ No newline at end of file diff --git a/archive/edge/hi-edge/consensus/bls.md b/archive/edge/hi-edge/consensus/bls.md new file mode 100644 index 0000000000..501ffa1fbb --- /dev/null +++ b/archive/edge/hi-edge/consensus/bls.md @@ -0,0 +1,144 @@ +--- +id: bls +title: BLS +description: "BLS मोड के बारे में स्पष्टीकरण और निर्देश." +keywords: + - docs + - polygon + - edge + - bls +--- + +## ओवरव्यू {#overview} + +BLS को Boneh–Lynn–Shacham (BLS) के रूप में भी जाना जाता है, एक क्रिप्टोग्राफिक सिग्नेचर स्कीम है जो एक यूजर को यह सत्यापित करने की अनुमति देती है कि signer सत्यापित हो जाए. यह एक सिग्नेचर स्कीम है जो एकाधिक हस्ताक्षर को एकत्रित कर सकती है. पॉलीगॉन एज में, IBFT सहमति मोड में बेहतर सुरक्षा प्रदान करने के लिए, डिफॉल्ट द्वारा BLS को इस्तेमाल किया जाता है. BLS सिग्नेचर्स को एक सिंगल बाइट ऐरे में शामिल कर सकता है और ब्लॉक के हेडर के आकार को कम करता है. हर चेन चुन सकती है कि उसे BLS का इस्तेमाल करना है या नहीं. ECDSA की का इस्तेमाल किया जाता है, चाहे वह BLS मोड में सक्षम हो या न हो. + +## वीडियो प्रेजेंटेशन {#video-presentation} + +[![bls वीडियो](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## कैसे BLS का इस्तेमाल करके एक नई चेन को सेटअप करें {#how-to-setup-a-new-chain-using-bls} + +सेटअप के विस्तृत निर्देश पाने के लिए [स्थानीय सेटअप](/docs/edge/get-started/set-up-ibft-locally) / [क्लाउड सेटअप](/docs/edge/get-started/set-up-ibft-on-the-cloud) सेक्शन्स देखें. + +## एक मौजूदा ECDSA PoA चेन को BLS PoA चेन में कैसे माइग्रेट करें {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +यह सेक्शन बताता है कि BLS मोड को, पहले से मौजूद PoA चेन में कैसे इस्तेमाल करें. +PoA चेन में BLS चालू करने के लिए निम्नलिखित स्टेप्स की आवश्यकता होती है. + +1. सभी नोड्स को रोकें +2. वैलिडेटर्स के लिए BLS की जनरेट करें +3. genesis.json में एक फ़ोर्क सेटिंग जोड़ें +4. सभी नोड्स को फिर से शुरू करें + +### 1. सभी नोड्स रोकें {#1-stop-all-nodes} + +Ctrl + c (कंट्रोल + c) को दबा कर वैलिडेटर्स की सभी प्रक्रियाओं को टर्मिनेट करें. कृपया, ब्लॉक की नवीनतम ऊँचाई याद रखें (ब्लॉक के प्रतिबद्ध लॉग में जो क्रमांक संख्या सबसे अधिक है). + +### 2. BLS की को जनरेट करें {#2-generate-the-bls-key} + +`--bls` के साथ `secrets init` BLS की को जनरेट करता है. मौजूदा ECDSA और नेटवर्क की को रखने और एक नई BLS की जोड़ने के लिए, `--ecdsa` और `--network` को अक्षम करने की ज़रूरत होती है. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. फ़ोर्क सेटिंग जोड़ें {#3-add-fork-setting} + +`ibft switch` कमांड एक फ़ोर्क सेटिंग जोड़ता है, जो मौजूदा चेन में BLS को `genesis.json` में सक्षम बनाता है . + +PA नेटवर्क के लिए, कमांड में वैलिडेटर्स दिए जाने चाहिए. जैसा कि `genesis` कमांड के साथ होता है, `--ibft-validators-prefix-path` या `--ibft-validator` फ्लैग का इस्तेमाल वैलिडेटर को निर्दिष्ट करने के लिए किया जा सकता है. + +उस ऊँचाई को निर्दिष्ट करें जिससे चेन `--from` फ्लैग के साथ BLS का इस्तेमाल शुरू करती है. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. सभी नोड फिर से शुरू करें {#4-restart-all-nodes} + +`server` कमांड द्वारा सभी नोड्स को फिर से शुरू करें. पिछले स्टेप में निर्दिष्ट `from` ब्लॉक का निर्माण होने के बाद, चेन BLS को सक्षम बनाता है और नीचे दिए गए रूप में लॉग दिखाता है: + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +साथ ही लॉग यह भी दिखाता है कि ब्लॉक बनने के बाद प्रत्येक ब्लॉक को जनरेट करने के लिए किस सत्यापन मोड का इस्तेमाल किया जाता है. + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## एक मौजूदा ECDSA PoS चेन को BLS PoS चेन में कैसे माइग्रेट करें {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +यह सेक्शन बताता है कि मौजूदा PoS चेन में BLS मोड का इस्तेमाल कैसे किया जाए. +PoS चेन में BLS चालू करने के लिए निम्नलिखित स्टेप्स की आवश्यकता होती है. + +1. सभी नोड्स को रोकें +2. वैलिडेटर्स के लिए BLS की जनरेट करें +3. genesis.json में एक फ़ोर्क सेटिंग जोड़ें +4. BLS पब्लिक की को रजिस्टर करने के लिए स्टैकिंग कॉन्ट्रैक्ट को कॉल करें +5. सभी नोड्स को दोबारा शुरू करें + +### 1. सभी नोड्स रोकें {#1-stop-all-nodes-1} + +Ctrl + c (कंट्रोल + c) को दबा कर वैलिडेटर्स की सभी प्रक्रियाओं को टर्मिनेट करें. कृपया, ब्लॉक की नवीनतम ऊँचाई याद रखें (ब्लॉक के प्रतिबद्ध लॉग में जो क्रमांक संख्या सबसे अधिक है). + +### 2. BLS की को जनरेट करें {#2-generate-the-bls-key-1} + +`secrets init`, `--bls` फ्लैग के साथ BLS की जनरेट करता है. मौजूदा ECDSA और नेटवर्क की को रखने के लिए और एक नई BLS की, जोड़ने के लिए, `--ecdsa` और `--network` को अक्षम करने की ज़रूरत होती है. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. फ़ोर्क सेटिंग जोड़ें {#3-add-fork-setting-1} + +`ibft switch` कमांड एक फ़ोर्क सेटिंग जोड़ता है, जो `genesis.json` में चेन के बीच में से BLS को सक्षम बनाता है . + +उस ऊँचाई को निर्दिष्ट करें जिससे चेन `from` फ्लैग के साथ BLS मोड का इस्तेमाल शुरू करती है, और जिस ऊँचाई पर कॉन्ट्रैक्ट को `development`फ्लैग के साथ अपडेट किया जाता है. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. स्टेकिंग कॉन्ट्रैक्ट में BLS की सार्वजनिक की रजिस्टर करें {#4-register-bls-public-key-in-staking-contract} + +फ़ोर्क को जोड़ने और वैलिडेटर्स को फिर से शुरू करने के बाद, हर वैलिडेटर को BLS की सार्वजनिक की को रजिस्टर करने के लिए स्टेकिंग कॉन्ट्रैक्ट में `registerBLSPublicKey` को कॉल करना पड़ता है. इसे अवश्य ही `--deployment`में निर्दिष्ट ऊँचाई के बाद और `--from`में निर्दिष्ट ऊँचाई के पहले किया जाना चाहिए. + +BLS सार्वजनिक की को रजिस्टर करने की स्क्रिप्ट को [स्टेकिंग स्मार्ट कॉन्ट्रैक्ट रेपो](https://github.com/0xPolygon/staking-contracts) में परिभाषित किया गया है. + +`.env` फ़ाइल में रजिस्टर होने के लिए `BLS_PUBLIC_KEY` को सेट करें. अन्य पैरामीटर्स के बारे में अधिक विवरण के लिए, [pos-stake-unstake](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) का संदर्भ लें. + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +निम्न कमांड, `.env` में दी गई BLS की सार्वजानिक की को कॉन्ट्रैक्ट में रजिस्टर्ड करता है. + +```bash +npm run register-blskey +``` + +:::warning वैलिडेटर्स को BLS सार्वजनिक की को मैन्युअल रूप से रजिस्टर करने की ज़रूरत होती है + +BLS मोड में, अवश्य ही वैलिडेटर्स का अपना पता और BLS की सार्वजनिक की होनी चाहिए. सहमति की लेयर उन वैलिडेटर्स को नज़रअंदाज करती है जिन्होंने कॉन्ट्रैक्ट में BLS की सार्वजनिक की को तब तक रजिस्टर नहीं कराया होता, जब सहमति कॉन्ट्रैक्ट से वैलिडेटर की जानकारी हासिल कर रही होती है. + +::: + +### 5. सभी नोड्स दोबारा शुरू करें {#5-restart-all-nodes} + +`server` कमांड द्वारा सभी नोड्स को दोबारा शुरू करें. पिछली स्टेप में निर्दिष्ट `from` पर ब्लॉक बनाने के बाद चेन, BLS को सक्षम बनाती है. diff --git a/archive/edge/hi-edge/consensus/migration-to-pos.md b/archive/edge/hi-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..961df030e3 --- /dev/null +++ b/archive/edge/hi-edge/consensus/migration-to-pos.md @@ -0,0 +1,41 @@ +--- +id: migration-to-pos +title: PoA से PoS में माइग्रेशन +description: "PoA से PoS IBFT मोड में माइग्रेट कैसे करें और इसके विपरीत कैसे करें." +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## ओवरव्यू {#overview} + +रन कर रहे क्लस्टर के लिए - ब्लॉकचेन को रीसेट करने की आवश्यकता के बिना, यह सेक्शन आपको PoA से PoS IBFT मोड में माइग्रेशन के ज़रिए गाइड करता है, और इसके विपरीत प्रक्रिया को समझता है. + +## PoS में माइग्रेट कैसे करें {#how-to-migrate-to-pos} + +आपको सभी नोड्स को बंद करना होगा, `ibft switch` कमांड द्वारा जेनेसिस. json में फ़ोर्क कॉन्फ़िगरेशन जोड़ना होगा और नोड्स को रीस्टार्ट करना होगा. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution ECDSA का इस्तेमाल करते समय स्विच करना +ECDSA का इस्तेमाल करते समय, `--ibft-validator-type`फ्लैग को स्विच में जोड़ा जाना चाहिए, जिसमें उल्लेख किया गया है कि ECDSA का इस्तेमाल किया जाता है. अगर शामिल नहीं किया जाता है, तो एज स्वतः BLS में स्विच हो जाएगा. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::PoS में स्विच करने के लिए, आपको 2 ब्लॉक की ऊंचाई: `deployment`और . स्टेकिंग कॉन्ट्रैक्ट को तैनात करने के लिए ऊंचाई `from``deployment`है और PoS की शुरुआत की ऊंचाई `from`है. स्टेकिंग कॉन्ट्रैक्ट को `deployment` के पते `0x0000000000000000000000000000000000001001` पर डिप्लॉय किया जाएगा, जैसा कि पहले डिप्लॉय किए गए कॉन्ट्रैक्ट के मामले में होता है. + +स्टेकिंग कॉन्ट्रैक्ट के बारे में अधिक जानकारी के लिए कृपया [प्रूफ़ ऑफ़ स्टेक](/docs/edge/consensus/pos-concepts) देखें. + +:::warning वैलिडेटर्स को मैन्युअल से स्टेक करना होगा + +PoS की शुरुआत में एक वैलिडेटर बनने के लिए `deployment`और `from` से पहले कॉन्ट्रैक्ट के बाद हर एक वैलिडेटर को स्टेक करने की ज़रूरत होती है. हर एक वैलिडेटर PoS की शुरुआत में स्टेकिंग कॉन्ट्रैक्ट में सेट द्वारा सेट किए गए अपने वैलिडेटर को अपडेट करेगा. + +स्टेकिंग के बारे में और जानने के लिए, **[सेट अप पर जाएँ और स्टेक के प्रूफ़ को इस्तेमाल करें](/docs/edge/consensus/pos-stake-unstake)**. + +::: diff --git a/archive/edge/hi-edge/consensus/poa.md b/archive/edge/hi-edge/consensus/poa.md new file mode 100644 index 0000000000..3b4365200e --- /dev/null +++ b/archive/edge/hi-edge/consensus/poa.md @@ -0,0 +1,103 @@ +--- +id: poa +title: अथॉरिटी का सबूत (PoA) +description: "प्रूफ ऑफ़ स्टेक की व्याख्या और निर्देश." +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## ओवरव्यू {#overview} + +IBFT PoA पॉलीगॉन एज में डिफ़ॉल्ट सहमति मैकेनिज्म है. PoA में, वैलिडेटर ब्लॉक बनाने और उन्हें श्रृंखला में ब्लॉकचेन में जोड़ने के लिए जिम्मेदार हैं. + +सभी वैलिडेटर एक गतिशील वैलिडेटर समूह बनाता हैं, जहां वैलिडेटर को वोटिंग मैकेनिज्म की मदद से समूह में जोड़ा या हटा दिया जा सकता है. इसका मतलब यह है कि वैलिडेटर द्वारा वैलिडेटर-समूह से अंदर/बाहर मतदान किया जा सकता है, यदि वैलिडेटर नोड्स का बहुमत (51%) समूह में/से एक निश्चित वैलिडेटर को जोड़ने/छोड़ने के लिए वोट देता है. इस तरह, दुर्भावनापूर्ण वैलिडेटर को नेटवर्क से पहचाना और हटाया जा सकता है, जबकि नेटवर्क में नए विश्वसनीय वैलिडेटर जोड़े जा सकते हैं. + +सभी वैलिडेटर बारी-बारी से अगले ब्लॉक (राउंड-रोबिन) का प्रस्ताव देते हैं और जिस ब्लॉक को ब्लॉकचेन में सत्यापित/प्रविष्ट कराया जाना होता है, उसे वैलिडेटर की अधिसंख्यता (2/3 से अधिक) को उक्त ब्लॉक को मंजूरी देनी चाहिए. + +वैलिडेटर के अलावा, नॉन-वैलिडेटर हैं जो ब्लॉक निर्माण में शामिल नहीं होंते हैं, लेकिन ब्लॉक वैलिडेशन प्रक्रिया में शामिल होते हैं. + +## वैलिडेटर समूह में वैलिडेटर को जोड़ना {#adding-a-validator-to-the-validator-set} + +गाइड 4 वैलिडेटर नोड के साथ एक नए वैलिडेटर नोड को IBFT नेटवर्क में जोड़ने का तरीका बताता है. अगर आपको नेटवर्क स्थापित करने में मदद की जरूरत है तो [स्थानीय सेटअप](/edge/get-started/set-up-ibft-locally.md) / [क्लाउड सेटअप](/edge/get-started/set-up-ibft-on-the-cloud.md) सेक्शन को संदर्भित करता है. + +### स्टेप 1: IBFT के लिए डेटा फ़ोल्डर को इनिशियलाइज करें और नए नोड के लिए वैलिडेटर कीस/कुँजियों को उत्पन्न करें {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +नए नोड पर IBFT के साथ तैयार होने और संचालित होने के लिए, आपको डेटा फ़ोल्डर को इनिशियलाइज करने और कीज/कुँजियों को उत्पन्न करने की जरूरत है: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +कमांड वैलिडेटर की/कुंजी (पता) और आईडी नोड आईडी को मुद्रित करेगा. अगले स्टेप के लिए आपको वैलिडेटर की/कुंजी (पते) की जरूरत होगी. + +### स्टेप 2: दूसरे वैलिडेटर नोड से एक उम्मीदवार को प्रोपोज करें {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +एक नोड के वैलिडेटर बनने के लिए कम से कम 51% वैलिडेटर को उसका प्रस्ताव देना होगा . + +grpc पता:127.0.0.1:10000 पर एक नए वैलिडेटर नोड को `0x8B15464F8233F718c8605B16eBADA6fc09181fC2`एक मौजूदा वैलिडेटर से प्रस्तावित करने का उदाहरण: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +IBFT कमांड की संरचना को [CLI कमांड](/docs/edge/get-started/cli-commands) सेक्शन में कवर किया गया है. + +:::info BLS सार्वजानिक की/कुंजी +BLS की/मुख्य रूप से जरूरी है अगर नेटवर्क BLS के साथ भाग रहा है, क्योंकि BLS `--bls`मोड में नेटवर्क नहीं चल रहा है/ +::: + +### स्टेप 3: नोड रन क्लाइंट {#step-3-run-the-client-node} + +चूंकि इस उदाहरण में हम नेटवर्क को रन करने का प्रयास कर रहे हैं जहां सभी नोड एक ही मशीन पर हैं, हमें पोर्ट परस्पर विरोधी से बचने के लिए ध्यान + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +ब्लॉक को लाने के बाद, आप कंसोल के अंदर ध्यान देंगे कि एक नोड वैलिडेशन में भाग ले रहा है + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info वैलिडेटर में एक non-validator को प्रोमोट करना +स्वाभाविक रूप से, एक non-validator प्रक्रिया द्वारा वैलिडेटर बन सकता है, लेकिन इसे वैलिडेटर सेट में सफलतापूर्वक शामिल किया जाना है, के लिए नोड को फ्लैग के साथ `--seal`शुरू करना होता है. +::: + +## वैलिडेटर सेट से वैलिडेटर को हटाने {#removing-a-validator-from-the-validator-set} + +ऑपरेशन काफी सरल है. वैलिडेटर नोड को हटाने के लिए कमांड को वैलिडेटर नोड के बहुमत के लिए किया जाना चाहिए. + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info BLS की/मुख्य +BLS की/मुख्य रूप से जरूरी है अगर नेटवर्क BLS के साथ भाग रहा है, क्योंकि BLS `--bls`मोड में नेटवर्क नहीं चल रहा है/ +::: + +कमांड के प्रदर्शन के बाद, अवलोकन करें कि वैलिडेटर की संख्या गिरा दी गई है (इस लॉग उदाहरण में लॉग उदाहरण में) + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/hi-edge/consensus/pos-concepts.md b/archive/edge/hi-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..c3ead5821c --- /dev/null +++ b/archive/edge/hi-edge/consensus/pos-concepts.md @@ -0,0 +1,100 @@ +--- +id: pos-concepts +title: प्रूफ ऑफ़ स्टेक +description: "प्रूफ ऑफ़ स्टेक की व्याख्या और निर्देश." +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## ओवरव्यू {#overview} + +इस सेक्शन का उद्देश्य, वर्तमान में प्रूफ ऑफ स्टेक (PoS) में मौजूद कुछ अवधारणाओं का बेहतर ओवरव्यू प्रदान करना है पॉलीगॉन एज का इम्प्लीमेंटेशन. + +पॉलीगॉन एज के प्रूफ ऑफ़ स्टेक (PoS) का इम्प्लीमेंटेशन, पहले से मौजूद PoA IBFT इम्प्लीमेंटेशन का एक विकल्प है, जिससे नोड ऑपरेटरों को, चेन शुरू होने पर आसानी से दोनों में से किसी को चुनने की क्षमता प्राप्त होती है. + +## PoS फीचर्स {#pos-features} + +प्रूफ ऑफ़ स्टेक इम्प्लीमेंटेशन के पीछे का कोर लॉजिक **[स्टेकिंग स्मार्ट कॉन्ट्रैक्ट](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)** + +अनुबंध को पहले से तैनात किया जाता है, जब कभी PoS मैकेनिज्म पॉलीगॉन एज चेन शुरू होती है, और पते`0x0000000000000000000000000000000000001001`पर उपलब्ध होती है ब्लॉक `0` से. + +### इपोच्स {#epochs} + +इपोच्स, पॉलीगॉन एज में PoS के जोड़ के साथ पेश की जाने वाली अवधारणा है. + +इपोच्स को एक विशेष समय सीमा (ब्लॉक में) माना जाता है, जिसमें वैलिडेटर्स का एक निश्चित सेट, ब्लॉक पैदा कर सकता है. उनकी लम्बाई, बदलने योग्य होती है, यानी नोड ऑपरेटर, जेनेसिस जनरेशन के दौरान इपोच की लंबाई को कॉन्फ़िगर कर सकते हैं. + +प्रत्येक इपोच के अंत में, एक _इपोच ब्लॉक_ बनता है, और उस इवेंट के बाद एक नया इपोच शुरू होता है. इपोच ब्लॉक्स के बारे में और जानने के लिए [इपोच ब्लॉक](/docs/edge/consensus/pos-concepts#epoch-blocks) सेक्शन देखें. + +वैलिडेटर सेट, प्रत्येक इपोच के अंत में अपडेट किए जाते हैं. स्टेकिंग स्मार्ट कॉन्ट्रैक्ट से वैलिडेटर सेट की नोड्स क्वेरी इपोच ब्लॉक के निर्माण के दौरान, और प्राप्त डेटा को स्थानीय स्टोरेज में सेव करें. यह क्वेरी और सेव साइकल प्रत्येक इपोच के अंत में दोहराया जाता है. + +आवश्यक रूप से, यह सुनिश्चित करता है कि वैलिडेटर सेट में पतों पर स्टेकिंग स्मार्ट कॉन्ट्रैक्ट का पूरा नियंत्रण है, और नोड्स के लिए केवल 1 जिम्मेदारी छोड़ता है - ताकि नवीनतम वैलिडेटर सेट जानकारी हासिल करने के लिए इपोच के दौरान अनुबंध पर क्वेरी की जा सके. इससे वैलिडेटर सेट की देखभाल करने से संबंधित व्यक्तिगत नोड्स की जिम्मेदारी कम होती है. + +### स्टेकिंग {#staking} + +पते, `stake`तरीके का इस्तेमाल करके और ट्रांजैक्शन में स्टेक्ड अमाउंट के लिए वैल्यू निर्दिष्ट करके स्टेकिंग स्मार्ट कॉन्ट्रैक्ट पर फंड्स स्टेक कर सकते हैं: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +स्टेकिंग स्मार्ट कॉन्ट्रैक्ट पर फ़ंड्स की स्टेकिंग करके, पते, वैलिडेटर सेट में प्रवेश कर सकते हैं और इस प्रकार ब्लॉक उत्पादन प्रक्रिया में में भाग ले सकते हैं. + +:::info स्टेकिंग सम्बन्धी सीमा +वर्तमान में, वैलिडेटर सेट में प्रवेश करने की न्यूनतम सीमा, स्टेकिंग `1 ETH` है +::: + +### अनस्टेकिंग {#unstaking} + +जिन पतों में स्टेक्ड फ़ंड्स हैं सिर्फ वही पते **एक बार में अपने सभी स्टेक्ड फ़ंड्स को अनस्टेक** कर सकते हैं. + +स्टेकिंग स्मार्ट कॉन्ट्रैक्ट पर `unstake`तरीके को कॉल करके अनस्टेकिंग को इनवोक किया जा सकता है: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +उनके फ़ंड्स की अनस्टेकिंग के बाद, स्टेकिंग स्मार्ट कॉन्ट्रैक्ट पर वैलिडेटर सेट से पतों को हटा दिया जाता है, और अगले इपोच के दौरान वैलिडेटर्स नहीं माना जाएगा. + +## इपोच ब्लॉक {#epoch-blocks} + +**इपोच ब्लॉक**, पॉलीगॉन एज में IBFT के PoS इम्प्लीमेंटेशन में प्रस्तुत की गई अवधारणा है. + +आवश्यक रूप से, इपोच ब्लॉक, विशेष ब्लॉक हैं जिसमें **कोई ट्रांजैक्शन शामिल नहीं** होता है और जो केवल **इपोच के अंत** में होते हैं. उदाहरण के लिए, अगर **इकोस का आकार** ब्लॉक में सेट किया जाता `50``100``150`है, तो इकोस ब्लॉक को ब्लॉक और इसी तरह के रूप `50`में माना जाएगा. + +इनका इस्तेमाल, अतिरिक्त लॉजिक का प्रदर्शन करने के लिए किया जाता है जो रेगुलर ब्लॉक उत्पादन के दौरान नहीं होने चाहिए. + +सबसे महत्वपूर्ण बात यह है कि वे नोड के लिए एक संकेत हैं कि **इसे नवीनतम वैलिडेटर सेट जानकारी हासिल करने की जरूरत है** जो स्टेकिंग स्मार्ट कॉन्ट्रैक्ट के भीतर होती है. + +इपोच ब्लॉक में वैलिडेटर सेट को अपडेट करने के बाद, वैलिडेटर सेट (या तो परिवर्तित या अपरिवर्तित ) परवर्ती `epochSize - 1`ब्लॉक के लिए इस्तेमाल किया जाता है, जब तक कि नवीनतम जानकारी हासिल करके इसे फिर अपडेट नहीं किया जाता जो स्टेकिंग स्मार्ट कॉन्ट्रैक्ट के भीतर होती है. + +इपोच लंबाई (ब्लॉक में) को विशिष्ट फ्लैग`--epoch-size` का इस्तेमाल करके जेनेसिस फ़ाइल जनरेट करते समय संशोधित किया जा सकता है: + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +इपोच की डिफ़ॉल्ट साइज़, पॉलीगॉन एज में `100000`ब्लॉक है. + +## अनुबंध प्री-डिप्लॉयमेंट {#contract-pre-deployment} + +पॉलीगॉन एज _प्री-डिप्ल_ॉयमेंट करता है [स्टेकिंग स्मार्ट कॉन्ट्रैक्ट](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol) +पता `0x0000000000000000000000000000000000001001`में **जेनेसिस जनरेशन** के दौरान. + +यह सीधे स्मार्ट कॉन्ट्रैक्ट के ब्लॉकचेन स्टेट को संशोधित करके, EVM को रन किए बिना ऐसा करता है जिसके लिए यह जेनेसिस कमांड में पास किए गए कॉन्फ़िगरेशन वैल्यू का इस्तेमाल करता है. diff --git a/archive/edge/hi-edge/consensus/pos-stake-unstake.md b/archive/edge/hi-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..38a2373257 --- /dev/null +++ b/archive/edge/hi-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,176 @@ +--- +id: pos-stake-unstake +title: भागीदारी का सबूत (पॉस) का सेट अप और इस्तेमाल +description: "स्टेक, अनस्टेक और स्टेकिंग से संबंधित अन्य निर्देश।" +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## ओवरव्यू {#overview} + +यह गाइड विस्तार से बताता है कि पॉलीगॉन एज के साथ किसी भागीदारी के सबूत नेटवर्क का कैसे सेट अप किया जाए, वैलिडेटर बनने के लिए नोड के लिए +कैसे फ़ंड को स्टेक किया जाए और फ़ंड को कैसे अनस्टेक किया जाए। + +यह पढ़ने और के माध्यम से जाने के लिए **अत्यधिक प्रोत्साहित** किया जाता है [लोकल सेटअप](/docs/edge/get-started/set-up-ibft-locally) +/ [क्लाउड सेटअप](/docs/edge/get-started/set-up-ibft-on-the-cloud) +सेक्शन। ये सेक्शन पॉलीगॉन एज के साथ ऑथोरिटी के सबूत (PoA) क्लस्टर को शुरू करने के लिए ज़रूरी स्टेप्स की +रूप-रेखा बताता है। + +फ़िलहाल, वैसे वैलिडेटरों की संख्या पर कोई पाबंदी नहीं है जो स्टेकिंग स्मार्ट कॉन्ट्रैक्ट पर फ़ंड स्टेक कर सकते हैं। + +## स्टेकिंग स्मार्ट कॉन्ट्रैक्ट {#staking-smart-contract} + +स्टेकिंग स्मार्ट कॉन्ट्रैक्ट के लिए रेपो [यहां](https://github.com/0xPolygon/staking-contracts) है। + +यह ज़रूरी टेस्टिंग स्क्रिप्ट, ABI फ़ाइल और सबसे ज़रूरी खुद स्टेकिंग स्मार्ट कॉन्ट्रैक्ट को रखता है। + +## एक N नोड क्लस्टर सेट अप करना {#setting-up-an-n-node-cluster} + +पॉलीगॉन एज के साथ एक नेटवर्क सेट अप करना इसमें कवर किया गया है +[लोकल सेटअप](/docs/edge/get-started/set-up-ibft-locally) +/ [कलाउड सेटअप](/docs/edge/get-started/set-up-ibft-on-the-cloud) सेक्शन। + +किसी पॉस और PoA क्लस्टर को सेट अप करने के बीच **एकमात्र अंतर** जेनेसिस जनरेशन वाले हिस्से में है। + +**पॉस क्लस्टर के लिए जेनेसिस फ़ाइल जनरेट करते समय एक अतिरिक्त फ़्लैग की ज़रूरत पड़ती है `--pos`**: + +```bash +polygon-edge genesis --pos ... +``` + +## किसी एपॉक की अवधि सेट करना {#setting-the-length-of-an-epoch} + +एपॉक के बारे में [एपॉक ब्लॉक्स](/docs/edge/consensus/pos-concepts#epoch-blocks) सेक्शन में विस्तार से बताया गया है। + +किसी क्लस्टर (ब्लॉक में) के लिए एक एपॉक की साइज़ तय करने के लिए, जेनेसिस फ़ाइल जनरेट करते समय, एक अतिरिक्त फ़्लैग +निर्दिष्ट किया जाता है`--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +जेनेसिस फ़ाइल में यह वैल्यू निर्दिष्ट करता है कि एपॉक साइज़ `50` ब्लॉक होना चाहिए। + +किसी एपॉक (ब्लॉक में) के साइज़ के लिए डिफ़ॉल्ट वैल्यू `100000` है। + +:::info एपॉक की अवधि कम करना + +जैसे कि [एपॉक ब्लॉक्स](/docs/edge/consensus/pos-concepts#epoch-blocks) सेक्शन में बताया गया है, +एपॉक ब्लॉक्स का इस्तेमाल नोड के लिए वैलिडेटर सेट को अपडेट करने के लिए होता है। + +ब्लॉक (`100000`) में एपॉक की डिफ़ॉल्ट अवधि वलिडेटर सेट के अपडेट्स के लिए लंबे समय तक बनी रह सकती है। यह मानते हुए कि नए +ब्लॉक जोड़े गए हैं ~2 सेकंड, वैलिडेटर सेट को बदलने में हो सकता है कि ~55.5 घंटे लगें। + +एपॉक की अवधि के लिए कम वैल्यू सेट करने से यह सुनिश्चित होता है कि वैलिडेटर सेट ज़ल्दी-ज़ल्दी अपडेट होता है। + +::: + +## स्टेकिंग स्मार्ट कॉन्ट्रैक्ट स्क्रिप्ट का इस्तेमाल करना {#using-the-staking-smart-contract-scripts} + +### आवश्यक शर्तें {#prerequisites} + +स्टेकिंग स्मार्ट कॉन्ट्रैक्ट रेपो एक हार्डहैट प्रोजेक्ट है, जिसके npm की जरूरत पड़ती है। + +इसे सही तरीके से शुरू करने के लिए, मुख्य डाइरेक्ट्री में इसे रन करें: + +```bash +npm install +```` + +### मुहैया किए गए हेल्पर स्क्रिप्ट का सेट अप करना {#setting-up-the-provided-helper-scripts} + +डिप्लॉय किए गए स्टेकिंग स्मार्ट कॉन्ट्रैक्ट के साथ इंटरैक्ट करने के लिए स्क्रिप्ट +[स्टेकिंग स्मार्ट कॉन्ट्रैक्ट रेपो](https://github.com/0xPolygon/staking-contracts) पर मौजूद हैं। + +स्मार्ट कॉन्ट्रैक्स्ट्स रेपो लोकेशन में नीचे दिए गए पैरामीटर के साथ एक `.env`फ़ाइल बनाएं: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +जहाँ पैरामीटर हैं: + +* **JSONRPC_URL** - रन हो रहे नोड के लिए JSON-RPC एंडपॉइंट +* **PRIVATE_KEYS** स्टेकर एड्रेस का निजी की। +* **STAKING_CONTRACT_ADDRESS** - स्टेकिंग स्मार्ट कॉन्ट्रैक्ट का एड्रेस +(डिफ़ॉल्ट`0x0000000000000000000000000000000000001001`) +* **BLS_PUBLIC_KEY** - स्टेकर का BLS सार्वजनिक की। केवल तभी ज़रूरत पड़ती है जब नेटवर्क BLS के साथ रन कर रहा हो + +### स्टेकिंग फ़ंड {#staking-funds} + +:::info स्टेकिंग एड्रेस +स्टेकिंग स्मार्ट कॉन्ट्रैक्ट एड्रेस पर पहले से डिप्लॉय +किया रहता है `0x0000000000000000000000000000000000001001`। + +स्टेकिंग मैकेनिज्म के साथ किसी भी तरह का इंटरैक्शन स्पष्ट रूप से बताए गए एड्रेस में स्टेकिंग स्मार्ट कॉन्ट्रैक्ट के ज़रिए किया जाता है। + +स्टेकिंग स्मार्ट कॉन्ट्रैक्ट के बारे में और जानने के लिए कृपया +**[स्टेकिंग स्मार्ट कॉन्ट्रैक्ट](/docs/edge/consensus/pos-concepts#contract-pre-deployment)** सेक्शन में जाएँ। + +::: + +वैलिडेटर सेट का हिस्सा बनने के लिए, किसी एड्रेस को सीमा से ऊपर जाकर एक खास अमाउंट के फ़ंड को स्टेक करना होगा। + +फ़िलहाल, वैलिडेटर सेट का हिस्सा बनने के लिए डिफ़ॉल्ट सीमा `1 ETH` है। + +स्टेकिंग स्मार्ट कॉन्ट्रैक्ट के `stake`तरीके को कॉल करके और किसी वैल्यू को निर्दिष्ट करके स्टेकिंग शुरू किया जा सकता है`>= 1 ETH`। + +पिछले सेक्शन में जिक्र किए गए `.env` फ़ाइल का +[सेटअप](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) करने और +पॉस मोड में एक चेन शुरू करने के बाद, स्टेकिंग स्मार्ट कॉन्ट्रैक्ट रेपो में नीचे दिए गए कमांड से स्टेकिंग की जा सकती है: + +```bash +npm run stake +``` + +`stake` हार्डहैट स्क्रिप्ट `1 ETH` का डिफ़ॉल्ट अमाउंट स्टेक करता है, जिसे `scripts/stake.ts` फ़ाइल को बदल कर बदला जा +सकता है। + +अगर स्टेक किए जा रहे फ़ंड `>= 1 ETH` हैं, तो स्टेकिंग स्मार्ट कॉन्ट्रैक्ट पर वैलिडेटर सेट अपडेट किया जाता है और एड्रेस +अगले एपॉक से शुरू हो रहे वैलिडेटर सेट का एक हिस्सा होगा। + +:::info BLS की रजिस्टर करना + +अगर नेटवर्क BLS मोड में रन हो रहा हो, तो नोड के वैलिडेटर बनने के लिए उन्हें स्टेकिंग के बाद अपने BLS सार्वजनिक की को रजिस्टर करना होगा + +इसे नीचे दिए गए कमांड से किया जा सकता है: + +```bash +npm run register-blskey +``` +::: + +### अनस्टेकिंग फ़ंड {#unstaking-funds} + +वैसे एड्रेस जिनमें कोई स्टेक होता है, केवल वे ही एक बार में **अपने सभी फ़ंड को अनस्टेक** कर सकते हैं। + +पिछले सेक्शन में जिक्र किए गए `.env` फ़ाइल का +[सेट अप करने](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) और +पॉस मोड में एक चेन शुरू करने के बाद, स्टेकिंग स्मार्ट कॉन्ट्रैक्ट रेपो में नीचे दिए गए कमांड से अनस्टेकिंग +की जा सकती है: + +```bash +npm run unstake +``` + +### स्टेकर्स की लिस्ट लाना {#fetching-the-list-of-stakers} + +फ़ंड को स्टेक करने वाले सभी एड्रेस स्टेकिंग स्मार्ट कॉन्ट्रैक्ट में सेव किए जाते हैं। + +पिछले सेक्शन में जिक्र किए गए `.env`फ़ाइल का +[सेट अप करने](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) और +पॉस मोड में एक चेन शुरू करने के बाद, स्टेकिंग स्मार्ट कॉन्ट्रैक्ट रेपो में नीचे दिए गए कमांड से +वैलिडेटरों की लिस्ट लाई जा सकती है: + +```bash +npm run info +``` diff --git a/archive/edge/hi-edge/faq/Contracts.md b/archive/edge/hi-edge/faq/Contracts.md new file mode 100644 index 0000000000..8913191d2c --- /dev/null +++ b/archive/edge/hi-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: स्मार्ट कॉन्ट्रैक्ट सामान्य सवाल +description: "पॉलीगॉन एज स्मार्ट कॉन्ट्रै के लिए सामान्य सवाल कान्ट्रैक्टस " +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## पॉलीगॉन एज स्मार्ट कॉन्ट्रैक्ट्स सहायता करता है? {#does-polygon-edge-support-smart-contracts} + +हाँ. पॉलीगॉन एज नेटवर्क एथेरियम कम्पैटीबल ब्लॉकचेन हैं, इसलिए स्मार्ट कॉन्ट्रैक्ट्स जो एथेरियम पर तैनात किए जा सकते हैं, पॉलीगॉन एज चेन पर भी तैनात किए जा सकते हैं. + +## क्या आप तैनाती के बाद पॉस के लिए स्टेकिंग अनुबंध तर्क को अपडेट कर सकते हैं? {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +अब, पॉस नेटवर्क शुरू करने के बाद, आप स्टेकिंग अनुबंध लॉजिक बदलें नहीं कर सकते हैं, क्योंकि यह जेनेसिस the का हिस्सा है. इसलिए, उदाहरण के लिए, आप वैधकर्ताओं की न्यूनतम/अधिकतम संख्या नहीं बदल सकते. सत्यापनकर्ताओं को जोड़ने या हटाने के लिए आप जो कर सकते हैं वह हिस्सेदारी या अनस्टेक है. + + + diff --git a/archive/edge/hi-edge/faq/Gas.md b/archive/edge/hi-edge/faq/Gas.md new file mode 100644 index 0000000000..0733392a2e --- /dev/null +++ b/archive/edge/hi-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: सामान्य सवाल गैस +description: "पॉलीगॉन एज के लिए गैस सामान्य सवाल" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## एक गैस की कीमत को न्यूनतम कैसे लागू करें? {#how-to-enforce-a-minimum-gas-price} +आप सर्वर कमांड पर प्रदान किए गए `--price-limit`फ्लैग का उपयोग कर सकते हैं. यह आपके नोड को केवल उन लेन-देन को स्वीकार करने के लिए बाध्य करेगा जिनके पास गैस आपके द्वारा निर्धारित कीमत सीमा के बराबर या अधिक है। यह सुनिश्चित करने के लिए कि यह पूरे नेटवर्क पर लागू है, आपको यह सुनिश्चित करना होगा कि सभी नोड्स की कीमत मूल्य सीमा समान हो. + + +## क्या आप 0 गैस शुल्क के साथ लेन-देन कर सकते हैं? {#can-you-have-transactions-with-0-gas-fees} +हाँ, आप कर सकते हैं. डिफ़ॉल्ट मूल्य सीमा जो नोड्स लागू करती है, `0`जिसका अर्थ है कि नोड्स उन लेनदेन को स्वीकार करेंगे जिनके पास गैस की कीमत निर्धारित है`0`. + +## गैस (देशी) टोकन कुल आपूर्ति कैसे सेट करें? {#how-to-set-the-gas-native-token-total-supply} + +का `--premine flag`उपयोग करके आप खातों (पते) के लिए एक पूर्वनिर्धारित शेष राशि निर्धारित कर सकते हैं. कृपया ध्यान दें कि यह उत्पत्ति फ़ाइल से एक कॉन्फ़िगरेशन है, और इसे बाद में बदला नहीं जा सकता. + +को`--premine flag` कैसे उपयोग करें पर उदाहरण: + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +यह 1000 एत का पूर्वनिर्धारित संतुलन 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862 पर सेट करता है (तर्क से राशि वीई में है). + +गैस टोकन की पूर्व रकम कुल आपूर्ति होगी. नेटिव/स्थानीय करन्सी (गैस टोकन) की रकम को बाद में कम नहीं किया जा सकता है. + +## एज एक गैस टोकन के रूप में ERC-20 सहायता करता है? {#does-edge-support-erc-20-as-a-gas-token} + +एज गैस टोकन के रूप में ERC-20 टोकन सहायता नहीं करता है. केवल एज करेंसी गैस के लिए समर्थित है. + +## गैस सीमा कैसे बढ़ाई जाए? {#how-to-increase-the-gas-limit} + +पॉलीगॉन एज में सीमा बढ़ाने के दो विकल्प हैं: +1. श्रृंखला को पोंछना और `block-gas-limit`इसको उत्पत्ति फ़ाइल में अधिकतम यूनिट64 मान तक बढ़ाना +2. सभी नोड्स की गैस सीमा बढ़ाने के लिए उच्च मान वाले `--block-gas-target`फ्लैग का उपयोग करें. इसके नोड रिबूट की आवश्यकता होती है. विस्तृत विवरण [इदर](/docs/edge/architecture/modules/txpool/#block-gas-target)मिलेगा. \ No newline at end of file diff --git a/archive/edge/hi-edge/faq/Tokens.md b/archive/edge/hi-edge/faq/Tokens.md new file mode 100644 index 0000000000..9019533946 --- /dev/null +++ b/archive/edge/hi-edge/faq/Tokens.md @@ -0,0 +1,24 @@ +--- +id: tokens +title: टोकन सामान्य सवाल +description: "पॉलीगॉन एज टोकन के लिए सामान्य सवाल" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## पॉलीगॉन एज EIP-1559 सहायता करता है? {#does-polygon-edge-support-eip-1559} +इस समय, पॉलीगॉन एज EIP-1559 सहायता नहीं करता है. + +## करेंसी टोकन सिम्बल कैसे सेट करें? {#how-to-set-the-currency-token-symbol} + +टोकन सिंबल सिर्फ यूआई चीज है, इसलिए इसे नेटवर्क में कहीं भी कॉन्फ़िगर या हार्डकोड नहीं किया जा सकता है. लेकिन आप इसे बदलें जब पता चलता है कि आप मेटामास्क की तरह नेटवर्क वॉलेट में जोड़ सकते हैं. + +## चेन रुक जाती है तो, ट्रांज़ैक्शन में क्या होता है? {#what-happens-to-transactions-when-a-chain-halts} + +सभी लेन-देन जो संसाधित नहीं किए गए हैं वे TxPool (पंक्तिबद्ध या प्रचारित कतार) के अंदर हैं. चेन रुक जाती है, (सबी ब्लॉक प्रोडक्शन) तो ये ट्रांज़ैक्शन ब्लॉक में कभी नहीं जाते हैं. +य
ह मामला केवल जब चेन रुकती है तो तब नहीं है. यदि नोड्स को रोक दिया जाता है या फिर से शुरू किया जाता है, तो सभी लेन-देन जो निष्पादित नहीं किए गए हैं, और अभी भी TxPool में हैं, चुपचाप हटा दिए जाएंगे.
+यही बात ट्रांज़ैक्शन के साथ होगी जब ब्रेकिंग बदलें शुरू किए जाते हैं, क्योंकि नोड्स को पुनरारंभ करने के लिए जरूरी होता है. diff --git a/archive/edge/hi-edge/faq/Validators.md b/archive/edge/hi-edge/faq/Validators.md new file mode 100644 index 0000000000..68a8450872 --- /dev/null +++ b/archive/edge/hi-edge/faq/Validators.md @@ -0,0 +1,84 @@ +--- +id: validators +title: वैलिडेटर्स के लिए सामान्य सवाल +description: "पॉलीगॉन एज के वैलिडेटर्स के लिए सामान्य सवाल" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## वैलिडेटर को कैसे जोड़ें/हटाएँ? {#how-to-add-remove-a-validator} + +### PoA {#poa} +वैलिडेटर्स को जोड़ना/हटाना वोटिंग द्वारा किया जाता है. आप [यहाँ](/docs/edge/consensus/poa) इस बारे में पूरी गाइड पा सकते हैं. + +### PoS {#pos} +आप फ़ंड को कैसे स्टेक करें के बारे में [यहाँ](/docs/edge/consensus/pos-stake-unstake)गाइड पा सकते हैं, ताकि एक नोड, एक वैलिडेटर बन सके और कैसे अनस्टेक करे (वैलिडेटर को हटाएँ). + +कृपया नोट करें कि: +- जेनेसिस फ्लैग `--max-validator-count` का इस्तेमाल करके आप अधिकतम संख्या में स्टेकर्स को सेट कर सकते हैं जो वैलिडेटर सेट में शामिल हो सकते हैं. +- जेनेसिस फ्लैग `--min-validator-count ` का इस्तेमाल करके आप न्यूनतम संख्या में स्टेकर्स को सेट कर सकते हैं जिन्हें वैलिडेटर सेट (`1` में बाय डिफ़ॉल्ट) शामिल करने की आवश्यकता है. +- अधिकतम वैलिडेटर की संख्या पूरी होने पर, जब तक आप सेट में पहले से मौजूद एक वैलिडेटर को हटा नहीं देते तब तक दूसरा इसमें नहीं जोड़ सकते (इससे कोई फ़र्क नहीं पड़ता अगर नए वाले की स्टेक की गई रकम अधिक है). अगर आप एक वैलिडेटर को हटाते हैं, तो बाकी बचे हुए वैलिडेटर्स की संख्या `--min-validator-count` से कम नहीं हो सकती. +- `1` की एक डिफ़ॉल्ट सीमा है, एक वैलिडेटर बनने के लिए स्थानीय नेटवर्क (गैस) की एक करेंसी है. + + + +## एक वैलिडेटर के लिए डिस्क में कितने स्पेस का सुझाव दिया जाता है? {#how-much-disk-space-is-recommended-for-a-validator} + +हम एक रूढ़िवादी अनुमानित रनवे के रूप में 100G के साथ शुरू करने की सलाह देते हैं, और सुनिश्चित करें कि बाद में डिस्क को मापना संभव हो. + + +## क्या वैलिडेटर्स की संख्या के लिए कोई सीमा है? {#is-there-a-limit-to-the-number-of-validators} + +अगर हम तकनीकी सीमाओं की बात कर रहे हैं, तो पॉलीगॉन एज में स्पष्ट रूप से नेटवर्क में आपके नोड्स की संख्या के लिए कैप नहीं है. आप कनेक्शन कैप को हर नोड को (इनबाउंड / आउटबाउंड कनेक्शन काउंट्स) के आधार पर सेट कर सकते हैं. + +अगर हम व्यावहारिक सीमाओं के बारे में बात करें तो आप 100 नोड के क्लस्टर का प्रदर्शन 10 नोड के क्लस्टर से खराब देखेंगे. अपने क्लस्टर में नोड्स की संख्या को बढ़ाकर आप संचार की जटिलता और सामान्य रूप से नेटवर्किंग ओवरहेड को बढ़ा देते हैं. यह सब इस बात पर निर्भर करता है कि आप किस तरह के नेटवर्क को रन कर रहे हैं और आपके पास किस तरह के नेटवर्क की टोपोलॉजी है. + +## PoA से PoS में कैसे स्विच करें? {#how-to-switch-from-poa-to-pos} + +PoA सहमति का डिफ़ॉल्ट मैकेनिज्म है. एक नए क्लस्टर के लिए, PoS में स्विच करने के लिए, आपको जेनेसिस फ़ाइल जनरेट करते समय `--pos` फ्लैग को जोड़ने की ज़रूरत होगी. अगर आपके पास एक रन कर रहा क्लस्टर है, तो आप [यहाँ](/docs/edge/consensus/migration-to-pos) देख सकते हैं कि इसे कैसे स्विच किया जाए. हमारे सहमति के मैकेनिज्म और सेटअप के बारे में आपको सभी जानकारी हमारे [सहमति सेक्शन](/docs/edge/consensus/poa) में मिल सकती है. + +## ब्रेकिंग बदलाव होने पर मैं अपने नोड्स को कैसे अपडेट करूँ? {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +इस प्रक्रिया को कैसे करें, जानने के लिए आपको [यहाँ](/docs/edge/validator-hosting#update) एक गाइड मिल सकती है. + +## क्या PoS एज के लिए स्टेकिंग की न्यूनतम रकम कॉन्फ़िगर करने योग्य है? {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +स्टेकिंग के लिए बाय डिफ़ॉल्ट न्यूनतम रकम `1 ETH` है, और यह कॉन्फ़िगर करने योग्य नहीं है. + +## क्यों JSON RPC की `eth_getBlockByNumber` और `eth_getBlockByHash` कमांड्स माइनर के पते को रिटर्न नहीं करतीं? {#not-return-the-miner-s-address} + +पॉलीगॉन एज में वर्तमान में इस्तेमाल की जाने वाली सहमति IBFT 2.0 है, जो बदले में, Clique PoA में वोटिंग के मैकेनिज्म के बारे बताए गए अनुसार बनता है: [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225). + +EIP-225 (Clique PoA) को देखते हुए, यह एक प्रासंगिक हिस्सा है जो बताता है कि क्या `miner`(उर्फ `beneficiary`) को इस्तेमाल करते हैं: + +
हम ethash हेडर फील्ड को इस तरह पुनर्निर्धारित करते हैं: +
    +
  • लाभार्थी / माइनर: अधिकृत साइनर्स की सूची को संशोधित करने का प्रस्ताव करने के लिए पता
  • +
      +
    • सामान्य रूप से ज़ीरो से भरे जाने चाहिए, केवल वोटिंग के समय संशोधित किया जाना चाहिए.
    • +
    • वोटिंग मैकेनिक्स के आसपास कार्यान्वयन में अतिरिक्त जटिलता से बचने के लिए मनमानी वैल्यूज़ की अनुमति है (यहाँ तक कि अर्थहीन जैसे कि नॉन-साइनर्स को वोट देना).
    • +
    • चेकपॉइंट (जैसे epoch से गुज़रना) के ब्लॉक्स पर अवश्य ही ज़ीरोज़ से भरा जाना चाहिए.
    • +
    + +
+ +
+ +इस प्रकार, `miner` फ़ील्ड का इस्तेमाल एक खास पते को वोट करने के प्रस्ताव के लिए इस्तेमाल किया जाता है, न कि ब्लॉक को प्रस्तावित करने वाले को दिखाने के लिए. + +ब्लॉक को प्रस्तावित करने वाले की जानकारी ब्लॉक हेडर में RLP के एन्कोड किए गए इस्तांबुल के अतिरिक्त डेटा फ़ील्ड के सील फ़ील्ड से पबकी को रिकवर करके प्राप्त की जा सकती है. + +## जेनेसिस के कौन-से हिस्सों और वैल्यू को सुरक्षित रूप से संशोधित किया जा सकता है. {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +कृपया इसे संपादित करने के प्रयास से पहले मौजूदा genesis.json की मैनुअल कॉपी बनाना सुनिश्चित करें. इसके अलावा, genesis.json फ़ाइल को संपादित करने से पहले पूरी चेन को रोकना पड़ता है. जेनेसिस फ़ाइल को संशोधित करने के बाद, इसके नए संस्करण को सभी non-validator और वैलिडेटर नोड्स में वितरित करना पड़ता है. + +::: + +**जेनेसिस फ़ाइल के बूटनोड्स सेक्शन को ही सुरक्षित रूप से संशोधित किया जा सकता है**, जहां आप सूची से बूटनोड्स को जोड़ या हटा सकते हैं. \ No newline at end of file diff --git a/archive/edge/hi-edge/get-started/cli-commands.md b/archive/edge/hi-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..e0be5cd0fe --- /dev/null +++ b/archive/edge/hi-edge/get-started/cli-commands.md @@ -0,0 +1,2220 @@ +--- +id: cli-commands +title: CLI कमांड्स +description: "पॉलीगॉन एज के लिए CLI कमांड्स और कमांड फ्लैग की सूची." +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +इस सेक्शन में, वर्तमान कमांड्स, पॉलीगॉन एज में कमांड फ्लैग और उसके इस्तेमाल करने का विवरण दिया गया है. + +:::tip JSON का सपोर्ट आउटपुट + +`--json` फ्लैग को कुछ कमांड्स पर सपोर्ट किया जाता है. यह फ्लैग JSON फॉर्मेट में आउटपुट को प्रिंट करने के लिए कमांड देता है + +::: + +## स्टार्टअप कमांड्स {#startup-commands} + +| **कमांड** | **वर्णन** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| सर्वर | वह डिफ़ॉल्ट कमांड जो सभी मॉड्यूल की एक साथ बूटस्ट्रेपिंग करके ब्लॉकचेन क्लाइंट को शुरू करता है | +| जेनेसिस | एक *genesis.json* फ़ाइल, जिसका इस्तेमाल क्लाइंट को शुरू करने से पहले एक पूर्वनिर्धारित चेन की स्थिति निर्धारित करने के लिए किया जाता है. जेनेसिस फ़ाइल की संरचना नीचे बताई गई है | +| जेनेसिस को डिप्लॉय करने से पहले | फ़्रेश नेटवर्क के लिए स्मार्ट कॉन्ट्रैक्ट को पहले डिप्लॉय करता है | + +### सर्वर फ्लैग्स {#server-flags} + + +| **सभी सर्वर फ्लैग्स** | +|---------------------------------------|---------------------------------------------| +| [डेटा-डायरेक्टरी](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-ब्लॉक-रेंज-लिमिट](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-बैच-रिक्वेस्ट-लिमिट](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [प्रोमेथियस](/docs/edge/get-started/cli-commands#prometheus) | [ब्लॉक-गैस-टारगेट](/docs/edge/get-started/cli-commands#block-gas-target) | +| [मैक्स-पीअर्स](/docs/edge/get-started/cli-commands#max-peers) | [मैक्स-इनबाउंड-पीअर्स](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [मैक्स-आउटबाउंड-पीअर्स](/docs/edge/get-started/cli-commands#max-outbound-peers) | [मैक्स-एनक्यूड](/docs/edge/get-started/cli-commands#max-enqueued) | +| [लॉग-लेवल](/docs/edge/get-started/cli-commands#log-level) | [लॉग-टू](/docs/edge/get-started/cli-commands#log-to) | +| [चेन](/docs/edge/get-started/cli-commands#chain) | [जॉइन](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [कीमत-सीमा](/docs/edge/get-started/cli-commands#price-limit) | [मैक्स-स्लॉट्स](/docs/edge/get-started/cli-commands#max-slots) | +| [कॉन्फ़िगरेशन](/docs/edge/get-started/cli-commands#config) | [सीक्रेट्स-कॉन्फ़िगरेशन](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-इंटरवल](/docs/edge/get-started/cli-commands#dev-interval) | +| [नो-डिस्कवर](/docs/edge/get-started/cli-commands#no-discover) | [रिस्टोर](/docs/edge/get-started/cli-commands#restore) | +| [ब्लॉक-टाइम](/docs/edge/get-started/cli-commands#block-time) | [एक्सेस-कंट्रोल-अलाउ-ऑरिजिन्स](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

डेटा-डायरेक्टरी + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +पॉलीगॉन एज के क्लाइंट डेटा को संग्रहीत करने के लिए इस्तेमाल की जाने वाली डेटा डायरेक्टरी को निर्दिष्ट करने के लिए इस्तेमाल किया जाता है. डिफ़ॉल्ट: `./test-chain`. + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +JSON-RPC, सेवा के लिए पते और पोर्ट को सेट करता है `address:port`. +अगर केवल पोर्ट को ही परिभाषित `:10001` किया गया है तो यह सभी इंटरफेस से जुड़ जाएगा `0.0.0.0:10001` +अगर हटा दिया जाता है तो सेवा डिफ़ॉल्ट `address:port` से जुड़ जाएगी . +डिफ़ॉल्ट पता: `0.0.0.0:8545`. + +--- + +####

json-rpc-ब्लॉक-रेंज-लिमिट + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +json-rpc अनुरोधों को एक्जीक्यूट करते समय ध्यान दी जाने वाली अधिकतम ब्लॉक की रेंज को सेट करता है जिसमें ब्लॉक/से ब्लॉक की वैल्यू शामिल होती है (जैसे eth_getLogs). डिफ़ॉल्ट:`1000`. + +--- + +####

json-rpc-बैच-रिक्वेस्ट-लिमिट + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +json-rpc बैच के अनुरोधों को संभालते समय ध्यान दी जाने वाली अधिकतम लंबाई को सेट करता है. डिफ़ॉल्ट: `20`. + +--- + +####

grpc + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +gRPC सेवा `address:port`के लिए पते और पोर्ट को सेट करता है. डिफ़ॉल्ट पता: `127.0.0.1:9632`. + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +libp2p सेवा `address:port`के लिए पते और पोर्ट को सेट करता है . डिफ़ॉल्ट पता: `127.0.0.1:1478`. + +--- + +####

प्रोमेथियस + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +प्रोमेथियस सर्वर के लिए पते और पोर्ट को सेट करता है `address:port`. +अगर केवल पोर्ट को परिभाषित `:5001` किया गया है तो सेवा सभी इंटरफ़ेस से जुड़ जाएगी `0.0.0.0:5001`. +अगर छोड़ दिया गया है, तो सेवा शुरू नहीं की जाएगी. + +--- + +####

ब्लॉक-गैस-टारगेट + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +चेन के लिए टारगेट ब्लॉक की गैस सीमा को सेट करता है. डिफ़ॉल्ट (लागू नहीं किया गया है): `0`. + +ब्लॉक गैस के टारगेट पर एक और विस्तृत स्पष्टीकरण [TxPool सेक्शन](/docs/edge/architecture/modules/txpool#block-gas-target) में मिल सकता है. + +--- + +####

मैक्स-पीअर्स + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +क्लाइंट के पीअर की अधिकतम गिनती को सेट करता है. डिफ़ॉल्ट: `40`. + +पीअर सीमा को या तो `max-peers` या `max-inbound/outbound-peers` फ्लैग का इस्तेमाल करके निर्दिष्ट किया जाना चाहिए. + +--- + +####

मैक्स-इनबाउंड-पीअर्स + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +क्लाइंट की अधिकतम इनबाउंड पीअर की गिनती को सेट करता है. अगर `max-peers` को सेट किया गया है, तो मैक्स-इनबाउंड-पीअर की सीमा की गणना निम्नलिखित फॉर्मूले का इस्तेमाल करके की जाती है. + +`max-inbound-peer = InboundRatio * max-peers`, जहाँ `InboundRatio` है `0.8`. + +--- + +####

मैक्स-आउटबाउंड-पीअर्स + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +क्लाइंट की अधिकतम आउटबाउंड पीअर की गिनती को सेट करता है. अगर `max-peers` को सेट किया गया है, तो मैक्स-आउटबाउंड-पीअर की सीमा की गणना निम्नलिखित फॉर्मूले का इस्तेमाल करके की जाती है. + +`max-outbound-peer = OutboundRatio * max-peers`, जहाँ `OutboundRatio` है `0.2`. + +--- + +####

मैक्स-एनक्यूड + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +हर अकाउंट लाइन में लगे ट्रांज़ैक्शन की अधिकतम संख्या को सेट करता है. डिफ़ॉल्ट:`128`. + +--- + +####

लॉग-लेवल + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +कंसोल आउटपुट के लिए लॉग लेवल को सेट करता है. डिफ़ॉल्ट: `INFO`. + +--- + +####

लॉग-टू + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +लॉग फ़ाइल के नाम को निर्धारित करता है जो सर्वर कमांड से सभी लॉग आउटपुट को होल्ड करेगा. +बाय डिफ़ॉल्ट सभी सर्वर लॉग्स, कंसोल (stdout) को आउटपुट देंगे +लेकिन अगर फ्लैग सेट किया गया है, तो सर्वर कमांड चलाने पर कंसोल को कोई आउटपुट नहीं मिलेगा. + +--- + +####

चेन + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +चेन शुरू करने के लिए इस्तेमाल की जाने वाली जेनेसिस फ़ाइल के बारे में खास तौर से बताता है. डिफ़ॉल्ट: `./genesis.json`. + +--- + +####

जॉइन + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +खास तौर से उस पीअर के पते को बताता है जिसे शामिल किया जाना चाहिए. + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +पोर्ट के बिना बाहरी आईपी पते को सेट करता है, ताकि इसे पीअर द्वारा देखा जा सके. + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +होस्ट DNS के पते को सेट करता है. इसका इस्तेमाल बाहरी DNS का विज्ञापन करने के लिए किया जा सकता है. `dns`,`dns4`,`dns6` को सपोर्ट करता है. + +--- + +####

प्राइस-लिमिट + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +पूल में स्वीकार किए जाने के लिए गैस की कीमत की न्यूनतम सीमा को सेट करता है. डिफ़ॉल्ट: `1`. + +--- + +####

मैक्स-स्लॉट्स + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +पूल में अधिकतम स्लॉट्स को सेट करता है. डिफ़ॉल्ट: `4096`. + +--- + +####

कॉन्फ़िगरेशन + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +CLI के कॉन्फ़िगरेशन के लिए रास्ते को निर्दिष्ट करता है. `.json` को सपोर्ट करता है. + +--- + +####

सीक्रेट्स-कॉन्फ़िगरेशन + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +SecretsManager कॉन्फ़िगरेशन फ़ाइल के लिए पाथ सेट करता है. Hashicorp वॉल्ट, AWS SSM और GCP सीक्रेट्स के मैनेजर के लिए इस्तेमाल किया जाता है. अगर हटा दिए गए हैं तो स्थानीय FS सीक्रेट्स के मैनेजर का इस्तेमाल किया जाता है. + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +क्लाइंट को dev मोड पर सेट करता है. `false`डिफ़ॉल्ट: देव मोड में, सहकर्मी की खोज को डिफ़ॉल्ट रूप से निष्क्रिय किया जाता है. + +--- + +####

dev-इंटरवल + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +क्लाइंट के dev नोटिफ़िकेशन इंटरवल को सेकंड में सेट करता है. डिफ़ॉल्ट: `0`. + +--- + +####

नो-डिस्कवर + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +क्लाइंट को दूसरे पीअर्स की खोज करने से रोकता है. डिफ़ॉल्ट: `false`. + +--- + +####

रिस्टोर + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +निर्दिष्ट आर्काइव फ़ाइल से ब्लॉक्स को रिस्टोर करें + +--- + +####

ब्लॉक-टाइम + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +सेकंड में ब्लॉक के उत्पादन का समय सेट करता है. डिफ़ॉल्ट: `2` + +--- + +####

एक्सेस-कंट्रोल-अलाउ-ऑरिजिन्स + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +JSON-RPC के अनुरोधों को साझा करने में सक्षम होने के लिए अधिकृत डोमेन को सेट करता है. +मल्टिपल फ्लैग्स `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"` को मल्टिपल अधिकृत डोमेन में जोड़ें. +अगर हटा दिया गया है, तो एक्सेस-कंट्रोल-अलाउ-ऑरिजिन्स को `*` में सेट कर दिया जाएगा और सभी डोमेन को अधिकृत कर दिया जाएगा. + +--- + +### जेनेसिस फ्लैग्स {#genesis-flags} +| **सभी जेनेसिस फ्लैग्स** | +|---------------------------------------|---------------------------------------------| +| [डायरेक्टरी](/docs/edge/get-started/cli-commands#dir) | [नाम](/docs/edge/get-started/cli-commands#name) | +| [pos](/docs/edge/get-started/cli-commands#pos) | [युग-साइज़](/docs/edge/get-started/cli-commands#epoch-size) | +| [premine](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [ibft-वैलिडेटर-प्रकार](/docs/edge/get-started/cli-commands#ibft-validator-type) | [ibft-वैलिडेटर-प्रीफिक्स-पाथ](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [ibft-वैलिडेटर](/docs/edge/get-started/cli-commands#ibft-validator) | [ब्लॉक-गैस-लिमिट](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [सहमति](/docs/edge/get-started/cli-commands#consensus) | [बूटनोड](/docs/edge/get-started/cli-commands#bootnode) | +| [मैक्स-वैलिडेटर-काउंट](/docs/edge/get-started/cli-commands#max-validator-count) | [मिनिमम-वैलिडेटर-काउंट](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

डायरेक्टरी + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +पॉलीगॉन एज के जेनेसिस डेटा के लिए डायरेक्टरी सेट करता है. डिफ़ॉल्ट: `./genesis.json`. + +--- + +####

नाम + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +चेन के लिए नाम सेट करता है. डिफ़ॉल्ट: `polygon-edge`. + +--- + +####

pos + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +फ्लैग सेट करता है जो दर्शाता है कि क्लाइंट को IBFT हिस्सेदारी के प्रूफ़ का इस्तेमाल करना चाहिए +अगर फ्लैग या `false` नहीं दिया गया है, तो प्राधिकरण के लिए डिफ़ॉल्ट प्रूफ़ देता है. + +--- + +####

युग-साइज़ + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +चेन के लिए युग का साइज़ सेट करता है. डिफ़ॉल्ट `100000`. + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +premined अकाउंट को सेट करता है और फॉर्मेट को बैलेंस करता है `address:amount`. +रकम या तो दशमलव या तो हेक्स में हो सकती है. +डिफ़ॉल्ट premined बैलेंस: `0xD3C21BCECCEDA1000000`(10 लाख स्थानीय करेंसी के टोकन). + +--- + +####

चेनआईडी + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +चेन की आईडी सेट करता है. डिफ़ॉल्ट: `100`. + +--- + +####

ibft-वैलिडेटर-प्रकार + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +ब्लॉक हेडर के वैलिडेशन मोड को निर्दिष्ट करता है. संभावित वैल्यूज़: `[ecdsa, bls]`. डिफ़ॉल्ट: `bls`. + +--- + +####

ibft-वैलिडेटर-प्रीफिक्स-पाथ + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +वैलिडेटर फ़ोल्डर डायरेक्टरी के लिए पहले से निर्धारित पाथ. अगर `ibft-validator` को हटाया जाता है, तो फ्लैग मौजूद होना चाहिए. + +--- + +####

ibft-वैलिडेटर + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +पास हुए पतों को IBFT वैलिडेटर के रूप में सेट करता है. अगर `ibft-validators-prefix-path` को हटाया जाता है, तो फ्लैग मौजूद होना चाहिए. +1. अगर नेटवर्क ECDSA, के साथ रन कर रहा है, तो फॉर्मेट `--ibft-validator [ADDRESS]`है . +2. अगर नेटवर्क BLS के साथ रन कर रहा है, तो फॉर्मेट `--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]`होता है . + +--- + +####

ब्लॉक-गैस-लिमिट + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +एक ब्लॉक में सभी कार्यों के लिए इस्तेमाल की जाने वाली गैस की अधिकतम मात्रा को संदर्भित करता है. डिफ़ॉल्ट: `5242880`. + +--- + +####

सहमति + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +प्रोटोकॉल की सहमति देता है. डिफ़ॉल्ट: `pow`. + +--- + +####

बूटनोड + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +p2p डिस्कवरी बूटस्ट्रैप के लिए Multiaddr URL . इस फ्लैग को कई बार इस्तेमाल किया जा सकता है. +आईपी पते की बजाय, बूटनोड के DNS का पता प्रदान किया जा सकता है. + +--- + +####

मैक्स-वैलिडेटर-काउंट + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +PoS में सहमति के लिए, वैलिडेटर सेट में शामिल हो सकने वाले स्टेकर्स की अधिकतम संख्या. +यह संख्या MAX_SAFE_INTEGER (2^53-2) की वैल्यू से अधिक नहीं हो सकती है. + +--- + +####

मिनिमम-वैलिडेटर-काउंट + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +PoS में सहमति के लिए, वैलिडेटर सेट में शामिल होने के लिए स्टेकर्स की न्यूनतम आवश्यक संख्या. +यह संख्या मैक्स-वैलिडेटर-काउंट की वैल्यू से अधिक नहीं हो सकती है. +1 के लिए डिफ़ॉल्ट. + +--- + +### पहले से डिप्लॉय किए जाने वाले जेनेसिस फ्लैग्स {#genesis-predeploy-flags} + +

आर्टिफैक्ट-पाथ

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +कॉन्ट्रैक्ट आर्टिफैक्ट JSON के लिए पाथ सेट करता है जिसमें `abi`, `bytecode` और `deployedBytecode`शामिल होते हैं. + +--- + +

चेन

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +`genesis.json` फ़ाइल के लिए पाथ सेट करता है जिसे अपडेट किया जाना चाहिए. डिफ़ॉल्ट `./genesis.json`. + +--- + +

constructor-args

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + + अगर कोई हो तो स्मार्ट कॉन्ट्रैक्ट के लिए कंस्ट्रक्टर आर्ग्युमेंट को सेट करता है. इन आर्ग्युमेंट को कैसा दिखना चाहिए, इस पर एक विस्तृत गाइड के लिए, कृपया [पहले से डिप्लॉय करने के बारे में लेख](/docs/edge/additional-features/predeployment) देखें. + +--- + +

पहले से डिप्लॉय किया गया एड्रेस

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +पहले से डिप्लॉय करने के लिए पता सेट करता है. डिफ़ॉल्ट `0x0000000000000000000000000000000000001100`. + +--- + + +## ऑपरेटर कमांड्स {#operator-commands} + +### पीअर कमांड्स {#peer-commands} + +| **कमांड** | **वर्णन** | +|------------------------|-------------------------------------------------------------------------------------| +| पीअर्स का पता | उनके libp2p पते का इस्तेमाल करके एक नया पीअर जोड़ता है | +| पीअर्स की सूची | उन सभी पीअर्स की सूची बनाता है जिनसे क्लाइंट libp2p के माध्यम से जुड़ा हुआ है | +| पीअर्स स्टेटस | libp2p पते का इस्तेमाल करके पीअर्स की सूची से एक खास पीअर का स्टेटस रिटर्न करता है | + +

पीअर्स के पते के फ्लैग्स

+ +

पता

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +multiaddr फॉर्मेट में पीअर का libp2p पता. + +--- + +

grpc-पता

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +gRPC API का पता. डिफ़ॉल्ट: `127.0.0.1:9632`. + +

पीअर्स की सूची के फ्लैग

+ +

grpc-पता

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +gRPC API का पता. डिफ़ॉल्ट: `127.0.0.1:9632`. + +

पीअर्स के स्टेटस के फ्लैग

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +p2p नेटवर्क के भीतर एक खास पीअर के Libp2p नोड की आईडी है. + +--- + +

grpc-पता

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +gRPC API का पता. डिफ़ॉल्ट: `127.0.0.1:9632`. + +### IBFT कमांड्स {#ibft-commands} + +| **कमांड** | **वर्णन** | +|------------------------|-------------------------------------------------------------------------------------| +| ibft स्नैपशॉट | IBFT के स्नैपशॉट को रिटर्न करता है | +| ibft के उम्मीदवार | यह प्रस्तावित उम्मीदवारों के मौजूदा सेट और साथ ही उन उम्मीदवारों से पूछताछ करता है जिन्हें अभी तक शामिल नहीं किया गया है | +| ibft के प्रस्ताव | वैलिडेटर के सेट में एक नए उम्मीदवार को जोड़ने/हटाने का प्रस्ताव करता है | +| ibft स्टेटस | IBFT क्लाइंट के ओवरआल स्टेटस को रिटर्न करता है | +| ibft स्विच | genesis.json फ़ाइल में फ़ोर्क की कॉन्फ़िगरेशन जोड़ें ताकि IBFT के प्रकार को स्विच किया जा सके | +| ibft कोरम | ब्लॉक की संख्या को निर्दिष्ट करता है जिससे बाद सहमति तक पहुंचने के लिए ऑप्टीमल कोरम के आकार के तरीके को इस्तेमाल किया जाएगा | + + +

ibft स्नैपशॉट के फ्लैग

+ +

नंबर

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +स्नैपशॉट के लिए ब्लॉक हाइट (संख्या में). + +--- + +

grpc-पता

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +gRPC API का पता. डिफ़ॉल्ट: `127.0.0.1:9632`. + +

ibft के उम्मीदवारों के फ्लैग्स

+ +

grpc-पता

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +gRPC API का पता. डिफ़ॉल्ट: `127.0.0.1:9632`. + +

ibft के प्रस्ताव के फ्लैग

+ +

वोट

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +वैलिडेटर सेट में बदलाव को प्रस्तावित करता है. संभावित वैल्यूज़: `[auth, drop]`. + +--- + +

पता

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +वोट किए जाने वाले अकाउंट का पता. + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +वोट किए जाने वाले अकाउंट की BLS की सार्वजनिक की जो केवल BLS मोड में आवश्यक है. + +--- + +

grpc-पता

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +gRPC API का पता. डिफ़ॉल्ट: `127.0.0.1:9632`. + +

ibft स्टेटस के फ्लैग

+ +

grpc-पता

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +gRPC API का पता. डिफ़ॉल्ट: `127.0.0.1:9632`. + +

ibft स्विच के फ्लैग

+ +

चेन

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +जेनेसिस फ़ाइल को अपडेट करने के लिए निर्दिष्ट करता है. डिफ़ॉल्ट: `./genesis.json`. + +--- + +

प्रकार

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +स्विच करने के लिए IBFT के प्रकार को निर्दिष्ट करता है. संभावित वैल्यूज़: `[PoA, PoS]`. + +--- + +

डिप्लॉयमेंट

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +कॉन्ट्रैक्ट को डिप्लॉय करने की हाइट को निर्दिष्ट करता है. केवल PoS के साथ उपलब्ध है. + +--- + +

फ्रॉम

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-वैलिडेटर-प्रकार

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +ब्लॉक हेडर के वैलिडेशन मोड को निर्दिष्ट करता है. संभावित वैल्यूज़: `[ecdsa, bls]`. डिफ़ॉल्ट: `bls`. + +--- + +

ibft-वैलिडेटर-प्रीफिक्स-पाथ

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +नए वैलिडेटर्स की डायरेक्टरिज़ के लिए पाथ को पहले से निर्धारित करता है. अगर `ibft-validator` फ्लैग को हटा दिया जाता है, तो मौजूद होना चाहिए. तभी उपलब्ध होता है जब IBFT मोड PoA हो (`--pos` फ्लैग को हटा दिया जाता है). + +--- + +

ibft-वैलिडेटर

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +फोर्क के बाद इस्तेमाल किए जाने वाले IBFT वैलिडेटर्स के रूप में पतों में पास किए गए सेट्स. अगर `ibft-validators-prefix-path` फ्लैग को हटा दिया जाता है, तो मौजूद होना चाहिए. केवल PoA मोड में उपलब्ध है. +1. अगर नेटवर्क ECDSA, के साथ रन कर रहा है, तो फॉर्मेट `--ibft-validator [ADDRESS]`है . +2. अगर नेटवर्क BLS के साथ रन कर रहा है, तो फॉर्मेट `--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]`होता है . + +--- + +

मैक्स-वैलिडेटर-काउंट

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +PoS में सहमति के लिए, वैलिडेटर सेट में शामिल हो सकने वाले स्टेकर्स की अधिकतम संख्या. +यह संख्या MAX_SAFE_INTEGER (2^53-2) की वैल्यू से अधिक नहीं हो सकती है. + +--- + +

मिनिमम-वैलिडेटर-काउंट

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +PoS में सहमति के लिए, वैलिडेटर सेट में शामिल होने के लिए स्टेकर्स की न्यूनतम आवश्यक संख्या. +यह संख्या मैक्स-वैलिडेटर-काउंट की वैल्यू से अधिक नहीं हो सकती है. +1 के लिए डिफ़ॉल्ट. + +फ़ोर्क की शुरूआती हाइट को निर्दिष्ट करता है. + +--- + +

ibft कोरम के फ्लैग

+ +

फ्रॉम

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +कोरम की गणना को QuorumOptimal से स्विच करने की हाइट, जिसमें `N`वैलिडेटर नोड्स की संख्या होने के नाते `(2/3 * N)`, फ़ार्मूला इस्तेमाल होता है. कृपया ध्यान दें कि यह पीछे की कम्पेटिबिलिटी के लिए है, मतलब कि केवल उन चेन के लिए है जो ब्लॉक की एक निश्चित हाइट तक कोरम की पुरानी गणना का इस्तेमाल करती थी. + +--- + +

चेन

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +जेनेसिस फ़ाइल को अपडेट करने के लिए निर्दिष्ट करता है. डिफ़ॉल्ट: `./genesis.json`. + +### ट्रांज़ैक्शन पूल कमांड्स {#transaction-pool-commands} + +| **कमांड** | **वर्णन** | +|------------------------|--------------------------------------------------------------------------------------| +| txpool का स्टेटस | पूल में ट्रांज़ैक्शन की संख्या को रिटर्न करता है | +| txpool की सदस्यता | ट्रांज़ैक्शन पूल में इवेंट्स के लिए सदस्यता लेता है | + +

txpool स्टेटस के फ्लैग

+ +

grpc-पता

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +gRPC API का पता. डिफ़ॉल्ट: `127.0.0.1:9632`. + +

txpool की सदस्यता के फ्लैग

+ +

grpc-पता

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +gRPC API का पता. डिफ़ॉल्ट: `127.0.0.1:9632`. + +--- + +

प्रमोटेड

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +TxPool में tx इवेंट्स को बढ़ावा देने के लिए सदस्यता लेता है. + +--- + +

ड्रॉप किए गए

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +TxPool में ड्रॉप हुए tx इवेंट्स के लिए सदस्यता लेता है. + +--- + +

डिमोटेड

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +TxPool में tx इवेंट्स के लिए डिमोट की गई सदस्यता लेता है. + +--- + +

एड की गई

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +TxPool में tx इवेंट्स के लिए एड की गई सदस्यता लेता है. + +--- + +

एनक्यूड

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +अकाउंट की एनक्यूड tx इवेंट्स के लिए सदस्यता लेता है. + +--- + +### ब्लॉकचेन कमांड्स {#blockchain-commands} + +| **कमांड** | **वर्णन** | +|------------------------|-------------------------------------------------------------------------------------| +| स्टेटस | क्लाइंट का स्टेटस रिटर्न करता है. विस्तृत प्रतिक्रिया नीचे पाई जा सकती है | +| मॉनिटर | ब्लॉकचेन के इवेंट स्ट्रीम में सदस्यता लेता है. विस्तृत प्रतिक्रिया नीचे देख सकते हैं | +| वर्जन | क्लाइंट के वर्तमान वर्जन को रिटर्न करता है | + +

स्टेटस के फ्लैग्स

+ +

grpc-पता

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +gRPC API का पता. डिफ़ॉल्ट: `127.0.0.1:9632`. + +

मॉनिटर फ्लैग्स

+ +

grpc-पता

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +gRPC API का पता. डिफ़ॉल्ट: `127.0.0.1:9632`. + +--- +

संस्करण कमांड

+ + + + + + version + + + + +रिलीज संस्करण, git शाखा, हैश को प्रतिबद्ध करें और निर्माण समय को प्रदर्शित करें. + +## सीक्रेट्स कमांड्स {#secrets-commands} + +| **कमांड** | **वर्णन** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| सीक्रेट्स शुरू करें | निजी कीज़ की संबंधित सीक्रेट्स मैनेजर से शुरूआत कराता है | +| सीक्रेट्स को जनरेट करें | एक सीक्रेट्स मैनेजर की कॉन्फ़िगरेशन फ़ाइल जनरेट करता है, जिसे पॉलीगॉन एज द्वारा पार्स किया जा सकता है | +| सीक्रेट्स आउटपुट | संदर्भ के लिए BLS और वैलिडेटर की सार्वजनिक की का पता, और नोड की आईडी प्रिंट करता है | + +### सीक्रेट्स की शुरुआत होने के फ्लैग्स {#secrets-init-flags} + +

कॉन्फ़िगरेशन

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +SecretsManager कॉन्फ़िगरेशन फ़ाइल के लिए पाथ सेट करता है. Hashicorp Vault के लिए इस्तेमाल किया गया. अगर हटा दिए गए हैं तो स्थानीय FS सीक्रेट्स के मैनेजर का इस्तेमाल किया जाता है. + +--- + +

डेटा-डायरेक्टरी

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +अगर स्थानीय FS का इस्तेमाल किया जाता है तो पॉलीगॉन एज डेटा के लिए डायरेक्टरी सेट करता है. + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +फ्लैग के सेट ये दर्शाते हैं कि ECDSA की जनरेट करनी है या नहीं. डिफ़ॉल्ट: `true`. + +--- + +

नेटवर्क

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +फ्लैग के सेट ये दर्शाते हैं कि Libp2p नेटवर्क की जनरेट करनी है या नहीं. डिफ़ॉल्ट: `true`. + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +फ्लैग के सेट ये दर्शाते हैं कि BLS की जनरेट करनी है या नहीं. डिफ़ॉल्ट: `true`. + +### सीक्रेट्स जनरेट करने के फ्लैग {#secrets-generate-flags} + +

डायरेक्टरी

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +सीक्रेट्स मैनेजर की कॉन्फ़िगरेशन फ़ाइल के लिए डिफ़ॉल्ट `./secretsManagerConfig.json` डायरेक्टरी सेट करता है: + +--- + +

प्रकार

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +सीक्रेट्स मैनेजर के प्रकार [`hashicorp-vault`]को निर्दिष्ट करता है . डिफ़ॉल्ट: `hashicorp-vault` + +--- + +

टोकन

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +सेवा के लिए एक्सेस टोकन को निर्दिष्ट करता है + +--- + +

सर्वर-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +सेवा के लिए सर्वर URL को निर्दिष्ट करता है + +--- + +

नाम

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +ऑन सर्विस रिकॉर्ड रखने के लिए नोड का नाम निर्दिष्ट करता है. डिफ़ॉल्ट: `polygon-edge-node` + +--- + +

नेमस्पेस

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Hashicorp वॉल्ट के सीक्रेट्स मैनेजर के लिए इस्तेमाल किए जाने वाले नेमस्पेस को निर्दिष्ट करता है. डिफ़ॉल्ट: `admin` + +### सीक्रेट्स आउटपुट फ्लैग्स {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +फ्लैग के सेट ये दर्शाते हैं कि केवल BLS की सार्वजनिक की का आउटपुट देना है या नहीं. डिफ़ॉल्ट: `true` + +--- + +

कॉन्फ़िगरेशन

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +SecretsManager कॉन्फ़िगरेशन फ़ाइल के लिए पाथ सेट करता है. अगर हटा दिए गए हैं तो स्थानीय FS सीक्रेट्स के मैनेजर का इस्तेमाल किया जाता है. + +--- + +

डेटा-डायरेक्टरी

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +अगर स्थानीय FS का इस्तेमाल किया जाता है तो पॉलीगॉन एज डेटा के लिए डायरेक्टरी सेट करता है. + +--- + +

नोड-आईडी

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +फ्लैग के सेट ये दर्शाते हैं कि केवल नेटवर्क नोड की आईडी का आउटपुट देना है या नहीं. डिफ़ॉल्ट: `true` + +--- + +

वैलिडेटर

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +फ्लैग के सेट ये दर्शाते हैं कि केवल वैलिडेटर के पते का आउटपुट देना है या नहीं. डिफ़ॉल्ट: `true` + +--- + +## प्रतिक्रियाएँ {#responses} + +### स्टेटस की प्रतिक्रिया {#status-response} + +प्रोटोकॉल के बफ़र्स को इस्तेमाल करके प्रतिक्रिया के ऑब्जेक्ट को परिभाषित किया जाता है. +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### मॉनिटर की प्रतिक्रिया {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## उपयोगिताएँ {#utilities} + +### वाइटलिस्ट की कमांड्स {#whitelist-commands} + +| **कमांड** | **वर्णन** | +|------------------------|-------------------------------------------------------------------------------------| +| वाइटलिस्ट शो करें | वाइटलिस्ट की जानकारी को प्रदर्शित करता है | +| वाइटलिस्ट डिप्लॉयमेंट | स्मार्ट कॉन्ट्रैक्ट को डिप्लॉय करने की वाइटलिस्ट को अपडेट करता है | + +

वाइटलिस्ट शो करें

+ + + + + whitelist show + + + + +वाइटलिस्ट की जानकारी को प्रदर्शित करता है. + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +जेनेसिस फ़ाइल को अपडेट करने के लिए निर्दिष्ट करता है. डिफ़ॉल्ट: `./genesis.json`. + +--- + +

वाइटलिस्ट का डिप्लॉयमेंट

+ +

चेन

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +जेनेसिस फ़ाइल को अपडेट करने के लिए निर्दिष्ट करता है. डिफ़ॉल्ट: `./genesis.json`. + +--- + +

पता

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +कॉन्ट्रैक्ट की डिप्लॉयमेंट वाइटलिस्ट में एक नया पता जोड़ता है. कॉन्ट्रैक्ट के डिप्लॉयमेंट की वाइटलिस्ट में केवल पते ही कॉन्ट्रैक्ट को डिप्लॉय कर सकते हैं. खाली होने पर कोई भी पता कॉन्ट्रैक्ट के डिप्लॉयमेंट को एग्ज़ीक्यूट कर सकता है + +--- + +

रिमूव

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +कॉन्ट्रैक्ट की डिप्लॉयमेंट वाइटलिस्ट से एक पते को हटा देता है. कॉन्ट्रैक्ट के डिप्लॉयमेंट की वाइटलिस्ट में केवल पते ही कॉन्ट्रैक्ट को डिप्लॉय कर सकते हैं. खाली होने पर कोई भी पता कॉन्ट्रैक्ट के डिप्लॉयमेंट को एग्ज़ीक्यूट कर सकता है + +--- + +### बैकअप के फ्लैग्स {#backup-flags} + +

grpc-पता

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +gRPC API का पता. डिफ़ॉल्ट: `127.0.0.1:9632`. + +--- + +

बाहर

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +आर्काइव फ़ाइल को सेव करने का पाथ. + +--- + +

फ्रॉम

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +आर्काइव में ब्लॉक्स की शुरूआती हाइट. डिफ़ॉल्ट: 0. + +--- + +

टू

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +आर्काइव में ब्लॉक्स के एंड की ऊँचाई. + +--- + +## जेनेसिस टेम्पलेट {#genesis-template} +ब्लॉकचेन के शुरुआती स्टेट को सेट करने के लिए जेनेसिस फ़ाइल का इस्तेमाल किया जाना चाहिए (उदाहरण के लिए अगर कुछ खातों में शुरू करने के लिए बैलेंस होना चाहिए). + +निम्नलिखित *./genesis.json* फ़ाइल को जनरेट किया गया है: +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### डेटा डायरेक्टरी {#data-directory} + +जब *डेटा-डायरेक्टरी* फ्लैग को एग्ज़ीक्यूट किया जाता है, एक **टेस्ट-चेन** फ़ोल्डर जनरेट होता है +फ़ोल्डर की संरचना में निम्नलिखित सब-फ़ोल्डर शामिल होते हैं: +* **ब्लॉकचेन** - ब्लॉकचेन ऑब्जेक्ट्स के लिए LevelDB को स्टोर करता है +* **trie** - Merkle कोशिश करने के लिए LevelDB को स्टोर करता है +* **कीस्टोर** - क्लाइंट के लिए निजी की को स्टोर करता है. इसमें libp2p की निजी की और सीलिंग / वैलिडेटर की निजी की भी शामिल होती है +* **सहमति** - सहमति की किसी भी जानकारी को स्टोर करता है जिसकी काम करते समय क्लाइंट को ज़रूरत हो सकती है + +## संसाधन {#resources} +* **[प्रोटोकॉल बफ़र्स](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/hi-edge/get-started/installation.md b/archive/edge/hi-edge/get-started/installation.md new file mode 100644 index 0000000000..20275d5032 --- /dev/null +++ b/archive/edge/hi-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: इंस्टॉल करना +description: "पॉलीगॉन एज कैसे इंस्टॉल करें." +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +कृपया अपने लिए इंस्टॉल करने के सही तरीके देखें. + +हम प्रि-बिल्ट रिलीज़ का इस्तेमाल करने और दिए गए चेकसम को सत्यापित करने का सुझाव देते हैं. + +## प्रि-बिल्ट रिलीज़ {#pre-built-releases} + +रिलीज़ की सूची के लिए [GitHub](https://github.com/0xPolygon/polygon-edge/releases) रिलीज़ पेज देखें. + +पॉलीगॉन एज Darwin और Linux के लिए क्रॉस-कम्पाइल्ड किए गए AMD64/ARM64 बाइनरी के साथ आता है. + +--- + +## डॉकर इमेज {#docker-image} + +आधिकारिक डॉकर इमेज को [hub.docker.com रजिस्ट्री](https://hub.docker.com/r/0xpolygon/polygon-edge) के तहत होस्ट किया जाता है. + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## सोर्स से बिल्डिंग {#building-from-source} + +`go install`का इस्तेमाल करने से पहले सुनिश्चित करें कि Go `>=1.18` इंस्टाल है और ठीक से कॉन्फ़िगर किया गया है. + +स्थिर शाखा नवीनतम रिलीज़ की शाखा है. + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## `go install` का इस्तेमाल करके + +`go install`का इस्तेमाल करने से पहले सुनिश्चित करें कि Go `>=1.17` इंस्टाल है और ठीक से कॉन्फ़िगर किया गया है. + +`go install github.com/0xPolygon/polygon-edge@release/` + +बाइनरी आपके `GOBIN`पर्यावरण वेरिएबल में उपलब्ध होगा, और नवीनतम रिलीज से होने वाले बदलावों को शामिल करेंगे. आप चेकआउट करने के लिए [गिटहब रिलिज कर](https://github.com/0xPolygon/polygon-edge/releases) सकते हैं कि जो एक latest. है. diff --git a/archive/edge/hi-edge/get-started/set-up-ibft-locally.md b/archive/edge/hi-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..53b3dc2db8 --- /dev/null +++ b/archive/edge/hi-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,412 @@ +--- +id: set-up-ibft-locally +title: स्थानीय सेटअप +description: "स्टेप-बाय-स्टेप स्थानीय सेटअप गाइड." +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution यह गाइड केवल परीक्षण प्रयोजनों के लिए है + +नीचे दी गई गाइड आपको इस बारे में निर्देश देगा कि परीक्षण और विकास प्रयोजनों के लिए अपने स्थानीय मशीन पर पॉलीगॉन एज नेटवर्क कैसे स्थापित करें. + +यह प्रक्रिया उस तरीके से काफी भिन्न है जिस तरह आप एक वास्तविक उपयोग परिदृश्य के लिए पॉलीगॉन एज नेटवर्क सेटअप करना चाहते हैं एक क्लाउड प्रोवाइडर पर: **[क्लाउड सेटअप](/docs/edge/get-started/set-up-ibft-on-the-cloud)** + +::: + + +## आवश्यकताएँ {#requirements} + +पॉलीगॉन एज इंस्टॉल करने के लिए [इंस्टॉलेशन](/docs/edge/get-started/installation) देखें. + +## ओवरव्यू {#overview} + +![स्थानीय सेटअप](/img/edge/ibft-setup/local.svg) + +इस गाइड में, हमारा लक्ष्य [IBFT सहमति प्रोटोकॉल](https://github.com/ethereum/EIPs/issues/650) के साथ काम करने वाला `polygon-edge`ब्लॉकचेन नेटवर्क स्थापित करना है. ब्लॉकचेन नेटवर्क में 4 नोड होते हैं जिनमें से सभी 4 को वैलिडेटर नोड कहा जाता है, और इसलिए वे ब्लॉक का प्रस्ताव करने और अन्य प्रस्तावकों से आए ब्लॉक को वैलिडेट करने दोनों के लिए पात्र होते हैं. +सभी 4 नोड एक ही मशीन पर रन करेंगे, क्योंकि यह गाइड आपको कम से कम समय में पूरी तरह से कार्यात्मक IBFT क्लस्टर प्रदान करने के लिए है. + +इसके लिए, हम 4 आसान स्टेप्स के माध्यम से आपको गाइड करेंगे: + +1. डेटा डायरेक्टरीज शुरू करने से 4 नोड में से प्रत्येक के लिए वैलिडेटर की उत्पन्न होगी और खाली ब्लॉकचेन डेटा डायेक्टरीज शुरू हो जाएगी. वैलिडेटर की, महत्वपूर्ण हैं क्योंकि हमें इन की का इस्तेमाल करके वैलिडेटर्स के प्रारंभिक सेट के साथ जेनेसिस ब्लॉक को बूटस्ट्रैप करने की जरूरत है. +2. बूटनोड के लिए कनेक्शन स्ट्रिंग की तैयारी करना हमारे द्वारा रन किए जाने वाले हर नोड के लिए महत्वपूर्ण जानकारी होगी कि पहली बार शुरू करते समय किस नोड को किससे कनेक्ट करना है. +3. जेनेसिस ब्लॉक में नेटवर्क के प्रारंभिक वैलिडेटर्स और **स्टेप 2** से बूटनोड कनेक्शन स्ट्रिंग को सेट करने के लिए इस्तेमाल किए गए **स्टेप 1** में जनरेट किए गए दोनों वैलिडेटर की को इनपुट के रूप में `genesis.json` फ़ाइल जनरेट करना पड़ेगा. +4. सभी नोड को रन करना इस गाइड का अंतिम लक्ष्य है और हम जो करते हैं उसका अंतिम स्टेप होगा, हम नोड्स को निर्देश देंगे कि किस डेटा डायरेक्टरी का इस्तेमाल करना है और `genesis.json` को कहाँ ढूँढना है जो शुरूआती नेटवर्क स्टेट को बूटस्ट्रैप करता है. + +चूंकि सभी चार नोड localhost पर रन करेंगे, इसलिए प्रक्रिया के दौरान यह उम्मीद की जाती है कि प्रत्येक नोड के लिए सभी डेटा डायरेक्टरीज एक ही पैरेंट डायरेक्टरी में हैं. + +:::info वैलिडेटर्स की संख्या + +क्लस्टर में नोड की न्यूनतम संख्या निर्धारित नहीं है, जिसका अर्थ है सिर्फ़ 1 वैलिडेटर नोड वाला क्लस्टर भी हो सकता है. +ध्यान रहे कि _सिंगल_ नोड क्लस्टर के साथ, **कोई क्रैश टॉलरेंस** और **BFT गारंटी** नहीं है. + +BFT गारंटी पाने के लिए नोड्स की न्यूनतम सुझाई गई संख्या 4 है - चूंकि 4 नोड क्लस्टर में, +होने पर काम चलाया जा सकता है, शेष 3 सामान्य रूप से काम करते हैं. + +::: + +## स्टेप 1: IBFT लिए डेटा फ़ोल्डर्स शुरू करें और वैलिडेटर कुंजी जनरेट करें {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +IBFT हासिल और रन करने के लिए, आपको डेटा फोल्डर्स को शुरू करने की जरूरत है, हर नोड के लिए एक: + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +इनमें से प्रत्येक कमांड वैलिडेटर की, सार्वजनिक की और [नोड ID](https://docs.libp2p.io/concepts/peer-id/) को प्रिंट करेगा. अगले स्टेप के लिए आपको पहले नोड की नोड ID की जरूरत होगी. + +### आउटपुटिंग सीक्रेट्स {#outputting-secrets} +अगर ज़रूरत हो तो सीक्रेट आउटपुट को दोबारा प्राप्त किया जा सकता है. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## स्टेप 2: बूटनोड के लिए multiaddr कनेक्शन स्ट्रिंग तैयार करें {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +नोड के लिए सफलतापूर्वक कनेक्टिविटी स्थापित करने के लिए, यह जरूर पता होना चाहिए कि किस `bootnode`सर्वर से कनेक्ट करना चाहिए +ताकि नेटवर्क पर शेष सभी नोड के बारे में जानकारी मिल जाए. को कभी-कभी p2p jargon में `rendezvous`सर्वर के रूप में भी जाना जाता `bootnode`है. + +`bootnode`पॉलीगॉन नोड का एक विशेष इंस्टैंस नहीं है. प्रत्येक पॉलीगॉन-एज नोड एक `bootnode`की तरह काम कर सकता है, लेकिन +हर पॉलीगॉन-एज नोड में निर्दिष्ट बूटनोड का सेट होना जरूरी है जिसे यह जानकारी प्राप्त करने के लिए संपर्क किया जाएगा कि नेटवर्क में सभी शेष नोड्स से कैसे कनेक्ट करें. + +अगर हमें बूटनोड निर्दिष्ट करने के लिए कनेक्शन स्ट्रिंग बनाना होगा, [तो हमें multiaddr फ़ॉर्मेट](https://docs.libp2p.io/concepts/addressing/) के अनुरूप होना होगा: +``` +/ip4//tcp//p2p/ +``` + +इस गाइड में, हम पहले और दूसरे नोड को अन्य सभी नोड के लिए बूटनोड के रूप में मानेंगे. इस परिदृश्य में क्या होगा कि नोड्स जो कनेक्ट करते हैं `node 1``node 2`या पारस्परिक रूप से संपर्क किए गए बूटनोड के माध्यम से एक दूसरे से कनेक्ट करने के तरीके के बारे में +जानकारी प्राप्त करेंगे. + +:::info नोड शुरू करने के लिए आपको कम से कम एक बूटनोड निर्दिष्ट करने की ज़रूरत है + +कम से कम **एक** बूटनोड की ज़रूरत होती है, इसलिए नेटवर्क में अन्य नोड एक दूसरे को खोज सकते हैं. अधिक बूटनोड्स का सुझाव दिया जाता है, क्योंकि +वे आउटेज के मामले में नेटवर्क को लचीलापन प्रदान करते हैं. इस गाइड में, हम दो नोड सूची देंगे, लेकिन `genesis.json`फ़ाइल की वैधता पर बिना किसा प्रभाव के, इसे फ्लाई पर बदला जा सकता है. + +::: + +चूंकि हम localhost पर रन कर रहे हैं, इसलिए यह मान लेना सुरक्षित है कि ``, `127.0.0.1`है + +`` के लिए हम `10001` का इस्तेमाल करेंगे, क्योंकि हम बाद में इस पोर्ट पर सुनने के लिए `node 1` के लिए libp2p सर्वर को कॉन्फ़िगर करेंगे. + +और अंत में, हमें की आवश्यकता है ``जिसे हम पहले से रन कर रहे `polygon-edge secrets init --data-dir test-chain-1`कमांड के आउटपुट से प्राप्त कर सकते हैं (जिसका इस्तेमाल के लिए की और डेटा डायरेक्टरी जनरेट करने के लिए किया गया था`node1`) + +असेंबली के बाद, के लिए multiaddr कनेक्शन स्ट्रिंग `node 1`जिसे हम बूटनोड के रूप में इस्तेमाल करेंगे, कुछ इस तरह दिखाई देगा (केवल जो अंत में है ``वह अलग होना चाहिए): +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +इसी तरह हम नीचे दिखाए गए अनुसार दूसरे बूटनोड के लिए multiaddr बनाते हैं +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info DNS होस्टनाम के नीचे दिखाया गया है, + +जो नोड्स कॉन्फ़िगरेशन के लिए DNS होस्टनाम का इस्तेमाल करता है. क्लाउड आधारित डिप्लॉयमेंट के लिए, यह एक बहुत ही उपयोगी सुविधा है, क्योंकि विभिन्न कारणों से नोड का ip बदल सकता है. + +DNS होस्टनाम का इस्तेमाल करते समय कनेक्शन स्ट्रिंग के लिए multiaddr फ़ॉर्मेट इस प्रकार है: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## स्टेप 3: 4 नोड के साथ जेनेसिस फ़ाइल तैयार करें {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +इस कमांड का क्या काम है: + +* `--ibft-validators-prefix-path` प्रीफिक्स फ़ोल्डर पाथ को एक निर्दिष्ट पाथ में सेट करता है जिसे IBFT, पॉलीगॉन एज में इस्तेमाल कर सकता +है. इस डायरेक्टरी का इस्तेमाल, फ़ो`consensus/`ल्डर को रखने के लिए किया जाता है, जहाँ वैलिडेटर की निजी कुंजी को रखा जाता है. जेनेसिस फ़ाइल - बूटस्ट्रैप नोड्स की प्रारंभिक सूची का निर्माण करने के लिए वैलिडेटर की सार्वजनिक कुंजी की जरूरत होती है. यह फ्लैग केवल स्थानीय होस्ट पर नेटवर्क सेट करते समय मायने रखता है, क्योंकि एक वास्तविक दुनिया परिदृश्य में हम उम्मीद नहीं कर सकते कि सभी नोड्स के डेटा डायरेक्टरीज, एक ही फ़ाइल सिस्टम पर होंगी जहां से हम उनकी सार्वजनिक कुंजी को आसानी से पढ़ सकते हैं. +* बूटनोड का पता सेट `--bootnode`करता है जो नोड्स को एक दूसरे को खोजने में सक्षम बनाता है. हम `node 1`की multiaddr स्ट्रिंग का इस्तेमाल करेंगे, जैसा कि **स्टेप 2** में बताया गया है. + +इस कमांड का परिणाम, `genesis.json` फ़ाइल है जिसमें हमारी नै ब्लॉकचेन का जेनेसिस ब्लॉक शामिल है, जिसमें पूर्वनिर्धारित वैलिडेटर सेट और कॉन्फ़िगरेशन भी शामिल है जिसके लिए पहले कनेक्टिविटी स्थापित करने के लिए नोड से संपर्क करना होगा. + +:::info ECDSA में स्विच करें + +BlS ब्लॉक हेडर का डिफ़ॉल्ट वैलिडेशन मोड है. अगर आप चाहते हैं कि आपकी सीरीज़ ECDSA मोड में चले, तो आप आर्ग्युमेंट के साथ `—ibft-validator-type`फ्लैग का इस्तेमाल कर सकते हैं`ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info Premining अकाउंट बैलेंस + +आप शायद अपने ब्लॉकचैन नेटवर्क को कुछ पतों और "premined" बैलेंस के साथ सेट करना चाहेंगे. + +इसे पाने के लिए, आप हर पते के रूप में जितने चाहें उतने फ़्लै`--premine`ग पास करें, जिसे आप ब्लॉकचैन पर एक निश्चित बैलेंस के साथ +शुरू करना चाहते हैं. + +उदाहरण के लिए, अगर हम अपने जेनेसिस ब्लॉक `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862`में के लिए 1000 ETH को premine करना चाहते हैं, तो हमें निम्नलिखित आर्ग्युमेंट देने होंगे: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**नोट करें कि premined रकम WEI में है, ETH में नहीं.** + +::: + +:::info ब्लॉक गैस लिमिट सेट करें + +हर ब्लॉक के लिए डिफ़ॉल्ट गैस लिमिट है`5242880`. यह वैल्यू जेनेसिस फ़ाइल में लिखी जाती है, पर आप इसे अपने अनुसार +बढ़ा/घटा सकते हैं. + +ये करने के लिए, आप नीचे दी गई डिज़ायर्ड वैल्यू के `--block-gas-limit`बाद, फ्लैग का इस्तेमाल कर सकते हैं : + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info सिस्टम फ़ाइल डिस्क्रिप्टर सीमा सेट करें + +कुछ ऑपरेटिंग सिस्टम पर डिफ़ॉल्ट फ़ाइल डिस्क्रिप्टर सीमा ( अधिकतम खुली फ़ाइलें ) बहुत कम है. +अगर नोड्स के हाई थ्रूपुट होने की उम्मीद है, तो आप इस सीमा को OS स्तर पर बढ़ाने पर विचार कर सकते हैं. + +Ubuntu डिस्ट्रो की प्रक्रिया इस प्रकार है (अगर आप Ubuntu/Debian डिस्ट्रो का इस्तेमाल नहीं कर रहे हैं, तो अपने OS के लिए आधिकारिक डॉक्स देखें) : +- मौजूदा os लिमिट चेक करें ( फ़ाइल खोलें ) +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- खुली फाइलों की लिमिट बढ़ाएँ + - स्थानीय रूप से - सिर्फ़ मौजूदा सत्र को प्रभावित करता है: + ```shell + ulimit -u 65535 + ``` + - वैश्विक रूप से या प्रति यूज़र ( /etc/security/limits.conf फ़ाइल के अंत में लिमिट जोड़ें) : + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +वैकल्पिक रूप से, अतिरिक्त पैरामीटर को संशोधित करें, फ़ाइल को सहेजें और सिस्टम को फिर से शुरू करें. फिर से शुरू करने का बाद फ़ाइल डिस्क्रिप्टर लिमिट चेक करें. +इसे limits.conf फ़ाइल में बताई गई वैल्यू पर सेट किया जाना चाहिए. + +::: + + +## स्टेप 4: सभी क्लाइंट्स रन करें {#step-4-run-all-the-clients} + +चूंकि हम पॉलीगॉन एज नेटवर्क को रन करने का प्रयास कर रहे हैं जिसमें एक ही मशीन पर सभी 4 नोड होते हैं, इसलिए हमें ख्याल रखना चाहिए कि पोर्ट टकराव न हो. इसीलिए हम नोड के प्रत्येक सर्वर के लिसनिंग पोर्ट का पता लगाने के लिए निम्नलिखित तर्क का इस्तेमाल करेंगे: + +- `node 1` के gRPC सर्वर के लिए `10000`, `node 2` के GRPC सर्वर के लिए `20000`, आदि. +- `node 1`के libp2p सर्वर के लिए `10001`, `node 2` के libp2p सर्वर के लिए `20001`, आदि. +- `node 1`के JSON-RPC सर्वर के लिए `10002`, `node 2` के JSON-RPC सर्वर के लिए `20002`, आदि. + +**पहला** क्लाइंट को रन करने के लिए (पोर्ट `10001` को नोट करें क्योंकि इसे नोड 1 की नोड ID के साथ **स्टेप 2** में libp2p multiaddr के हिस्से के रूप में इस्तेमाल किया गया था): + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +**दूसरा** क्लाइंट रन करने के लिए: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +**तीसरा** क्लाइंट रन करने के लिए: + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +**चौथा** क्लाइंट रन करने के लिए: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +अब तक जो कुछ किया गया है, उसे संक्षेप में पूरा करने के लिए: + +* क्लाइंट डेटा की डायरेक्टरी को **./test-chain-\***के रूप में निर्दिष्ट किया गया है +* क्रमशः हर नोड के लिए पोर्ट **1000**, **2000**, **3000** और **4000** पर GRPC सर्वर शुरू किए गए हैं +* क्रमशः हर नोड के लिए पोर्ट **10001**, **20001**, **30001** और **40001** पर libp2p सर्वर शुरू किए गए हैं +* क्रमशः हर नोड के लिए पोर्ट **10002**, **20002**, **30002** and **40002** पर JSON-RPC सर्वर शुरू किए गए हैं +* *सील* फ्लैग का मतलब है कि जिस नोड को शुरू किया जा रहा है वह ब्लॉक सीलिंग में भाग लेने वाला है +* *चेन* फ्लैग निर्दिष्ट करता है कि चेन कॉन्फ़िगरेशन के लिए किस जेनेसिस फ़ाइल का इस्तेमाल किया जाना चाहिए + +जेनेसिस फ़ाइल की संरचना [CLI कमांड्स](/docs/edge/get-started/cli-commands) सेक्शन में होती है. + +पिछली कमांड को चलाने के बाद, आपने एक 4 नोड पॉलीगॉन एज नेटवर्क सेट अप किया है, जो ब्लॉक को सील करने और +नोड विफलता से उबरने में सक्षम है. + +:::info config फ़ाइल का इस्तेमाल करके क्लाइंट शुरू करें + +CLI आर्ग्युमेंट के रूप में सभी कॉन्फ़िगरेशन पैरामीटर को निर्दिष्ट करने के बजाय, क्लाइंट को नीचे दी गई कमांड को एक्जीक्यूट करके एक फ़ाइल का इस्तेमाल किया जा सकता है: + +````bash +polygon-edge server --config +```` +उदाहरण: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +वर्तमान में, हम `yaml` और `json` आधारित कॉन्फ़िगरेशन फ़ाइल का समर्थन करते हैं, सैम्पल कॉन्फ़िगरेशन फ़ाइल **[यहाँ](/docs/edge/configuration/sample-config)** मिल सकती है + +::: + +:::info नॉन-वैलिडेटर नोड रन करने के स्टेप + +नॉन-वैलिडेटर हमेशा वैलिडेटर नोड से प्राप्त नए ब्लॉक को सिंक करेगा, आप नीचे दिए गए कमांड को रन करके एक नॉन-वैलिडेटर नोड शुरू कर सकते हैं. + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +उदाहरण के लिए, आप नीचे दी गई कमांड को एक्जीक्यूट करके **पांचवां** नॉन-वैलिडेटर क्लाइंट पता कर सकते हैं : + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info प्राइस लिमिट निर्दिष्ट करें +आने वाले ट्रांज़ैक्शन के लिए, तय **प्राइस लिमिट** के साथ एक पॉलीगॉन एज नोड शुरू किया जा सकता है. + +प्राइस लिमिट के लिए यूनिट है`wei`. + +कीमत सीमा निर्धारित करने का अर्थ है कि मौजूदा नोड द्वारा संसाधित किए गए किसी भी ट्रांज़ैक्शन में गैस की क़ीमत निर्धारित कीमत सीमा से **अधिक** +होगी, अन्यथा इसे ब्लॉक में शामिल नहीं होगा. + +अधिकांश नोड्स एक निश्चित क़ीमत की सीमा के नियम के तहत होते हैं, कि नेटवर्क में ट्रांज़ैक्शन एक निश्चित क़ीमत की +सीमा से कम नहीं हो सकता है. + + वैल्यू लिमिट की डिफ़ॉल्ट वैल्यू है, जिसका अर्थ है `0`कि यह डिफ़ॉल्ट रूप से लागू नहीं होता है. + + `--price-limit`फ्लैग के इस्तेमाल का उदाहरण: +````bash +polygon-edge server --price-limit 100000 ... +```` + +यह ध्यान देने लायक है कि प्राइस लिमिट **केवल गैर-स्थानीय ट्रांज़ैक्शन पर लागू होती है**, जिसका अर्थ है +कि प्राइस लिमिट नोड पर स्थानीय रूप से जोड़े गए ट्रांज़ैक्शन पर लागू नहीं होती है. + +::: + +:::info WebSocket URL + +डिफ़ॉल्ट रूप से, जब आप पॉलीगॉन एज चलाते हैं, तो यह चेन लोकेशन के आधार पर एक WebSocket URL जेनरेट करता है. +URL स्कीम HTTPS और HTTP के `ws://`लिए इस्तेमाल `wss://`होती हैं. + +Localhost वेबसॉकेट का URL: +````bash +ws://localhost:10002/ws +```` +नोट करें कि पोर्ट नंबर नोड के लिए चुने गए JSON-RPC पोर्ट पर निर्भर करता है. + +Edgenet वेबसॉकेट का URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## स्टेप 5: पॉलीगॉन-एज नेटवर्क के साथ इंटरैक्ट करें {#step-5-interact-with-the-polygon-edge-network} + +अब जबकि आपने कम से कम 1 रनिंग क्लाइंट को सेट कर लिया है, इसलिए अब आप ऊपर प्रीमाइन किए गए अकाउंट का इस्तेमाल करके और 4 में से किसी भी नोड में JSON-RPC URL को निर्दिष्ट करके ब्लॉकचेन के साथ इंटरैक्ट कर सकते हैं: +- नोड 1:`http://localhost:10002` +- नोड 2:`http://localhost:20002` +- नोड 3:`http://localhost:30002` +- नोड 4:`http://localhost:40002` + +नव निर्मित क्लस्टर को ऑपरेटर कमांड जारी करने के लिए इस गाइड को फॉलो करें: [ऑपरेटर जानकारी को कैसे क्वेरी करें](/docs/edge/working-with-node/query-operator-info) (हमारे द्वारा बनाए गए क्लस्टर के लिए GRPC पोर्ट, क्रमशः प्रत्येक नोड के लिए `10000`/`20000`/`30000`/`40000` होते हैं) diff --git a/archive/edge/hi-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/hi-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..54cfe57da1 --- /dev/null +++ b/archive/edge/hi-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,441 @@ +--- +id: set-up-ibft-on-the-cloud +title: क्लाउड सेटअप +description: "स्टेप-बाय-स्टेप क्लाउड गाइड." +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info यह गाइड मेननेट या टेस्टनेट सेटअप के लिए है + +नीचे दी गई गाइड आपको जानने में मदद करेगी कि टेस्टनेट या मेननेट के उत्पादन सेटअप के लिए क्लाउड प्रोवाइडर पर पॉलीगॉन एज नेटवर्क कैसे सेट करें. + +अगर आप प्रोडक्शन-लाइक सेटअप करने से पहले क्विक टेस्ट `polygon-edge` करने के लिए पॉलीगॉन एज नेटवर्क को स्थानीय रूप से सेट अप करना चाहते हैं, तो कृपया +**[स्थानीय सेटअप](/docs/edge/get-started/set-up-ibft-locally)** + +::: + +## आवश्यकताएँ देखें {#requirements} + +पॉलीगॉन एज इंस्टॉल करने के लिए [इंस्टॉलेशन](/docs/edge/get-started/installation) देखें. + +### VM कनेक्टिविटी सेट अप करें {#setting-up-the-vm-connectivity} + +क्लाउड प्रोवाइडर की अपनी पसंद के आधार पर, आप फ़ायरवॉल, सुरक्षा समूहों, या एक्सेस कंट्रोल की सूचियों का इस्तेमाल कर सकते हैं +और VM के बीच कनेक्टिविटी और नियम सेट अप कर सकते हैं. + +`polygon-edge` के एक भाग के रूप में libp2p सर्वर को अन्य VM के संपर्क में लाने की ज़रूरत है, +इसके लिए सिर्फ़ डिफ़ॉल्ट libp2p पोर्ट `1478` पर VM के बीच संचार की अनुमति देना काफ़ी है. + +## ओवरव्यू {#overview} + +![क्लाउड सेटअप](/img/edge/ibft-setup/cloud.svg) + +इस गाइड में, हमारा लक्ष्य [IBFT सहमति प्रोटोकॉल](https://github.com/ethereum/EIPs/issues/650) के साथ `polygon-edge`काम करने वाला ब्लॉकचेन नेटवर्क स्थापित करना है. ब्लॉकचेन नेटवर्क में 4 नोड होते हैं जिनमें से सभी 4 को वैलिडेटर नोड कहा जाता है, और ब्लॉक का प्रस्ताव करने वाले और अन्य प्रस्तावों से आए ब्लॉक को वैलिडेट करने के लिए वे दोनों ही पात्र होते हैं. +सभी 4 नोड अपने VM पर रन करेंगे, क्योंकि इस गाइड का उद्देश्य आपको एक भरोसेमंद नेटवर्क सेटअप सुनिश्चित करने के लिए वैलिडेटर की को निजी रखते हुए पूरी तरह काम करने वाला पॉलीगॉन एज नेटवर्क देना है. + +इसके लिए, हम 4 आसान स्टेप्स के माध्यम से आपको गाइड करेंगे: + +0. ऊपर दी गई **आवश्यकताओं** की सूची देखें +1. सभी वैलिडेटर्स के लिए निजी की तैयार करें और डेटा डायरेक्टरी को शुरू करें +2. साझा किए गए `genesis.json` में रखने के लिए बूटनोड के लिए कनेक्शन स्ट्रिंग तैयार करें +3. अपनी स्थानीय मशीन पर `genesis.json` बनाएँ और इसे प्रत्येक नोड्स पर भेजें/ट्रांसफ़र करें +4. सभी नोड शुरू करें + +:::info वैलिडेटर्स की संख्या + +क्लस्टर में नोड की न्यूनतम संख्या निर्धारित नहीं है, जिसका अर्थ है सिर्फ़ 1 वैलिडेटर नोड वाला क्लस्टर भी हो सकता है. +ध्यान रहे कि _सिंगल_ नोड क्लस्टर के साथ, **कोई क्रैश टॉलरेंस** और **BFT गारंटी** नहीं है. + +BFT गारंटी पाने के लिए नोड्स की न्यूनतम सुझाई गई संख्या 4 है - चूंकि 4 नोड क्लस्टर में, +होने पर काम चलाया जा सकता है, शेष 3 सामान्य रूप से काम करते हैं. + +::: + +## स्टेप 1: डेटा फ़ोल्डर को शुरू करें और वैलिडेटर की जनरेट करें {#step-1-initialize-data-folders-and-generate-validator-keys} + +पॉलीगॉन एज शुरू करने और रन करने के लिए, आपको प्रत्येक नोड पर डेटा फ़ोल्डर्स शुरू करना होगा: + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +इनमें से प्रत्येक कमांड वैलिडेटर की, सार्वजनिक की और [नोड ID](https://docs.libp2p.io/concepts/peer-id/) को प्रिंट करेगा. अगले स्टेप के लिए आपको पहले नोड की नोड ID की जरूरत होगी. + +### आउटपुटिंग सीक्रेट्स {#outputting-secrets} +अगर ज़रूरत हो तो सीक्रेट आउटपुट को दोबारा प्राप्त किया जा सकता है. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning अपनी डेटा डायरेक्टरी अपने पास रखें! + +ब्लॉकचैन स्टेट को बनाए रखने के लिए डायरेक्टरी को शुरू करने के अलावा, ऊपर जनरेट की गई डेटा डायरेक्टरी आपके वैलिडेटर की निजी की भी जनरेट करेगी. **इस की को सीक्रेट रखा जाना चाहिए, क्योंकि इसे चुराने से कोई व्यक्ति आपको नेटवर्क में वैलिडेटर के रूप में दिखा सकता है!** +::: + +## स्टेप 2: बूटनोड के लिए multiaddr कनेक्शन स्ट्रिंग तैयार करें {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +कनेक्टिविटी को सफलतापूर्वक स्थापित करने के लिए, नोड के लिए, यह पता करना होगा कि किस `bootnode` सर्वर से कनेक्ट करना होगा +ताकि नेटवर्क पर शेष सभी नोड के बारे में जानकारी मिल जाए. `bootnode` को कभी-कभी p2p jargon में `rendezvous` सर्वर के रूप में भी जाना जाता है. + +`bootnode` पॉलीगॉन एज नोड का एक विशेष उदाहरण नहीं है. हर पॉलीगॉन नोड एक `bootnode` के रूप में काम कर सकता है और +प्रत्येक पॉलीगॉन एज नोड में बूटनोड्स का एक ख़ास सेट होना चाहिए, जिससे नेटवर्क में सभी शेष नोड्स के साथ जुड़ने के तरीके के बारे में +जानकारी प्रदान करने के लिए संपर्क किया जाएगा. + +अगर हमें बूटनोड निर्दिष्ट करने के लिए कनेक्शन स्ट्रिंग बनाना होगा, [तो हमें multiaddr फ़ॉर्मेट](https://docs.libp2p.io/concepts/addressing/) के अनुरूप होना होगा: +``` +/ip4//tcp//p2p/ +``` + +इस गाइड में, हम पहले और दूसरे नोड को अन्य सभी नोड के लिए बूटनोड के रूप में मानेंगे. इस परिदृश्य में क्या होगा कि नोड्स जो कनेक्ट करते हैं `node 1``node 2`या पारस्परिक रूप से संपर्क किए गए बूटनोड के माध्यम से एक दूसरे से कनेक्ट करने के तरीके के बारे में +जानकारी प्राप्त करेंगे. + +:::info नोड शुरू करने के लिए आपको कम से कम एक बूटनोड निर्दिष्ट करने की ज़रूरत है + +कम से कम **एक** बूटनोड की ज़रूरत होती है, इसलिए नेटवर्क में अन्य नोड एक दूसरे को खोज सकते हैं. अधिक बूटनोड्स का सुझाव दिया जाता है, क्योंकि +वे आउटेज के मामले में नेटवर्क को लचीलापन प्रदान करते हैं. इस गाइड में, हम दो नोड सूची देंगे, लेकिन `genesis.json` फ़ाइल की वैधता पर बिना किसा प्रभाव के, इसे फ्लाई पर बदला जा सकता है. + +::: + +चूंकि `` multiaddr कनेक्शन स्ट्रिंग का पहला भाग है, यहाँ आपको अन्य नोड्स द्वारा पहुँच योग्य IP पता दर्ज करने की ज़रूरत होगी, आपके सेटअप के आधार पर यह निजी या सार्वजनिक IP पता हो सकता है, `127.0.0.1`या नहीं. + +`` के लिए, हम `1478` का इस्तेमाल करेंगे, क्योंकि यह डिफ़ॉल्ट libp2p पोर्ट है. + +और अंत में, हमें `` की आवश्यकता है जिसे हम पहले से रन कर रहे `polygon-edge secrets init --data-dir data-dir`कमांड के आउटपुट से प्राप्त कर सकते हैं (जिसका इस्तेमाल `node 1` के लिए की और डेटा डायरेक्टरी जनरेट करने के लिए किया गया था) + +असेंबली के बाद, `node 1` के लिए multiaddr कनेक्शन स्ट्रिंग जिसे हम बूटनोड के रूप में इस्तेमाल करेंगे, कुछ इस तरह दिखाई देगा (केवल ``जो अंत में है वह अलग होना चाहिए): +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +इसी तरह हम दूसरे बूटनोड के लिए multiaddr को बनाते हैं जैसा कि ips पॉलीगॉन एज के बजाय +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info DNS होस्टनाम के नीचे दिखाया गया है, + +जो नोड्स कॉन्फ़िगरेशन के लिए DNS होस्टनाम का इस्तेमाल करता है. क्लाउड आधारित डिप्लॉयमेंट के लिए, यह एक बहुत ही उपयोगी सुविधा है, क्योंकि विभिन्न कारणों से नोड का ip बदल सकता है. + +DNS होस्टनाम का इस्तेमाल करते समय कनेक्शन स्ट्रिंग के लिए multiaddr फ़ॉर्मेट इस प्रकार है: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## स्टेप 3: 4 नोड के साथ जेनेसिस फ़ाइल तैयार करें {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +यह स्टेप आपकी स्थानीय मशीन पर रन किया जा सकता है, लेकिन आपको 4 वैलिडेटर्स में से प्रत्येक के लिए सार्वजनिक वैलिडेटर की की ज़रूरत होगी. + +वैलिडेटर `Public key (address)` को सुरक्षित रूप से साझा कर सकते हैं जैसा कि आउटपुट में नीचे उनके `secrets init`कमांड में दिखाया गया है, ताकि +आप प्रारंभिक वैलिडेटर सेट में उन वैलिडेटर्स के साथ सुरक्षित रूप से Genesis.json जनरेट कर सकते हैं, जो उनकी सार्वजनिक की द्वारा पहचाने जाते हैं: + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +दिखाया गया है कि आपने सभी 4 वैलिडेटर्स की सार्वजनिक की प्राप्त कर ली हैं, `genesis.json` जनरेट करने के लिए, आप निम्नलिखित कमांड रन कर सकते हैं + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +इस कमांड का क्या काम है: + +* `--ibft-validator` वैलिडेटर की सार्वजनिक की सेट करता है जिसे जेनेसिस ब्लॉक में प्रारंभिक वैलिडेटर सेट में शामिल किया जाना चाहिए. कई प्रारंभिक वैलिडेटर हो सकते हैं. +* `--bootnode` बूटनोड का पता सेट करता है जो नोड्स को एक दूसरे को खोजने में सक्षम बनाता है. जैसा कि **स्टेप 2** में है, हम `node 1` के multiaddr स्ट्रिंग का इस्तेमाल करेंगे, हालाँकि जैसा कि ऊपर दिखाया गया है, आप जितने चाहें उतने बूटनोड्स जोड़ सकते हैं. + +:::info ECDSA में स्विच करें + +BlS ब्लॉक हेडर का डिफ़ॉल्ट वैलिडेशन मोड है. अगर आप चाहते हैं कि आपकी सीरीज़ ECDSA मोड में चले, तो आप आर्ग्युमेंट के साथ `—ibft-validator-type`फ्लैग का इस्तेमाल कर सकते हैं`ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info Premining अकाउंट बैलेंस + +आप शायद अपने ब्लॉकचैन नेटवर्क को कुछ पतों और "premined" बैलेंस के साथ सेट करना चाहेंगे. + +इसे पाने के लिए, आप हर पते के रूप में जितने चाहें उतने फ़्लै`--premine`ग पास करें, जिसे आप ब्लॉकचैन पर एक निश्चित बैलेंस के साथ +शुरू करना चाहते हैं. + +उदाहरण के लिए, अगर हम अपने जेनेसिस ब्लॉक `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862`में के लिए 1000 ETH को premine करना चाहते हैं, तो हमें निम्नलिखित आर्ग्युमेंट देने होंगे: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**नोट करें कि premined रकम WEI में है, ETH में नहीं.** + +::: + +:::info ब्लॉक गैस लिमिट सेट करें + +हर ब्लॉक के लिए डिफ़ॉल्ट गैस लिमिट है`5242880`. यह वैल्यू जेनेसिस फ़ाइल में लिखी जाती है, पर आप इसे अपने अनुसार +बढ़ा/घटा सकते हैं. + +ये करने के लिए, आप नीचे दी गई डिज़ायर्ड वैल्यू के `--block-gas-limit`बाद, फ्लैग का इस्तेमाल कर सकते हैं : + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info सिस्टम फ़ाइल डिस्क्रिप्टर सीमा सेट करें + +कुछ ऑपरेटिंग सिस्टम पर डिफ़ॉल्ट फ़ाइल डिस्क्रिप्टर सीमा ( अधिकतम खुली फ़ाइलें ) बहुत कम है. +अगर नोड्स के हाई थ्रूपुट होने की उम्मीद है, तो आप इस सीमा को OS स्तर पर बढ़ाने पर विचार कर सकते हैं. + +Ubuntu डिस्ट्रो की प्रक्रिया इस प्रकार है (अगर आप Ubuntu/Debian डिस्ट्रो का इस्तेमाल नहीं कर रहे हैं, तो अपने OS के लिए आधिकारिक डॉक्स देखें) : +- मौजूदा os लिमिट चेक करें ( फ़ाइल खोलें ) +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- खुली फाइलों की लिमिट बढ़ाएँ + - स्थानीय रूप से - सिर्फ़ मौजूदा सत्र को प्रभावित करता है: + ```shell + ulimit -u 65535 + ``` + - वैश्विक रूप से या प्रति यूज़र ( /etc/security/limits.conf फ़ाइल के अंत में लिमिट जोड़ें) : + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +वैकल्पिक रूप से, अतिरिक्त पैरामीटर को संशोधित करें, फ़ाइल को सहेजें और सिस्टम को फिर से शुरू करें. फिर से शुरू करने का बाद फ़ाइल डिस्क्रिप्टर लिमिट चेक करें. +इसे limits.conf फ़ाइल में बताई गई वैल्यू पर सेट किया जाना चाहिए. + +::: + +निर्दिष्ट करने के बाद: +1. वैलिडेटर की सार्वजनिक की जेनेसिस ब्लॉक में शामिल की जानी चाहिए क्योंकि वैलिडेटर +2. बूटनोड multiaddr कनेक्शन स्ट्रिंग्स सेट करता है +3. जेनेसिस ब्लॉक में शामिल किए जाने वाले Premined अकाउंट और बैलेंस + +और `genesis.json` जनरेट करने के लिए, आपको इसे नेटवर्क के सभी VM में कॉपी करना चाहिए. अपने सेटअप के आधार पर आप +इसे कॉपी/पेस्ट कर सकते हैं, नोड ऑपरेटर को भेज सकते हैं या बस SCP/FTP पर भेज सकते हैं. + +जेनेसिस फ़ाइल की संरचना [CLI कमांड्स](/docs/edge/get-started/cli-commands) सेक्शन में होती है. + +## स्टेप 4: सभी क्लाइंट्स रन करें {#step-4-run-all-the-clients} + +:::note क्लाउड प्रोवाइडर्स पर नेटवर्किंग + +अधिकांश क्लाउड प्रोवाइडर आपके VM पर सीधे नेटवर्क इंटरफेस के रूप में IP पते (ख़ासकर सार्वजनिक) को साझा नहीं करते हैं बल्कि एक अदृश्य NAT प्रॉक्सी सेट करते हैं. + + +इस मामले में नोड्स को एक दूसरे से कनेक्ट करने की अनुमति देने के लिए, आपको सभी इंटरफेस पर बाइंड करने के लिए `0.0.0.0`IP पते की ज़रूरत होगी, लेकिन आपको अभी भी IP पते या DNS पता निर्दिष्ट करने की ज़रूरत होगी जो अन्य नोड्स आपके उदाहरणों से कनेक्ट करने के लिए इस्तेमाल कर सकते हैं. यह या तो `--nat` या `--dns` आर्ग्युमेंट का इस्तेमाल करके प्राप्त किया जाता है जहाँ आप क्रमशः अपना बाहरी IP या DNS पता निर्दिष्ट कर सकते हैं. + + +#### उदाहरण {#example} + +संबंधित IP पता जिस पर आप ध्यान देना चाहते हैं वह `192.0.2.1`है, लेकिन यह सीधे आपके किसी भी नेटवर्क इंटरफेस से जुड़ा नहीं होता. + +नोड्स को कनेक्ट करने की अनुमति देने के लिए, आपको निम्नलिखित पैरामीटर पास करने होंगे: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +या, अगर आप एक DNS पता `dns/example.io` निर्दिष्ट करना चाहते हैं, तो निम्नलिखित पैरामीटर पास करें: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +यह आपके नोड के सभी इंटरफेस पर ध्यान देगा, लेकिन इसके बारे में भी जानकारी देगा कि ग्राहक निर्दिष्ट `--nat` या `--dns` पते के माध्यम से इससे जुड़ रहे हैं. + +::: + +**पहला** क्लाइंट रन करने के लिए: + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +**दूसरा ** क्लाइंट रन करने के लिए: + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +**तीसरा** क्लाइंट रन करने के लिए: + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +**पहला** क्लाइंट रन करने के लिए: + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +पिछली कमांड को चलाने के बाद, आपने एक 4 नोड पॉलीगॉन एज नेटवर्क सेट अप किया है, जो ब्लॉक को सील करने और +नोड विफलता से उबरने में सक्षम है. + +:::info config फ़ाइल का इस्तेमाल करके क्लाइंट शुरू करें + +CLI आर्ग्युमेंट के रूप में सभी कॉन्फ़िगरेशन पैरामीटर को निर्दिष्ट करने के बजाय, क्लाइंट को नीचे दी गई कमांड को एक्जीक्यूट करके एक फ़ाइल का इस्तेमाल किया जा सकता है: + +````bash +polygon-edge server --config +```` +उदाहरण : + +````bash +polygon-edge server --config ./test/config-node1.json +```` +अभी हम सिर्फ़ `json` आधारित कॉन्फ़िगरेशन फ़ाइल की सहायता करते हैं, सैंपल कॉन्फ़िगरेशन फ़ाइल **[यहाँ](/docs/edge/configuration/sample-config)** मिल सकती है + +::: + +:::info नॉन-वैलिडेटर नोड रन करने के स्टेप + +नॉन-वैलिडेटर हमेशा वैलिडेटर नोड से प्राप्त नए ब्लॉक को सिंक करेगा, आप नीचे दिए गए कमांड को रन करके एक नॉन-वैलिडेटर नोड शुरू कर सकते हैं. + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +उदाहरण के लिए, आप नीचे दी गई कमांड को एक्जीक्यूट करके **पांचवां** नॉन-वैलिडेटर क्लाइंट पता कर सकते हैं : + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info प्राइस लिमिट निर्दिष्ट करें +आने वाले ट्रांज़ैक्शन के लिए, तय **प्राइस लिमिट** के साथ एक पॉलीगॉन एज नोड शुरू किया जा सकता है. + +प्राइस लिमिट के लिए यूनिट है`wei`. + +प्राइस लिमिट निर्धारित करने का अर्थ है कि मौजूदा नोड द्वारा संसाधित किए गए किसी भी ट्रांज़ैक्शन के लिए निर्धारित क़ीमत की सीमा से **अधिक** +गैस प्राइस की ज़रूरत होगी, नहीं तो इसे एक ब्लॉक में शामिल नहीं किया जाएगा. + +अधिकांश नोड्स एक निश्चित क़ीमत की सीमा के नियम के तहत होते हैं, कि नेटवर्क में ट्रांज़ैक्शन एक निश्चित क़ीमत की +सीमा से कम नहीं हो सकता है. + + वैल्यू लिमिट की डिफ़ॉल्ट वैल्यू है, जिसका अर्थ है `0`कि यह डिफ़ॉल्ट रूप से लागू नहीं होता है. + + `--price-limit`फ्लैग के इस्तेमाल का उदाहरण: +````bash +polygon-edge server --price-limit 100000 ... +```` + +यह ध्यान देने लायक है कि प्राइस लिमिट **केवल गैर-स्थानीय ट्रांज़ैक्शन पर लागू होती है**, जिसका अर्थ है +कि प्राइस लिमिट नोड पर स्थानीय रूप से जोड़े गए ट्रांज़ैक्शन पर लागू नहीं होती है. + +::: + +:::info WebSocket URL + +डिफ़ॉल्ट रूप से, जब आप पॉलीगॉन एज चलाते हैं, तो यह चेन लोकेशन के आधार पर एक WebSocket URL जेनरेट करता है. +URL स्कीम HTTPS और HTTP के `ws://`लिए इस्तेमाल `wss://`होती हैं. + +Localhost वेबसॉकेट का URL: +````bash +ws://localhost:10002/ws +```` +नोट करें कि पोर्ट नंबर नोड के लिए चुने गए JSON-RPC पोर्ट पर निर्भर करता है. + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/hi-edge/get-started/terraform-aws-deployment.md b/archive/edge/hi-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..bc208dbbb8 --- /dev/null +++ b/archive/edge/hi-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,169 @@ +--- +id: terraform-aws-deployment +title: Terraform AWS डिप्लॉयमेंट +description: "Terraform का इस्तेमाल करके AWS प्रोवाइडर पर पॉलीगॉन एज नेटवर्क डिप्लॉय करें" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info उत्पादन डिप्लॉयमेंट गाइड + +यह आधिकारिक है, प्रोडक्शन के लिए तैयार है, पूरी तरह से स्वचालित एक AWS डिप्लॉयमेंट गाइड है. + +***[क्लाउड](set-up-ibft-on-the-cloud)*** या ***[स्थानीय](set-up-ibft-locally)*** पर मैनुअल डिप्लॉयमेंट +का सुझाव दिया जाता है ताकि प्रोवाइडर AWS ना होने पर टेस्टिंग की जा सके. + +::: + +:::info + +यह डिप्लॉयमेंट सिर्फ़ POA है. +अगर PoS मैकेनिज्म की ज़रूरत है, तो PoA से PoS पर स्विच करने के लिए अभी इस ***[गाइड](/docs/edge/consensus/migration-to-pos)*** का पालन करें. +::: + +इस गाइड में विस्तार से AWS क्लाउड प्रोवाइडर पर पॉलीगॉन एज ब्लॉकचेन नेटवर्क डिप्लॉय करने की प्रक्रिया का वर्णन करेंगे, +जो कि उत्पादन के लिए तैयार है क्योंकि वैलिडेटर नोड्स कई उपलब्धता ज़ोन में फैले हुए हैं. + +## आवश्यक शर्तें {#prerequisites} + +### सिस्टम टूल {#system-tools} +* [terraform](https://www.terraform.io/) +* [aws cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [aws एक्सेस की ID और सीक्रेट एक्सेस की](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Terraform वेरिएबल्स {#terraform-variables} +दो वेरिएबल जो डिवेलप को चलाने से पहले प्रदान किया जाना चाहिए: + +* `alb_ssl_certificate` - https प्रोटोकॉल के लिए ALB द्वारा इस्तेमाल किए जाने वाले AWS प्रमाणपत्र मैनेजर के प्रमाणपत्र का ARN. डिप्लॉयमेंट शुरू करने से पहले प्रमाणपत्र जनरेट किया जाना चाहिए और उसका स्टेटस **जारी** किया जाना चाहिए +* `premine`- वह अकाउंट जो premined नेटिव मुद्रा प्राप्त करेगा. +वैल्यू को आधिकारिक [CLI](/docs/edge/get-started/cli-commands#genesis-flags) फ़्लैग विनिर्देशों का पालन करना चाहिए + +## डिप्लॉयमेंट की जानकारी {#deployment-information} +### डिप्लॉय किए गए संसाधन {#deployed-resources} +डिप्लॉय किए गए संसाधनों का हाई लेवल ओवरव्यू: + +* डेडिकेटेड VPC +* 4 वेलिडेटर नोड्स (जो बूट नोड्स भी हैं) +* नोड्स आउटबाउंड इंटरनेट ट्रैफ़िक को अनुमति देने के लिए 4 NAT गेटवे +* Lambda फ़ंक्शन का इस्तेमाल पहले (जेनेसिस) ब्लॉक को जनरेट करने और सीरीज़ शुरू करने के लिए किया जाता है +* डेडिकेटेड सुरक्षा समूह और IAM भूमिकाएँ +* genesis.json फ़ाइल को स्टोर करने के लिए इस्तेमाल किया गया S3 बकेट +* एप्लिकेशन लोड बैलेंसर JSON-RPC एंडपॉइंट को खुलासा करने के लिए इस्तेमाल किया जाता है + +### फॉल्ट टोलेरेंस {#fault-tolerance} + +इस डिप्लॉयमेंट के लिए सिर्फ़ 4 उपलब्धता क्षेत्रों वाले ज़ोन की ज़रूरत होती है. हर नोड सिंगल AZ में डिप्लॉय किया जाता है. + +हर नोड को एक सिंगल AZ में रखकर, पूरे ब्लॉकचैन क्लस्टर सिंगल नोड (AZ) विफलता के लिए फॉल्ट टोलेरेंस है, क्योंकि पॉलीगॉन एज IBFT सर्वसम्मति को लागू करता है +जो सिंगल नोड को 4 वैलिडेटर नोड क्लस्टर में विफल होने की अनुमति देता है. + +### कमांड लाइन एक्सेस {#command-line-access} + +वैलिडेटर नोड्स सार्वजनिक इंटरनेट के लिए किसी भी तरह से सार्वजनिक नहीं होते हैं (JSON-PRC को केवल ALB के माध्यम से एक्सेस किया जाता है) +और उनके पास सार्वजनिक IP पते भी नहीं होते हैं. नोड कमांड लाइन का इस्तेमाल सिर्फ़ [AWS सिस्टम्स मैनेजर - सेशन मैनेजर](https://aws.amazon.com/systems-manager/features/) के माध्यम से संभव है. + +### बेस AMI अपग्रेड {#base-ami-upgrade} + +यह डिप्लॉयमेंट में `ubuntu-focal-20.04-amd64-server`AWS AMI का इस्तेमाल किया जाता है. अगर AWS AMI अपडेट हो जाता है तो यह *EC2 रिडिप्लॉयमेंट को* ट्रिगर **नहीं** करेगा. + +अगर, किसी कारण से, बेस AMI को अपडेट करने की ज़रूरत है, ये प्रत्येक इंस्टैंस के लिए `terraform taint`कमांड रन करके प्राप्त किया जा सकता है `terraform apply`. कमांड `terraform taint module.instances[].aws_instance.polygon_edge_instance`चलाकर इंस्टैंस को टेंटेड +किया जा सकता है. + +उदाहरण: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info + +ब्लॉकचैन नेटवर्क को फ़ंक्शनल बनाए रखने के लिए एक उत्पादन क्षेत्र में `terraform taint`को एक-एक करके रन किया जाना चाहिए. +::: + +## डिप्लॉयमेंट की प्रक्रिया {#deployment-procedure} + +### प्रि डिप्लॉयमेंट स्टेप्स {#pre-deployment-steps} +* [पॉलीगॉन-टेक्नोलॉजी-एज](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) terraform रजिस्ट्री रीडमी के माध्यम से पढ़ें +* मॉड्यूल के रीडमी पेज पर *प्रावधान के निर्देशों* का इस्तेेमाल करके मॉड्यूल `polygon-technology-edge` को अपनी `main.tf`फ़ाइल में जोड़ें +* सभी आवश्यक Terraform निर्भरताओं को इंस्टॉल करने के लिए `terraform init` कमांड चलाएँ +* [AWS प्रमाणपत्र मैनेजर](https://aws.amazon.com/certificate-manager/) में एक नया प्रमाणपत्र प्रदान करें +* यह सुनिश्चित करें कि प्रदान किया गया प्रमाणपत्र **जारी** है और प्रमाणपत्र के **ARN** पर भी ध्यान दें +* CLI में मॉड्यूल का आउटपुट प्राप्त करने के लिए अपना आउटपुट स्टेटमेंट सेट अप करें + +#### `main.tf` उदाहरण {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### `terraform.tfvars` उदाहरण {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### डिप्लॉयमेंट के स्टेप्स {#deployment-steps} +* `terraform.tfvars` फ़ाइल बनाएँ +* इस फ़ाइल में आवश्यक terraform वैरिएबल्स सेट करें (जैसा कि ऊपर बताया गया है). +:::info + +अन्य गैर-ज़रूरी वैरिएबल्स हैं जो इस डिप्लॉमेंट को पूरी तरह से कस्टमाइज़ कर सकते हैं. आप ख़ुद `terraform.tfvars` फ़ाइल में जोड़कर डिफ़ॉल्ट वैल्यू को ओवरराइड कर सकते हैं. + + सभी उपलब्ध वैरिेबल्स की विशिष्टता मॉड्यूल की Terraform ***[रजिस्ट्री](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)*** में पाई जा सकती है + +::: +* सुनिश्चित करें कि आपने `aws s3 ls` रन कराकर aws cli ऑथेंटिकेशन ठीक से सेट अप किया है - कोई गड़बड़ी नहीं होनी चाहिए +* इंफ्रास्ट्रक्चर डिप्लॉय करें `terraform apply` + +### पोस्ट डिप्लॉयमेंट के स्टेप्स {#post-deployment-steps} +* एक बार डिप्लॉयमेंट पूरा हो जाने के बाद, cli में प्रिंटेड `json_rpc_dns_name` वेरिएबल वैल्यू को नोट करें +* एक सार्वजनिक dns cname रिकॉर्ड बनाएँ जो आपके डोमेन नाम को प्रदान किए गए `json_rpc_dns_name` वैल्यू की ओर पॉइंट करे. उदाहरण के लिए: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* एक बार जब cname रिकॉर्ड प्रोपोगेट हो जाए, तो JSON-PRC एंडपॉइंट को कॉल करके चेक करें कि क्या चेन ठीक से काम कर रही है. + ऊपर दिए गए उदाहरण से: + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## डेस्ट्रॉय करने की प्रक्रिया {#destroy-procedure} +:::warning + +नीचे दी गई प्रक्रिया स्थायी रूप से इन terraform स्क्रिप्ट के साथ डिप्लॉय आपके पूरे इंफ्रास्ट्रक्चर को हटा देगी. +सुनिश्चित करें कि आपके पास उचित [ब्लॉकचेन डेटा बैकअप](docs/edge/working-with-node/backup-restore) है और/या आप एक टेस्टिंग क्षेत्र में काम कर रहे हैं. + +::: + +अगर आपको पूरे इंफ्रास्ट्रक्चर को हटाने की ज़रूरत है, तो नीचे दिए गए कमांड को रन करें `terraform destroy`. इसके अतिरिक्त, आपको डिप्लॉय वाले क्षेत्र के लिए [AWS Parameter Store](https://aws.amazon.com/systems-manager/features/) में संग्रहीत सीक्रेट को +मैन्युअल रूप से हटाने की ज़रूरत होगी. diff --git a/archive/edge/hi-edge/overview.md b/archive/edge/hi-edge/overview.md new file mode 100644 index 0000000000..cad8268a99 --- /dev/null +++ b/archive/edge/hi-edge/overview.md @@ -0,0 +1,35 @@ +--- +id: overview +title: पॉलीगॉन एज +sidebar_label: What is Edge +description: "पॉलीगॉन एज का परिचय." +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +पॉलीगॉन एज एथेरेयम ब्लॉकचेन नेटवर्क, साइडचैनस, और स्केलिंग सॉल्यूशंस बिल्डिंग के लिए मॉडुलर और एक्स्टेंसिबल फ्रेमवर्क है. + +इसका प्राथमिक उपयोग एथेरियम स्मार्ट अनुबंधों और लेनदेन के साथ पूर्ण संगतता प्रदान करते हुए एक नए ब्लॉकचेन नेटवर्क को बूटस्ट्रैप करना है. यह IBFT (इस्तांबुल बीजान्टिन दोष सहिष्णु) सर्वसम्मति मेकनिज़म का उपयोग करता है, जो [PoA (प्राधिकरण का प्रमाण)](/docs/edge/consensus/poa) और [PoS (हिस्सेदारी का प्रमाण)](/docs/edge/consensus/pos-stake-unstake) के रूप में दो स्वादों में समर्थित है. + +पॉलीगॉन एज कई ब्लॉकचेन नेटवर्क के साथ संचार का भी समर्थन करता है, [केंद्रीकृत पुल समाधान](/docs/edge/additional-features/chainbridge/overview)का उपयोग करके [ईआरसी-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) और [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) टोकन दोनों के हस्तांतरण को सक्षम करता है. + +उद्योग मानक वॉलेट का उपयोग [JSON-RPC](/docs/edge/working-with-node/query-json-rpc) एन्ड्पॉईंट के माध्यम से पॉलीगॉन एज के साथ इंटेरक्ट करने के लिए किया जा सकता है और नोड ऑपरेटर [gRPC](/docs/edge/working-with-node/query-operator-info) प्रोटोकॉल के माध्यम से नोड्स पर विभिन्न क्रियाएं कर सकते हैं. + +पॉलीगाँन के बारे में अधिक जानने के लिए, [ऑफिसियल वेबसाइट](https://polygon.technology)पर जाएँ. + +**[गिटहब रिपोजिटरी](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +यह प्रगति में एक काम है इसलिए भविष्य में वास्तुशिल्प परिवर्तन हो सकते हैं. कोड का ऑडिट नहीं किया गया है फिर भी, तो कृपया पॉलीगॉन टीम से संपर्क करें यदि आप इसे प्रोडक्शन में इस्तेमाल करना चाहेंगे. + +::: + + + +`polygon-edge`स्थानीय रूप से एक नेटवर्क चलाकर शुरू करने के लिए, कृपया पढ़ें: [इंस्टॉलेशन](/docs/edge/get-started/installation)और [स्थानीय सेटप](/docs/edge/get-started/set-up-ibft-locally). diff --git a/archive/edge/hi-edge/performance-reports/overview.md b/archive/edge/hi-edge/performance-reports/overview.md new file mode 100644 index 0000000000..7aa1eefeba --- /dev/null +++ b/archive/edge/hi-edge/performance-reports/overview.md @@ -0,0 +1,30 @@ +--- +id: overview +title: ओवरव्यू +description: "पॉलीगॉन एज टेस्ट का परिचय." +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +कृपया ध्यान दें कि इन परीक्षणों को प्रदर्शित करने के लिए `loadbot`जो हमारा इस्तेमाल किया गया था, अब कम हो गया है. +::: + +| प्रकार | वैल्यू | टेस्ट की लिंक | +| ---- | ----- | ------------ | +| रेगुलर ट्रांसफ़र | 1428 tps | [4 जुलाई, 2022](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| ERC-20 ट्रांसफ़र | 1111 tps | [4 जुलाई, 2022](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| NFT मिंटिंग | 714 tps | [4 जुलाई, 2022](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +हमारा लक्ष्य ब्लॉकचेन क्लाइंट सॉफ्टवेयर को सेटअप करने और बनाए रखने के लिए एक उच्च highly-performant, feature-rich और आसान बनाना है. +पॉलीगॉन एज Loadbot का इस्तेमाल करके सभी टेस्ट किए गए थे. आप सेक्शन में पाएंगे हर प्रदर्शन की रिपोर्ट को सही ढंग से डेटेड किया गया है, क्षेत्र को स्पष्ट रूप से वर्णित किया गया है और तरीका स्पष्ट रूप से स्पष्ट रूप से समझाता है. + +इन प्रदर्शन टेस्ट का लक्ष्य पॉलीगॉन एज ब्लॉकचेन नेटवर्क का एक वास्तविक विश्व प्रदर्शन दिखाना है. अपने loadbot का इस्तेमाल करते हुए एक ही क्षेत्र पर पोस्ट किए गए परिणाम को किसी को भी प्राप्त करने में सक्षम होना चाहिए. + +सभी प्रदर्शन टेस्ट EC2 इंस्टैंस नोड्स से मिलकर चेन पर AWS प्लेटफ़ॉर्म पर किए गए थे. \ No newline at end of file diff --git a/archive/edge/hi-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/hi-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..2b03e7581a --- /dev/null +++ b/archive/edge/hi-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,131 @@ +--- +id: test-2022-01-21 +title: 21 जनवरी, 2022 +description: "21 जनवरी से प्रदर्शन का टेस्ट." +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## 21 जनवरी, 2022 {#january-21st-2022} + +### सारांश {#summary} + +:::caution +कृपया ध्यान दें कि इन परीक्षणों को प्रदर्शित करने के लिए `loadbot`जो हमारा इस्तेमाल किया गया था, अब कम हो गया है. +::: + +यह टेस्ट TxPool रिफैक्टर के बाद किया गया था, जिससे प्रदर्शन में काफी सुधार हुआ ([v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0) में जारी). + +इसका लक्ष्य सही से टेस्ट करने के ऑर्डर में 30 सक्रिय रूप से भाग लेने वाले वैलिडेटर्स से मिलकर एक नेटवर्क स्थापित करना था सहमति और TxPool ट्रांज़ैक्शन की gossiping, क्योंकि सभी ट्रांज़ैक्शन सिंगल नोड के JSON-RPC, में भेजे गए थे. + +हमारा लक्ष्य जितना संभव हो सके, उतने अधिकतम TPS तक पहुँचना भर नहीं था, क्योंकि नेटवर्क का आकार नकारात्मक प्रदर्शन को प्रभावित करता है, +और ब्लॉक गैस लिमिट और ब्लॉक समय सेन वैल्यू पर सेट होते हैं जो बाद से सिस्टम संसाधनों का इस्तेमाल नहीं करते हैं और यह कमोडिटी हार्डवेयर पर रन करने की अनुमति देता है. + +### परिणाम {#results} + +| मीट्रिक | वैल्यू | +| ------ | ----- | +| प्रति सेकंड ट्रांज़ैक्शन | 344 | +| ट्रांज़ैक्शन विफल हो गया है | 0 | +| ट्रांज़ैक्शन सफल रहा | 10000 | +| रन करने का कुल समय | 30s | + +### क्षेत्र {#environment} + +
+ होस्ट कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
क्लाउड प्रोवाइडरAWS
इंस्टैंस का आकारt2.xlarge
नेटवर्किंगनिजी सबनेट
ऑपरेटिंग सिस्टमLinux Ubuntu 20.04 LTS - फ़ोकल फ़ोसा
फ़ाइल डिस्क्रिप्टर लिमिट65535
Max यूज़र की प्रक्रियाएँ65535
+
+
+
+
+ +
+ ब्लॉकचेन कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
पॉलीगॉन एज वर्जनविकसित शाखा पर 8377162281d1a2e4342ae27cd4e5367c4364aee2 कमिट करें
वैलिडेटर नोड30
नॉन-वैलिडेटर नोड0
सहमतिIBFT PoA
ब्लॉक समय2000ms
ब्लॉक की गैस लिमिट5242880
+
+
+
+
+ +
+ Loadbot कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + +
कुल ट्रांज़ैक्शन10000
प्रति सेकंड भेजे गए ट्रांज़ैक्शन400
ट्रांज़ैक्शन का प्रकारEOA से EOA ट्रांसफ़र
+
+
+
+
diff --git a/archive/edge/hi-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/hi-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..8511f25853 --- /dev/null +++ b/archive/edge/hi-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,390 @@ +--- +id: test-2022-03-02 +title: 2 मार्च 2022 +description: "2 मार्च से परफ़ॉर्मेंस टेस्ट।" +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### सारांश {#summary} + +:::caution +कृपया ध्यान दें कि इन परीक्षणों को प्रदर्शित करने के लिए `loadbot`जो हमारा इस्तेमाल किया गया था, अब कम हो गया है. +::: + +यह टेस्ट ज़्यादा लोड और ट्रांज़ैक्शन की स्पीड के साथ SC erc20 टोकन ट्रांसफ़र और SC erc721 टोकन मिंटिंग फ़ंक्शनैलिटी को मापने के लिए किया गया था। + +इसका लक्ष्य यह देखना था कि क्या ज़्यादा लोड पड़ने पर सब कुछ इच्छा के अनुसार काम कर रहा था। यह भी कारण है कि हमने loadbot आउटपुट में गैस मीट्रिक शुरू किया है, जो हमें दिखाता है कि क्या ब्लॉक सही तरीके से ट्रांज़ैक्शन से भरे हुए हैं. + +सभी ट्रांज़ैक्शन GRPC API के माध्यम से सिंगल नोड में भेजे गए थे, और रसीदें JSON-RPC API के माध्यम से प्राप्त की गई थीं। सभी ट्रांज़ैक्शन किए जाने के बाद, हर ब्लॉक से गैस की जानकारी पढ़ी गई थी, जिसमें eth_getBlockByNumber JSON-RPC तरीके का इस्तेमाल किया गया था। + +हमारा लक्ष्य अधिकतम संभव TPS तक पहुँचने की कोशिश करना नहीं था, +चूंकि ब्लॉक गैस लिमिट और ब्लॉक समय सेन वैल्यू पर सेट होते हैं जो सिस्टम संसाधनों की ज़्यादा खपत नहीं करते हैं और इसे कमोडिटी हार्डवेयर पर रन करने की अनुमति देंगे। + +### नतीजे erc20 {#results-erc20} + +| मीट्रिक | वैल्यू | +| ------ | ----- | +| ट्रांज़ैक्शन का प्रकार | erc20 | +| प्रति सेकंड ट्रांज़ैक्शन | 65 | +| ट्रांज़ैक्शन पूरा न हो सका | 0 | +| ट्रांज़ैक्शन सफल रहा | 5000 | +| erc20 ट्रांज़ैक्शन के रन करने का समय | 76.681690 सेकंड | +| SC डिप्लॉय करने का समय | 4.048250 सेकंड | + +### नतीजे erc721 {#results-erc721} + +| मीट्रिक | वैल्यू | +| ------ | ----- | +| ट्रांज़ैक्शन का प्रकार | erc721 | +| प्रति सेकंड ट्रांज़ैक्शन | 20 | +| ट्रांज़ैक्शन पूरा न हो सका | 0 | +| ट्रांज़ैक्शन सफल रहा | 2000 | +| erc721 ट्रांज़ैक्शन के रन करने का समय | 97.239920 सेकंड | +| SC डिप्लॉय करने का समय | 3.048970 सेकंड | + +### एनवायरमेंट erc20 {#environment-erc20} + +
+ होस्ट कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
क्लाउड प्रोवाइडरAWS
इंस्टैंस का आकारt2.micro
नेटवर्किंगनिजी सबनेट
ऑपरेटिंग सिस्टमLinux Ubuntu 20.04 LTS - फ़ोकल फ़ोसा
फ़ाइल डिस्क्रिप्टर लिमिट65535
Max यूज़र की प्रक्रियाएँ65535
+
+
+
+
+ +
+ ब्लॉकचेन कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
पॉलीगॉन एज वर्ज़नडेवलप ब्रांच पर कमिट 8a033aa1afb191abdac04636d318f83f32511f3c
वैलिडेटर नोड6
नॉन-वैलिडेटर नोड0
सहमतिIBFT PoA
ब्लॉक समय2 सेकंड
ब्लॉक के गैस की सीमा5242880
ब्लॉक की औसत उपयोगिता95%
+
+
+
+
+ +
+ Loadbot कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + +
कुल ट्रांज़ैक्शन5000
प्रति सेकंड भेजे गए ट्रांज़ैक्शन200
ट्रांज़ैक्शन का प्रकारerc20 से erc20 में ट्रांसफ़र
+
+
+
+
+ +
+ Loadbot लॉग + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### एनवायरमेंट erc721 {#environment-erc721} + +
+ होस्ट कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
क्लाउड प्रोवाइडरAWS
इंस्टैंस का आकारt2.micro
नेटवर्किंगनिजी सबनेट
ऑपरेटिंग सिस्टमLinux Ubuntu 20.04 LTS - फ़ोकल फ़ोसा
फ़ाइल डिस्क्रिप्टर लिमिट65535
Max यूज़र की प्रक्रियाएँ65535
+
+
+
+
+ +
+ ब्लॉकचेन कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
पॉलीगॉन एज वर्ज़नडेवलप ब्रांच पर कमिट 8a033aa1afb191abdac04636d318f83f32511f3c
वैलिडेटर नोड6
नॉन-वैलिडेटर नोड0
सहमतिIBFT PoA
ब्लॉक समय2 सेकंड
ब्लॉक के गैस की सीमा5242880
ब्लॉक की औसत उपयोगिता94%
+
+
+
+
+ +
+ Loadbot कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + +
कुल ट्रांज़ैक्शन2000
प्रति सेकंड भेजे गए ट्रांज़ैक्शन200
ट्रांज़ैक्शन का प्रकारerc721 टोकन मिंट
+
+
+
+
+ +
+ Loadbot लॉग + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/hi-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/hi-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..b561f4792c --- /dev/null +++ b/archive/edge/hi-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,955 @@ +--- +id: test-2022-03-23 +title: मार्च 23 rd 2022 +description: "23 मार्च से टेस्ट का प्रदर्शन किया गया." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### सारांश {#summary} + +:::caution +कृपया ध्यान दें कि इन परीक्षणों को प्रदर्शित करने के लिए `loadbot`जो हमारा इस्तेमाल किया गया था, अब कम हो गया है. +::: + +यह टेस्ट, SC ERC20 टोकन के स्थानांतरण, SC ERC721 टोकन की मिंटिंग और EOA से EOA में ट्रांज़ैक्शन करने की फ़ंक्शनैलिटी को मापने के लिए किया गया था, जिन नोड्स पर भारी लोड था और उच्च हार्डवेयर संसाधनों के साथ ट्रांज़ैक्शन की गति तेज़ थी. + +इसका लक्ष्य यह देखना था कि क्या ज़्यादा लोड पड़ने पर सब कुछ इच्छा के अनुसार काम कर रहा है. यह भी कारण है कि हमने loadbot आउटपुट में गैस मीट्रिक शुरू किए हैं, जो हमें दिखाते हैं कि ब्लॉक सही तरीके से ट्रांज़ैक्शन से भरे हुए हैं. + +सभी ट्रांज़ैक्शन GRPC API के माध्यम से सिंगल नोड में भेजे गए थे, और रसीदें JSON-RPC API के माध्यम से प्राप्त की गई थीं. सभी ट्रांज़ैक्शन किए जाने के बाद, हर ब्लॉक से गैस की जानकारी पढ़ी गई थी, जिसमें eth_getBlockByNumber JSON-RP तरीके का इस्तेमाल किया गया था. + +हमारा उद्देश्य उपलब्ध हार्डवेयर संसाधनों से जितना हो सके अधिकतम TPS तक पहुंचने का प्रयास करना था. +इसे प्राप्त करने के लिए, हमने ब्लॉक की गैस सीमा और ब्लॉक के समय के पैरामीटर को संशोधित किया है, ताकि हमें जितना हो सके उतना सर्वोत्तम tps परिणाम मिल सकें और सिस्टम की अखंडता और स्थिरता बनाई रखी जा सके. + +:::info गैस सीमा ब्लॉक +गैस सीमा को अपेक्षाकृत उच्च संख्या में बढ़ाया जा सकता है अगर the the काफी गैस का इस्तेमाल कर रहे हैं उदाहरण के लिए कहा गया erc721 टोकन की टकसाल गैस सीमा के साथ काफी तेजी से काम किया गया था जो ब्लॉक सीमा से 80 00 (20 मील की जगह ) तक निर्धारित की गई थी लेकिन erc20 टोकन के साथ 80 मील ब्लॉक गैस की सीमा के साथ transfers transfers के साथ percerc20 टोकन के साथ किया गया था, +::: + +:::info उत्पादन वाले क्षेत्र + +उत्पादन वाले क्षेत्र को कॉन्फ़िगर करते समय, अगर आप चेन के उच्च प्रदर्शन को प्राप्त करने की कोशिश कर रहे हैं तो आपको सावधान रहना होगा. +अगर ब्लॉक की गैस सीमा को पैरामीटर की ऊंची वैल्यू पर सेट किया जाता है और ब्लॉक का समय 1 सेकंड पर सेट किया जाता है, और एक अकेले नोड पर ट्रांज़ैक्शन का ज़्यादा लोड होता है, तो वह नोड बहुत अधिक (अगर पूरी उपलब्ध नहीं है) रैम का इस्तेमाल करेगा जो सर्वर के क्रैश होने का कारण बन सकता है. +सभी का अच्छी तरह से परीक्षण करने के लिए loadbot का इस्तेमाल करें, सिस्टम द्वारा संसाधन उपयोगिता को मॉनिटर करें और उसके अनुसार अपने कॉन्फ़िगरेशन पैरामीटर्स को सेट करें. + +::: + +:::info मेमोरी की त्रुटियों में से +कुछ लाइनक्स डिस्ट्रो प्रक्रिया को ऑटोमेटिक रूप से मार देगा जिसमें बहुत ही उच्च RAM इस्तेमाल होता है ( OOM error the ी त्रुटि ) OM The The ी की त्रुटि का लॉग आउटपुट कुछ सहकर्मी जैसा दिखता है. +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### EOA से EOA में ट्रांसफ़र के परिणाम {#results-of-eoa-to-eoa-transfers} +| मीट्रिक | वैल्यू | +| ------ | ----- | +| ट्रांज़ैक्शन का प्रकार | EOA से EOA में | +| प्रति सेकंड ट्रांज़ैक्शन | 689 | +| ट्रांज़ैक्शन पूरा न हो सका | 0 | +| ट्रांज़ैक्शन सफल रहा | 2000 | +| इस्तेमाल किए गए कुल ब्लॉक | 25 | +| रन करने का कुल समय | 29. 92110 के दशक | + +### ERC20 टोकन ट्रांसफ़र के परिणाम {#results-of-erc20-token-transfers} + +| मीट्रिक | वैल्यू | +| ------ | ----- | +| ट्रांज़ैक्शन का प्रकार | erc20 | +| प्रति सेकंड ट्रांज़ैक्शन | 500 | +| ट्रांज़ैक्शन पूरा न हो सका | 0 | +| ट्रांज़ैक्शन सफल रहा | 2000 | +| इस्तेमाल किए गए कुल ब्लॉक | 33 | +| erc20 ट्रांज़ैक्शन के रन करने का समय | 40. 402900 के दशक | +| SC डिप्लॉय करने का समय | 2. 004140 के दशक | + +### ERC721 टोकन की मिंटिंग के परिणाम {#results-of-erc721-token-minting} + +| मीट्रिक | वैल्यू | +| ------ | ----- | +| ट्रांज़ैक्शन का प्रकार | erc721 | +| प्रति सेकंड ट्रांज़ैक्शन | 157 | +| ट्रांज़ैक्शन पूरा न हो सका | 0 | +| ट्रांज़ैक्शन सफल रहा | 2000 | +| इस्तेमाल किए गए कुल ब्लॉक | 124 | +| erc721 ट्रांज़ैक्शन के रन करने का समय | 127. 537340 के दशक | +| SC डिप्लॉय करने का समय | 2. 004420 के दशक | + + +### erc721 टोकन के परिणाम बहुत ब्लॉक की गैस सीमा के साथ {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| मीट्रिक | वैल्यू | +| ------ | ----- | +| ट्रांज़ैक्शन का प्रकार | erc721 | +| प्रति सेकंड ट्रांज़ैक्शन | 487 | +| ट्रांज़ैक्शन पूरा न हो सका | 0 | +| ट्रांज़ैक्शन सफल रहा | 2000 | +| इस्तेमाल किए गए कुल ब्लॉक | 34 | +| erc721 ट्रांज़ैक्शन के रन करने का समय | 41. 098410 | +| SC डिप्लॉय करने का समय | 2. 004300 के दशक | + + +### EOA से EOA का क्षेत्र {#environment-eoa-to-eoa} +
+ होस्ट कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
क्लाउड प्रोवाइडरAWS
इंस्टैंस का आकारc5. 2xबड़ी
नेटवर्किंगनिजी सबनेट
ऑपरेटिंग सिस्टमअमेज़न लिनक्स 2 AMI (HVM) - Kernel 5.10
फ़ाइल डिस्क्रिप्टर लिमिट65535
Max यूज़र की प्रक्रियाएँ65535
+
+
+
+
+ +
+ ब्लॉकचेन कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
पॉलीगॉन एज वर्ज़नCommit 06e1eac8d98c79c938fc53dda2da3318cfebbe04
वैलिडेटर नोड4
नॉन-वैलिडेटर नोड0
सहमतिIBFT PoA
ब्लॉक का समय1s
ब्लॉक के गैस की सीमा2000
अधिकतम स्लॉट1000000
ब्लॉक की औसत उपयोगिता84. 00%
+
+
+
+
+ +
+ Loadbot कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + +
कुल ट्रांज़ैक्शन2000
प्रति सेकंड भेजे गए ट्रांज़ैक्शन689
ट्रांज़ैक्शन का प्रकारEOA से EOA ट्रांसफ़र
+
+
+
+
+ +
+ Loadbot लॉग + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### एनवायरमेंट erc20 {#environment-erc20} +
+ होस्ट कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
क्लाउड प्रोवाइडरAWS
इंस्टैंस का आकारc5. 2xबड़ी
नेटवर्किंगनिजी सबनेट
ऑपरेटिंग सिस्टमअमेज़न लिनक्स 2 AMI (HVM) - Kernel 5.10
फ़ाइल डिस्क्रिप्टर लिमिट65535
Max यूज़र की प्रक्रियाएँ65535
+
+
+
+
+ +
+ ब्लॉकचेन कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
पॉलीगॉन एज वर्ज़नCommit 06e1eac8d98c79c938fc53dda2da3318cfebbe04
वैलिडेटर नोड4
नॉन-वैलिडेटर नोड0
सहमतिIBFT PoA
ब्लॉक का समय1s
ब्लॉक के गैस की सीमा2000
अधिकतम स्लॉट1000000
ब्लॉक की औसत उपयोगिता88. 38%
+
+
+
+
+ +
+ Loadbot कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + +
कुल ट्रांज़ैक्शन2000
प्रति सेकंड भेजे गए ट्रांज़ैक्शन500
ट्रांज़ैक्शन का प्रकारerc20 से erc20 में ट्रांसफ़र
+
+
+
+
+ +
+ Loadbot लॉग + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### एनवायरमेंट erc721 {#environment-erc721} +
+ होस्ट कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
क्लाउड प्रोवाइडरAWS
इंस्टैंस का आकारc5. 2xबड़ी
नेटवर्किंगनिजी सबनेट
ऑपरेटिंग सिस्टमअमेज़न लिनक्स 2 AMI (HVM) - Kernel 5.10
फ़ाइल डिस्क्रिप्टर लिमिट65535
Max यूज़र की प्रक्रियाएँ65535
+
+
+
+
+ +
+ ब्लॉकचेन कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
पॉलीगॉन एज वर्ज़नCommit 06e1eac8d98c79c938fc53dda2da3318cfebbe04
वैलिडेटर नोड4
नॉन-वैलिडेटर नोड0
सहमतिIBFT PoA
ब्लॉक का समय1s
ब्लॉक के गैस की सीमा2000
अधिकतम स्लॉट1000000
ब्लॉक की औसत उपयोगिता92. 90%
+
+
+
+
+ +
+ Loadbot कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + +
कुल ट्रांज़ैक्शन2000
प्रति सेकंड भेजे गए ट्रांज़ैक्शन157
ट्रांज़ैक्शन का प्रकारerc721 टोकन मिंट
+
+
+
+
+ +
+ Loadbot लॉग + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### पर्यावरण ERC20 - बहुत हाई ब्लॉक गैस सीमा {#environment-erc20-very-high-block-gas-limit} +
+ होस्ट कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
क्लाउड प्रोवाइडरAWS
इंस्टैंस का आकारc5. 2xबड़ी
नेटवर्किंगनिजी सबनेट
ऑपरेटिंग सिस्टमअमेज़न लिनक्स 2 AMI (HVM) - Kernel 5.10
फ़ाइल डिस्क्रिप्टर लिमिट65535
Max यूज़र की प्रक्रियाएँ65535
+
+
+
+
+ +
+ ब्लॉकचेन कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
पॉलीगॉन एज वर्ज़नCommit 06e1eac8d98c79c938fc53dda2da3318cfebbe04
वैलिडेटर नोड4
नॉन-वैलिडेटर नोड0
सहमतिIBFT PoA
ब्लॉक का समय1s
ब्लॉक के गैस की सीमा8000
अधिकतम स्लॉट1000000
ब्लॉक की औसत उपयोगिता---
+
+
+
+
+ +
+ Loadbot कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + +
कुल ट्रांज़ैक्शन2000
प्रति सेकंड भेजे गए ट्रांज़ैक्शन---
ट्रांज़ैक्शन का प्रकारerc20 से erc20 में ट्रांसफ़र
+
+
+
+
+ +
+ OOM त्रुटि लॉग + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### पर्यावरण ERC721 - बहुत हाई ब्लॉक गैस सीमा {#environment-erc721-very-high-block-gas-limit} +
+ होस्ट कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
क्लाउड प्रोवाइडरAWS
इंस्टैंस का आकारc5. 2xबड़ी
नेटवर्किंगनिजी सबनेट
ऑपरेटिंग सिस्टमअमेज़न लिनक्स 2 AMI (HVM) - Kernel 5.10
फ़ाइल डिस्क्रिप्टर लिमिट65535
Max यूज़र की प्रक्रियाएँ65535
+
+
+
+
+ +
+ ब्लॉकचेन कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
पॉलीगॉन एज वर्ज़नCommit 06e1eac8d98c79c938fc53dda2da3318cfebbe04
वैलिडेटर नोड4
नॉन-वैलिडेटर नोड0
सहमतिIBFT PoA
ब्लॉक का समय1s
ब्लॉक के गैस की सीमा8000
अधिकतम स्लॉट1000000
ब्लॉक की औसत उपयोगिता84.68%
+
+
+
+
+ +
+ Loadbot कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + +
कुल ट्रांज़ैक्शन2000
प्रति सेकंड भेजे गए ट्रांज़ैक्शन487
ट्रांज़ैक्शन का प्रकारerc721 टोकन मिंट
+
+
+
+
+ +
+ Loadbot लॉग + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/hi-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/hi-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..033355021b --- /dev/null +++ b/archive/edge/hi-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,568 @@ +--- +id: test-2022-07-04 +title: 4 जुलाई, 2022 +description: "4 जुलाई से प्रदर्शन का परीक्षण." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### सारांश {#summary} + +:::caution +कृपया ध्यान दें कि इन परीक्षणों को प्रदर्शित करने के लिए `loadbot`जो हमारा इस्तेमाल किया गया था, अब कम हो गया है. +::: + +यह टेस्ट, SC ERC20 टोकन के स्थानांतरण, SC ERC721 टोकन की मिंटिंग और EOA से EOA में ट्रांज़ैक्शन करने की फ़ंक्शनैलिटी को मापने के लिए किया गया था, जिन नोड्स पर भारी लोड था और उच्च हार्डवेयर संसाधनों के साथ ट्रांज़ैक्शन की गति तेज़ थी. + +इसका लक्ष्य यह देखना था कि क्या ज़्यादा लोड पड़ने पर सब कुछ इच्छा के अनुसार काम कर रहा है. यह भी कारण है कि हमने loadbot आउटपुट में गैस मीट्रिक शुरू किए हैं, जो हमें दिखाते हैं कि ब्लॉक सही तरीके से ट्रांज़ैक्शन से भरे हुए हैं. + +सभी ट्रांज़ैक्शन GRPC API के माध्यम से सिंगल नोड में भेजे गए थे, और रसीदें JSON-RPC API के माध्यम से प्राप्त की गई थीं. सभी ट्रांज़ैक्शन किए जाने के बाद, हर ब्लॉक से गैस की जानकारी पढ़ी गई थी, जिसमें eth_getBlockByNumber JSON-RP तरीके का इस्तेमाल किया गया था. + +हमारा उद्देश्य उपलब्ध हार्डवेयर संसाधनों से जितना हो सके अधिकतम TPS तक पहुंचने का प्रयास करना था. +इसे प्राप्त करने के लिए, हमने ब्लॉक की गैस सीमा और ब्लॉक के समय के पैरामीटर को संशोधित किया है, ताकि हमें जितना हो सके उतना सर्वोत्तम tps परिणाम मिल सकें और सिस्टम की अखंडता और स्थिरता बनाई रखी जा सके. + + +:::info उत्पादन वाले क्षेत्र + +उत्पादन वाले क्षेत्र को कॉन्फ़िगर करते समय, अगर आप चेन के उच्च प्रदर्शन को प्राप्त करने की कोशिश कर रहे हैं तो आपको सावधान रहना होगा. +अगर ब्लॉक की गैस सीमा को पैरामीटर की ऊंची वैल्यू पर सेट किया जाता है और ब्लॉक का समय 1 सेकंड पर सेट किया जाता है, और एक अकेले नोड पर ट्रांज़ैक्शन का ज़्यादा लोड होता है, तो वह नोड बहुत अधिक (अगर पूरी उपलब्ध नहीं है) रैम का इस्तेमाल करेगा जो सर्वर के क्रैश होने का कारण बन सकता है. +सभी का अच्छी तरह से परीक्षण करने के लिए loadbot का इस्तेमाल करें, सिस्टम द्वारा संसाधन उपयोगिता को मॉनिटर करें और उसके अनुसार अपने कॉन्फ़िगरेशन पैरामीटर्स को सेट करें. + +::: + + + +### EOA से EOA में ट्रांसफ़र के परिणाम {#results-of-eoa-to-eoa-transfers} +| मीट्रिक | वैल्यू | +| ------ | ----- | +| ट्रांज़ैक्शन का प्रकार | EOA से EOA में | +| प्रति सेकंड ट्रांज़ैक्शन | 1428 | +| ट्रांज़ैक्शन पूरा न हो सका | 0 | +| ट्रांज़ैक्शन सफल रहा | 30000 | +| इस्तेमाल किए गए कुल ब्लॉक | 15 | +| रन करने का कुल समय | 21.374620s | + +### ERC20 टोकन ट्रांसफ़र के परिणाम {#results-of-erc20-token-transfers} + +| मीट्रिक | वैल्यू | +| ------ | ----- | +| ट्रांज़ैक्शन का प्रकार | erc20 | +| प्रति सेकंड ट्रांज़ैक्शन | 1111 | +| ट्रांज़ैक्शन पूरा न हो सका | 0 | +| ट्रांज़ैक्शन सफल रहा | 50000 | +| इस्तेमाल किए गए कुल ब्लॉक | 38 | +| ERC20 ट्रांज़ैक्शन को रन करने का समय | 45.906450s | +| SC डिप्लॉय करने का समय | 2.006580s | + +### ERC721 टोकन की मिंटिंग के परिणाम {#results-of-erc721-token-minting} + +| मीट्रिक | वैल्यू | +| ------ | ----- | +| ट्रांज़ैक्शन का प्रकार | erc721 | +| हर सेकंड ट्रांज़ैक्शन | 714 | +| ट्रांज़ैक्शन पूरा न हो सका | 0 | +| ट्रांज़ैक्शन सफल रहा | 30000 | +| इस्तेमाल किए गए कुल ब्लॉक | 39 | +| ERC721 ट्रांज़ैक्शन को रन करने का समय | 42.864140 | +| SC डिप्लॉय करने का समय | 2.005500s | + + + + +### EOA से EOA का क्षेत्र {#environment-eoa-to-eoa} +
+ होस्ट कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
क्लाउड प्रोवाइडरAWS EC2
इंस्टैंस का आकारc6a.48xबड़ी
नेटवर्किंगनिजी सबनेट
ऑपरेटिंग सिस्टमLinux Ubuntu 20.04 LTS - फ़ोकल फ़ोसा
फ़ाइल डिस्क्रिप्टर लिमिट65535
Max यूज़र की प्रक्रियाएँ65535
+
+
+
+
+ +
+ ब्लॉकचेन कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
पॉलीगॉन एज वर्ज़नv0.4.1 का रिलीज़
वैलिडेटर नोड4
नॉन-वैलिडेटर नोड0
सहमतिIBFT PoA
ब्लॉक का समय1s
ब्लॉक की गैस लिमिट70778880
अधिकतम स्लॉट276480
ब्लॉक का औसत उपयोग59.34%
+
+
+
+
+ +
+ Loadbot कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + +
कुल ट्रांज़ैक्शन30000
प्रति सेकंड भेजे गए ट्रांज़ैक्शन1428
ट्रांज़ैक्शन का प्रकारEOA से EOA ट्रांसफ़र
+
+
+
+
+ +
+ Loadbot लॉग + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### एनवायरमेंट erc20 {#environment-erc20} +
+ होस्ट कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
क्लाउड प्रोवाइडरAWS EC2
इंस्टैंस का आकारc6a.48xबड़ी
नेटवर्किंगनिजी सबनेट
ऑपरेटिंग सिस्टमLinux Ubuntu 20.04 LTS - फ़ोकल फ़ोसा
फ़ाइल डिस्क्रिप्टर लिमिट65535
Max यूज़र की प्रक्रियाएँ65535
+
+
+
+
+ +
+ ब्लॉकचेन कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
पॉलीगॉन एज वर्ज़नv0.4.1 का रिलीज़
वैलिडेटर नोड4
नॉन-वैलिडेटर नोड0
सहमतिIBFT PoA
ब्लॉक का समय1s
ब्लॉक की गैस लिमिट47185920
अधिकतम स्लॉट184320
ब्लॉक का औसत उपयोग81.29%
+
+
+
+
+ +
+ Loadbot कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + +
कुल ट्रांज़ैक्शन50000
हर सेकंड भेजे गए ट्रांज़ैक्शन1111
ट्रांज़ैक्शन का प्रकारerc20 से erc20 में ट्रांसफ़र
+
+
+
+
+ +
+ Loadbot लॉग + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### एनवायरमेंट erc721 {#environment-erc721} +
+ होस्ट कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
क्लाउड प्रोवाइडरAWS EC2
इंस्टैंस का आकारc6a.48xबड़ी
नेटवर्किंगनिजी सबनेट
ऑपरेटिंग सिस्टमLinux Ubuntu 20.04 LTS - फ़ोकल फ़ोसा
फ़ाइल डिस्क्रिप्टर लिमिट65535
Max यूज़र की प्रक्रियाएँ65535
+
+
+
+
+ +
+ ब्लॉकचेन कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
पॉलीगॉन एज वर्ज़नv0.4.1 का रिलीज़
वैलिडेटर नोड4
नॉन-वैलिडेटर नोड0
सहमतिIBFT PoA
ब्लॉक का समय1s
ब्लॉक की गैस लिमिट94371840
अधिकतम स्लॉट1000000
ब्लॉक की औसत उपयोगिता93.88%
+
+
+
+
+ +
+ Loadbot कॉन्फ़िगरेशन +
+
+ + + + + + + + + + + + + +
कुल ट्रांज़ैक्शन30000
हर सेकंड भेजे गए ट्रांज़ैक्शन714
ट्रांज़ैक्शन का प्रकारerc721 टोकन मिंट
+
+
+
+
+ +
+ Loadbot लॉग + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/hi-edge/troubleshooting.md b/archive/edge/hi-edge/troubleshooting.md new file mode 100644 index 0000000000..9944a06182 --- /dev/null +++ b/archive/edge/hi-edge/troubleshooting.md @@ -0,0 +1,70 @@ +--- +id: troubleshooting +title: ट्रबलशूटिंग +description: "पॉलीगॉन एज के लिए ट्रबलशूटिंग सेक्शन" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# ट्रबलशूटिंग {#troubleshooting} + +## `method=eth_call err="invalid signature"` गड़बड़ी {#error} + +जब आप पॉलीगॉन एज के साथ ट्रांज़ैक्शन करने के लिए एक वॉलेट का इस्तेमाल कर रहे हैं, तो कृपया सुनिश्चित करें कि आपके वॉलेट में स्थानीय नेटवर्क को सेट किया गया हो: + +1. `chainID` सही है. एज के लिए डिफ़ॉल्ट `chainID`, `100` है, लेकिन इसे जेनेसिस फ्लैग `--chain-id` का इस्तेमाल करके कस्टमाइज़ किया जा सकता है. + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. सुनिश्चित करें कि "RPC URL" फ़ील्ड पर आप उस नोड के JSON RPC पोर्ट का इस्तेमाल करें जिससे आप कनेक्ट हो रहे हैं. + + +## वेबसॉकेट का URL कैसे प्राप्त करें {#how-to-get-a-websocket-url} + +जब आप बाय डिफ़ॉल्ट, पॉलीगॉन एज रन करते हैं, तो यह चेन की लोकेशन के आधार पर एक वेबसॉकेट एंडपॉइंट जनरेट करता है. +URL स्कीम HTTPS और HTTP के `ws://` लिए इस्तेमाल `wss://`होती हैं. + +Localhost वेबसॉकेट का URL: +````bash +ws://:/ws +```` +नोट करें कि पोर्ट नंबर नोड के लिए चुने गए JSON-RPC पोर्ट पर निर्भर करता है. + +Edgenet वेबसॉकेट का URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## एक कॉन्ट्रैक्ट को डिप्लॉय करते समय `insufficient funds` गड़बड़ी हुई {#error-when-trying-to-deploy-a-contract} + +अगर आपको यह गड़बड़ी मिलती है, तो कृपया सुनिश्चित करें कि आपके पास वांछित पते पर पर्याप्त फंड्स हों और इस्तेमाल किया गया पता सही हो.
+Premined बैलेंस को सेट करने के लिए, आप जेनेसिस फ़ाइल को जनरेट करते समय आप जेनेसिस फ्लैग `genesis [--premine ADDRESS:VALUE]` का इस्तेमाल कर सकते हैं. +इस फ्लैग को इस्तेमाल करने का उदाहरण: +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +इस premines 1000000000000000000000 WEI से 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862. + + +## चेनब्रिज का इस्तेमाल करते समय ERC20 टोकन जारी नहीं किए गए {#erc20-tokens-not-released-while-using-chainbridge} + +अगर आप पॉलीगॉन PoS और एक स्थानीय एज नेटवर्क के बीच ERC20 टोकन ट्रांसफ़र करने की कोशिश करते हैं, और आपके ERC20 टोकन डिपॉज़िट हो जाते हैं, और रिलेयर पर भी प्रस्ताव एग्ज़ीक्यूट किया जाता है, लेकिन टोकन आपके एज नेटवर्क में जारी नहीं किए जाते हैं, तो कृपया सुनिश्चित करें कि पॉलीगॉन एज चेन में ERC20 हैंडलर में जारी करने के लिए पर्याप्त टोकन हैं.
डेस्टिनेशन चेन के हैंडलर कॉन्ट्रैक्ट में लॉक-रिलीज़ मोड के लिए जारी करने को पर्याप्त टोकन होने चाहिए. अगर आपके पास अपने स्थानीय एज नेटवर्क के ERC20 हैंडलर में कोई ERC20 टोकन नहीं हैं, तो कृपया नए टोकन मिंट करें और उन्हें ERC20 हैंडलर में ट्रांसफ़र करें. + +## चेनब्रिज का इस्तेमाल करते समय `Incorrect fee supplied` गड़बड़ी हुई {#error-when-using-chainbridge} + +मुंबई पॉलीगॉन PoS चेन और स्थानीय पॉलीगॉन एज सेटअप के बीच ERC20 टोकन ट्रांसफ़र करने की कोशिश करते समय आपको यह गड़बड़ी मिल सकती है. यह गड़बड़ी तब दिखाई देती है जब आप `--fee` फ्लैग का इस्तेमाल करके डिप्लॉय करने पर फ़ीस सेट करते हैं, लेकिन आप जमा ट्रांज़ैक्शन में समान वैल्यू सेट नहीं करते हैं. +आप फ़ीस को बदलने के लिए नीचे की कमांड का इस्तेमाल कर सकते हैं: +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +आप [यहाँ](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md) इस फ्लैग के बारे में अधिक जानकारी पा सकते हैं. + + + + + diff --git a/archive/edge/hi-edge/validator-hosting.md b/archive/edge/hi-edge/validator-hosting.md new file mode 100644 index 0000000000..caf8558746 --- /dev/null +++ b/archive/edge/hi-edge/validator-hosting.md @@ -0,0 +1,262 @@ +--- +id: validator-hosting +title: वैलिडेटर होस्टिंग +description: "पॉलीगॉन एज के लिए होस्टिंग संबंधी आवश्यकताएँ" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +नीचे पॉलीगॉन एज नेटवर्क में वैलिडेटर नोड को सही तरीके से होस्ट करने के लिए सुझाव दिए गए हैं. कृपया सुनिश्चित करने के लिए नीचे सूची में दिए गए सभी आइटम्स पर ध्यान दें +कि आपका वैलिडेटर सेटअप सुरक्षित, स्थिर है और प्रदर्शन के लिए सही तरीके से कॉन्फ़िगर किया गया है. + +## नॉलेज बेस {#knowledge-base} + +वैलिडेटर नोड को रन कराने की कोशिश करने से पहले, कृपया इस डॉक्यूमेंट को ध्यान से पूरा पढ़ें. +इसके अतिरिक्त जो डॉक्यूमेंट्स काम आ सकते हैं वे हैं: + +- [इंस्टॉल करना](get-started/installation) +- [क्लाउड सेटअप](get-started/set-up-ibft-on-the-cloud) +- [CLI कमांड्स](get-started/cli-commands) +- [सर्वर कॉन्फ़िगरेशन फ़ाइल](configuration/sample-config) +- [निजी कीज़](configuration/manage-private-keys) +- [प्रोमेथियस मैट्रिक्स](configuration/prometheus-metrics) +- [सीक्रेट मैनेजर्स](/docs/category/secret-managers) +- [बैकअप/रिस्टोर](working-with-node/backup-restore) + +## सिस्टम की न्यूनतम आवश्यकताएँ {#minimum-system-requirements} + +| प्रकार | वैल्यू | द्वारा प्रभावित | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 2 कोर |
  • JSON-RPC क्वेरीज़ की संख्या
  • ब्लॉकचेन स्टेट का आकार
  • ब्लॉक की गैस लिमिट
  • ब्लॉक समय
| +| रैम | 2 जीबी |
  • JSON-RPC क्वेरीज़ की संख्या
  • ब्लॉकचेन स्टेट का आकार
  • ब्लॉक की गैस लिमिट
| +| डिस्क |
  • 10 जीबी रुट का विभाजन
  • डिस्क एक्सटेंशन के लिए LVM के साथ 30 जीबी रुट का विभाजन
|
  • ब्लॉकचेन स्टेट का आकार
| + + +## सर्विस कॉन्फ़िगरेशन {#service-configuration} + +`polygon-edge` बाइनरी को स्थापित नेटवर्क कनेक्टिविटी पर स्वचालित रूप से सिस्टम सर्विस के रूप में रन और शुरू करने / बंद करने / रीस्टार्ट करने की आवश्यकता है +फ़ंक्शनैलिटीज़. हम `systemd.` जैसे सर्विस मैनेजर को इस्तेमाल करने की सलाह देते हैं + +उदाहरण के लिए `systemd` सिस्टम कॉन्फ़िगरेशन फ़ाइल: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### बाइनरी {#binary} + +उत्पादन के वर्कलोड और `polygon-edge` बाइनरी को केवल पहले से बने GitHub बाइनरी से ही डिप्लॉय किया जाना चाहिए, - न कि मैन्युअल रूप से इसको इकट्ठा किया जाना चाहिए. +:::info + +मैन्युअल रूप से `develop` की GitHub ब्रांच को इकट्ठा करके आप अपने क्षेत्र में ब्रेकिंग बदलाव शुरू कर सकते हैं. +इसी वजह से इसे पॉलीगॉन एज की बाइनरी को रिलीज़ करके डिप्लॉय करने की सलाह दी जाती है, क्योंकि इसमें शामिल होगा +ज़बरदस्त बदलावों और उन्हें कैसे दूर किया जाए के बारे में जानकारी. + +::: + +कृपया इंस्टॉलेशन के तरीके के पूरे ओवरव्यू के लिए [इंस्टॉलेशन](/docs/edge/get-started/installation) देखें. + +### डेटा स्टोरेज {#data-storage} + +`data/` फ़ोल्डर को जिसमें ब्लॉकचेन स्टेट के पूरे हिस्से को एक डेडीकेटेड डिस्क / वॉल्यूम पर माउंट किया जाना शामिल होना चाहिए +स्वचालित डिस्क बैकअप, वॉल्यूम के विस्तार और वैकल्पिक रूप से डिस्क/वॉल्यूम के असफल होने के मामले में दूसरे इंस्टैंस में माउंट करें. + + +### लॉग की फ़ाइलें {#log-files} + +लॉग की फ़ाइलों को नियमित रूप से रोटेट किया जाना चाहिए (जैसे `logrotate`टूल के साथ). +:::warning + +अगर लॉग की रोटेशन के बिना कॉन्फ़िगर किया गया, तो लॉग की फ़ाइलें, डिस्क की सारी उपलब्ध जगह का इस्तेमाल कर सकती हैं जो वैलिडेटर के अपटाइम को बाधित कर सकता है. + +::: + +उदाहरण `logrotate` कॉन्फ़िगरेशन: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +लॉग के स्टोरेज के संबंध में सिफारिशों के लिए नीचे [लॉगिंग](#logging) सेक्शन को देखें. + +### अतिरिक्त निर्भर्ताएँ {#additional-dependencies} + +`polygon-edge` को व्यवस्थित रूप से इकट्ठा किया जाता है, जिसमें किसी अतिरिक्त होस्ट OS पर निर्भरताओं की आवश्यकता नहीं है. + +## रखरखाव {#maintenance} + +नीचे पॉलीगॉन एज नेटवर्क के एक रन कर रहे वैलिडेटर नोड के रखरखाव के लिए सबसे अच्छे अभ्यास दिए हैं. + +### बैकअप {#backup} + +पॉलीगॉन एज के नोड्स के बैकअप के लिए दो प्रकार की प्रक्रिया की सलाह दी गई है. + +यह सुझाव है कि जब भी संभव हो, दोनों का इस्तेमाल करें, पॉलीगॉन एज के बैकअप के लिए यह हमेशा उपलब्ध विकल्प है. + +* ***वॉल्यूम बैकअप***: + पॉलीगॉन एज नोड की डेली बढ़ने वाले `data/` के वॉल्यूम के बैकअप या अगर संभव हो तो पूरे VM के लिए. + + +* ***पॉलीगॉन एज बैकअप***: + डेली CRON जॉब जो पॉलीगॉन एज के नियमित बैकअप को करता है और `.dat` फ़ाइलों को एक ऑफसाइट जगह पर ले जाता है या सुरक्षित क्लाउड ऑब्जेक्ट की स्टोरेज की सलाह दी जाती है. + +पॉलीगॉन एज के बैकअप को सही से ऊपर बताए गए वॉल्यूम के बैकअप के साथ ओवरलैप नहीं करना चाहिए. + +पॉलीगॉन एज के बैकअप को करने के निर्देशों के लिए [बैकअप/रिस्टोर नोड इंस्टैंस](working-with-node/backup-restore) को देखें. + +### लॉगिंग {#logging} + +पॉलीगॉन एज नोड्स द्वारा आउटपुट दिए गए लॉग को: +- इंडेक्स करने और सर्च करने की क्षमताओं के साथ बाहरी डेटा स्टोर में भेजा जा सकता है +- जिनके पास 30 दिनों के लॉग रिटेंशन की अवधि होती है + +अगर आप पहली बार पॉलीगॉन एज वैलिडेटर को सेट कर रहे हैं तो हम नोड शुरू करने की सलाह देते हैं +`--log-level=DEBUG` ऑप्शन के साथ आप आगे आने वाले किसी भी मुद्दों को जल्दी से डिबग करने में सक्षम हो सकते हैं. + +:::info + + `--log-level=DEBUG` नोड के लॉग के आउटपुट को जितना संभव हो उतना verbose बना देगा. +लॉग को डीबग करने से लॉग की फ़ाइल के आकार में भारी वृद्धि होगी जिसे सेट करते समय ध्यान में रखा जाना चाहिए +लॉग के रोटेशन का सोल्यूशन. + +::: +### OS के सुरक्षा पैच {#os-security-patches} + +एडमिनिस्ट्रेटर्स को यह सुनिश्चित करने की आवश्यकता है कि वैलिडेटर इंस्टेंस OS को हमेशा हर महीने कम से कम एक बार नवीनतम पैचों के साथ अपडेट किया जाए. + +## मैट्रिक्स {#metrics} + +### सिस्टम मैट्रिक्स {#system-metrics} + +एडमिनिस्ट्रेटर्स को कुछ प्रकार के सिस्टम मैट्रिक्स मॉनिटर को सेटअप करने की आवश्यकता है, (जैसे Telegraf + InfluxDB + Grafana या तीसरे पक्ष के SaaS). + +जिन मैट्रिक्स पर निगरानी रखी जानी चाहिए और जिन्हें अलार्म के नोटिफ़िकेशन के सेटअप की आवश्यकता है: + +| मीट्रिक का नाम | अलार्म की थ्रेशोल्ड | +|-----------------------|-------------------------------| +| CPU का इस्तेमाल (%) | 5 मिनट से अधिक के लिए > 90% | +| रैम की उपयोगिता (%) | 5 मिनट से अधिक के लिए > 90% | +| रुट डिस्क की उपयोगिता | > 90% | +| डेटा डिस्क की उपयोगिता | > 90% | + +### वैलिडेटर मैट्रिक्स {#validator-metrics} + +एडमिनिस्ट्रेटर्स को पॉलीगॉन एज के प्रोमेथियस API से मैट्रिक्स के कलेक्शन को सेटअप करने की आवश्यकता है, ताकि वे सक्षम हो सकें +ब्लॉकचेन के प्रदर्शन पर निगरानी रखें. + +कौन से मैट्रिक्स एक्सपोज़ किए जा रहे हैं और प्रोमेथियस मीट्रिक के कलेक्शन को कैसे सेट किया जाए यह समझने के लिए [प्रोमेथियस मैट्रिक्स](configuration/prometheus-metrics) देखें. + + +निम्नलिखित मैट्रिक्स पर अतिरिक्त ध्यान दिए जाने की आवश्यकता है: +- ***ब्लॉक के उत्पादन*** - अगर ब्लॉक के उत्पादन का समय सामान्य से अधिक है, तो हो सकता है नेटवर्क के साथ कोई समस्या है +- ***सहमति के राउंड की संख्या*** - अगर 1 से अधिक राउंड होते हैं तो हो सकता है नेटवर्क के वैलिडेटर सेट में कोई समस्या है +- ***पीअर्स की संख्या*** - अगर पीअर्स के ड्रॉप होने की संख्या है, तो नेटवर्क से कनेक्टिविटी की समस्या है + +## सुरक्षा {#security} + +नीचे पॉलीगॉन एज नेटवर्क के एक रन कर रहे वैलिडेटर नोड को हासिल करने के लिए सबसे अच्छे अभ्यास दिए हैं. + +### API सर्विसेज़ {#api-services} + +- ***JSON-RPC*** - +केवल वह API सर्विस जिसे सार्वजनिक रूप से एक्सपोज़ किया जाना चाहिए (लोड बैलेंसर के माध्यम से या सीधे तौर पर.). +API को सभी इंटरफ़ेस पर रन करना चाहिए या एक खास IP पते (उदाहरण: `--json-rpc 0.0.0.0:8545` या `--json-prc 192.168.1.1:8545` ) पर. +:::info +चूंकि, यह सार्वजनिक रूप से API का सामना कर रहा है, इसलिए इसकी सुरक्षा और रेट की सीमा प्रदान करने के लिए एक लोड बैलेंसर / रिवर्स प्रॉक्सी होने की सलाह दी जाती है. + +::: + + +- ***LibP2P*** - +यह नोड्स द्वारा पीअर कम्युनिकेशन के लिए इस्तेमाल की जाने वाली API नेटवर्किंग है. इसे सभी इंटरफ़ेस पर या एक निर्दिष्ट आईपी पते पर रन करने की आवश्यकता है +( `--libp2p 0.0.0.0:1478` या `--libp2p 192.168.1.1:1478` ). इस API को सार्वजनिक रूप से एक्सपोज़ नहीं किया जाना चाहिए, +लेकिन, इसे दूसरे सभी नोड्स से प्राप्त किया जाना चाहिए. +:::info +अगर localhost ( `--libp2p 127.0.0.1:1478` ) पर रन किया गया था, तो दूसरे नोड्स कनेक्ट नहीं हो सकेंगे. + +::: + + +- ***GRPC*** - +यह API केवल ऑपरेटर की कमांड को रन करने के लिए इस्तेमाल किया जाता है और किसी चीज़ के लिए नहीं. जैसे कि इसे केवल localhost ( `--grpc-address 127.0.0.1:9632`) पर ही रन कराया जाना चाहिए. + +### पॉलीगॉन एज के सीक्रेट्स {#polygon-edge-secrets} + +पॉलीगॉन एज के सीक्रेट्स ( `ibft` और `libp2p` कीज़ ) को स्थानीय फ़ाइल सिस्टम पर स्टोर नहीं किया जाना चाहिए. +इसके बजाय, एक सपोर्ट किए गए [सीक्रेट मैनेजर](configuration/secret-managers/set-up-aws-ssm) का इस्तेमाल किया जाना चाहिए. +स्थानीय फ़ाइल सिस्टम के लिए सीक्रेट्स को स्टोर किए जाने का इस्तेमाल केवल गैर-उत्पादन वाले क्षेत्र में किया जाना चाहिए. + +## अपडेट {#update} + +वैलिडेटर नोड्स के लिए वांछित अपडेट की प्रक्रिया निम्नलिखित है, जिसे स्टेप-बाय-स्टेप निर्देशों के रूप में बताया गया है. + +### अपडेट करने की प्रक्रिया {#update-procedure} + +- आधिकारिक GitHub [रिलीज़](https://github.com/0xPolygon/polygon-edge/releases) से पॉलीगॉन एज की नवीनतम बाइनरी को डाउनलोड करें +- पॉलीगॉन एज सर्विस को रोकें ( उदाहरण: `sudo systemctl stop polygon-edge.service` ) +- पहले से मौजूद `polygon-edge` बाइनरी को डाउनलोड की गई से बदलें (उदाहरण: `sudo mv polygon-edge /usr/local/bin/` ) +- `polygon-edge version` को रन करके जाँचें कि सही `polygon-edge` वर्जन जगह पर है या नहीं - इसे रिलीज़ वर्जन के अनुरूप होना चाहिए +- रिलीज़ डॉक्यूमेंटेशन की जाँच करें कि `polygon-edge` सर्विस शुरू करने से पहले कोई पीछे के कम्पेटिबिलिटी स्टेप्स को करने की आवश्यकता है या नहीं +- सर्विस शुरू करें `polygon-edge`( उदाहरण: `sudo systemctl start polygon-edge.service` ) +- अंत में, `polygon-edge` लॉग के आउटपुट की जाँच करें और सुनिश्चित करें कि सब कुछ बिना किसी `[ERROR]` लॉग के रन करें + +:::warning +जब कोई ब्रेकिंग रिलीज़ होती है, तो यह अपडेट प्रक्रिया सभी नोड्स पर अवश्य ही की जानी चाहिए +जैसे वर्तमान में रन कर रही बाइनरी नई रिलीज़ के साथ कॉम्पैटिबल नहीं है. + +इसका मतलब है कि चेन को थोड़े समय के लिए अवश्य ही रोका जाना चाहिए ( जब तक कि `polygon-edge` बाइनरी को रिप्लेस किया जाता है सर्विस फिर से शुरू नहीं की जाती ) +तो इसके अनुसार योजना बनाएँ. + +आप अपडेट को कुशलता से करने के लिए **[Ansible](https://www.ansible.com/)** या कुछ कस्टम स्क्रिप्ट जैसे टूल्स का इस्तेमाल कर सकते हैं +और चेन के डाउनटाइम को कम कर सकते हैं. + +::: + +## शुरू करने की प्रक्रिया {#startup-procedure} + +पॉलीगॉन एज वैलिडेटर के लिए स्टार्टअप की प्रक्रिया का वांछित फ़्लो निम्नलिखित है + +- [नॉलेज बेस](#knowledge-base) सेक्शन में सूचीबद्ध डॉक्यूमेंट के माध्यम से पढ़ें +- नवीनतम OS पैचों को वैलिडेटर नोड पर अप्लाई करें +- आधिकारिक GitHub के [रिलीज़](https://github.com/0xPolygon/polygon-edge/releases) से नवीनतम `polygon-edge` बाइनरी को डाउनलोड करें और इसे स्थानीय इंस्टैंस `PATH`में जगह दें +- `polygon-edge secrets generate`CLI कमांड को इस्तेमाल करते हुए सपोर्ट किए गए [सीक्रेट मैनेजर्स](/docs/category/secret-managers) में से एक को पहले शुरू करें +- `polygon-edge secrets init` [CLI कमांड](/docs/edge/get-started/cli-commands#secrets-init-flags) का इस्तेमाल करते हुए सीक्रेट्स को जनरेट करें और स्टोर करें +- `NodeID` और `Public key (address)` वैल्यू को नोट करें +- `genesis.json` फ़ाइल को [क्लाउड सेटअप](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators) में बताए अनुसार `polygon-edge genesis` [CLI कमांड](/docs/edge/get-started/cli-commands#genesis-flags) का इस्तेमाल करके जनरेट करें +- `polygon-edge server export`[CLI कमांड](/docs/edge/configuration/sample-config) का इस्तेमाल करते हुए डिफ़ॉल्ट कॉन्फ़िगरेशन की फ़ाइल को जनरेट करें +- स्थानीय वैलिडेटर नोड के क्षेत्र को समायोजित करने के लिए `default-config.yaml` फ़ाइल को एडिट करें ( फ़ाइल, पाथ, आदि ) +- पॉलीगॉन एज सर्विस को बनाएँ ( `systemd` या इसी तरह की ) जहाँ `polygon-edge` बाइनरी सर्वर को एक `default-config.yaml` फ़ाइल से रन कराएगी +- सर्विस को शुरू करके पॉलीगॉन एज सर्वर शुरू करें ( उदाहरण: `systemctl start polygon-edge` ) +- `polygon-edge` लॉग आउटपुट की जाँच करें और यह सुनिश्चित करें कि ब्लॉक को जनरेट किया जा रहा है और वहाँ कोई `[ERROR]` लॉग नहीं है +- JSON-RPC के तरीके जैसे [`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid) को कॉल करके चेन की फंक्शनैलिटी की जाँच करें diff --git a/archive/edge/hi-edge/working-with-node/backup-restore.md b/archive/edge/hi-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..f3d9a6d585 --- /dev/null +++ b/archive/edge/hi-edge/working-with-node/backup-restore.md @@ -0,0 +1,92 @@ +--- +id: backup-restore +title: नोड इंस्टैंस को बैकअप/रिस्टोर करें +description: "पॉलीगॉन एज नोड के इंस्टैंस को कैसे बैकअप और रिस्टोर करें." +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## ओवरव्यू {#overview} + +यह गाइड पॉलीगॉन एज के नोड इंसटैंस को कैसे बैकअप और रिस्टोर करें के बारे में विस्तार से बताती है. +यह बेस फ़ोल्डर्स और उनमें क्या शामिल है, इसके साथ ही सफल बैकअप और रिस्टोर करने के लिए कौन सी फ़ाइलें महत्वपूर्ण हैं के बारे में भी बताता है. + +## बेस फ़ोल्डर्स {#base-folders} + +पॉलीगॉन एज LevelDB को अपने स्टोरेज इंजन के रूप में इस्तेमाल करता है. +पॉलीगॉन एज नोड को शुरू करते समय, निम्नलिखित सब-फ़ोल्डर्स को निर्दिष्ट कार्यकारी डायरेक्टरी में बनाया जाता है: +* **ब्लॉकचेन**, - ब्लॉकचेन के डेटा को स्टोर करता है +* **trie** - Merkle tries को स्टोर करता है (वर्ल्ड स्टेट डेटा) +* **कीस्टोर** - क्लाइंट के लिए निजी की को स्टोर करता है. इसमें libp2p की निजी की और सीलिंग / वैलिडेटर की निजी की भी शामिल होती है +* **सहमति**, - सहमति की किसी भी जानकारी को स्टोर करता है जिसकी काम करते समय क्लाइंट को ज़रूरत हो सकती है. अभी, यह नोड की *निजी वैलिडेटर की* को स्टोर करता है + +पॉलीगॉन एज के इंस्टैंस को सुचारू रूप से रन कराने के लिए इन फ़ोल्डर्स को संरक्षित किया जाना महत्वपूर्ण है. + +## रन कर रहे नोड से बैकअप बनाएँ और नए नोड के लिए रिस्टोर करें {#create-backup-from-a-running-node-and-restore-for-new-node} + +यह सेक्शन आपको रन कर रहे नोड में ब्लॉकचेन के आर्काइव डेटा को बनाने और दूसरे इंस्टैंस में रिस्टोर करने के लिए गाइड करता है. + +### बैकअप {#backup} + +`backup` कमांड, रन कर रहे नोड से ब्लॉक को gRPC द्वारा निकालता है और एक आर्काइव फ़ाइल को जनरेट करता है. अगर `--from`और `--to` कमांड में नहीं दिए गए हों तो यह कमांड जेनेसिस से लेटेस्ट ब्लॉक निकाल लेगा. + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### रिस्टोर {#restore} + +`--restore` फ्लैग के साथ शुरू होते समय एक सर्वर ब्लॉक्स को आर्काइव से इम्पोर्ट करता है. कृपया सुनिश्चित करें कि नए नोड के लिए एक की हो. कीज़ को इम्पोर्ट करने या जनरेट करने के बारे में अधिक जानने के लिए, [सीक्रेट्स मैनेजर सेक्शन](/docs/edge/configuration/secret-managers/set-up-aws-ssm) को विज़िट करें. + +```bash +$ polygon-edge server --restore archive.dat +``` + +## पूरे डेटा को बैकअप/रिस्टोर करें {#back-up-restore-whole-data} + +यह सेक्शन आपको स्टेट और की के डेटा को बैकअप करने और नए इंस्टैंस में रिस्टोर करने के लिए गाइड करता है. + +### स्टेप 1: रन कर रहे क्लाइंट को रोकें {#step-1-stop-the-running-client} + +चूँकि, पॉलीगॉन एज डेटा को स्टोर करने के लिए **LevelDB** को इस्तेमाल करता है, इसलिए बैकअप के दौरान नोड को रोकना ज़रूरी है, +क्योंकि **LevelDB** अपने डाटाबेस की फ़ाइलों तक कॉन्करंट एक्सेस की अनुमति नहीं देता है. + +इसके अलावा पॉलीगॉन एज बंद होने पर डेटा फ्लशिंग भी करता है. + +पहले स्टेप में क्लाइंट को रन करने से रोकना शामिल है (या तो सर्विस मैनेजर द्वारा या किसी दूसरे मैकेनिज्म के माध्यम से, जो प्रक्रिया को SIGINT सिग्नल भेजता है), +तो यह अच्छी तरह से बंद होते समय 2 इवेंट को ट्रिगर कर सकता है: +* डिस्क में डेटा फ्लश को रन कर रहा है +* LevelDB द्वारा DB फ़ाइलों का लॉक रिलीज़ करना + +### स्टेप 2: डायरेक्टरी का बैकअप {#step-2-backup-the-directory} + +अब जबकि क्लाइंट रन नहीं कर रहा है, डेटा की डायरेक्टरी को दूसरे माध्यम में बैकअप किया जा सकता है. +ध्यान रखें कि `.key` एक्सटेंशन वाली फ़ाइलों में निजी की डेटा होता है जिसे वर्तमान नोड को प्रतिरूपित करने के लिए इस्तेमाल किया जा सकता है, +और उन्हें कभी तीसरे/अनजान पक्ष के साथ साझा नहीं किया जाना चाहिए. + +:::info +कृपया, जनरेट की गई `genesis` फ़ाइल का मैन्युअल रूप से बैकअप और रिस्टोर करें ताकि रिस्टोर किया गया नोड पूरी तरह से काम करे. + +::: + +## रिस्टोर {#restore-1} + +### स्टेप 1: रन कर रहे क्लाइंट को रोकें {#step-1-stop-the-running-client-1} + +अगर पॉलीगॉन एज का कोई भी इंस्टैंस रन हो रहा है, तो इसे स्टेप 2 को सफल बनाने के लिए रोका जाना चाहिए. + +### स्टेप 2: बैकअप किए गए डेटा की डायरेक्टरी को वांछित फ़ोल्डर में कॉपी करें {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +एक बार जब क्लाइंट रन नहीं कर रहा होता है, जिस डेटा डायरेक्टरी को पहले से बैकअप किया गया था, उसे वांछित फ़ोल्डर में कॉपी किया जा सकता है. +इसके अलावा, पहले से कॉपी की गई `genesis` फ़ाइल को रिस्टोर कर सकते हैं. + +### स्टेप 3: डेटा की सही डायरेक्टरी को निर्दिष्ट करते समय पॉलीगॉन एज के क्लाइंट को रन करें {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +पॉलीगॉन एज के लिए रिस्टोर की गई डेटा डायरेक्टरी को इस्तेमाल करने के लिए इसके लॉन्च होने पर यूज़र को इसके पाथ को निर्दिष्ट करने की ज़रूरत है +डेटा डायरेक्टरी. कृपया `data-dir`फ्लैग के बारे जानकारी पाने के लिए, [CLI कमांड्स](/docs/edge/get-started/cli-commands) सेक्शन से परामर्श करें. diff --git a/archive/edge/hi-edge/working-with-node/query-json-rpc.md b/archive/edge/hi-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..3807c77b26 --- /dev/null +++ b/archive/edge/hi-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,92 @@ +--- +id: query-json-rpc +title: क्वेरी JSON RPC एंडपॉइंट +description: "डेटा क्वेरी करें और एक premined अकाउंट के साथ चेन शुरू करें." +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## ओवरव्यू {#overview} + +पॉलीगॉन एज की JSON-RPC लेयर डेवलपर्स को ब्लॉकचेन के साथ आसानी से बातचीत करने की फ़ंक्शनैलिटी प्रदान करती है +HTTP अनुरोधों के माध्यम से. + +इस उदाहरण में टूल्स जैसे **कर्ल** का इस्तेमाल करके जानकारी की पूछताछ करने के साथ-साथ एक premined अकाउंट के साथ चेन शुरू करना शामिल है, +और एक ट्रांज़ैक्शन भेजता है. + +## स्टेप 1: एक premined अकाउंट के साथ एक जेनेसिस फ़ाइल बनाएँ {#step-1-create-a-genesis-file-with-a-premined-account} + +एक जेनेसिस फ़ाइल जनरेट करने के लिए, निम्नलिखित कमांड को रन करें: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +**premine** फ्लैग उस पते को सेट करता है जिसे **जेनेसिस फ़ाइल** में शुरूआती बैलेंस के साथ शामिल किया जाना चाहिए.
+इस मामले में, `0x1010101010101010101010101010101010101010` पते में शुरू करने के लिए `0xD3C21BCECCEDA1000000`का **डिफ़ॉल्ट बैलेंस ** होगा +(10 लाख नेटिव करेंसी टोकन). + +अगर हम बैलेंस को निर्दिष्ट करना चाहते हैं, तो हम बैलेंस और पते को एक `:` के साथ अलग कर सकते हैं, जैसे : +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +बैलेंस या तो एक `hex` या एक `uint256` वैल्यू में हो सकता है. + +:::warning केवल वे premine अकाउंट जिनके लिए आपके पास निजी की है! +अगर आपके पास ऐसे premine अकाउंट हैं जिनकी निजी की आपके पास नहीं है, तो आप उनके बैलेंस का इस्तेमाल नहीं कर सकते + +::: + +## स्टेप 2: पॉलीगॉन एज को dev मोड में शुरू करें {#step-2-start-the-polygon-edge-in-dev-mode} + +पॉलीगॉन एज को विकास मोड में शुरू करने के लिए, जिसे [CLI कमांड](/docs/edge/get-started/cli-commands) सेक्शन में समझाया गया है, +इनको रन करें: +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## स्टेप 3: अकाउंट के बैलेंस संबंधी क्वेरी {#step-3-query-the-account-balance} + +अब जबकि क्लाइंट dev मोड में रन कर रहा है,** स्टेप 1** में जनरेट की गई जेनेसिस फ़ाइल का इस्तेमाल करते हुए हम इस्तेमाल कर सकते हैं टूल जैसे +**कर्ल**, अकाउंट के बैलेंस संबंधी क्वेरी: +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +कमांड को निम्नलिखित आउटपुट रिटर्न करना चाहिए: +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## स्टेप 4: ट्रांसफ़र की ट्रांज़ैक्शन भेजें {#step-4-send-a-transfer-transaction} + +अब जब हमने पुष्टि कर ली है कि हमने premined के रूप में सेट किए गए अकाउंट में सही बैलेंस है, तो हम कुछ ईथर ट्रांसफ़र कर सकते हैं: + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/hi-edge/working-with-node/query-operator-info.md b/archive/edge/hi-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..68bc3b6aa2 --- /dev/null +++ b/archive/edge/hi-edge/working-with-node/query-operator-info.md @@ -0,0 +1,85 @@ +--- +id: query-operator-info +title: क्वेरी ऑपरेटर जानकारी +description: "ऑपरेटर की जानकारी कैसे पूछें." +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## आवश्यक शर्तें {#prerequisites} + +[यह मार्गदर्शिका मानती है कि आपने क्लाउड पर IBFT क्लस्टर सेट करने के ](/docs/edge/get-started/set-up-ibft-on-the-cloud)तरीके पर [स्थानीय सेटअप ](/docs/edge/get-started/set-up-ibft-locally)या मार्गदर्शिका का पालन किया है. + +किसी भी प्रकार की ऑपरेटर जानकारी को क्वेरी करने के लिए एक क्रियाशील नोड की आवश्यकता होती है. + +पॉलीगॉन एज के साथ, नोड ऑपरेटर नियंत्रण में हैं और सूचित करते हैं कि वे जिस नोड का संचालन कर रहे हैं वह क्या कर रहा है.
+किसी भी समय, वे जीआरपीसी के शीर्ष पर निर्मित नोड सूचना परत का उपयोग कर सकते हैं, और सार्थक जानकारी प्राप्त कर सकते हैं - कोई लॉग सिफ्टिंग की आवश्यकता नहीं है. + +:::note + +यदि आपका नोड नहीं चल रहा है तो आपको इस दस्तावेज़ में सूचीबद्ध आदेशों में एक `127.0.0.1:8545`फ़्लैग जोड़ना `--grpc-address `चाहिए. + +::: + +## सहकर्मी जानकारी {#peer-information} + +### साथियों की सूची {#peers-list} + +कनेक्टेड साथियों की पूरी सूची प्राप्त करने के लिए (रनिंग नोड सहित), निम्नलिखित कमांड चलाएँ: +````bash +polygon-edge peers list +```` + +यह libp2p पतों की एक सूची लौटाएगा जो वर्तमान में चल रहे क्लाइंट के सहकर्मी हैं. + +### सहकर्मी की स्थिति {#peer-status} + +विशिष्ट सहकर्मी की स्थिति के लिए, रन: +````bash +polygon-edge peers status --peer-id
+```` +*पते* के साथ पैरामीटर सहकर्मी का libp2p पता है. + +## IBFT जानकारी {#ibft-info} + +ಅನೇಕ ಬಾರಿ, IBFT ಒಮ್ಮತದಲ್ಲಿ ಆಪರೇಟರ್ ನೋಡ್‌ನ ಸ್ಥಿತಿಯ ಬಗ್ಗೆ ಆಪರೇಟರ್ ತಿಳಿದುಕೊಳ್ಳಲು ಬಯಸಬಹುದು. + +सौभाग्य से, पॉलीगॉन एज इस जानकारी को खोजने का एक आसान तरीका प्रदान करता है. + +### स्नैपशॉट्स {#snapshots} + +निम्न आदेश चलाना सबसे हालिया स्नैपशॉट देता है. +````bash +polygon-edge ibft snapshot +```` +किसी ऊँचाई ब्लॉक नंबर पर स्नैपशॉट को क्वैरी क्वेरी करने के लिए, ऑपरेटर रन बना सकता है: +````bash +polygon-edge ibft snapshot --num +```` + +### उम्मीदवार {#candidates} + +उम्मीदवारों पर जानकारी प्राप्त करने के लिए, ऑपरेटर रन बना सकता है: +````bash +polygon-edge ibft candidates +```` +यह कमांड प्रस्तावित उम्मीदवारों के मौजूदा सेट और साथ ही उन उम्मीदवारों को पूछताछ करता है जिन्हें अभी तक शामिल नहीं किया गया है. + +### स्टेटस {#status} + +निम्न कमांड रन बनाए गए IBFT क्लाइंट की मौजूदा validator की लौटाता है: +````bash +polygon-edge ibft status +```` + +## ट्रैन्सैक्शन पूल {#transaction-pool} + +ट्रैन्सैक्शन पूल में लेनदेन की वर्तमान संख्या का पता लगाने के लिए, ऑपरेटर चला सकता है: +````bash +polygon-edge txpool status +```` diff --git a/archive/edge/id-edge/additional-features/blockscout.md b/archive/edge/id-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..155f4c424a --- /dev/null +++ b/archive/edge/id-edge/additional-features/blockscout.md @@ -0,0 +1,403 @@ +--- +id: blockscout +title: Blockscout +description: Cara mengatur instans Blockscout agar berfungsi dengan Polygon Edge. +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## Ikhtisar {#overview} +Panduan ini menjelaskan perincian cara mengompilasi dan menyebar instans Blockscout agar berfungsi dengan Polygon-Edge. +Blockscout memiliki [dokumentasi](https://docs.blockscout.com/for-developers/manual-deployment) sendiri, tetapi panduan ini berfokus pada instruksi langkah yang sederhana, tetapi mendetail tentang cara mengatur instans Blockscout. + +## Lingkungan {#environment} +* Sistem Operasi: Ubuntu Server 20.04 LTS [tautan unduhan](https://releases.ubuntu.com/20.04/) dengan izin sudo +* Perangkat Keras Server: 8 CPU / RAM 16 GB / HDD 50 GB (LVM) +* Server Pangkalan Data: Server khusus dengan 2 CPU / RAM 4 GB / SSD 100 GB / PostgreSQL 13.4 + +### Server DB {#db-server} +Syarat untuk mengikuti panduan ini adalah server pangkalan data yang siap pakai, pangkalan data dan pengguna telah dikonfigurasi +Panduan ini tidak akan menjelaskan cara menyebar dan mengkonfigurasi server PostgreSQL. +Ada banyak panduan untuk melakukan hal ini, misalnya [Panduan DigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart) + +:::info PENAFIAN +Panduan ini hanya untuk membantu Anda menjalankan Blockscout pada instans tunggal yang bukan pengaturan produksi yang ideal. +Untuk produksi, Anda mungkin ingin memperkenalkan proksi terbalik, penyeimbang beban, pilihan skalabilitas, dll. ke dalam arsitektur. + +::: + +# Prosedur Penyebaran Blockscout {#blockscout-deployment-procedure} + +## Bagian 1 - instal dependensi {#part-1-install-dependencies} +Sebelum memulai, kita perlu memastikan semua biner sudah terinstal yang menjadi dependensi blockscout. + +### Memperbarui & meningkatkan sistem {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### Tambah repo erlang {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### Tambah repo NodeJS {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### Instal Rust {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### Instal versi Erlang yang dibutuhkan {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### Instal versi Elixir yang dibutuhkan {#install-required-version-of-elixir} +Versi Elixir harus `1.13`. Jika menginstal versi ini dari repo resmi, +`erlang` akan memperbarui ke `Erlang/OTP 25` dan kita tidak menginginkan hal itu. +Maka kita perlu menginstal versi yang `elixir` telah dikompilasi khusus dari halaman rilis GitHub. + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +Sekarang kita perlu mengatur biner sistem `exlixir` dengan benar. +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +Jalankan `elixir -v` untuk memeriksa apakah `erlang` dan `elixir` telah diinstall dengan benar. +Hasilnya akan seperti ini: +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning +`Erlang/OTP`harus versi `24`dan `Elixir`harus versi .`1.13.*` Jika itu bukan kasusnya, Anda akan jalankan ke isu dengan mengkompilasi Blockscout dan/atau menjalankannya. +::: +:::info +Periksa ***[halaman persyaratan Blockscout](https://docs.blockscout.com/for-developers/information-and-settings/requirements)*** resmi +::: + +### Install NodeJS {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### Instal Cargo {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### Instal dependensi lainnya {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### Secara opsional, instal klien postgresql untuk memeriksa koneksi db {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## Bagian 2 - atur variabel lingkungan {#part-2-set-environment-variables} +Sebelum memulai kompilasi Blockscout, kita perlu mengatur variabel lingkungan. Dalam panduan ini kita hanya akan mengatur minimum dasar untuk membuatnya bekerja. Daftar lengkap variabel yang dapat diatur ada [di sini](https://docs.blockscout.com/for-developers/information-and-settings/env-variables) + +### Atur koneksi pangkalan data sebagai variabel lingkungan {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +Sekarang, tes koneksi DB dengan parameter yang tersedia. +Karena Anda menyediakan PG env vars, Anda akan dapat menghubungkan ke pangakalan data hanya dengan menjalankan: +```bash +psql +``` + +Jika pangkalan data dikonfigurasi dengan benar, Anda akan melihat baris perintah psql: +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +Jika tidak, Anda mungkin melihat error seperti ini: +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +Jika hal ini terjadi, [dokumen ini](https://ubuntu.com/server/docs/databases-postgresql) mungkin dapat membantu Anda. + +:::info Koneksi DB + +Pastikan Anda telah menyelesaikan semua isu koneksi sebelum melanjutkan ke bagian selanjutnya. +Anda perlu untuk menyediakan hak istimewa pengguna super untuk pengguna blockscout. + +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## Bagian 3 - mengkloning dan mengompilasi Blockscout {#part-3-clone-and-compile-blockscout} +Sekarang kita akhirnya dapat mulai instalasi Blockscout. + +### Mengkloning repo Blockscout {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### Buat basis kunci rahasia untuk melindungi build produksi {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +Pada baris yang terakhir, Anda akan melihat string panjang yang berisi karakter acak. +Ini akan diatur sebagai variabel lingkungan `SECRET_KEY_BASE`, sebelum langkah selanjutnya. +Misalnya: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### Atur mode produksi {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### Mengompilasi {#compile} +Cd ke direktori klona dan mulai kompilasi + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info + +Jika sudah disebarkan, hilangkan aset statis dari build ***mix phx.digest.clean*** sebelumnya. + +::: + +### Memigrasi pangkalan data {#migrate-databases} +:::info + +Bagian ini akan gagal jika Anda tidak mengatur koneksi DB dengan benar, tidak menyediakan parameter, +atau menentukan parameter yang salah pada variabel lingkungan DATABASE_URL. +Pengguna pangkalan data harus memiliki hak istimewa superuser. + +::: +```bash +mix do ecto.create, ecto.migrate +``` + +Jika Anda harus mengeluarkan pangkalan data terlebih dahulu, jalankan +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### Instal dependensi npm dan kompilasikan aset frontend {#install-npm-dependencies-and-compile-frontend-assets} +Anda harus mengubah direktori ke folder yang berisi aset frontend. + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info Mohon bersabar + +Kompilasi aset dapat memerlukan waktu beberapa menit dan tidak akan menampilkan output. +Ini dapat terlihat seperti proses yang macet, tetapi tetap bersabar. +Ketika proses kompilasi selesai, outpu akan seperti: `webpack 5.69.1 compiled with 3 warnings in 104942 ms` + +::: + +### Aset statis build {#build-static-assets} +Untuk langkah ini, Anda harus kembali ke root folder klona Blockscout. +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### Buat sertifikat yang ditandatangani sendiri {#generate-self-signed-certificates} +:::info +Anda dapat melewatkan langkah ini jika Anda tidak akan menggunakannya `https`. +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## Bagian 4 - buat dan jalankan layanan Blockscout {#part-4-create-and-run-blockscout-service} +Di bagian ini kita perlu mengatur layanan sistem karena kita ingin Blockscout jalankan di latar belakang dan bertahan setelah sistem reboot. + +### Buat file layanan {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### Edit file layanan {#edit-service-file} +Gunakan editor teks linux favorit Anda untuk mengedit file ini dan konfigurasikan layanan. +```bash +sudo vi /etc/systemd/system/explorer.service +``` +Isi file explorer.service akan terlihat seperti ini: +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### Aktifkan layanan awal di boot sistem {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### Pindah folder klon Blockscout Anda ke lokasi seluruh sistem {#move-your-blockscout-clone-folder-to-system-wide-location} +Layanan Blockscout perlu memiliki akses ke folder yang telah Anda kloning dari repo Blockscout dan mengkompilasi semua aset. +```bash +sudo mv ~/blockscout /usr/local +``` + +### Buat file env vars yang akan digunakan oleh layanan Blockscout {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info + +Gunakan `SECRET_KEY_BASE` yang telah Anda buat di Bagian 3. + +:::Simpan file dan keluar. + +### Akhirnya, mulai layanan Blockscout {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## Bagian 5 - tes fungsi instance Blockscout Anda {#part-5-test-out-the-functionality-of-your-blockscout-instance} +Sekarang yang harus dilakukan tinggal periksa apakah layanan Blockscout berjalan. Periksa status layanan dengan: +```bash +sudo systemctl status explorer.service +``` + +Untuk memeriksa output layanan: +```bash +sudo journalctl -u explorer.service -f +``` + +Anda dapat memeriksa apakah ada port mendengarkan baru: +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +Anda harus mendapatkan daftar port mendengarkan dan di daftar itu harus ada sesuatu seperti ini: +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +Layanan web Blockscout menjalankan port dan protokol yang ditentukan di file env. Dalam contoh ini itu jalankan di `4000`(http). Jika semuanya normal, Anda akan dapat mengakses portal web Blockscout dengan `http://:4000`. + +## Pertimbangan {#considerations} +Untuk kinerja terbaik, itu disarankan memiliki node non validator arsip penuh `polygon-edge`yang berdedikasi/lokal yang akan digunakan secara eksklusif untuk query Blockscout. API `json-rpc` dari node ini, tidak perlu diekspos secara publik, karena Blockscout jalankan semua query dari backend. + + +## Pemikiran akhir {#final-thoughts} +Kita telah meluncurkan instans Blockscout tunggal yang beroperasi dengan baik, tetapi untuk produksi, Anda harus mempertimbangkan penempatan instans ini di belakang proxy terbalik seperti Nginx. +Anda juga harus memikirkan basis data dan skalabilitas instance, tergantung pada kasus pengguna Anda. + +Anda harus memeriksa [dokumentasi Blockscout](https://docs.blockscout.com/) resmi karena ada banyak opsi kustomisasi. \ No newline at end of file diff --git a/archive/edge/id-edge/additional-features/chainbridge/definitions.md b/archive/edge/id-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..5a53b56578 --- /dev/null +++ b/archive/edge/id-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,221 @@ +--- +id: definitions +title: Definisi Umum +description: Definisi Umum untuk istilah yang digunakan dalam chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## Relayer {#relayer} +Chainbridge adalah jembatan jenis relayer. Peran relayer adalah memberi suara untuk eksekusi dari suatu permintaan (misalnya, berapa jumlah token untuk dibakar/dirilis). +Relayer memantau kejadian dari setiap rantai dan memberi suara untuk proposal di dalam kontrak Bridge rantai tujuan saat menerima kejadian `Deposit` dari rantai. Relayer memanggil suatu metode dalam kontrak Bridge untuk mengeksekusi proposal setelah jumlah suara yang dibutuhkan telah dikirim. Jembatan mendelegasikan eksekusi ke kontrak Handler. + + +## Jenis kontrak {#types-of-contracts} +Di ChainBridge, ada tiga jenis kontrak pada setiap rantai yang disebut Bridge/Handler/Target. + +| **Jenis** | **Deskripsi** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Kontrak jembatan | Kontrak Bridge (Jembatan) yang mengelola permintaan, suara, eksekusi perlu disebar pada setiap rantai. Pengguna akan memanggil `deposit` di Bridge untuk memulai transfer dan Bridge mendelegasikan kontrak terkait kepada Handler. Setelah kontrak Handler berhasil memanggil kontrak Target, kontrak Bridge mengirim kejadian `Deposit` untuk memberi tahu relayer. | +| Kontrak Handler | Kontrak ini berinteraksi dengan kontrak Target untuk mengeksekusi setoran atau proposal. Ini memvalidasi permintaan pengguna, memanggil kontrak Target, dan membantu beberapa pengaturan untuk kontrak Target. Ada beberapa kontrak Handler tertentu untuk memanggil setiap kontrak Target yang memiliki antarmuka berbeda. Panggilan tidak langsung oleh kontrak Handler membuat jembatan mengaktifkan transfer semua jenis aset atau data. Saat ini, ada tiga jenis kontrak Handler yang diterapkan oleh ChainBridge: ERC20Handler, ERC721Handler, dan GenericHandler. | +| Kontrak Target | Kontrak yang mengelola aset untuk ditukar atau pesan yang ditransfer antara rantai. Interaksi antara kontrak ini akan dibuat dari setiap sisi jembatan. | + +
+ +![Arsitektur ChainBridge](/img/edge/chainbridge/architecture.svg) +*Arsitektur ChainBridge* + +
+ +
+ +![Alur kerja transfer token ERC20](/img/edge/chainbridge/erc20-workflow.svg) +*mis. Alur kerja transfer token ERC20* + +
+ +## Jenis akun {#types-of-accounts} + +Pastikan akun memiliki token asli dalam jumlah mencukupi untuk membuat transaksi sebelum memulai. Di Polygon Edge, Anda dapat menetapkan saldo prapenambangan ke akun saat membuat blok genesis. + +| **Jenis** | **Deskripsi** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Admin | Akun ini akan diberi peran admin secara default. | +| Pengguna | Akun pengirim/penerima yang mengirim/menerima aset. Akun pengirim membayar biaya gas saat menyetujui transfer token dan memanggil setoran di kontrak Bridge untuk memulai transfer. | + +:::info Peran admin + +Tindakan tertentu hanya dapat dilakukan oleh akun dengan peran admin. Secara default, penyebar kontrak Bridge memiliki peran admin, Di bawah ini, Anda akan menemukan cara memberi peran admin ke akun lain atau menghapusnya. + +### Menambah peran admin {#add-admin-role} + +Menambahkan admin + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### Mencabut peran admin {#revoke-admin-role} + +Menghapus admin + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## Operasi yang diizinkan oleh akun `admin` adalah sebagai berikut. {#account-are-as-below} + +### Mengatur Sumber Daya {#set-resource} + +Daftarkan ID sumber daya dengan alamat kontrak untuk handler. + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Membuat kontrak yang dapat dibakar (burn)/dibuat (mint) {#make-contract-burnable-mintable} + +Mengatur kontrak token agar dapat dibuat/dibakar di handler. + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Membatalkan proposal {#cancel-proposal} + +Membatalkan proposal untuk eksekusi + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### Menjeda/Menghentikan Jeda {#pause-unpause} + +Menjeda sementara untuk penyetoran, pembuatan proposal, pemberian suara, dan eksekusi setoran. + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### Mengubah Biaya {#change-fee} + +Mengubah biaya yang akan dibayar kepada Kontrak Bridge + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### Menambah/Menghapus relayer {#add-remove-a-relayer} + +Menambah akun sebagai relayer baru atau menghapus akun dari relayer + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### Mengubah ambang batas relayer {#change-relayer-threshold} + +Mengubah jumlah suara yang dibutuhkan untuk eksekusi proposal + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## ID Rantai {#chain-id} + +Chainbridge `chainId` adalah nilai suka-suka yang digunakan pada jembatan untuk membedakan antara jaringan blockchain, dan harus dalam rentang uint8. Supaya tidak bingung dengan ID rantai jaringan, keduanya bukan hal yang sama. Nilai ini harus unik, tetapi tidak harus sama dengan ID jaringan tersebut. + +Dalam contoh ini, kita mengatur `99` pada `chainId`, karena ID rantai dari testnet Mumbai adalah `80001`, yang tidak dapat direpresentasikan dengan uint8. + +## ID Sumber Daya {#resource-id} + +ID sumber daya adalah nilai 32-byte unik dalam lingkungan lintas rantai yang diasosiasikan dengan aset (sumber daya) tertentu yang ditransfer antar jaringan. + +ID sumber bersifat suka-suka, tetapi sebagai kaidah, biasanya byte terakhir mengandung ID rantai dari rantai sumber daya (jaringan asal aset ini). + +## URL JSON-RPC untuk Polygon PoS {#json-rpc-url-for-polygon-pos} + +Untuk panduan ini, kita akan menggunakan https://rpc-mumbai.matic.today, URL JSON-RPC publik yang disediakan oleh Polygon, yang dapat memiliki lalu lintas atau batas kecepatan. Ini akan digunakan hanya untuk menghubungkan dengan tesnet Polygon Mumbai. Kami menyarankan Anda untuk mendapatkan URL JSON-RPC melalui layanan eksternal seperti Infura karena menyebar kontrak akan mengirim banyak kueri/permintaan kepada JSON-RPC. + +## Cara memproses transfer token {#ways-of-processing-the-transfer-of-tokens} +Ketika mentransfer token ERC20 antara beberapa rantai, token itu akan diproses pada dua mode: + +### Mode lock/release (kunci/rilis) {#lock-release-mode} +Rantai sumber: Token yang Anda kirim akan terkunci di dalam Kontrak Handler.
+Rantai tujuan: Jumlah token yang sama seperti yang Anda kirim di rantai sumber akan terbuka dan ditransfer dari kontrak Handler kepada akun penerima di rantai tujuan. + +### Mode burn/mint (bakar/cetak) {#burn-mint-mode} +Rantai sumber: Token yang Anda kirim akan dibakar.
+Rantai tujuan: Jumlah token yang sama yang Anda kirim dan bakar di rantai sumber akan dicetak/dibuat di rantai tujuan dan dikirim ke akun penerima. + +Anda dapat menggunakan berbagai meode pada setiap rantai. Ini berarti Anda dapat mengunci token pada rantai utama sembari mencetak token di subrantai untuk transfer. Misalnya, mungkin masuk akal untuk mengunci/melepas token jika pasokan total atau jadwal cetak dikendalikan. Token akan dicetak/dibakar jika kontrak di subrantai harus mengikuti pasokan di rantai utama. + +Mode default adalah mode lock/release (kunci/rilis). Jika ingin membuat Token dapat dicetak/dibakar, Anda harus memanggil metode `adminSetBurnable`. Jika ingin mencetak token pada eksekusi, Anda harus memberi peran `minter` kepada kontrak Handler ERC20. + + diff --git a/archive/edge/id-edge/additional-features/chainbridge/overview.md b/archive/edge/id-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..02fc1cf5a0 --- /dev/null +++ b/archive/edge/id-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Ikhtisar +description: Ikhtisar ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Apa itu ChainBridge? {#what-is-chainbridge} + +ChainBridge adalah jembatan blockchain modular multiarah yang mendukung rantai yang kompatibel dengan EVM dan Substrat, yang dibuat oleh ChainSafe. Jembatan ini memungkinkan pengguna mentransfer semua jenis aset atau pesan antara dua rantai berbeda. + +Untuk mencari tahu lebih banyak tentang ChainBrige, silakan baca [dokumen resmi](https://chainbridge.chainsafe.io/) yang disediakan oleh pengembangnya. + +Panduan ini untuk membantu integrasi Chainbridge ke Polygon Edge. Panduan ini membahas penyiapan jembatan antara Polygon PoS yang berjalan (testnet Mumbai) dan jaringan Polygon Edge lokal. + +## Persyaratan {#requirements} + +Dalam panduan ini, Anda akan menjaankan node Polygon Edge, relayer ChainBridge (lebih lanjut tentang hal ini [di sini](/docs/edge/additional-features/chainbridge/definitions)), dan alat cb-sol-cli yang merupakan alat CLI untuk menyebarkan kontrak secara lokal, mendaftarkan sumber daya, dan mengubah pengaturan jembatan (Anda dapat membacanya [di sini](https://chainbridge.chainsafe.io/cli-options/#cli-options) juga). Lingkungan berikut diperlukan sebelum memulai penyiapan: + +* Baca: >= 1.17 +* Node.js >= 16.13.0 +* Git + + +Selain itu, Anda perlu mengklona repositori berikut bersama versinya untuk menjalankan beberapa aplikasi. + +* [Polygon Edge](https://github.com/0xPolygon/polygon-edge): di cabang `develop` +* [ChainBridge](https://github.com/ChainSafe/ChainBridge): v1.1.5 +* [Alat Penyebaran ChainBridge](https://github.com/ChainSafe/chainbridge-deploy): `f2aa093` di cabang `main` + + +Anda perlu menyiapkan jaringan Polygon Edge sebelum melanjutkan ke bagian selanjutnya. Silakan baca [Penyiapan Lokal](/docs/edge/get-started/set-up-ibft-locally) atau [Penyiapan Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) untuk informasi selengkapnya. \ No newline at end of file diff --git a/archive/edge/id-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/id-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..2e85957c6c --- /dev/null +++ b/archive/edge/id-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,142 @@ +--- +id: setup-erc20-transfer +title: Transfer Token ERC20 +description: Cara menyiapkan transfer ERC-20 di chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Sejauh ini, kita telah menyiapkan jembatan untuk bertukar aset/data antara Polygon PoS dan rantai Polygon Edge. Bagian ini akan memandu Anda menyiapkan jembatan ERC20 dan mengirim token antara berbagai blockchain. + +## Langkah 1: Mendaftarkan ID sumber daya {#step-1-register-resource-id} + +Pertama, Anda akan mendaftarkan ID sumber daya yang menghubungkan sumber daya pada lingkungan lintas rantai. ID Sumber Daya adalah nilai 32-byte yang harus unik untuk sumber yang kita transfer antara berbagai blockchain ini. ID Sumber Daya bersifat suka-suka, tetapi harus memiliki ID rantai dari rantai asal pada byte terakhirnya, sebagai aturan dasar (rantai asal merujuk ke jaringan tempat sumber daya ini berasal). + +Untuk mendaftarkan ID sumber daya, Anda dapat menggunakan perintah `cb-sol-cli bridge register-resource`. Anda harus memberikan kunci privat akun `admin` tersebut. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (Opsional) Buat kontrak yang dapat dibuat/dibakar (mintable/burnable) {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## Langkah 2: Mentransfer Token ERC20 {#step-2-transfer-erc20-token} + +Kita akan mengirim Token ERC20 dari rantai Polygon PoS ke rantai Polygon Edge. + +Pertama, Anda akan mendapat token dengan melakukan pencetakan/pembuatan. Akun dengan peran `minter` dapat mencetak token baru. Akun yang telah menyebar kontrak ERC20 memiliki peran `minter` secara default. Untuk menetapkan akun lain sebagai anggota dari peran `minter`, Anda perlu menjalankan perintah `cb-sol-cli erc20 add-minter`. + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +Untuk memeriksa saldo saat ini, Anda dapat menggunakan perintah `cb-sol-cli erc20 balance`. + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +Pertama, Anda perlu menyetujui transfer token ERC20 dari akun oleh ERC20 Handler + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +Untuk mentransfer token ke rantai Polygon Edge, Anda akan memanggil `deposit`. + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Setelah transaksi setor berhasil, relayer akan mendapat kejadian itu dan memberi suara untuk proposal itu. Ini mengeksekusi transaksi mengirim token ke akun penerima di rantai Polygon Edge setelah jumlah suara yang dibutuhkan sudah dikirimkan. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Setelah transaksi eksekusi berhasil, Anda akan mendapat token di rantai Polygon Edge. + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/id-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/id-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..b9e4513f02 --- /dev/null +++ b/archive/edge/id-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,134 @@ +--- +id: setup-erc721-transfer +title: Transfer ERC721 NFT +description: Cara menyiapkan ERC721 di chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Bagian ini memandu Anda melakukan penyiapan bridge ERC721 dan mengirim NFT antara beberapa jaringan blockchain. + +## Langkah 1: Mendaftarkan ID sumber daya {#step-1-register-resource-id} + +Pertama, Anda harus mendaftarkan ID sumber daya token ERC721 di kontrak Bridge pada kedua rantai. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (Opsional): Buat kontrak agar dapat dicetak/dibakar {#optional-make-contracts-mintable-burnable} + +Agar Token dapat dicetak/dibakar, Anda harus memanggil perintah berikut: + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## Langkah 2: Mentransfer NFT {#step-2-transfer-nft} + +Pertama, Anda harus mencetak NFT jika membutuhkannya. + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Untuk memeriksa pemilik NFT, Anda dapat menggunakan `cb-sol-cli erc721 owner` + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Lalu, Anda akan menyetujui transfer NFT oleh ERC721 Handler + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Terakhir, Anda akan memulai transfer + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +Relayer akan mendapatkan peristiwa dan memilih proposal. Ini mengeksekusi transaksi untuk mengirim NFT kepada akun penerima di rantai Polygon Edge setelah jumlah suara yang dibutuhkan sudah dikirimkan. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Anda dapat memeriksa pemilik NFT di jaringan Polygon Edge setelah eksekusi selesai. + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/id-edge/additional-features/chainbridge/setup.md b/archive/edge/id-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..3ad059a688 --- /dev/null +++ b/archive/edge/id-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,198 @@ +--- +id: setup +title: Pengaturan +description: Cara mengatur rantai +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Penyebaran kontrak {#contracts-deployment} + +Dalam bagian ini, Anda akan menyebarkan kontrak yang diperlukan untuk rantai Polygon PoS dan Polygon Edge dengan `cb-sol-cli`. + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +Pertama, kita akan menyebarkan kontrak ke rantai Polygon PoS menggunakan perintah `cb-sol-cli deploy`. Bendera `--all` membuat perintah penyebaran semua kontrak, termasuk Bridge, ERC20 Handler, ERC721 Handler, Generic Handler, ERC20, dan kontrak ERC721. Selain itu, ini akan mengatur alamat akun relayer default dan ambang + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +Pelajari tentang chainID dan URL JSON-RPC [di sini](/docs/edge/additional-features/chainbridge/definitions) + +:::caution + +Harga gas default di `cb-sol-cli` adalah `20000000` (`0.02 Gwei`). Untuk menetapkan harga gas yang tepat dalam transaksi, atur nilai menggunakan argumen `--gasPrice`. + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +Kontrak Bridge membutuhkan gas 0x3f97b8 (4167608) untuk penyebaran. Pastikan blok yang dihasilkan memiliki batas gas blok yang cukup untuk memuat transaksi pembuatan kontrak. Untuk mempelajari lebih lanjut tentang batas gas blok di Polygon Edge, kunjungi +[Local Setup](/docs/edge/get-started/set-up-ibft-locally) + +::: + +Setelah kontrak disebarkan, Anda akan mendapatkan hasil berikut: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +Sekarang kita dapat menyebarkan kontrak ke rantai Polygon Edge. + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Simpan output terminal dengan alamat kontrak cerdas yang disebarkan karena kita akan membutuhkannya di langkah berikutnya. + +## Pengaturan relayer {#relayer-setup} + +Dalam bagian ini, Anda memulai relayer untuk penukaran data di antara 2 rantai. + +Pertama, kita perlu mengklona dan membangun repositori ChainBridge. + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +Selanjutnya, Anda perlu membuat `config.json` dan mengatur URL JSON-RPC, alamat relayer, dan alamat kontrak setiap rantai. + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +Untuk memulai relayer, Anda harus mengimpor kunci privat yang sesuai dengan alamat akun relayer. Anda perlu memasukan kata sandi ketika mengimpor kunci privat. Setelah impor sukses, kunci akan disimpan pada `keys/
.key`. + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +Kemudian, Anda memulai relayer. Anda harus memasukan kata sandi serupa yang dipilih untuk menyimpan kunci di awal. + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +Setelah relayer dimulai, ini akan mulai melihat blok baru di setiap rantai diff --git a/archive/edge/id-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/id-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..dda82e97c3 --- /dev/null +++ b/archive/edge/id-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,255 @@ +--- +id: use-case-erc20-bridge +title: Kasus penggunaan - Jembatan ERC20 +description: Contoh untuk jembatan kontrak ERC20 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +Bagian ini bertujuan menyajikan aliran pengaturan Jembatan ERC20 untuk kasus penggunaan praktis. + +Dalam panduan ini, Anda akan menggunakan testnet Mumbai Polygon PoS dan rantai lokal Polygon Edge. Pastikan Anda memiliki titik akhir JSON-RPC untuk Mumbai dan telah mengatur Polygon Edge di lingkungan lokal. Lihat [Pengaturan lokal](/docs/edge/get-started/set-up-ibft-locally) atau [Pengaturan Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) untuk perincian lebih lanjut. + +## Skenario {#scenario} + +Skenario ini untuk mengatur Jembatan token ERC20 yang telah disebarkan di rantai publik (Polygon PoS) guna memungkinkan transfer berbiaya rendah di rantai privat (Polygon Edge) untuk pengguna dalam kasus biasa. Dalam kasus tersebut, total pasokan token telah ditentukan dalam rantai publik dan hanya jumlah token yang telah ditransfer dari rantai publik ke rantai privat harus ada di rantai privat. Untuk itu, Anda perlu menggunakan mode kunci/rilis di rantai publik dan mode bakar/cetak dalam rantai privat. + +Ketika mengirim token dari rantai publik ke rantai privat, token akan dikunci di kontrak ERC20 Handler rantai publik dan jumlah token yang sama akan dicetak di rantai privat. Selain itu, dalam kasus transfer rantai privat ke rantai publik, token di rantai privat akan dibakar dan jumlah token yang sama akan dirilis dari ERC20 Handler di rantai publik. + +## Kontrak {#contracts} + +Menjelaskan dengan kontrak ERC20 sederhana alih-alih kontrak yang dikembangkan oleh ChainBridge. Untuk mode bakar/cetak, kontrak ERC20 harus memiliki metode `mint` dan `burnFrom` selain metode untuk ERC20 seperti ini: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +Semua kode dan skrip berada di Repo Github [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Langkah 1: Sebarkan kontak Bridge dan ERC20 Handler {#step1-deploy-bridge-and-erc20-handler-contracts} + +Pertama, Anda dapat menyebarkan kontrak Bridge dan ERC20 Handler menggunakan `cb-sol-cli` di kedua rantai. + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Anda akan mendapatkan alamat kontrak Bridge dan ERC20Handler seperti ini: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Langkah 2: Sebarkan kontrak ERC20 {#step2-deploy-your-erc20-contract} + +Anda dapat menyebarkan kontrak ERC20. Contoh ini memandu Anda dengan proyek hardhat [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Buat file `.env` dan atur nilai berikut. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Berikutnya, Anda dapat menyebarkan kontrak ERC20 di kedua rantai. + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +Setelah penyebaran sukses, Anda akan mendapatkan alamat kontrak seperti ini: + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## Langkah 3: Daftarkan ID sumber daya di Bridge {#step3-register-resource-id-in-bridge} + +Anda dapat mendaftarkan ID sumber daya yang menghubungkan sumber daya di lingkungan lintas rantai. Anda perlu mengatur ID sumber daya yang sama di kedua rantai. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## Langkah 4: Atur mode Cetak/Bakar di jembatan ERC20 dari Edge {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +Jembatan diharapkan berfungsi sebagai mode bakar/cetak di Polygon Edge. Anda dapat mengatur mode bakar/cetak menggunakan `cb-sol-cli`. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +Anda juga perlu memberikan peran pencetak dan pembakar untuk kontrak ERC20 Handler. + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Langkah 5: Cetak Token {#step5-mint-token} + +Anda dapat mencetak token ERC20 baru di rantai Mumbai. + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +Setelah transaksi sukses, akun akan memiliki token yang telah dicetak. + +## Langkah 6: Mulai mentransfer ERC20 {#step6-start-erc20-transfer} + +Sebelum memulai langkah ini, pastikan Anda telah memulai relayer. Lihat [Pengaturan](/docs/edge/additional-features/chainbridge/setup) untuk perincian lebih lanjut. + +Selama transfer token dari Mumbai ke Edge, kontrak ERC20 Handler di Mumbai menarik token dari akun Anda. Anda akan memanggil persetujuan sebelum mentransfer. + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +Terakhir, Anda dapat mulai mentransfer token dari Mumbai ke Edge menggunakan `cb-sol-cli`. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Setelah transaksi penyetoran sukses, relayer akan mendapatkan peristiwa dan suara untuk proposal. Ini mengeksekusi transaksi pengiriman token ke akun penerima di rantai Polygon Edge setelah jumlah suara yang dibutuhkan sudah terkirim. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Setelah transaksi eksekusi sukses, Anda akan mendapatkan token di rantai Polygon Edge. diff --git a/archive/edge/id-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/id-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..2ffdafb039 --- /dev/null +++ b/archive/edge/id-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,308 @@ +--- +id: use-case-erc721-bridge +title: Kasus penggunaan - Bridge ER721 +description: Contoh kontrak jembatan ERC721 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +Bagian ini bertujuan menyajikan alur pengaturan Bridge ERC721 untuk kasus penggunaan praktis. + +Dalam panduan ini, Anda akan menggunakan testnet Mumbai Polygon PoS dan rantai lokal Polygon Edge. Pastikan Anda memiliki titik akhir JSON-RPC untuk Mumbai dan telah mengatur Polygon Edge di lingkungan lokal. Lihat [Pengaturan lokal](/docs/edge/get-started/set-up-ibft-locally) atau [Pengaturan Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) untuk perincian lebih lanjut. + +## Skenario {#scenario} + +Skenario ini mengatur Bridge untuk NFT ERC721 yang telah disebarkan di rantai publik (Polygon PoS) untuk mengaktifkan transfer berbiaya rendah pada rantai privat (Polygon Edge) bagi pengguna pada kasus biasa. Dalam kasus semacam itu, metadata asli telah ditetapkan pada rantai publik dan hanya NFT yang telah ditransfer dari rantai Publik yang bisa ada di dalam rantai privat. Untuk itu, Anda perlu menggunakan mode kunci/rilis di rantai publik dan mode bakar/cetak di rantai privat. + +Saat mengirim NFT dari rantai publik ke rantai privat, NFT akan dikunci di kontrak ERC721 Handler di rantai publik dan NFT yang sama akan dicetak di rantai privat. Dalam kasus transfer dari rantai privat ke rantai publik, NFT di rantai privat akan dibakar dan NFT yang sama akan dilepas dari kontrak ERC721 Handler di rantai publik. + +## Kontrak {#contracts} + +Menjelaskan dengan kontrak ERC721 yang sederhana alih-alih kontrak yang dikembangkan oleh ChainBridge. Untuk mode bakar/cetak, kontrak ERC721 harus memiliki metode `mint` dan `burn` selain metode yang ditetapkan dalam ERC721 seperti ini: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +Semua kode dan skrip berada di Repo Github [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Langkah 1: Sebarkan kontrak Bridge dan ERC721 Handler {#step1-deploy-bridge-and-erc721-handler-contracts} + +Pertama, Anda dapat menyebarkan kontrak Bridge dan ERC721 Handler menggunakan `cb-sol-cli` pada kedua rantai. + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Anda akan mendapat alamat kontrak Bridge dan ERC721 Handler seperti ini: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Langkah 2: Sebarkan kontrak ERC721 {#step2-deploy-your-erc721-contract} + +Anda akan menyebarkan kontrak ERC721. Contoh ini memandu Anda tentang proyek hardhat [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Buat file `.env` dan atur nilai berikut. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Kemudian, Anda akan menyebarkan kontrak ERC721 pada kedua rantai. + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +Setelah penyebaran berhasil, Anda akan mendapat alamat kontrak seperti ini: + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## Langkah 3: Daftarkan ID sumber daya di Bridge {#step3-register-resource-id-in-bridge} + +Anda akan mendaftarkan ID sumber daya yang terkait sumber daya pada lingkungan lintas rantai. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## Langkah 4: Atur mode Cetak/Bakar pada jembatan ERC721 dari Edge {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +Bridge diharapkan berfungsi sebagai mode bakar/cetak in Edge. Anda akan mengatur mode bakar/cetak. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +Anda juga perlu memberi peran pencetak dan pembakar kepada kontrak ERC721 Handler. + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Langkah 5: Cetak NFT {#step5-mint-nft} + +Anda akan mencetak ERC721 NFT baru di rantai Mumbai. + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +Setelah transaksi berhasil, akun akan memiliki NFT yang telah dicetak. + +## Langkah 6: Mulai mentransfer ERC721 {#step6-start-erc721-transfer} + +Sebelum memulai langkah ini, pastikan Anda telah memulai relayer. Lihat [Pengaturan](/docs/edge/additional-features/chainbridge/setup) untuk perincian lebih lanjut. + +Selamat transfer NFT dari Mumbai ke Edge, kontrak ERC721 Handler di Mumbai menarik NFT dari akun Anda. Anda dapat menyetujui sebelum mentransfer. + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +Terakhir, Anda akan memulai transfer NFT dari Mumbai ke Edge. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +Setelah transaksi setoran berhasil, relayer akan mendapat kejadian dan suara untuk proposal itu. +Ini mengeksekusi transaksi untuk mengirim NFT ke akun penerima di rantai Polygon Edge setelah jumlah suara yang dibutuhkan sudah terkirim. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Setelah transaksi eksekusi berhasil, Anda akan mendapat NFT di rantai Polygon Edge. diff --git a/archive/edge/id-edge/additional-features/permission-contract-deployment.md b/archive/edge/id-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..5bbecf7c63 --- /dev/null +++ b/archive/edge/id-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,86 @@ +--- +id: permission-contract-deployment +title: Izin penyebaran kontrak cerdas +description: Cara menambah izin penyebaran kontrak cerdas. +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## Ikhtisar {#overview} + +Panduan ini menguraikan cara membuat daftar putih alamat yang dapat menyebar kontrak cerdas. +Terkadang, operator jaringan ingin mencegah pengguna menyebar kontrak cerdas yang tidak berkaitan dengan tujuan jaringan. Operator jaringan dapat: + +1. Membuat daftar putih alamat untuk penyebaran Kontrak Cerdas +2. Menghapus alamat dari daftar putih untuk penyebaran Kontrak Cerdas + +## Presentasi video {#video-presentation} + +[![video contract deployment - video](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## Bagaimana cara menggunakannya? {#how-to-use-it} + + +Anda dapat menemukan semua perintah CLI yang berkaitan dengan daftar putih penyebaran di halaman [Perintah CLI](/docs/edge/get-started/cli-commands#whitelist-commands). + +* `whitelist show`: Menampilkan informasi daftar putih +* `whitelist deployment --add`: Menambah alamat baru ke daftar putih penyebaran kontrak +* `whitelist deployment --remove`: Menghapus alamat baru dari daftar putih penyebaran kontrak + +#### Menampilkan semua alamat di daftar putih penyebaran {#show-all-addresses-in-the-deployment-whitelist} + +Ada 2 cara untuk menemukan alamat dari daftar putih penyebaran. +1. Perhatikan `genesis.json` tempat daftar putih tersimpan +2. Menjalankan `whitelist show` akan mencetak informasi dari semua daftar putih yang didukung oleh Polygon Edge + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### Menambah alamat ke daftar putih penyebaran {#add-an-address-to-the-deployment-whitelist} + +Untuk menambah alamat baru ke daftar putih penyebaran, jalankan perintah CLI `whitelist deployment --add [ADDRESS]`. Tidak ada batasan jumlah alamat yang ada di dalam daftar putih. Hanya alamat yang ada di dalam daftar putih penyebaran kontrak yang dapat menyebarkan kontrak. Jika daftar putih kosong, alamat apa pun dapat melakukan penyebaran + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### Hapus alamat dari daftar putih penyebaran {#remove-an-address-from-the-deployment-whitelist} + +Untuk menghapus alamat dari daftar putih penyebaran, jalankan perintah CLI `whitelist deployment --remove [ADDRESS]`. Hanya alamat yang ada di dalam daftar putih penyebaran kontrak yang dapat menyebarkan kontrak. Jika daftar putih kosong, alamat apa pun dapat melakukan penyebaran + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/id-edge/architecture/modules/blockchain.md b/archive/edge/id-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..3222d9a91b --- /dev/null +++ b/archive/edge/id-edge/architecture/modules/blockchain.md @@ -0,0 +1,160 @@ +--- +id: blockchain +title: Blockchain +description: Penjelasan modul blockchain dan kondisi Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## Ikhtisar {#overview} + +Salah satu modul utama Polygon Edge adalah **Blockchain** dan **Kondisi**.
+ +**Blockchain** adalah pusat aktivitas yang menangani pengaturan ulang blok. Artinya, blockchain berkaitan dengan logika yang terjadi ketika blok baru disertakan ke blockchain. + +**Kondisi** mewakili objek *transisi kondisi*. Ini menangani perubahan kondisi ketika ada blok baru disertakan.
**Kondisi** menangani antara lain: +* Mengeksekusi transaksi +* Mengeksekusi EVM +* Mengubah trie Merkle +* Masih banyak lagi yang dicakup dalam bagian **Kondisi** yang terkait 🙂 + +Poin utamanya yakni 2 bagian ini sangat terkait dan bekerja sama agar klien dapat berfungsi.
Misalnya, ketika lapisan **Blockchain** menerima blok baru (dan tidak terjadi pengaturan ulang), Blockchain memanggil **Kondisi** untuk melakukan transisi kondisi. + +**Blockchain** juga harus menangani beberapa bagian yang berkaitan konsensus (mis. *apakah ethHash ini benar?*, *apakah PoW ini benar?*).
Singkatnya, **ini adalah inti utama logika tempat semua blok dimasukkan**. + +## *WriteBlock* + +Salah satu bagian terpenting yang berkaitan dengan lapisan **Blockchain** adalah metode *WriteBlocks*: + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +Metode *WriteBlocks* adalah titik awal untuk menulis blok ke blockchain. Sebagai parameter, ini dibutuhkan dalam berbagai blok.
+Pertama, blok divalidasi. Setelah itu, blok ditulis ke rantai. + +*Transisi kondisi* aktual dilakukan dengan memanggil metode *processBlock* di dalam *WriteBlocks*. + +Hal ini perlu disebutkan, karena ini titik awal untuk menulis blok ke blockchain, modul lain (seperti **Sealer**) menggunakan metode ini. + +## Langganan Blockchain {#blockchain-subscriptions} + +Perlu ada cara untuk memantau perubahan terkait blockchain.
+Di sinilah peran **Langganan**. + +Langagnan (Subscriptions) adalah cara memasukkan aliran peristiwa blockchain dan langsung menerima data yang berarti. + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +**Peristiwa Blockchain** berisi informasi mengenai perubahan yang dibuat ke rantai yang sebenarnya. Ini termasuk pengaturan ulang, serta blok baru: + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip Kilas Balik + +Apakah Anda ingat ketika kami menyebutkan perintah ***monitor*** di [Perintah CLI](/docs/edge/get-started/cli-commands)? + +Peristiwa Blockchain adalah peristiwa asli yang terjadi di Polygon Edge, kemudian peristiwa dipetakan ke format pesan Protokol Buffer untuk memudahkan transfer. + +::: \ No newline at end of file diff --git a/archive/edge/id-edge/architecture/modules/consensus.md b/archive/edge/id-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..be630190be --- /dev/null +++ b/archive/edge/id-edge/architecture/modules/consensus.md @@ -0,0 +1,512 @@ +--- +id: consensus +title: Konsensus +description: Penjelasan modul konsensus Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## Ikhtisar {#overview} + +Modul **Konsensus** menyajikan antarmuka untuk mekanisme konsensus. + +Saat ini, tersedia mesin konsensus berikut: +* **IBFT PoA** +* **IBFT PoS** + +Polygon Edge ingin mempertahankan kondisi modularitas dan kemampuan plugin.
+Inilah alasan logika konsensus inti dipisahkan agar mekanisme konsensus baru dapat dibangun di atasnya, tanpa +mengorbankan kegunaan dan kemudahan penggunaan. + +## Konsensus Antarmuka {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + +Antarmuka ***Konsensus*** adalah inti dari pemisahan yang disebutkan.
+* Metode **VerifyHeader** mewakili fungsi bantuan yang diekspos lapisan konsensus ke lapisan **blockchain** +Metode ini menangani verifikasi header +* Metode **Mulai** hanya memulai proses konsensus dan semua yang terkait dengannya. Yang termasuk sinkronisasi, +penyegelan, dan semua yang perlu dilakukan +* Metode **Tutup** menutup koneksi konsensus + +## Konfigurasi Konsensus {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +Ada kalanya Anda mungkin ingin memberikan lokasi khusus kepada protokol konsensus untuk menyimpan data atau mungkin +Anda ingin mekanisme konsensus menggunakan peta nilai kunci khusus. Hal ini dapat dicapai melalui struktur ***Config***, +yang akan dibaca ketika instans konsensus baru dibuat. + +## IBFT {#ibft} + +### ExtraData {#extradata} + +Objek header blockchain memiliki salah satu bidang yang disebut **ExtraData**. + +IBFT menggunakan bidang tambahan ini untuk menyimpan informasi operasional mengenai blok dan menjawab pertanyaan seperti: +* "Siapa yang menandatangani blok ini?" +* "Siapa validator untuk blok ini?" + +Bidang tambahan ini untuk IBFT didefinisikan sebagai berikut: +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### Menandatangani data {#signing-data} + +Agar node menandatangani informasi di IBFT, node menggunakan metode *signHash*: +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +Metode terkenal lainnya adalah metode *VerifyCommittedFields* yang memverifikasi bahwa segel yang dijalankan berasal dari validator valid: +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### Snapshot {#snapshots} + +Snapshot, seperti namanya, untuk menyediakan *gambaran* atau *kondisi* sistem pada setiap tinggi blok (jumlah). + +Snapshot berisi satu set node yang menjadi validator, serta informasi pemungutan suara (validator dapat memilih validator lain). +Validator termasuk informasi pemungutan suara di header **Miner** yang diajukan dan mengubah nilai **nonce**: +* Nonce adalah **semua angka 1** jika node ingin menghapus validator +* Nonce adalah **semua angka 0** jika node ingin menambah validator + +Snapshot dihitung menggunakan metode ***processHeaders***: + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +Metode ini biasanya dipanggil dengan 1 header, tetapi alirannya sama bahkan dengan beberapa header.
+Untuk setiap header yang lulus, IBFT perlu memverifikasi bahwa pengusul header adalah validator. Ini dapat dilakukan dengan mudah yakni +meraih snapshot terbaru dan memeriksa apakah node berada di set validator. + +Selanjutnya, nonce diperiksa. Suara dimasukkan dan dihitung - jika ada cukup suara, node ditambahkan/dihapus dari +set validator, kemudian snapshot baru disimpan. + +#### Snapshot Store {#snapshot-store} + +Layanan snapshot mengelola dan memperbarui entitas yang disebut **snapshotStore** yang menyimpan daftar dari semua snapshot yang tersedia. +Dengan itu, layanan dapat dengan cepat mengetahui snapshot mana yang dikaitkan dengan tinggi blok. +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### Memulai IBFT {#ibft-startup} + +Untuk memulai IBFT, Polygon Edge harus mengatur transportasi IBFT terlebih dahulu: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +Pada dasarnya, ini membuat topik baru dengan IBFT proto, dengan pesan proto buff baru.
+Pesan akan digunakan oleh validator. Kemudian Polygon Edge berlangganan topik dan menangani pesan yang sesuai. + +#### MessageReq {#messagereq} + +Pesan ditukar oleh validator: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +Bidang **View** di **MessageReq** mewakili posisi node saat ini di dalam rantai. +Ini memiliki atribut *round*, and *sequence*. +* **round** mewakili rangkaian pengusul untuk tinggi +* **sequence** mewakili tinggi blockchain + +Bidang *msgQueue* yang diajukan dalam implementasi IBFT memiliki tujuan menyimpan permintaan pesan. Itu memerintahkan pesan berdasarkan +*View* (pertama berdasarkan sequence, kemudian berdasarkan round). Implementasi IBFT juga memiliki antrean yang berbeda untuk kondisi yang berbeda dalam sistem. + +### Kondisi IBFT {#ibft-states} + +Setelah mekanisme konsensus dimulai menggunakan metode **Start**, itu berjalan ke putaran tak terbatas yang menyimulasikan mesin kondisi: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### SyncState {#syncstate} + +Semua node awalnya dimulai pada kondisi **Sync**. + +Hal ini karena data baru perlu diambil dari blockchain. Klien perlu mencari tahu apakah itu validator, +menemukan snapshot saat ini. Kondisi ini menyelesaikan blok yang tertunda. + +Setelah sinkronisasi selesai, dan klien menentukan bahwa itu memang validator, kemudian ditransfer ke **AcceptState**. +Jika klien **bukan** validator, sinkronisasi akan berlanjut dan tetap pada **SyncState** + +#### AcceptState {#acceptstate} + +Kondisi **Accept** selalu memeriksa snapshot dan set validator. Jika node saat ini tidak ada dalam set validator, +node bergerak kembali ke kondisi **Sync**. + +Selain itu, jika node **adalah** validator, node akan menghitung pengusul. Jika ternyata node saat ini adalah +pengusul, blok akan dibangun dan mengirimkan pesan preprepare, lalu pesan prepare. + +* Pesan preprepare - pesan yang dikirim oleh pengusul kepada validator, untuk memberi tahu tentang proposal +* Pesan prepare - pesan ketika validator menyetujui proposal. Semua node menerima semua pesan prepare +* Pesan commit - pesan berisi informasi commit untuk proposal + +Jika node saat ini **bukan** validator, digunakan metode *getNextMessage* untuk membaca pesan dari antrean yang ditunjukkan sebelumnya.
+Tunggu pesan preprepare. Setelah dikonfirmasi semuanya benar, node pindah ke kondisi **Validate**. + +#### ValidateState {#validatestate} + +Kondisi **Validate** lebih sederhana - yang dilakukan node dalam kondisi ini adalah membaca pesan dan menambahkannya ke kondisi snapshot lokal. diff --git a/archive/edge/id-edge/architecture/modules/json-rpc.md b/archive/edge/id-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..627dbbc842 --- /dev/null +++ b/archive/edge/id-edge/architecture/modules/json-rpc.md @@ -0,0 +1,181 @@ +--- +id: json-rpc +title: JSON RPC +description: Penjelasan modul JSON RPC dari Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## Ikhtisar {#overview} + +Modul **JSON RPC** mengimplementasikan **lapisan API JSON RPC**, sesuatu yang digunakan pengembang dApp untuk berinteraksi dengan +blockchain. + +Ini termasuk dukungan standar **[titik akhir json-rpc](https://eth.wiki/json-rpc/API)**, serta titik akhir +websocket. + +## Antarmuka Blockchain {#blockchain-interface} + +Polygon Edge menggunakan ***antarmuka blockchain*** untuk menentukan semua metode yang perlu digunakan oleh modul JSON RPC +untuk mengirimkan titik akhirnya. + +Antarmuka blockchain is diimplementasikan oleh server **[Minimal](/docs/edge/architecture/modules/minimal)**. Ini adalah implementasi dasar +yang diteruskan ke lapisan JSON. + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## Titik akhir ETH {#eth-endpoints} + +Semua titik akhir JSON standar diimplementasikan dalam: + +````bash +jsonrpc/eth_endpoint.go +```` + +## Filter Manager {#filter-manager} + +**Filter Manager** adalah layanan yang beroperasi bersama server JSON RPC. + +Ini memberikan dukungan untuk memfilter blok di blockchain.
+Terutama, termasuk **log** dan filter tingkat **blok**. + +Filter Manager sangat bergantung pada Peristiwa Langganan yang disebutkan di +bagian [Blockchain](blockchain#blockchain-subscriptions) + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +Peristiwa Filter Manager dikirim dalam metode *Run*: + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## 📜 Sumber daya {#resources} +* **[Ethereum JSON-RPC](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/id-edge/architecture/modules/minimal.md b/archive/edge/id-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..bef434d19f --- /dev/null +++ b/archive/edge/id-edge/architecture/modules/minimal.md @@ -0,0 +1,119 @@ +--- +id: minimal +title: Minimal +description: Penjelasan modul minimal dari Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## Ikhtisar {#overview} + +Seperti yang disebutkan sebelumnya, Polygon Edge adalah serangkaian modul yang semuanya terhubung satu sama lain.
+**Blockchain** terhubung ke **State** (Kondisi) atau misalnya, **Synchronization** (Sinkronisasi) yang menyalurkan blok baru ke **Blockchain**. + +**Minimal** adalah saka guru bagi berbagai modul yang terinterkoneksi ini.
+Ini bertindak sebagai hub pusat untuk semua layanan yang beroperasi di Polygon Edge. + +## Startup Magic {#startup-magic} + +Minimal bertanggung jawab antara lain untuk: +* Menyiapkan direktori data +* Membuat keystore untuk komunikasi libp2p +* Membuat penyimpanan +* Menyiapkan konsensus +* Menyiapkan objek blockchain dengan GRPC, JSON RPC, dan Synchronization + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/id-edge/architecture/modules/networking.md b/archive/edge/id-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..f33046470b --- /dev/null +++ b/archive/edge/id-edge/architecture/modules/networking.md @@ -0,0 +1,80 @@ +--- +id: networking +title: Jaringan +description: Penjelasan modul jaringan Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## Ikhtisar {#overview} + +Node harus berkomunikasi dengan node lain di jaringan untuk bertukar informasi bermanfaat.
+Untuk menyelesaikan tugas ini, Polygon Edge memanfaatkan kerangka kerja **libp2p** yang telah teruji. + +Pilihan **libp2p** terutama berfokus pada: +* **Kecepatan** - libp2p memiliki peningkatan kinerja yang signifikan dibandingkan devp2p (yang digunakan pada GETH dan klien lain) +* **Ekstensibilitas** - ini berfungsi sebagai landasan bagus untuk fitur lain dari sistem +* **Modularitas** - libp2p secara alami bersifat modular, seperti Polygon Edge. Agar makin fleksibel, terutama ketika bagian-bagian Polygon Edge perlu dapat dipertukarkan + +## GRPC {#grpc} + +Selain **libp2p**, Polygon Edge menggunakan protokol **GRPC**.
+Secara teknis, Polygon Edge menggunakan beberapa protokol GRPC yang akan dibahas nanti. + +Lapisan GRPC membantu memisahkan semua protokol permintaan/balasan dan menyederhanakan protokol streaming yang dibutuhkan oleh Polygon Edge supaya dapat berfungsi. + +GRPC bergantung pada **Buffer Protokol** untuk menetapkan *layanan* dan *struktur pesan*.
+Layanan dan struktur ditetapkan pada file *.proto* yang dikompilasi dan bersifat language-agnostic. + +Sebelumnya, kami menyebutkan bahwa Polygon Edge memanfaatkan beberapa protokol GRPC.
+Ini dilakukan guna mendorong UX keseluruhan untuk operator node, sesuatu yang sering kali tertinggal pada klien seperti GETH dan Parity. + +Operator node memiliki pandangan umum yang lebih baik terhadap apa yang terjadi pada sistem dengan memanggil layanan GRPC, alih-alih menyaring log untuk menemukan informasi yang dicari. + +### GRPC untuk Operator Node {#grpc-for-node-operators} + +Bagian berikut ini mungkin tampak familier karena sudah dibahas secara singkat pada bagian [Perintah CLI](/docs/edge/get-started/cli-commands). + +Layanan GRPC yang digunakan oleh **operator node** ditetapkan sebagai berikut: +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip + +Perintah CLI sebenarnya memanggil penerapan dari metode layanan ini. + +Metode ini diterapkan pada ***minimal/system_service.go***. + +::: + +### GPRC untuk Node Lain {#grpc-for-other-nodes} + +Polygon Edge juga menerapkan beberapa metode layanan yang digunnakan oleh node lain di jaringan.
+Layanan tersebut dijelaskan pada bagian **[Protokol](docs/edge/architecture/modules/consensus)**. + +## 📜 Sumber daya {#resources} +* **[Buffer Protokol](https://developers.google.com/protocol-buffers)** +* **[libp2p](https://libp2p.io/)** +* **[gRPC](https://grpc.io/)** diff --git a/archive/edge/id-edge/architecture/modules/other-modules.md b/archive/edge/id-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..b871d4dd29 --- /dev/null +++ b/archive/edge/id-edge/architecture/modules/other-modules.md @@ -0,0 +1,36 @@ +--- +id: other-modules +title: Modul lain +description: Penjelasan beberapa modul Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## Kripto {#crypto} + +Modul **Kripto** berisi fungsi penggunaan kripto. + +## Rantai {#chain} + +Modul **Rantai** berisi parameter rantai (fork aktif, mesin konsensus, dll.) + +* **rantai** - Konfigurasi rantai yang ditentukan sebelumnya (mainnet, goerli, ibft) + +## Helper {#helper} + +Modul **Helper** berisi paket helper. + +* **dao** - Penggunaan Dao +* **enode** - Fungsi encode/decode enode +* **hex** - Fungsi encode/decode hex +* **ipc** - Fungsi koneksi IPC +* **keccak** - Fungsi keccak +* **rlputil** - Fungsi helper encode/decode Rlp + +## Perintah {#command} + +Modul **Perintah** berisi antarmuka untuk perintah CLI. \ No newline at end of file diff --git a/archive/edge/id-edge/architecture/modules/sealer.md b/archive/edge/id-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..c93bab202c --- /dev/null +++ b/archive/edge/id-edge/architecture/modules/sealer.md @@ -0,0 +1,73 @@ +--- +id: sealer +title: Sealer +description: Penjelasan modul sealer di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## Ikhtisar {#overview} + +**Sealer** adalah entitas yang mengumpulkan transaksi dan menciptakan blok baru.
+Kemudian, blok itu dikirim ke modul **Konsensus** untuk menyegelnya. + +Logika penyegelan akhir terletak di dalam modul **Konsensus**. + +## Jalankan Metode {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution Sedang dikerjakan + +Modul **Sealer** dan **Consensus** akan digabungkan menjadi satu entitas dalam waktu dekat. + +Modul baru akan menggabungkan logika modular untuk berbagai jenis mekanisme konsensus yang membutuhkan implementasi penyegelan berbeda: +* **PoS** (Proof of Stake) +* **PoA** (Proof of Authority) + +Saat ini, modul **Sealer** dan **Consensus** berfungsi dengan PoW (Proof of Work). + +::: \ No newline at end of file diff --git a/archive/edge/id-edge/architecture/modules/state.md b/archive/edge/id-edge/architecture/modules/state.md new file mode 100644 index 0000000000..c006a11e96 --- /dev/null +++ b/archive/edge/id-edge/architecture/modules/state.md @@ -0,0 +1,248 @@ +--- +id: state +title: State +description: Penjelasan modul state dari Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +Untuk benar-benar memahami cara kerja **State** (Kondisi), Anda harus memahami beberapa konsep dasar Ethereum.
+ +Kami sangat menganjurkan membaca **[Panduan State di Ethereum](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)**. + +## Ikhtisar {#overview} + +Setelah memahami konsep Ethereum, ikhtisar selanjutnya akan mudah. + +Kami menyebutkan bahwa **World state trie** memiliki semua akun Ethereum yang ada.
+Akun ini merupakan daun dari Trie (pohon) Merkle. Masing-masing daun memiliki informasi **Kondisi Akun** yang dikodekan. + +Ini memungkinkan Polygon Edge mendapat trie Merkle spesifik pada suatu waktu tertentu.
+Misalnya, kita bisa mendapat hash dari kondisi pada blok 10. + +Trie Merkle, pada titik waktu apa pun, disebut ***Snapshot*** (Kondisi). + +Kita bisa memiliki ***Snapshot*** untuk **state trie** atau **trie penyimpanan** - pada dasarnya semua sama.
+Satu-satunya perbedaan adalah pada yang diwakili daun: + +* Dalam kasus pohon penyimpanan, daun memuat kondisi manasuka yang tidak dapat diproses atau diketahui isinya +* Dalam kasus pohon kondisi, daun mewakili akun + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + +Antarmuka **Snapshot** ditetapkan sebagai berikut: + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +Informasi yang dapat dikomitmenkan akan ditetapkan oleh *Object struct*: + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +Penerapan pohon Merkle berada pada folder *state/immutable-trie*.
+*state/immutable-trie/state.go* menerapkan antarmuka **State**. + +*state/immutable-trie/trie.go* adalah objek pohon Merkle utama. Ini merepresentasikan versi pohon Merkle yang dioptimalkan, +yang menggunakan kembali sebanyak mungkin memori. + +## Executor {#executor} + +*state/executor.go* mencakup semua informasi yang dibutuhkan oleh Polygon Edge untuk memutuskan cara blok mengubah +kondisi saat ini. Penerapan *ProcessBlock* berada di sini. + +Metode *apply* (terapkan) melakukan transisi kondisi aktual. Executor memanggil EVM. + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## Runtime {#runtime} + +Saat suatu transisi kondisi dieksekusi, modul utama yang mengeksekusi transisi kondisi adalah EVM (berada di +state/runtime/evm). + +**dispatch table** melakukan pencocokan antara **opcode** dan instruksi. + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +Logika inti yang menyokong EVM adalah loop *Run*.
+ +Ini adalah titik masuk utama untuk EVM. Ini melakukan loop dan memeriksa opcode saat ini, mengambil instruksi, memeriksa +apakah dapat dieksekusi, menggunakan gas, dan mengeksekusi instruksi hingga gagal atau berhenti. + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/id-edge/architecture/modules/storage.md b/archive/edge/id-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..d35b6947e6 --- /dev/null +++ b/archive/edge/id-edge/architecture/modules/storage.md @@ -0,0 +1,117 @@ +--- +id: storage +title: Penyimpanan +description: Penjelasan modul penyimpanan Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## Ikhtisar {#overview} + +Polygon Edge menggunakan **LevelDB** untuk penyimpanan data, serta penyimpanan data **dalam memori**. + +Di seluruh Polygon Edge, ketika modul perlu berinteraksi dengan penyimpanan data yang ada, modul tidak perlu tahu mesin atau layanan DB mana yang diajak bicara. + +Lapisan DB dipisahkan di antara modul yang disebut **Penyimpanan** yang mengekspor antarmuka kueri modul itu. + +Setiap lapisan DB, saat ini hanya **LevelDB**, menerapkan metode ini secara terpisah dan memastikan kecocokannya dengan penerapan. + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### Prefiks {#prefixes} + +Untuk membuat kueri penyimpanan LevelDB menjadi deterministik dan untuk menghindari bentrokan penyimpanan kunci, Polygon Edge memanfaatkan +prefiks dan subprefiks ketika menyimpan data + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## Rencana Mendatang {#future-plans} + +Rencana dalam waktu dekat termasuk menambahkan beberapa solusi DB paling populer, seperti: +* PostgreSQL +* MySQL + + +## 📜 Sumber daya {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/id-edge/architecture/modules/syncer.md b/archive/edge/id-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..690f90f7ca --- /dev/null +++ b/archive/edge/id-edge/architecture/modules/syncer.md @@ -0,0 +1,68 @@ +--- +id: syncer +title: Syncer +description: Penjelasan modul syncer di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## Ikhtisar {#overview} + +Modul ini berisi logika untuk protokol sinkronisasi. Modul ini untuk menyinkronkan node baru dengan jaringan yang sedang berjalan atau memvalidasi/memasukkan blok baru bagi node yang tidak turut serta dalam konsensus (non-validator). + +Polygon Edge menggunakan **libp2p** sebagai lapisan jaringan dan juga menjalankan **gRPC**. + +Pada dasarnya, ada 2 jenis sinkronisasi di Polygon Edge: +* Sinkronisasi Massal - menyinkronkan berbagai blok secara bersamaan +* Sinkronisasi Watch - menyinkronkan per blok + +### Sinkronisasi Massal {#bulk-sync} + +Langkah-langkah untuk Sinkronisasi Massal cukup mudah untuk mengakomodasi tujuan Sinkronisasi Massal - menyinkronkan blok sebanyak mungkin (tersedia) dari peer lain untuk mengejar secepat mungkin. + +Ini adalah aliran proses dari Sinkronisasi Massal: + +1. ** Tentukan apakah node perlu Sinkronisasi Massal ** - Pada langkah ini, node memeriksa peta peer untuk melihat apakah ada yang memiliki nomor blok lebih besar daripada yang dimiliki node secara lokal +2. ** Cari peer terbaik (menggunakan peta peer sinkronisasi) ** - Pada langkah ini, node menemukan peer terbaik untuk disinkronkan berdasarkan kriteria yang disebutkan pada contoh di atas. +3. ** Buka aliran sinkronisasi massal ** - Pada langkah ini, node membuka aliran gRPC ke peer terbaik untuk menyinkronkan blok sinkronisasi massal dari nomor blok umum +4. ** Peer terbaik menutup aliran saat melakukan pengiriman massal ** - Pada langkah ini, peer terbaik yang disinkronkan dengan node akan menutup aliran setelah mengirim semua blok tersedia yang dimilikinya +5. ** Saat melakukan sinkronisasi massal, periksa apakah node adalah validator ** - Pada langkah ini, aliran ditutup oleh peer terbaik dan node perlu memeriksa apakah itu merupakan validator setelah sinkronisasi massal. + * Jika benar, node melompat keluar dari kondisi sinkronisasi dan mulai turut serta dalam konsensus + * Jika bukan, node terus melakukan ** Sinkronisasi Watch ** + +### Sinkronisasi Watch {#watch-sync} + +:::info + +Langkah Sinkronisasi Watch hanya dijalankan jika node tersebut bukan validator, tetapi node non-validator biasa di jaringan yang hanya mendengarkan blok yang datang. + +::: + +Perilaku Sinkronisasi Watch cukup mudah, node sudah disinkronkan dengan jaringan lainnya dan hanya perlu mengurai blok baru yang masuk. + +Ini adalah alur proses Sinkronisasi Watch: + +1. ** Tambah blok baru ketika status peer diperbarui ** - Pada langkah ini, node mendengarkan peristiwa blok baru. Ketika memiliki blok baru, node akan menjalankan panggilan fungsi gRPC, mendapatkan blok, dan memperbarui kondisi lokal. +2. ** Periksa apakah node adalah validator setelah menyinkronkan blok terbaru ** + * Jika benar, node melompat keluar dari kondisi sinkronisasi + * Jika bukan, node terus mendengarkan peristiwa blok baru + +## Laporan kinerja {#perfomance-report} + +:::info + +Kinerja diukur di mesin lokal dengan menyinkronkan ** jutaan blok ** + +::: + +| Nama | Hasil | +|----------------------|----------------| +| Menyinkronkan 1J blok | ~ 25 menit | +| Mentransfer 1J blok | ~ 1 menit | +| Jumlah panggilan GRPC | 2 | +| Cakupan tes | ~ 93% | \ No newline at end of file diff --git a/archive/edge/id-edge/architecture/modules/txpool.md b/archive/edge/id-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..9407ba27e6 --- /dev/null +++ b/archive/edge/id-edge/architecture/modules/txpool.md @@ -0,0 +1,231 @@ +--- +id: txpool +title: TxPool +description: Penjelasan modul TxPool di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## Ikhtisar {#overview} + +Modul TxPool mewakili implementasi kumpulan transaksi tempat transaksi ditambahkan dari berbagai bagian +sistem. Modul ini juga mengekspos beberapa fitur yang berguna bagi operator node yang tercakup di bawah ini. + +## Perintah Operator {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +Operator node dapat melakukan kueri titik akhir GRPC ini, seperti yang dijelaskan di bagian **[Perintah CLI](/docs/edge/get-started/cli-commands#transaction-pool-commands)**. + +## Memproses Transaksi {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +Metode ***addImpl*** adalah metode yang paling banyak digunakan dalam modul **TxPool**. +Ini adalah tempat utama untuk menambahkan transaksi dalam sistem ini yang dipanggil dari layanan GRPC, titik akhir JSON RPC, +dan setiap kali klien menerima transaksi melalui protokol **gosip**. + +Ini menyertakan **ctx** sebagai argumen yang hanya menunjukkan konteks dari mana transaksi ditambahkan (GRPC, JSON RPC...).
+Parameter lainnya adalah daftar transaksi yang akan ditambahkan ke dalam kumpulan tersebut. + +Hal utama yang perlu diperhatikan di sini yaitu memeriksa bidang **From** dalam transaksi: +* Jika bidang **From** **kosong**, maka transaksi ini dianggap sebagai transaksi yang tidak dienkripsi/tidak ditandatangani. Transaksi semacam ini hanya +diterima dalam mode pengembangan +* Jika bidang **From** **tidak kosong**, artinya transaksi tersebut adalah transaksi yang ditandatangani, sehingga verifikasi tanda tangan akan terjadi + +Setelah semua validasi tersebut, transaksi akan dianggap valid. + +## Struktur data {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +Bidang dalam objek TxPool yang dapat menyebabkan kebingungan adalah **queue** dan daftar **sorted**. +* **queue** - Implementasi susunan daftar transaksi akun yang diurutkan (berdasarkan nonce) +* **sorted** - Daftar yang diurutkan untuk semua transaksi yang dipromosikan saat ini (semua transaksi yang dapat dieksekusi). Diurutkan berdasarkan harga gas + +## Manajemen error batas gas {#gas-limit-error-management} + +Setiap kali mengirim sebuah transaksi, ada tiga cara yang dapat diproses oleh TxPool. + +1. Semua transaksi yang menunggu dapat dimuat dalam sebuah blok +2. Satu atau beberapa transaksi yang menunggu tidak dapat dimuat dalam sebuah blok +3. Satu atau beberapa transaksi yang menunggu tidak akan dimuat dalam sebuah blok + +Di sini, kata **_muat_** berarti bahwa transaksi memiliki batas gas yang lebih rendah dari gas yang tersisa di TxPool. + +Skenario pertama tidak menghasilkan error apa pun. + +### Skenario kedua {#second-scenario} + +- Gas yang tersisa dalam TxPool diatur ke batas gas blok terakhir, misalnya **5000** +- Transaksi pertama diproses dan memerlukan gas **3000** dalam TxPool + - Gas yang tersisa dalam TxPool sekarang **2000** +- Transaksi kedua, yang sama seperti transaksi pertama - keduanya mengonsumsi 3000 unit gas, akan dikirimkan +- Karena gas TxPool yang tersisa **lebih rendah** dari gas transaksi, transaksi itu tidak dapat diproses dalam blok +saat ini + - Transaksi itu akan dikembalikan ke antrean transaksi yang menunggu sehingga dapat diproses dalam blok berikutnya +- Blok pertama sudah ditulis, kita namai saja **blok #1** +- Gas yang tersisa pada TxPool diatur ke blok induk - batas gas **blok #1** +- Transaksi yang dikembalikan ke antrean transaksi yang menunggu dalam TxPool sekarang diproses dan ditulis dalam blok + - Gas yang tersisa dalam TxPool menjadi **2000** +- Blok kedua sudah ditulis +- ... + +![Skenario error TxPool #1](/img/edge/txpool-error-1.png) + +### Skenario ketiga {#third-scenario} +- Gas yang tersisa dalam TxPool diatur ke batas gas dari blok terakhir, misalnya **5000** +- Transaksi pertama diproses dan memerlukan gas **3000** dalam TxPool + - Gas yang tersisa dalam TxPool sekarang **2000** +- Transaksi kedua dengan bidang gas yang diatur ke **6000** sudah dikirimkan +- Karena batas gas blok tersebut **lebih rendah** dari gas transaksi, maka transaksi ini diabaikan + - Transaksi tersebut tidak akan muat dalam sebuah blok +- Blok pertama sudah ditulis +- ... + + +![Skenario error TxPool #2](/img/edge/txpool-error-2.png) + +> Ini terjadi setiap kali Anda mendapatkan error berikut: +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## Target Gas Blok {#block-gas-target} + +Ada situasi ketika node ingin menjaga batas gas blok tetap rendah atau berada pada target tertentu di rantai yang beroperasi. + +Operator node dapat mengatur batas gas target pada node tertentu yang akan mencoba menerapkan batas ini pada blok yang baru dibuat. +Jika mayoritas node lainnya juga memiliki batas gas target yang serupa (atau sama), maka batas gas blok tersebut akan selalu berada +di sekitar target gas blok tersebut dan perlahan-lahan bergerak mencapai target (maksimal `1/1024 * parent block gas limit`) saat blok baru dibuat. + +### Skenario contoh {#example-scenario} + +* Operator node mengatur batas gas blok untuk node tunggal menjadi `5000` +* Node lainnya dikonfigurasi sebagai `5000` juga, terlepas dari node tunggal yang dikonfigurasi menjadi `7000` +* Ketika node yang target gasnya diatur ke `5000` menjadi pengusul, node tersebut akan memeriksa apakah batas gas sudah berada dalam target +* Jika batas gas tidak berada pada target (lebih besar/lebih rendah), node pengusul akan mengatur target gas blok sebagian besar (1/1024 * batas gas induk) ke arah target + 1. Contoh: `parentGasLimit = 4500` dan `blockGasTarget = 5000`, pengusul akan menghitung batas gas untuk blok baru yaitu `4504.39453125` (`4500/1024 + 4500`) + 2. Contoh: `parentGasLimit = 5500` dan `blockGasTarget = 5000`, pengusul akan menghitung batas gas untuk blok baru yaitu `5494.62890625` (`5500 - 5500/1024`) +* Ini akan memastikan bahwa batas gas blok dalam rantai akan dijaga agar tetap berada pada target, karena pengusul tunggal yang targetnya dikonfigurasi ke `7000` tidak dapat meningkatkan batas secara signifikan, dan sebagian besar +node yang telah diatur ke `5000` akan selalu berusaha menjaga agar tetap berada di batas itu \ No newline at end of file diff --git a/archive/edge/id-edge/architecture/modules/types.md b/archive/edge/id-edge/architecture/modules/types.md new file mode 100644 index 0000000000..4b9e0b61eb --- /dev/null +++ b/archive/edge/id-edge/architecture/modules/types.md @@ -0,0 +1,43 @@ +--- +id: types +title: Types +description: Penjelasan modul types di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## Ikhtisar {#overview} + +Modul **Types** mengimplementasikan tipe objek inti, seperti: + +* **Alamat** +* **Hash** +* **Header** +* banyak fungsi helper + +## Encoding / Decoding RLP {#rlp-encoding-decoding} + +Tidak seperti klien seperti GETH, Polygon Edge tidak menggunakan refleksi untuk melakukan encode.
+Preferensinya yakni tidak menggunakan refleksi karena itu menimbulkan masalah baru, seperti penurunan +kinerja dan penskalaan lebih sulit. + +Modul **Types** menyediakan antarmuka yang mudah digunakan untuk marshaling dan unmarshalling RLP, menggunakan paket FastRLP. + +Marshaling dilakukan melalui metode *MarshalRLPWith* dan *MarshalRLPTo*. Metode analog ada untuk +unmarshalling. + +Dengan menentukan metode ini secara manual, Polygon Edge tidak perlu menggunakan refleksi. Dalam *rlp_marshal.go*, Anda dapat menemukan +metode untuk marshaling: + +* **Isi** +* **Blok** +* **Header** +* **Tanda terima** +* **Log** +* **Transaksi** \ No newline at end of file diff --git a/archive/edge/id-edge/architecture/overview.md b/archive/edge/id-edge/architecture/overview.md new file mode 100644 index 0000000000..f4f7f26ff7 --- /dev/null +++ b/archive/edge/id-edge/architecture/overview.md @@ -0,0 +1,61 @@ +--- +id: overview +title: Ikhtisar Arsitektur +sidebar_label: Overview +description: Pengantar arsitektur Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +Kami mulai dengan ide membuat perangkat lunak yang *modular*. + +Ini hampir semua bagian Polygon Edge. Di bawah ini, Anda akan menemukan gambaran singkat +arsitektur yang dibangun dan lapisannya. + +## Lapisan Polygon Edge {#polygon-edge-layering} + +![Arsitektur Polygon Edge](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +Ini semua dimulai pada lapisan jaringan dasar yang memanfaatkan **libp2p**. Kami memutuskan untuk menggunakan teknologi ini, karena +cocok dengan filosofi desain Polygon Edge. Libp2p adalah: + +- Modular +- Dapat diperluas +- Cepat + +Yang paling penting, ini menyediakan dasar yang bagus untuk fitur lebih canggih yang akan kita bahas nanti. + + +## Sinkronisasi & Konsensus {#synchronization-consensus} +Pemisahan protokol sinkronisasi dan konsensus memungkinkan modularitas dan implementasi sinkronisasi **kustom** dan mekanisme konsensus - tergantung bagaimana klien dijalankan. + +Polygon Edge dirancang untuk menawarkan algoritma konsensus yang dapat dibuat plugin. + +Daftar algoritme konsensus yang didukung saat ini: + +* IBFT PoA +* IBFT PoS + +## Blockchain {#blockchain} +Lapisan Blockchain adalah lapisan pusat yang mengoordinasikan segala sesuatu dalam sistem Polygon Edge. Hal ini dibahas secara mendalam dalam bagian *Modul* terkait. + +## Kondisi {#state} +Lapisan dalam kondisi berisi logika transisi kondisi. Ini berkaitan dengan bagaimana perubahan kondisi ketika blok baru disertakan. Hal ini dibahas secara mendalam dalam bagian *Modul* terkait. + +## JSON RPC {#json-rpc} +Lapisan JSON RPC adalah lapisan API yang digunakan pengembang dApp untuk berinteraksi dengan blockchain. Hal ini dibahas secara mendalam dalam bagian *Modul* terkait. + +## TxPool {#txpool} +Lapisan TxPool mewakili kumpulan transaksi dan terkait erat dengan modul lain dalam sistem, karena transaksi dapat ditambahkan dari beberapa titik masuk. + +## grpc {#grpc} +gRPC, atau Google Remote Procedure Call, adalah kerangka RPC sumber terbuka yang kuat yang dibuat oleh Google untuk membangun API yang dapat dibaca dan cepat. Lapisan GRPC sangat penting untuk interaksi operator. Melalui lapisan itu, operator node dapat berinteraksi dengan klien dan memberikan UX yang bagus. diff --git a/archive/edge/id-edge/community/propose-new-feature.md b/archive/edge/id-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..274f787703 --- /dev/null +++ b/archive/edge/id-edge/community/propose-new-feature.md @@ -0,0 +1,60 @@ +--- +id: propose-new-feature +title: Usulan fitur baru +description: "Templat dan instruksi PR untuk mengusulkan fitur baru." +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## Ikhtisar {#overview} + +Jika ingin menyertakan perbaikan, atau hanya berkontribusi pada kode, sebaiknya hubungi tim terlebih dahulu.
+Polygon Edge menggunakan templat proposisi fitur yang relatif mendasar, yaitu ringkas dan lugas. + +## Templat PR {#pr-template} + +### Deskripsi {#description} + +Berikan deskripsi terperinci tentang apa yang dilakukan pada PR ini + +### Perubahan mencakup {#changes-include} + +- [ ] Bugfix (perubahan yang tidak bersifat mengganggu, tetapi menyelesaikan masalah) +- [ ] Hotfix (perubahan yang menyelesaikan masalah mendesak dan membutuhkan perhatian secepatnya) +- [ ] Fitur baru (perubahan yang tidak bersifat mengganggu, tetapi menambah fungsionalitas) +- [ ] Perubahan yang menggangu (perubahan yang tidak kompatibel mundur dan/atau mengubah fungsionalitas) + +### Perubahan yang menggangu {#breaking-changes} + +Lengkapi bagian ini jika terdapat perubahan yang mengganggu. Jika tidak, hapus saja + +### Daftar Periksa {#checklist} + +- [ ] Saya telah menugaskan PR ini kepada diri sendiri +- [ ] Saya sudah menambah setidaknya 1 peninjau +- [ ] Saya telah menambah label yang relevan +- [ ] Saya telah memperbarui dokumentasi resmi +- [ ] Saya telah menambah dokumentasi yang memadai di dalam kode + +### Pengujian {#testing} + +- [ ] Saya telah menguji kode ini dengan paket tes resmi +- [ ] Saya telah menguji kode ini secara manual + +## Pengujian manual {#manual-tests} + +Lengkapi bagian ini jika Anda menjalankan pengujian manual untuk fungsionalitas ini, jika tidak, hapus saja + +### Pembaruan dokumentasi {#documentation-update} + +Tautkan PR pembaruan dokumentasi pada bagian ini jika ada, jika tidak ada, hapus saja + +### Komentar tambahan {#additional-comments} + +Kirimkan komentar tambahan pada bagian ini jika ada, jika tidak ada, hapus saja \ No newline at end of file diff --git a/archive/edge/id-edge/community/report-bug.md b/archive/edge/id-edge/community/report-bug.md new file mode 100644 index 0000000000..76d2fc2699 --- /dev/null +++ b/archive/edge/id-edge/community/report-bug.md @@ -0,0 +1,55 @@ +--- +id: report-bug +title: Laporan masalah +description: Templat dan instruksi untuk melaporkan masalah Polygon Edge. +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## Ikhtisar {#overview} + +Kadang kala, ada kerusakan.
+Sebaiknya, selalu beri tahu tim dukungan tentang masalah apa pun yang mungkin Anda temui.
+Di halaman Polygon Edge GitHub, Anda dapat mengajukan masalah baru dan mulai membahasnya dengan tim dukungan. + +## Templat Masalah {#issue-template} + +## [Subjek masalah] + +### Deskripsi {#description} + +Jelaskan masalah dengan terperinci di sini + +### Lingkungan Anda {#your-environment} + +* OS dan versi +* Versi Polygon Edge +* Cabang yang menyebabkan masalah ini + +### Langkah reproduksi {#steps-to-reproduce} + +* Jelaskan cara mereproduksi masalah ini
+* Di mana masalahnya, jika Anda tahu
+* Perintah mana yang memicu masalah tersebut, jika ada + +### Perilaku yang diharapkan {#expected-behaviour} + +Jelaskan apa yang akan terjadi + +### Perilaku sebenarnya {#actual-behaviour} + +Jelaskan apa yang seharusnya terjadi + +### Log {#logs} + +Tempelkan log di sini yang menunjukkan masalah tersebut, jika ada + +### Solusi yang diusulkan {#proposed-solution} + +Jika Anda memiliki ide tentang cara memperbaiki masalah ini, tuliskan di sini, sehingga kami dapat mulai mendiskusikannya \ No newline at end of file diff --git a/archive/edge/id-edge/configuration/manage-private-keys.md b/archive/edge/id-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..6d6a740c3f --- /dev/null +++ b/archive/edge/id-edge/configuration/manage-private-keys.md @@ -0,0 +1,79 @@ +--- +id: manage-private-keys +title: Mengelola kunci privat +description: "Cara mengelola kunci privat dan berbagai jenis kunci yang ada." +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## Ikhtisar {#overview} + +Polygon Edge memiliki dua jenis kunci privat yang secara langsung mengelola: + +* **Kunci privat yang digunakan untuk mekanisme konsensus** +* **Kunci privat untuk jaringan oleh libp2p** +* **(Opsional) Kunci Privat BLS digunakan untuk mekanisme konsensus yang mengagregasikan tanda tangan validator** + +Saat ini, Polygon Edge tidak menawarkan dukungan pengelolaan akun secara langsung. + +Berdasarkan struktur direktori yang diuraikan dalam [Panduan Pencadangan & Pemulihan](/docs/edge/working-with-node/backup-restore), +Polygon Edge menyimpan file kunci pada dua direktori berbeda - **consensus** dan **keystore**. + +## Format kunci {#key-format} + +Kunci privat disimpan dalam **format Base64** sederhana, sehingga dapat dibaca manusia dan portabel. + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info Jenis Kunci + +Semua kunci privat yang dibuat dan digunakan di dalam Polygon Edge bergantung pada kurva [secp256k1](https://en.bitcoin.it/wiki/Secp256k1). + +Karena kurvanya tidak standar, kurva itu tidak dapat dikodekan dan disimpan dalam format PEM standar apa pun. +Mengimpor kunci yang tidak sesuai dengan kunci ini tidak didukung. + +::: +## Kunci Privat Konsensus {#consensus-private-key} + +File kunci privat yang disebut sebagai *kunci privat konsensus* juga dirujuk sebagai **kunci perivat validator**. +Kunci privat ini digunakan saat node bertindak sebagai validator di dalam jaringan dan perlu menandatangani data baru. + +File kunci privat berada di `consensus/validator.key` dan mematuhi [format kunci](/docs/edge/configuration/manage-private-keys#key-format) tersebut. + +:::warning + +Kunci privat validator bersifat unik untuk setiap node validator. Kunci yang sama tidak dibagikan di semua validator, karena ini dapat mengganggu keamanan rantai Anda. + +::: + +## Kunci Privat Jaringan {#networking-private-key} + +File kunci privat tersebut untuk jaringan digunakan oleh libp2p untuk membuat PeerID terkait dan memungkinkan node berpartisipasi dalam jaringan. + +Ini terletak di `keystore/libp2p.key` dan mematuhi [format kunci](/docs/edge/configuration/manage-private-keys#key-format) tersebut. + +## Kunci Rahasia BLS {#bls-secret-key} + +File kunci rahasia BLS digunakan untuk mengumpulkan segel yang ditetapkan di dalam lapisan konsensus, Ukuran segel yang ditetapkan itu dikumpulkan oleh BLS dan kurang dari rangkaian tanda tangan ECDSA yang ditetapkan. + +Fitur BLS bersifat opsional dan memungkinkan untuk memilih apakah akan menggunakan BLS atau tidak. Lihat [BLS](/docs/edge/consensus/bls) untuk detail selengkapnya. + +## Impor / Ekspor {#import-export} + +Saat disimpan dalam format Base64 sederhana di disk, file kunci dapat dicadangkan atau diimpor dengan mudah. + +:::caution Mengubah file kunci + +Segala jenis perubahan yang dilakukan pada file kunci di jaringan yang sudah disiapkan/berjalan dapat menyebabkan gangguan serius pada jaringan/konsensus, +karena konsensus dan mekanisme penemuan peer menyimpan data yang didapat dari kunci ini di penyimpanan node tertentu dan bergantung pada data untuk +memulai koneksi dan melakukan logika konsensus + +::: \ No newline at end of file diff --git a/archive/edge/id-edge/configuration/prometheus-metrics.md b/archive/edge/id-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..677909f90c --- /dev/null +++ b/archive/edge/id-edge/configuration/prometheus-metrics.md @@ -0,0 +1,35 @@ +--- +id: prometheus-metrics +title: Metrik Prometheus +description: "Cara mengaktifkan metrik Prometheus untuk Polygon Edge." +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## Ikhtisar {#overview} + +Polygon Edge dapat melaporkan dan melayani metrik Prometheus yang nantinya dapat dimanfaatkan menggunakan kolektor Prometheus. + +Metrik Prometheus dinonaktifkan secara default. Metrik ini dapat diaktifkan dengan menentukan alamat listener (pendengar) menggunakan bendera `--prometheus` atau bidang `Telemetry.prometheus` di file konfigurasi. +Metrik dapat disajikan di `/metrics` pada alamat yang ditentukan. + +## Metrik yang tersedia {#available-metrics} + +Tersedia metrik berikut ini: + +| **Nama** | **Tipe** | **Deskripsi** | +|-----------------------------------------------|---------------|-------------------------------------------------| +| txpool_pending_transactions | Ukuran | Jumlah transaksi yang menunggu di TxPool | +| consensus_validators | Ukuran | Jumlah Validator | +| consensus_rounds | Ukuran | Jumlah Babak | +| consensus_num_txs | Ukuran | Jumlah Transaksi di blok terbaru | +| consensus_block_interval | Ukuran | Waktu antara blok ini dan terakhir dalam detik | +| network_peers | Ukuran | Jumlah peer yang terhubung | +| network_outbound_connections_count | Ukuran | Jumlah koneksi keluar | +| network_inbound_connections_count | Ukuran | Jumlah koneksi masuk | +| network_pending_outbound_connections_count | Ukuran | Jumlah koneksi keluar yang menunggu | +| network_pending_inbound_connections_count | Ukuran | Jumlah koneksi masuk yang menunggu | \ No newline at end of file diff --git a/archive/edge/id-edge/configuration/sample-config.md b/archive/edge/id-edge/configuration/sample-config.md new file mode 100644 index 0000000000..f0df47a83f --- /dev/null +++ b/archive/edge/id-edge/configuration/sample-config.md @@ -0,0 +1,151 @@ +--- +id: sample-config +title: File Konfigurasi Server +description: "Memulai server Polygon Edge menggunakan file konfigurasi." +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# File konfigurasi server {#server-configuration-file} +Memulai server dengan beragam opsi konfigurasi dapat dilakukan menggunakan file konfigurasi alih-alih hanya bendera. +Perintah yang digunakan untuk memulai server dengan file config: `polygon-edge server --config ` + +## Ekspor file config dengan konfigurasi default {#export-config-file-with-default-configuration} +Konfigurasi dengan pengaturan default untuk server Polygon Edge dapat diekspor ke file konfigurasi dalam format file `yaml` atau `json`. +File ini dapat digunakan sebagai templat untuk menjalankan server menggunakan file konfigurasi. + +### YAML {#yaml} +Untuk membuat file konfigurasi dalam format `yaml`: +```bash +polygon-edge server export --type yaml +``` +atau hanya +```bash +polygon-edge server export +``` +file konfigurasi bernama `default-config.yaml` akan dibuat pada direktori yang sama tempat perintah ini dijalankan. + +Contoh file: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +Untuk membuat file konfigurasi dalam format `json`: +```bash +polygon-edge server export --type json +``` +file konfigurasi bernama `default-config.json` akan dibuat pada direktori yang sama tempat perintah ini dijalankan. + +Contoh file: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +Baca bagian [Perintah CLI](/docs/edge/get-started/cli-commands) untuk mendapatkan informasi tentang cara menggunakan parameter ini. + +### Skema Typscript {#typescript-schema} + +Yang berikut ini adalah format contoh untuk file konfigurasi. Ini ditulis dalam format TypeScript untuk menyatakan jenis properti (`string`, `number`, `boolean`), Anda dapat memperoleh konfigurasi dari sini. Perlu diketahui bahwa jenis `PartialDeep` dari `type-fest` digunakan untuk menyatakan bahwa semua properti bersifat opsional. + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/id-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/id-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..2d04f798d6 --- /dev/null +++ b/archive/edge/id-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,138 @@ +--- +id: set-up-aws-ssm +title: Pengaturan AWS SSM (Pengelola Sistem) +description: "Pengaturan AWS SSM (Pengelola Sistem) untuk Polygon Edge." +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## Ikhtisar {#overview} + +Saat ini, Polygon Edge berkaitan dengan penyimpanan 2 rahasia runtime utama: +* **Kunci privat validator** digunakan oleh node, jika node merupakan validator +* **Kunci privat jaringan** digunakan oleh libp2p untuk turut serta dan berkomunikasi dengan peer lainnya + +Untuk informasi tambahan, silakan baca [Panduan Mengelola Kunci Privat](/docs/edge/configuration/manage-private-keys) + +Modul Polygon Edge **tidak perlu mengetahui cara menyimpan rahasia**. Intinya, modul tidak perlu peduli apakah +rahasia disimpan di server yang jauh atau secara lokal di disk node. + +Semua yang perlu diketahui modul tentang penyimpanan rahasia adalah **mengetahui cara penggunaan rahasia**, **mengetahui rahasia mana yang harus didapat +atau disimpan**. Perincian implementasi yang lebih baik dari operasi ini didelegasikan ke `SecretsManager` yang tentunya merupakan abstraksi. + +Operator node yang memulai Polygon Edge sekarang dapat menentukan pengelola rahasia mana yang ingin digunakan dan ketika +pengelola rahasia yang benar dipakai, modul menangani rahasia melalui antarmuka yang disebutkan - +tanpa memedulikan apakah rahasia disimpan di disk maupun di server. + +Artikel ini menjelaskan langkah-langkah yang diperlukan untuk mendapatkan Polygon Edge dan menjalankan +[Penyimpanan Parameter Manajer Sistem AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html). + +:::info Panduan sebelumnya + +**Sebaiknya**, sebelum mempelajari artikel ini, baca artikel tentang [**Pengaturan Lokal**](/docs/edge/get-started/set-up-ibft-locally) +dan [**Pengaturan Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +::: + + +## Prasyarat {#prerequisites} +### Kebijakan IAM {#iam-policy} +Pengguna perlu membuat Kebijakan IAM yang memungkinkan operasi baca/tulis untuk Penyimpanan Parameter Manajer Sistem AWS. +Setelah berhasil membuat Kebijakan IAM, pengguna perlu menempelkannya ke instans EC2 yang menjalankan server Polygon Edge. +Kebijakan IAM akan terlihat seperti ini: +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +Informasi lebih lanjut tentang Peran IAM AWS SSM dapat ditemukan di [dokumen AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html). + +Informasi yang dibutuhkan sebelum melanjutkan: +* **Wilayah** (wilayah tempat keberadaan Pengelola Sistem dan node) +* **Jalur Parameter** (jalur arbitrer untuk menempatkan rahasia itu, misalnya `/polygon-edge/nodes`) + +## Langkah 1 - Buat konfigurasi pengelola rahasia {#step-1-generate-the-secrets-manager-configuration} + +Agar Polygon Edge dapat berkomunikasi dengan AWS SSM secara lancar, perlu mengurai +file konfigurasi yang telah dihasilkan, yang berisi semua informasi yang diperlukan untuk penyimpanan rahasia di AWS SSM. + +Untuk menghasilkan konfigurasi, jalankan perintah berikut: + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +Parameter yang ada: +* `PATH` adalah jalur ke mana file konfigurasi harus diekspor. Default `./secretsManagerConfig.json` +* `NODE_NAME` adalah nama node saat ini yang diatur sebagai konfigurasi AWS SSM. Ini dapat berupa nilai manasuka. Default `polygon-edge-node` +* `REGION` adalah wilayah lokasi AWS SSM. Ini harus merupakan wilayah yang sama dengan node yang menggunakan AWS SSM. +* `SSM_PARAM_PATH` adalah nama jalur rahasia akan disimpan. Misalnya jika `--name node1` dan `ssm-parameter-path=/polygon-edge/nodes` +ditentukan, rahasia akan disimpan sebagai `/polygon-edge/nodes/node1/` + +:::caution Nama node + +Berhati-hatilah ketika menentukan nama node. + +Polygon Edge menggunakan nama node yang ditentukan untuk melacak rahasia yang dihasilkan dan digunakan di AWS SSM. +Menentukan nama node yang ada dapat memiliki konsekuensi gagal menulis rahasia ke AWS SSM. + +Rahasia disimpan di jalur dasar berikut: `SSM_PARAM_PATH/NODE_NAME` + +::: + +## Langkah 2 - Inisialisasi kunci rahasia menggunakan konfigurasi {#step-2-initialize-secret-keys-using-the-configuration} + +Karena file konfigurasi sudah ada, kita dapat menginisialisasi kunci rahasia yang dibutuhkan dengan pengaturan +file konfigurasi di langkah 1 menggunakan `--config`: + +```bash +polygon-edge secrets init --config +``` + +Parameter `PATH` adalah lokasi parameter pengelola rahasia yang dihasilkan sebelumnya dari langkah 1. + +:::info Kebijakan IAM +Langkah ini akan gagal jika Kebijakan IAM yang memungkinkan operasi baca/tulis tidak dikonfigurasi dengan benar dan/atau tidak melekat ke instans EC2 yang menjalankan perintah ini. + +::: + +## Langkah 3 - Buat file genesis {#step-3-generate-the-genesis-file} + +File genesis harus dibuat dengan cara yang mirip dengan [**Pengaturan Lokal**](/docs/edge/get-started/set-up-ibft-locally) +dan panduan [**Pengaturan Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud) dengan perubahan kecil. + +Karena AWS SSM digunakan sebagai ganti sistem file lokal, alamat validator harus ditambahkan melalui bendera `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Langkah 4 - Mulai klien Polygon Edge {#step-4-start-the-polygon-edge-client} + +Setelah kunci diatur dan file genesis dihasilkan, langkah terakhir proses ini yaitu memulai +Polygon Edge dengan perintah `server`. + +Perintah `server` digunakan dengan cara yang sama seperti pada panduan yang disebutkan sebelumnya, dengan tambahan kecil - bendera `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +Parameter `PATH` adalah lokasi parameter pengelola rahasia yang dihasilkan sebelumnya dari langkah 1. \ No newline at end of file diff --git a/archive/edge/id-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/id-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..fbd21f627a --- /dev/null +++ b/archive/edge/id-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,121 @@ +--- +id: set-up-gcp-secrets-manager +title: Menyiapkan GCP Secrets Manager +description: "Menyiapkan GCP Secrets Manager untuk Polygon Edge." +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## Ikhtisar {#overview} + +Saat ini, Polygon Edge berkaitan dengan penyimpanan 2 rahasia runtime utama: +* **Kunci privat validator** digunakan oleh node, jika node merupakan validator +* **Kunci privat jaringan** digunakan oleh libp2p untuk turut serta dan berkomunikasi dengan peer lainnya + +Untuk informasi tambahan, silakan baca [Panduan Mengelola Kunci Privat](/docs/edge/configuration/manage-private-keys) + +Modul Polygon Edge **tidak perlu mengetahui cara menyimpan rahasia**. Intinya, modul tidak perlu peduli apakah +rahasia disimpan di server yang jauh atau secara lokal di disk node. + +Semua yang perlu diketahui modul tentang penyimpanan rahasia adalah **mengetahui cara penggunaan rahasia**, **mengetahui rahasia mana yang harus didapat +atau disimpan**. Perincian implementasi yang lebih baik dari operasi ini didelegasikan ke `SecretsManager` yang tentunya merupakan abstraksi. + +Operator node yang memulai Polygon Edge sekarang dapat menentukan pengelola rahasia mana yang ingin digunakan dan ketika +pengelola rahasia yang benar dipakai, modul menangani rahasia melalui antarmuka yang disebutkan - +tanpa memperhatikan apakah rahasia disimpan di disk atau server. + +Artikel ini menjabarkan langkah-langkah yang dibutuhkan untuk membuat Polygon Edge siap beroperasi dengan [GCP Secret Manager](https://cloud.google.com/secret-manager). + +:::info panduan sebelumnya + +**Sebaiknya**, sebelum mempelajari artikel ini, baca artikel tentang [**Pengaturan Lokal**](/docs/edge/get-started/set-up-ibft-locally) +dan [**Pengaturan Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +::: + + +## Prasyarat {#prerequisites} +### Akun Penagihan GCP {#gcp-billing-account} +Untuk memanfaatkan GCP Secrets Manager, pengguna harus memiliki [Akun Penagihan](https://console.cloud.google.com/) yang diaktifkan pada portal GCP. +Akun Google baru pada platform GCP disediakan dengan beberapa dana untuk memulai, sebagai raja dari percobaan gratis. +Info selangkapnya tentang [Dokumen GCP](https://cloud.google.com/free) + +### API Secrets Manager {#secrets-manager-api} +Pengguna harus mengaktifkan API GCP Secrets Manager, sebelum bisa menggunakannya. +Ini dapat dilakukan di [portal API Secrets Manager](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com). +Info selengkapnya: [Mengonfigurasi Secret Manger](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + +### Kredensial GCP {#gcp-credentials} +Akhirnya, pengguna harus membuat kredensial baru yang akan digunakan untuk autentikasi. +Ini dapat dilakukan dengan mengikuti instruksi yang diposkan [di sini](https://cloud.google.com/secret-manager/docs/reference/libraries). +File json yang dibuat dan memuat kredensial, harus ditransfer ke setiap node yang perlu menggunakan GCP Secrets Manager. + +Informasi yang dibutuhkan sebelum melanjutkan: +* **ID Proyek** (id proyek yang ditetapkan di platform GCP) +* **Lokasi File Kredensial** (jalur ke file json yang memuat kredensial) + +## Langkah 1 - Buat konfigurasi pengelola rahasia {#step-1-generate-the-secrets-manager-configuration} + +Supaya Polygon Edge dapat berkomunikasi lancar dengan GCP SM, perlu melakukan penguraian terhadap +file konfigurasi yang dibuat dan memuat semua informasi yang dibutuhkan untuk penyimpanan rahasia di GCP SM. + +Untuk menghasilkan konfigurasi, jalankan perintah berikut: + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +Parameter yang ada: +* `PATH` adalah jalur ke mana file konfigurasi harus diekspor. Default `./secretsManagerConfig.json` +* `NODE_NAME` adalah nama node saat ini yang disiapkan untuk konfigurasi GCP SM. Ini dapat berupa nilai manasuka. Default `polygon-edge-node` +* `PROJECT_ID` adalah ID dari proyek yang ditentukan oleh pengguna pada konsol GCP selama penyiapan akun dan aktivasi API Secrets Manager. +* `GCP_CREDS_FILE` adalah jalur ke file json yang memuat kredensial yang memungkinkan akses baca/tulis ke Secrets Manager. + +:::caution Nama node + +Berhati-hatilah ketika menentukan nama node. + +Polygon Edge menggunakan nama node tertentu untuk melacak rahasia yang dihasilkan dan digunakan di GCP SM. +Menentukan nama node yang sudah ada dapat berkonsekuensi pada kegagalan penulisan rahasia ke GCP SM. + +Rahasia disimpan di jalur dasar berikut: `projects/PROJECT_ID/NODE_NAME` + +::: + +## Langkah 2 - Inisialisasi kunci rahasia menggunakan konfigurasi {#step-2-initialize-secret-keys-using-the-configuration} + +Karena file konfigurasi sudah ada, kita dapat menginisialisasi kunci rahasia yang dibutuhkan dengan pengaturan +file konfigurasi di langkah 1 menggunakan `--config`: + +```bash +polygon-edge secrets init --config +``` + +Parameter `PATH` adalah lokasi parameter pengelola rahasia yang dihasilkan sebelumnya dari langkah 1. + +## Langkah 3 - Buat file genesis {#step-3-generate-the-genesis-file} + +File genesis harus dibuat dengan cara yang mirip dengan [**Pengaturan Lokal**](/docs/edge/get-started/set-up-ibft-locally) +dan panduan [**Pengaturan Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud), dengan perubahan kecil. + +Karena GCP SM digunakan alih-alih sistem file lokal, alamat validator harus ditambahkan melalui bendera `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Langkah 4 - Mulai klien Polygon Edge {#step-4-start-the-polygon-edge-client} + +Setelah kunci diatur dan file genesis dihasilkan, langkah terakhir proses ini yaitu memulai +Polygon Edge dengan perintah `server`. + +Perintah `server` digunakan dengan cara yang sama seperti pada panduan yang disebutkan sebelumnya, dengan tambahan kecil - bendera `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +Parameter `PATH` adalah lokasi parameter pengelola rahasia yang dihasilkan sebelumnya dari langkah 1. \ No newline at end of file diff --git a/archive/edge/id-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/id-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..32613e9902 --- /dev/null +++ b/archive/edge/id-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,118 @@ +--- +id: set-up-hashicorp-vault +title: Menyiapkan Hashicorp Vault +description: "Menyiapkan Hashicorp Vault untuk Polygon Edge." +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## Ikhtisar {#overview} + +Saat ini, Polygon Edge berkaitan dengan penyimpanan 2 rahasia runtime utama: +* **Kunci privat validator** digunakan oleh node, jika node merupakan validator +* **Kunci privat jaringan** digunakan oleh libp2p untuk turut serta dan berkomunikasi dengan peer lainnya + +:::warning + +Kunci privat validator bersifat unik bagi setiap node validator. Kunci yang sama tidak disimpan di semua validator, karena ini dapat mengganggu keamanan rantai Anda. + +::: + +Untuk informasi tambahan, silakan baca [Panduan Mengelola Kunci Privat](/docs/edge/configuration/manage-private-keys) + +Modul Polygon Edge **tidak perlu mengetahui cara menyimpan rahasia**. Intinya, modul tidak perlu peduli apakah +rahasia disimpan di server yang jauh atau secara lokal di disk node. + +Semua yang perlu diketahui modul tentang penyimpanan rahasia adalah **mengetahui cara penggunaan rahasia**, **mengetahui rahasia mana yang harus didapat +atau disimpan**. Perincian implementasi yang lebih baik dari operasi ini didelegasikan ke `SecretsManager` yang tentunya merupakan abstraksi. + +Operator node yang memulai Polygon Edge sekarang dapat menentukan pengelola rahasia mana yang ingin digunakan dan ketika +pengelola rahasia yang benar dipakai, modul menangani rahasia melalui antarmuka yang disebutkan - +tanpa memperhatikan apakah rahasia disimpan di disk atau di server. + +Artikel ini menjabarkan langkah-langkah yang dibutuhkan untuk menyiapkan dan menjalankan Polygon Edge dengan server [Hashicorp Vault](https://www.vaultproject.io/). + +:::info Panduan sebelumnya + +**Sebaiknya**, sebelum mempelajari artikel ini, baca artikel tentang [**Pengaturan Lokal**](/docs/edge/get-started/set-up-ibft-locally) +dan [**Pengaturan Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +::: + + +## Prasyarat {#prerequisites} + +Artikel ini mengasumsikan bahwa instans yang berfungsi dari server Hashicorp Vault **sudah disiapkan**. + +Selain itu, server Hashicorp Vault yang digunakan untuk Polygon Edge wajib telah **mengaktifkan penyimpanan KV**. + +Informasi yang dibutuhkan sebelum melanjutkan: +* **URL server** (URL API server Hashicorp Vault) +* **Token** (token akses untuk mengakses mesin penyimpanan KV) + +## Langkah 1 - Buat konfigurasi pengelola rahasia {#step-1-generate-the-secrets-manager-configuration} + +Supaya Polygon Edge dapat berkomunikasi lancar dengan server Vault, perlu menguraikan file +konfigurasi yang sudah dihasilkan dan memuat semua informasi yang dibutuhkan untuk penyimpanan rahasia di Vault. + +Untuk menghasilkan konfigurasi, jalankan perintah berikut: + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +Parameter yang ada: +* `PATH` adalah jalur ke mana file konfigurasi harus diekspor. Default `./secretsManagerConfig.json` +* `TOKEN` adalah token akses yang disebutkan sebelumnya di [bagian prasyarat](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `SERVER_URL` adalah URL API untuk server Vault yang juga disebutkan di [bagian prasyarat](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `NODE_NAME` adalah nama node saat ini yang disiapkan sebagai konfigurasi Vault. Ini dapat berupa nilai manasuka. Default `polygon-edge-node` + +:::caution Nama node + +Berhati-hatilah ketika menentukan nama node. + +Polygon Edge menggunakan nama node spesifik untuk melacak rahasia yang dibuatnya dan digunakan di instans Vault. +Menyebutkan nama node yang ada dapat memiliki konsekuensi yaitu data di server Vault akan terhapus. + +Rahasia disimpan di jalur dasar berikut: `secrets/node_name` + +::: + +## Langkah 2 - Inisialisasi kunci rahasia menggunakan konfigurasi {#step-2-initialize-secret-keys-using-the-configuration} + +Karena file konfigurasi sudah ada, kita dapat menginisialisasi kunci rahasia yang dibutuhkan dengan pengaturan +file konfigurasi di langkah 1 menggunakan `--config`: + +```bash +polygon-edge secrets init --config +``` + +Parameter `PATH` adalah lokasi parameter pengelola rahasia yang dihasilkan sebelumnya dari langkah 1. + +## Langkah 3 - Buat file genesis {#step-3-generate-the-genesis-file} + +File genesis harus dibuat dengan cara yang mirip dengan [**Pengaturan Lokal**](/docs/edge/get-started/set-up-ibft-locally) +dan panduan [**Pengaturan Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud), dengan perubahan kecil. + +Karena Hashicorp Vault digunakan alih-alih sistem file lokal, alamat validator harus ditambahkan melalui bendera `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Langkah 4 - Mulai klien Polygon Edge {#step-4-start-the-polygon-edge-client} + +Setelah kunci diatur dan file genesis dihasilkan, langkah terakhir proses ini yaitu memulai +Polygon Edge dengan perintah `server`. + +Perintah `server` digunakan dengan cara yang sama seperti pada panduan yang disebutkan sebelumnya, dengan tambahan kecil - bendera `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +Parameter `PATH` adalah lokasi parameter pengelola rahasia yang dihasilkan sebelumnya dari langkah 1. \ No newline at end of file diff --git a/archive/edge/id-edge/consensus/bls.md b/archive/edge/id-edge/consensus/bls.md new file mode 100644 index 0000000000..4490c89619 --- /dev/null +++ b/archive/edge/id-edge/consensus/bls.md @@ -0,0 +1,144 @@ +--- +id: bls +title: BLS +description: "Penjelasan dan instruksi mengenai mode BLS." +keywords: + - docs + - polygon + - edge + - bls +--- + +## Ikhtisar {#overview} + +BLS juga dikenal sebagai Boneh–Lynn–Shacham (BLS)—is skema tanda tangan kriptografi yang memungkinkan pengguna untuk memverifikasi bahwa seorang penandatangan otentik. Ini adalah skema tanda tangan yang dapat memperbesar beberapa tanda. Dalam Polygon Edge, BLS digunakan secara default untuk menyediakan keamanan lebih baik dalam mode konsensus IBFT. BLS dapat menggabungkan tanda tangan ke dalam array byte tunggal dan mengurangi ukuran header blok. Setiap rantai dapat memilih apakah akan menggunakan BLS atau tidak. Kunci ECDSA digunakan tanpa peduli apakah mode BLS diaktifkan atau tidak. + +## Presentasi video {#video-presentation} + +[![bls - video](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## Bagaimana mengatur rantai baru menggunakan BLS {#how-to-setup-a-new-chain-using-bls} + +Lihat bagian [Pengaturan Lokal](/docs/edge/get-started/set-up-ibft-locally)/[Pengaturan Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) untuk instruksi pengaturan terperinci. + +## Cara migrasi dari rantai PoA ECDSA yang ada ke rantai PoA BLS {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +Bagian ini menjelaskan cara penggunaan mode di rantai PoA yang ada. +Langkah berikut diperlukan untuk mengaktifkan BLS di rantai PoA. + +1. Hentikan semua node +2. Buat kunci BLS untuk validator +3. Tambah pengaturan fork ke genesis.json +4. Mulai ulang semua node + +### 1. Hentikan semua node {#1-stop-all-nodes} + +Akhiri semua proses validator dengan menekan Ctrl + c (Control + c). Ingatlah tinggi blok terbaru (nomor urut tertinggi dalam log komitmen blok). + +### 2. Buat kunci BLS {#2-generate-the-bls-key} + +`secrets init` dengan `--bls` menghasilkan kunci BLS. Untuk mempertahankan kunci ECDSA dan Jaringan serta menambah kunci BLS baru, `--ecdsa` dan `--network` perlu dinonaktifkan. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Tambah pengaturan fork {#3-add-fork-setting} + +Perintah `ibft switch` menambah pengaturan fork yang mengaktifkan BLS di rantai yang ada, menjadi .`genesis.json`. + +Untuk jaringan PoA, validator perlu diberikan dalam perintah. Sedengkan untuk perintah `genesis`, bendera `--ibft-validators-prefix-path` atau `--ibft-validator` dapat digunakan untuk menentukan validator. + +Tentukan tinggi dari mana rantai mulai menggunakan BLS dengan bendera `--from`. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. Mulai ulang semua node {#4-restart-all-nodes} + +Mulai ulang semua node dengan perintah `server`. Setelah blok di `from` yang ditentukan pada langkah sebelumnya sudah dibuat, rantai mengaktifkan BLS dan menunjukkan log seperti di bawah ini: + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +Juga log menunjukkan mode verifikasi mana yang digunakan untuk menghasilkan setiap blok setelah blok dibuat. + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## Cara migrasi dari rantai PoS Polygon ECDSA ke rantai PoS Polygon BLS {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +Bagian ini menjelaskan cara penggunaan mode BLS di rantai PoS Polygon yang ada. +Langkah berikut diperlukan untuk mengaktifkan BLS dalam rantai PoS Polygon. + +1. Hentikan semua node +2. Buat kunci BLS untuk validator +3. Tambah pengaturan fork ke genesis.json +4. Panggil kontrak staking untuk mendaftarkan Kunci Publik BLS +5. Mulai ulang semua node + +### 1. Hentikan semua node {#1-stop-all-nodes-1} + +Akhiri semua proses validator dengan menekan Ctrl + c (Control + c). Ingatlah tinggi blok terbaru (nomor urut tertinggi dalam log komitmen blok). + +### 2. Buat kunci BLS {#2-generate-the-bls-key-1} + +`secrets init` dengan bendera `--bls` menghasilkan kunci BLS. Untuk mempertahankan kunci ECDSA dan Jaringan yang ada serta menambah kunci BLS baru, `--ecdsa` dan `--network` perlu dinonaktifkan. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Tambah pengaturan fork {#3-add-fork-setting-1} + +Perintah `ibft switch` menambahkan pengaturan fork yang mengaktifkan BLS dari tengah rantai ke `genesis.json`. + +Tentukan tinggi dari mana rantai mulai menggunakan mode BLS dengan bendera `from` dan tinggi tempat kontrak diperbarui dengan bendera `development`. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. Daftarkan Kunci Publik dalam kontrak staking {#4-register-bls-public-key-in-staking-contract} + +Setelah fork ditambahkan dan validator dimulai ulang, setiap validator perlu memanggil `registerBLSPublicKey` dalam kontrak staking untuk mendaftarkan Kunci Publik BLS. Ini harus dilakukan setelah tinggi yang ditentukan di `--deployment` sebelum tinggi yang ditentukan di `--from`. + +Skrip untuk mendaftarkan Kunci Publik BLS didefinisikan di [repo Kontrak Cerdas Staking](https://github.com/0xPolygon/staking-contracts). + +Set `BLS_PUBLIC_KEY` untuk didaftarkan ke file `.env`. Lihat [pos-stake-unstake](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) untuk perincian lebih lanjut tentang parameter lainnya. + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +Perintah berikut mendaftarkan Kunci Publik BLS yang diberikan di `.env` ke kontrak. + +```bash +npm run register-blskey +``` + +:::warning Validator perlu mendaftarkan Kunci Publik BLS secara manual + +Dalam mode BLS, validator harus memiliki alamat dan kunci publik BLS. Lapisan konsensus mengabaikan validator yang belum mendaftarkan kunci publik BLS di kontrak ketika konsensus mengambil info validator dari kontrak. + +::: + +### 5. Mulai ulang semua node {#5-restart-all-nodes} + +Mulai ulang semua node dengan `server` perintah. Rantai mengaktifkan BLS setelah blok di `from` yang ditentukan pada langkah sebelumnya sudah dibuat. diff --git a/archive/edge/id-edge/consensus/migration-to-pos.md b/archive/edge/id-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..4e244b7141 --- /dev/null +++ b/archive/edge/id-edge/consensus/migration-to-pos.md @@ -0,0 +1,40 @@ +--- +id: migration-to-pos +title: Migrasi dari PoA ke PoS +description: "Cara migrasi dari mode PoA ke mode PoS IBFT, dan sebaliknya." +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## Ikhtisar {#overview} + +Bagian ini memandu tentang migrasi mode PoA ke PoS IBFT, dan sebaliknya, untuk klaster aktif - tanpa perlu mengatur ulang blockchain. + +## Cara migrasi ke PoS {#how-to-migrate-to-pos} + +Anda harus menghentikan semua node, menambah konfigurasi fork ke genesis.json dengan perintah `ibft switch`, dan memulai ulang node. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution Beralih ketika menggunakan ECDSA +Ketika menggunakan ECDSA, `--ibft-validator-type`bendera harus ditambahkan ke dalam switch, menyebutkan bahwa ECDSA digunakan. Jika tidak termasuk, Edge akan secara otomatis beralih ke BLS. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::Untuk beralih ke PoS, Anda harus menentukan ketinggian 2 blok: `deployment`dan `from``deployment`adalah tinggi untuk menyebarkan kontrak staking `from`dan merupakan puncak awal PoS. Kontrak staking akan disebarkan di alamat `deployment` di `0x0000000000000000000000000000000000001001`, seperti kasus kontrak sebelum disebarkan. + +Lihat [Proof of Stake](/docs/edge/consensus/pos-concepts) untuk perincian lebih lanjut tentang kontrak Staking. + +:::warning Validator perlu melakukan stake secara manual + +Setiap validator perlu melakukan stake kontrak setelah kontrak disebarkan di `deployment` dan sebelum `from` untuk menjadi validator di awal PoS. Setiap validator akan memperbarui set validator yang diatur oleh set kontrak staking di awal PoS. + +Untuk mencari tahu lebih lanjut tentang Staking, kunjungi **[Set up dan menggunakan Proof of Stake](/docs/edge/consensus/pos-stake-unstake)**. +::: diff --git a/archive/edge/id-edge/consensus/poa.md b/archive/edge/id-edge/consensus/poa.md new file mode 100644 index 0000000000..31f0851944 --- /dev/null +++ b/archive/edge/id-edge/consensus/poa.md @@ -0,0 +1,110 @@ +--- +id: poa +title: Proof of Authority (PoA) +description: "Penjelasan dan instruksi mengenai Proof of Autority." +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## Ikhtisar {#overview} + +PoA IBFT adalah mekanisme konsensus default di Polygon Edge. Di PoA, validator yang bertanggung jawab membuat blok dan menambahkannya ke blockchain dalam rangkaian. + +Semua validator membentuk set validator dinamis, agar validator dapat ditambahkan ke atau dihapus dari set dengan menggunakan mekanisme pemungutan suara. Ini berarti bahwa validator dapat dipilih masuk/keluar dari set validator jika mayoritas (51%) node validator memilih menambah/menurunkan validator tertentu ke/dari set. Dengan cara ini, validator berbahaya dapat dikenali dan dihapus dari jaringan, sementara validator tepercaya baru dapat ditambahkan ke jaringan. + +Semua validator bergantian mengajukan blok berikutnya (giliran) dan untuk blok yang akan divalidasi/dimasukkan di blockchain, mayoritas (lebih dari 2/3) validator harus menyetujui blok tersebut. + +Selain validator, ada nonvalidator yang turut serta dalam pembuatan blok, tetapi turut serta dalam proses validasi blok. + +## Menambahkan validator ke set validator {#adding-a-validator-to-the-validator-set} + +Panduan ini menjelaskan cara menambah node validator baru ke jaringan IBFT aktif dengan 4 node validator. +Jika Anda perlu bantuan mengatur jaringan mengacu pada bagian [Setup](/edge/get-started/set-up-ibft-locally.md) / [Pengaturan](/edge/get-started/set-up-ibft-on-the-cloud.md) Cloud. + +### Langkah 1: Inisialisasi folder data untuk IBFT dan buat kunci validator​ untuk node baru {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +Untuk memulai dan menjalankan IBFT di node baru, Anda perlu menginisialisasi folder data dan membuat kunci terlebih dahulu: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +Perintah ini akan mencetak kunci validator (alamat) dan ID node. Anda akan membutuhkan kunci validator (alamat) untuk langkah berikutnya. + +### Langkah 2: Mengusulkan kandidat baru dari node validator lainnya {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +Agar node baru menjadi validator, setidaknya 51% validator perlu mengusulkan dirinya. + +Contoh cara mengusulkan validator baru (`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`) dari node validasi yang ada di alamat grpc: 127.0.0.1:10000: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +Struktur perintah IBFT tercakup di bagian [Perintah CLI](/docs/edge/get-started/cli-commands). + +:::info Kunci publik BLS + +Kunci publik BLS hanya diperlukan jika jaringan berjalan dengan BLS, untuk jaringan yang tidak berjalan dalam mode BLS, `--bls` tidak diperlukan + +::: + +### Langkah 3: Jalankan node klien {#step-3-run-the-client-node} + +Karena dalam contoh ini kita coba menjalankan jaringan tempat semua node berada di mesin yang sama, maka harus berhati-hati untuk menghindari konflik port. + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +Setelah mengambil semua blok, di dalam konsol Anda akan memperhatikan bahwa node baru turut serta dalam validasi + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info Mempromosikan nonvalidator ke validator + +Secara alami, nonvalidator dapat menjadi validator melalui proses pemungutan suara, tetapi agar berhasil dimasukkan dalam set validator setelah proses pemungutan suara, node harus dimulai ulang dengan bendera `--seal`. + +::: + +## Menghapus validator dari set validator {#removing-a-validator-from-the-validator-set} + +Operasi ini cukup sederhana. Untuk menghapus node validator dari set validator, perintah ini perlu dilakukan pada mayoritas node validator. + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info Kunci publik BLS + +Kunci publik BLS hanya diperlukan jika jaringan berjalan dengan BLS. Untuk jaringan yang tidak berjalan dalam mode BLS, tidak perlu `--bls` + +::: + +Setelah perintah dilaksanakan, amati bahwa jumlah validator telah turun (dalam contoh log ini dari 4 ke 3). + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/id-edge/consensus/pos-concepts.md b/archive/edge/id-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..8b2014c6fa --- /dev/null +++ b/archive/edge/id-edge/consensus/pos-concepts.md @@ -0,0 +1,120 @@ +--- +id: pos-concepts +title: Proof of Stake +description: "Penjelasan dan instruksi mengenai Proof of Stake." +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## Ikhtisar {#overview} + +Bagian ini untuk memberikan gambaran yang lebih baik tentang beberapa konsep yang saat ini ada dalam implementasi +Proof of Stake (PoS) Polygon Edge. + +Implementasi Proof of Stake (PoS) di Polygon Edge merupakan alternatif implemantasi PoA IBFT yang ada +yang memberikan kemampuan kepada operator node untuk memilih di antara kedua implementasi itu ketika memulai rantai. + +## Fitur PoS {#pos-features} + +Logika inti di balik implementasi Proof of Stake terletak di dalam +**[yang membuat Kontrak Cerdas ](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)**. + +Kontrak ini sudah disebarkan kapan pun mekanisme PoS rantai Polygon Edge diinisialisasi dan tersedia di alamat +`0x0000000000000000000000000000000000001001`dari blok `0`. + +### Epoch {#epochs} + +Epoch adalah konsep yang diperkenalkan dengan penambahan PoS ke Polygon Edge. + +Epoch dianggap sebagai kerangka waktu khusus (dalam blok) ketika set validator tertentu dapat menghasilkan blok. +Panjangnya dapat diubah, node operator dapat mengatur panjang epoch selama pembuatan genesis. + +Pada akhir setiap epoch, sebuah _blok epoch_ dibuat dan setelah peristiwa itu, epoch baru dimulai. Untuk mempelajari lebih lanjut +blok epoch, lihat bagian [Blok Epoch](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Set Validator diperbarui pada akhir setiap epoch. Node melakukan kueri set validator dari Kontrak Cerdas Staking +selama pembuatan blok epoch dan menyimpan data yang diperoleh ke penyimpanan lokal. Kueri ini dan menyimpan siklus +diulang pada akhir setiap epoch. + +Pada dasarnya, itu memastikan bahwa Kontrak Cerdas Staking memiliki kontrol penuh atas alamat di set validator dan +meninggalkan node hanya dengan 1 tanggung jawab - untuk melakukan kueri kontrak satu kali selama epoch guna mengambil informasi set +validator terbaru. Ini mengurangi tanggung jawab masing-masing node untuk menangani set validator. + +### Staking {#staking} + +Alamat dapat melakukan stake dana di Kontrak Cerdas Staking dengan menerapkan metode `stake` dan menentukan nilai +jumlah stake dalam transaksi: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +Dengan melakukan staking dana di Kontrak Cerdas Staking, alamat dapat memasuki set validator, sehingga dapat turut serta dalam +proses produksi blok. + +:::info Ambang batas staking + +Saat ini, ambang batas minimum untuk memasuki set validator adalah staking `1 ETH` + +::: + +### Unstaking {#unstaking} + +Alamat yang telah melakukan stake dana hanya dapat **melakukan unstake pada semua dana yang dilakukan stake sekaligus**. + +Unstaking dapat diajukan dengan memanggil metode `unstake` di Kontrak Cerdas Staking: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +Setelah melakukan unstaking dana, alamat dihapus dari set validator di Kontrak Cerdas Staking dan tidak akan +dianggap sebagai validator selama epoch berikutnya. + +## Blok Epoch {#epoch-blocks} + +**Blok Epoch** adalah konsep yang diperkenalkan dalam implementasi PoS IBFT di Polygon Edge. + +Pada dasarnya, blok epoch adalah blok khusus yang berisi **tidak ada transaksi** dan hanya terjadi di **akhir epoch**. +Misalnya, jika **ukuran epoch** diatur ke `50`blok, blok epoch akan dianggap sebagai blok `50``100``150`dan seterusnya. + +Itu digunakan untuk melakukan logika tambahan yang seharusnya tidak terjadi selama produksi blok reguler. + +Yang paling penting, itu adalah indikasi node yang informasi **set validator terbarunya perlu diambil** +dari Kontrak Cerdas Staking. + +Setelah memperbarui set validator di blok epoch, set validator (berubah atau tidak berubah) +digunakan untuk blok `epochSize - 1` berikutnya, sampai diperbarui lagi dengan menarik informasi terbaru dari +Kontrak Cerdas Staking. + +Panjang Epoch (dalam blok) dapat dimodifikasi ketika menghasilkan file genesis, dengan menggunakan bendera khusus `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +Ukuran default epoch adalah `100000` blok di Polygon Edge. + +## Kontrak prapenyebaran {#contract-pre-deployment} + +Polygon Edge melakukan _prapenyebaran_ +[Kontrak Cerdas Staking](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol) selama **pembuatan genesis** ke alamat `0x0000000000000000000000000000000000001001`. + +Hal itu dilakukan tanpa EVM aktif, dengan memodifikasi kondisi blockchain dari Kontrak Cerdas secara langsung, menggunakan nilai konfigurasi +yang diberikan ke perintah genesis. diff --git a/archive/edge/id-edge/consensus/pos-stake-unstake.md b/archive/edge/id-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..a6fb36fa83 --- /dev/null +++ b/archive/edge/id-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,177 @@ +--- +id: pos-stake-unstake +title: Mengatur dan menggunakan Proof of Stake (PoS) +description: "Stake, unstake, dan instruksi lain terkait staking." +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## Ikhtisar {#overview} + +Panduan ini menjelaskan perincian cara mengatur jaringan Proof of Stake dengan Polygon Edge, cara melakukan stake dana pada node +untuk menjadi validator dan cara melakukan unstake dana. + +Ini **sangat didorong** untuk membaca dan pergi [Pengaturan Lokal](/docs/edge/get-started/set-up-ibft-locally) +/[Pengaturan Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) sebelum melanjutkan +panduan PoS ini. Bagian ini menguraikan langkah yang diperlukan untuk memulai klaster Proof of Authority (PoA) dengan +Polygon Edge. + +Saat ini, tidak ada batasan jumlah validator yang dapat melakukan stake dana pada Kontrak Cerdas Staking. + +## Kontrak Cerdas Staking {#staking-smart-contract} + +Repo untuk Kontrak Cerdas Staking berada [di sini](https://github.com/0xPolygon/staking-contracts). + +Ini berisi skrip pengujian yang diperlukan, file ABI, dan yang paling penting adalah Kontrak Cerdas Staking itu sendiri. + +## Mengatur klaster node N {#setting-up-an-n-node-cluster} + +Mengatur jaringan dengan Polygon Edge tercakup dalam bagian +[Pengaturan Lokal](/docs/edge/get-started/set-up-ibft-locally) +/[Pengaturan Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +**Satu-satunya perbedaan** mengatur klaster PoS dan PoA yakni dalam hal pembuatan genesis. + +**Ketika menghasilkan file genesis untuk klaster PoS, perlu bendera tambahan `--pos`**: + +```bash +polygon-edge genesis --pos ... +``` + +## Mengatur panjang epoch {#setting-the-length-of-an-epoch} + +Epoch dibahas secara terperinci di bagian [Blok Epoch](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Untuk mengatur ukuran epoch bagi klaster (dalam blok) ketika menghasilkan file genesis, bendera tambahan +`--epoch-size` ditentukan: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +Nilai yang ditentukan di file genesis yakni ukuran epoch harus berupa `50` blok. + +Nilai default untuk ukuran epoch (dalam blok) adalah `100000`. + +:::info Mengurangi panjang epoch + +Seperti yang diuraikan di bagian [Blok Epoch](/docs/edge/consensus/pos-concepts#epoch-blocks), +blok epoch digunakan untuk memperbarui set validator node. + +Panjang epoch default di blok (`100000`) mungkin butuh waktu lama untuk pembaruan set validator. Mengingat bahwa blok +baru ditambahkan memakan waktu ~2d, mungkin akan perlu waktu ~55,5j untuk perubahan set validator. + +Mengatur nilai yang lebih rendah untuk panjang epoch memastikan bahwa set validator lebih sering diperbarui. + +::: + +## Menggunakan skrip Kontrak Cerdas Staking {#using-the-staking-smart-contract-scripts} + +### Prasyarat {#prerequisites} + +Repo Kontrak Cerdas Staking adalah proyek Hardhat yang membutuhkan NPM. + +Untuk menginisialisasinya dengan benar, di direktori utama jalankan: + +```bash +npm install +```` + +### Mengatur skrip pembantu yang disediakan {#setting-up-the-provided-helper-scripts} + +Skrip untuk berinteraksi dengan Kontrak Cerdas Staking yang disebarkan terletak di +[repo Kontrak Smart Staking](https://github.com/0xPolygon/staking-contracts). + +Buat file `.env` dengan parameter berikut di lokasi repo Kontrak Cerdas: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +Di mana prameternya adalah: + +* **JSONRPC_URL** - titik akhir JSON-RPC untuk node yang sedang berjalan +* **PRIVATE_KEYS** - kunci privat dari alamat staker. +* **STAKING_CONTRACT_ADDRESS** - alamat kontrak cerdas staking ( +default `0x0000000000000000000000000000000000001001`) +* **BLS_PUBLIC_KEY** - kunci publik BLS dari staker. Hanya diperlukan jika jaringan beroperasi dengan BLS + +### Dana staking {#staking-funds} + +:::info Alamat staking + +Kontrak Cerdas Staking sebelum disebarkan di +alamat `0x0000000000000000000000000000000000001001`. + +Interaksi apa pun dengan mekanisme staking melalui kontrak Cerdas Staking di alamat yang ditentukan. + +Untuk mempelajari lebih lanjut tentang Kontrak Cerdas Staking, kunjungi bagian +the **[Staking Smart Contract](/docs/edge/consensus/pos-concepts#contract-pre-deployment)**. + +::: + +Untuk menjadi bagian dari set validator, alamat perlu melakukan stake jumlah dana tertentu di atas ambang. + +Saat ini, ambang batas default untuk menjadi bagian dari set validator adalah `1 ETH`. + +Staking dapat dimulai dengan memanggil metode `stake` dari Kontrak Cerdas Staking dan menentukan nilai `>= 1 ETH`. + +Setelah file `.env` yang disebutkan di +[bagian sebelumnya](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) telah disiapkan dan +rantai telah dimulai di mode PoS, staking dapat dilakukan dengan perintah berikut di repo Kontrak Cerdas Staking: + +```bash +npm run stake +``` + +Skrip Hardhat `stake` melakukan stake jumlah default `1 ETH` yang dapat diubah dengan memodifikasi file `scripts/stake.ts`. + + +Jika dana yang dilakukan stake adalah `>= 1 ETH`, set validator di Kontrak Cerdas Staking diperbarui, dan alamat +akan menjadi bagian dari set validator dimulai dari epoch berikutnya. + +:::info Mendaftarkan kunci BLS + +Jika jaringan berjalan dalam mode BLS, agar node menjadi validator, perlu mendaftarkan kunci publik BLS setelah staking + +Ini dapat dilakukan dengan perintah berikut: + +```bash +npm run register-blskey +``` +::: + +### Unstaking dana {#unstaking-funds} + +Alamat yang memiliki stake dapat **hanya melakukan unstake semua dana** secara sekaligus. + +Setelah file `.env` yang disebutkan di +[bagian sebelumnya](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) +telah diatur dan rantai telah dimulai di mode PoS, unstaking dapat dilakukan dengan perintah berikut di +Repo Kontrak Cerdas Staking: + +```bash +npm run unstake +``` + +### Mengambil daftar staker {#fetching-the-list-of-stakers} + +Semua alamat yang melakukan stake dana disimpan ke Kontrak Cerdas Staking. + +Setelah file `.env` yang disebutkan di +[bagian sebelumnya](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) +telah diatur dan rantai telah dimulai di mode PoS, pengambilan daftar validator dapat dilakukan dengan +perintah berikut di repo Kontrak Cerdas Staking: + +```bash +npm run info +``` diff --git a/archive/edge/id-edge/faq/Contracts.md b/archive/edge/id-edge/faq/Contracts.md new file mode 100644 index 0000000000..436d049eb3 --- /dev/null +++ b/archive/edge/id-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: FAQ Kontrak Cerdas +description: "FAQ untuk Kontrak Cerdas Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## Apakah Polygon Edge mendukung Kontrak Cerdas? {#does-polygon-edge-support-smart-contracts} + +Ya. Jaringan Polygon Edge adalah blockchain yang kompatibel dengan Ethereum, jadi Kontrak Cerdas yang dapat disebarkan di Ethereum juga dapat disebarkan di rantai Polygon Edge. + +## Dapatkah Anda memperbarui logika kontrak staking untuk PoS setelah penyebaran? {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +Untuk saat ini, setelah memulai jaringan PoS, Anda tidak dapat mengubah logika kontrak staking, karena itu bagian dari file genesis. Maka Anda tidak dapat, misalnya, mengubah jumlah validator minimal/maksimal. Anda dalam melakukan stake atau unstake untuk menambah atau menghapus validator. + + + diff --git a/archive/edge/id-edge/faq/Gas.md b/archive/edge/id-edge/faq/Gas.md new file mode 100644 index 0000000000..de5a7fe0cd --- /dev/null +++ b/archive/edge/id-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: FAQ Gas +description: "FAQ Gas untuk Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Bagaimana cara menerapkan harga gas minimum? {#how-to-enforce-a-minimum-gas-price} +Anda dapat menggunakan bendera `--price-limit` yang disediakan di perintah server. Ini akan menerapkan node untuk hanya menerima transaksi yang memiliki gas yang lebih tinggi atau sama dengan batas harga yang ditentukan. Guna memastikan hal ini diterapkan di jaringan ini, Anda harus memastikan semua node memiliki batas harga yang sama. + + +## Dapatkah Anda memiliki transaksi dengan biaya gas 0? {#can-you-have-transactions-with-0-gas-fees} +Ya, bisa. Batas harga default yang diberlakukan oleh node adalah `0`, artinya node akan menerima transaksi yang memiliki harga gas yang ditetapkan ke `0`. + +## Bagaimana mengatur total pasokan token gas (asli)? {#how-to-set-the-gas-native-token-total-supply} + +Anda dapat mengatur saldo yang telah ditambang ke akun (alamat) dengan menggunakan `--premine flag`. Harap diperhatikan bahwa ini konfigurasi dari file genesis dan tidak dapat diubah. + +Contoh cara menggunakan `--premine flag`: + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +Ini mengatur saldo yang telah ditambang dari 1000 ETH ke 0x3956E90e632AebBF34DEB49b71c28A83Bc029862 (nilai argumen dalam wei). + +jumlah token gas yang ditambang akan menjadi total pasokan. Tidak ada jumlah mata uang asli lainnya (token gas) yang dapat dibuat. + +## Apakah Edge mendukung ERC-20 sebagai token gas? {#does-edge-support-erc-20-as-a-gas-token} + +Edge tidak mendukung token ERC-20 sebagai token gas. Hanya mata uang Edge asli yang didukung untuk gas. + +## Bagaimana untuk meningkatkan batas gas? {#how-to-increase-the-gas-limit} + +Ada dua pilihan untuk meningkatkan batas gas dalam Polygon Edge: +1. Wiping rantai dan meningkatkan `block-gas-limit`nilai uint64 maksimum dalam file genesis +2. Gunakan `--block-gas-target`bendera dengan nilai yang tinggi untuk meningkatkan batas gas dari semua node. Ini membutuhkan reboot node. [Penjelasan](/docs/edge/architecture/modules/txpool/#block-gas-target) yang terinci \ No newline at end of file diff --git a/archive/edge/id-edge/faq/Tokens.md b/archive/edge/id-edge/faq/Tokens.md new file mode 100644 index 0000000000..aeb959602b --- /dev/null +++ b/archive/edge/id-edge/faq/Tokens.md @@ -0,0 +1,23 @@ +--- +id: tokens +title: FAQ Token +description: "FAQ untuk token Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## Apakah Polygon Edge mendukung EIP-1559? {#does-polygon-edge-support-eip-1559} +Saat ini, Polygon Edge tidak mendukung EIP-1559. + +## Bagaimana cara mengatur simbol mata uang (token)? {#how-to-set-the-currency-token-symbol} + +Simbol token tercakup dalam UI, sehingga tidak dapat dikonfigurasi atau dikode keras di mana saja di dalam jaringan. +Tapi Anda dapat tambah perubahan ketika Anda tambah jaringan ke dompet, seperti Metamask, misalnya. + +## Apa yang terjadi pada transaksi ketika terjadi a {#what-happens-to-transactions-when-a-chain-halts} + +Semua transaksi yang belum diproses berada di dalam antrian TxPool(enqueued atau dipromosikan ). Jika halte rantai (semua pemberhentian produksi blok), transaksi ini tidak akan pernah menjadi blok.
Ini bukan hanya kasus ketika rantai berhenti. Jika node dihentikan atau di-ulang, semua transaksi yang belum dieksekusi, dan masih ada di TxPool, akan dihilangkan secara diam-diam.
Hal yang sama akan terjadi pada transaksi ketika perubahan yang melanggar diperkenalkan, karena diperlukan node untuk di-ulang. diff --git a/archive/edge/id-edge/faq/Validators.md b/archive/edge/id-edge/faq/Validators.md new file mode 100644 index 0000000000..2002caa232 --- /dev/null +++ b/archive/edge/id-edge/faq/Validators.md @@ -0,0 +1,85 @@ +--- +id: validators +title: FAQ Validator +description: "FAQ untuk validator Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Bagaimana cara menambahkan/menghapus validator? {#how-to-add-remove-a-validator} + +### PoA {#poa} +Menambahkan/menghapus validator dilakukan dengan pemungutan suara. Anda dapat menemukan panduan lengkap tentang hal ini [di sini](/docs/edge/consensus/poa). + +### PoS {#pos} +Anda dapat menemukan panduan tentang cara melakukan stake dana [di sini](/docs/edge/consensus/pos-stake-unstake), sehingga sebuah node dapat menjadi validator, dan cara melakukan unstake (menghapus validator). + +Harap diperhatikan bahwa: +- Anda dapat menggunakan bendera genesis `--max-validator-count` untuk mengatur jumlah maksimum staker yang dapat bergabung dengan set validator. +- Anda dapat menggunakan bendera genesis `--min-validator-count ` untuk mengatur jumlah minimum staker yang dibutuhkan untuk bergabung dengan set validator (`1` secara default). +- Ketika jumlah validator maksimal terpenuhi, Anda tidak dapat menambah validator lain sampai Anda menghapus satu validator yang ada dari set validator (tidak peduli apakah jumlah stake pada set validator baru ini lebih tinggi). Jika menghapus sebuah validator, maka jumlah validator yang tersisa tidak boleh kurang dari `--min-validator-count`. +- Ada ambang batas default unit `1` dari mata uang jaringan (gas) asli untuk menjadi validator. + + + +## Berapa ruang diska yang direkomendasikan untuk validator? {#how-much-disk-space-is-recommended-for-a-validator} + +Sebaiknya, mulai dengan ruang diska 100 G sebagai landasan utama yang diperkirakan secara konservatif dan pastikan ada kemungkinan menskalakan diska nantinya. + + +## Apakah ada batas jumlah validator? {#is-there-a-limit-to-the-number-of-validators} + +Jika kita membahas tentang batas teknis, Polygon Edge tidak secara eksplisit menentukan batas jumlah node yang bisa dimiliki dalam jaringan. Anda dapat mengatur batas koneksi (jumlah koneksi masuk/keluar) pada setiap node. + +Jika kita membahas tentang batas praktis, Anda akan melihat penurunan performa yang lebih buruk pada klaster dengan 100 node dibandingkan klaster dengan 10 node. Dengan menaikkan jumlah node dalam klaster, Anda akan meningkatkan kompleksitas komunikasi dan hanya overhead jaringan secara umum. Semua tergantung pada jenis jaringan yang dijalankan dan topologi jaringan yang dimiliki. + +## Bagaimana cara beralih dari PoA ke PoS? {#how-to-switch-from-poa-to-pos} + +PoA adalah mekanisme konsensus default. Untuk klaster baru dan berpindah ke PoS, Anda perlu menambah bendera `--pos` ketika membuat file genesis. Jika klaster sudah beroperasi, Anda dapat menemukan cara beralih [di sini](/docs/edge/consensus/migration-to-pos). Semua info yang dibutuhkan tentang mekanisme dan pengaturan konsensus dapat ditemukan di [bagian konsensus](/docs/edge/consensus/poa). + +## Bagaimana cara memperbarui node ketika ada perubahan yang menyebabkan bagian lain gagal? {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +Anda dapat menemukan panduan terperinci tentang cara melakukan prosedur ini [di sini](/docs/edge/validator-hosting#update). + +## Apakah jumlah stake minimum dapat dikonfigurasi untuk Pos Edge? {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +Jumlah stake minimum default adalah `1 ETH` dan tidak dapat dikonfigurasi. + +## Mengapa perintah JSON RPC `eth_getBlockByNumber` dan `eth_getBlockByHash` tidak menampilkan alamat penambang? {#not-return-the-miner-s-address} + +Konsensus yang digunakan di Polygon Edge adalah IBFT 2.0, yang kemudian dibangun berdasarkan mekanisme pemungutan suara yang dijelaskan dalam Clique PoA: [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225). + +Jika melihat EIP-225 (Clique PoA), ini bagian relevan yang menjelaskan kegunaan `miner` (alias `beneficiary`): + +
+Kami menyempurnakan bidang header ethash menjadi seperti berikut: +
    +
  • penerima manfaat/penambang: Alamat untuk mengusulkan perubahan daftar penandatangan yang sah.
  • +
      +
    • Harus diisi dengan nol, biasanya hanya diubah ketika pemungutan suara.
    • +
    • Nilai arbitrer tetap diperkenankan (bahkan yang tidak berarti seperti pemungutan suara untuk memilih non-penandatangan) guna menghindari kompleksitas lain dalam implementasi seputar mekanika pemungutan suara.
    • +
    • Harus diisi dengan nol pada blok titik periksa (yaitu transisi epoch).
    • +
    + +
+ +
+ +Jadi, bidang `miner` digunakan untuk mengusulkan pemilihan alamat tertentu, bukan menampilkan pengusul blok. + +Informasi tentang pengusul blok dapat ditemukan dengan memulihkan pubkey dari bidang Seal dari bidang data ekstra Istanbul yang dikodekan RLP dalam header blok. + +## Bagian dan nilai Kejadian yang dapat dimodifikasi dengan aman? {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +Pastikan untuk membuat salinan manual dari file genesis.json yang ada sebelum mencoba untuk mengubahnya. Juga, seluruh rantai harus dihentikan sebelum menyunting file genesis.json. Setelah file genesis dimodifikasi, versi baru dari itu harus didistribusikan ke seluruh node non-validator dan valdiator. + +::: + +**Hanya bagian bootnode dari file genesis yang dapat dimodifikasi dengan aman**, di mana Anda dapat menambahkan atau menghapus bootnode dari daftar. \ No newline at end of file diff --git a/archive/edge/id-edge/get-started/cli-commands.md b/archive/edge/id-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..833b7220ba --- /dev/null +++ b/archive/edge/id-edge/get-started/cli-commands.md @@ -0,0 +1,2220 @@ +--- +id: cli-commands +title: Perintah CLI +description: "Daftar perintah CLI dan bendera perintah untuk Polygon Edge." +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +Bagian ini memerinci perintah yang ada, bendera perintah di Polygon Edge, dan cara penggunaannya. + +:::tip Mendukung output JSON + +Bendera `--json` didukung pada beberapa perintah. Bendera ini menginstruksikan perintah untuk mencetak output dalam format JSON + +::: + +## Perintah Startup {#startup-commands} + +| **Perintah** | **Deskripsi** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| server | Perintah default yang memulai klien blockchain dengan melakukan bootstrap bersama semua modul | +| genesis | Menghasilkan file *genesis.json*, yang digunakan untuk mengatur kondisi rantai sebelum memulai klien. Struktur file genesis dijelaskan di bawah | +| genesis predeploy | Pre-deploys s a Smart Contract untuk jaringan segar | + +### bendera server {#server-flags} + + +| **Semua bendera** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [prometheus](/docs/edge/get-started/cli-commands#prometheus) | [target-gas-blok](/docs/edge/get-started/cli-commands#block-gas-target) | +| [max-peers](/docs/edge/get-started/cli-commands#max-peers) | [max-inbound-peers](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [max-outbound-peers](/docs/edge/get-started/cli-commands#max-outbound-peers) | [max-enqueued](/docs/edge/get-started/cli-commands#max-enqueued) | +| [level-log](/docs/edge/get-started/cli-commands#log-level) | [log-ke](/docs/edge/get-started/cli-commands#log-to) | +| [rantai](/docs/edge/get-started/cli-commands#chain) | [bergabung](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [image](/docs/edge/get-started/cli-commands#price-limit) | [max-slots](/docs/edge/get-started/cli-commands#max-slots) | +| [Konfig](/docs/edge/get-started/cli-commands#config) | [konfig-rahasia](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-interval](/docs/edge/get-started/cli-commands#dev-interval) | +| [tidak ada-penemuan](/docs/edge/get-started/cli-commands#no-discover) | [mengembalikan](/docs/edge/get-started/cli-commands#restore) | +| [waktu-blok](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +Digunakan untuk menentukan direktori data yang menyimpan data klien Polygon Edge. Default: `./test-chain`. + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +Menentukan alamat dan port untuk layanan JSON-RPC `address:port`. +Jika hanya port ditentukan `:10001`, itu akan mengikat ke semua antarmuka `0.0.0.0:10001`. +Jika dihilangkan, layanan akan mengikat ke default `address:port`. +Alamat default: `0.0.0.0:8545`. + +--- + +####

json-rpc-block-range-limit + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +Menentukan jangkauan blok maksimum yang dipertimbangkan ketika mengeksekusi permintaan json-rpc yang termasuk nilai fromBlock/toBlock (misalnya eth_getLogs). Default:`1000`. + +--- + +####

json-rpc-batch-request-limit + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +Menentukan panjang maksimum yang dipertimbangkan ketika menangani permintaan batch json-rpc. Default: `20`. + +--- + +####

grpc + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +Menentukan alamat dan port untuk layanan gRPC `address:port`. Alamat default: `127.0.0.1:9632`. + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +Menentukan alamat dan port untuk layanan libp2p `address:port`. Alamat default: `127.0.0.1:1478`. + +--- + +####

prometheus + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +Menentukan alamat dan port untuk server prometheus `address:port`. +Jika hanya port yang ditentukan `:5001`, layanan akan mengikat ke semua antarmuka `0.0.0.0:5001`. +Jika dihilangkan, layanan tidak akan dimulai. + +--- + +####

block-gas-target + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +Menentukan batas gas blok target untuk rantai . Default (tidak dilaksanakan): `0`. + +Penjelasan lebih terperinci tentang target gas blok dapat ditemukan di [bagian TxPool](/docs/edge/architecture/modules/txpool#block-gas-target). + +--- + +####

max-peers + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +Menentukan jumlah peer maksimum klien. Default: `40`. + +Batas peer harus ditentukan baik dengan menggunakan `max-peers` maupun bendera `max-inbound/outbound-peers`. + +--- + +####

max-inbound-peers + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +Menentukan jumlah peer maksimum klien. JIka `max-peers` ditetapkan, batas max-inbound-peer dihitung menggunakan formula berikut. + +`max-inbound-peer = InboundRatio * max-peers`, di mana `InboundRatio` adalah `0.8`. + +--- + +####

max-outbound-peers + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +Menentukan jumlah peer outbound maksimum klien. Jika `max-peers` ditetapkan, jumlah max-outbound-peer dihitung menggunakan formula berikut. + +`max-outbound-peer = OutboundRatio * max-peers`, di mana `OutboundRatio` adalah `0.2`. + +--- + +####

max-enqueued + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +Menentukan jumlah maksimum antrean transaksi per akun. Default:`128`. + +--- + +####

log-level + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +Menentukan level log untuk output konsol. Default: `INFO`. + +--- + +####

log-to + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +Menentukan nama file log yang akan menampung semua output log dari perintah server. +Secara default, semua log server akan ditampilkan ke konsol (stdout), +tetapi jika bendera ditetapkan, tidak akan ada output ke konsol ketika menjalankan perintah server. + +--- + +####

chain + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +Menentukan file genesis untuk memulai rantai. Default: `./genesis.json`. + +--- + +####

join + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Menentukan alamat peer yang harus bergabung. + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +Menentukan alamat IP eksternal tanpa port, seperti yang dapat dilihat oleh peer. + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +Menentukan alamat DNS host. Ini dapat digunakan untuk mengiklankan DNS eksternal. Dukung `dns`,`dns4`,`dns6`. + +--- + +####

image + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +Menentukan batas harga gas minimum untuk memberlakukan penerimaan ke dalam pool. Default: `1`. + +--- + +####

max-slots + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +Menentukan slot maksimum dalam pool. Default: `4096`. + +--- + +####

config + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +Menentukan jalur ke konfigurasi CLI. Mendukung `.json`. + +--- + +####

secrets-config + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +Menentukan jalur ke file konfigurasi SecretsManager. Digunakan untuk Hashicorp Vault, AWS SSM, dan Manajer Rahasia GCP. Jika dihilangkan, manajer rahasia FS lokal akan digunakan. + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +Menentukan klien ke mode dev. Default `false`: Dalam mode dev, penemuan peer dinonaktifkan secara default. + +--- + +####

dev-interval + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +Menentukan interval notifikasi dev klien dalam beberapa detik. Default: `0`. + +--- + +####

no-discover + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +Mencegah klien menemukan peer lain. Default: `false`. + +--- + +####

restore + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +Mengembalikan blok dari file arsip yang ditentukan + +--- + +####

block-time + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +Menetapkan waktu produksi blok dalam beberapa detik. Default: `2` + +--- + +####

access-control-allow-origins + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +Menentukan domain yang diotorisasi untuk dapat berbagi respons dari permintaan JSON-RPC. +Tambah beberapa bendera `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"` untuk mengotorisasi beberapa domain. +Jika dihilangkan header Access-Control-Allow-Origins akan ditetapkan ke `*` dan semua domain akan diotorisasi. + +--- + +### bendera genesis {#genesis-flags} +| **Semua bendera genesis** | +|---------------------------------------|---------------------------------------------| +| [dir](/docs/edge/get-started/cli-commands#dir) | [nama](/docs/edge/get-started/cli-commands#name) | +| [pos](/docs/edge/get-started/cli-commands#pos) | [epoch-size](/docs/edge/get-started/cli-commands#epoch-size) | +| [premine](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [tipe-validator-ibft](/docs/edge/get-started/cli-commands#ibft-validator-type) | [jalur-prefiks-validator-ibft](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [validator-ibft](/docs/edge/get-started/cli-commands#ibft-validator) | [batas-gas-blok](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [konsensus](/docs/edge/get-started/cli-commands#consensus) | [bootnode](/docs/edge/get-started/cli-commands#bootnode) | +| [jumlah-validator-maksimal](/docs/edge/get-started/cli-commands#max-validator-count) | [jumlah-validator-minimal](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

dir + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +Menentukan direktori untuk data genesis Polygon Edge. Default: `./genesis.json`. + +--- + +####

Nama + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +Menentukan nama rantai ini. Default: `polygon-edge`. + +--- + +####

pos + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +Menentukan bendera yang mengindikasikan bahwa klien harus menggunakan Proof of Stake IBFT. +Default pada Proof of Authority jika bendera tidak disediakan atau `false`. + +--- + +####

epoch-size + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +Menentukan ukuran epoch untuk rantai ini. Default `100000`. + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +Menentukan akun premined dan saldo dalam format `address:amount`. +Jumlah dapat berada dalam desimal atau hex. +Default telah ditambang keseimbangan: `0xD3C21BCECCEDA1000000`(1 juta token mata uang asli). + +--- + +####

chainid + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +Menentukan ID rantai. Default: `100`. + +--- + +####

ibft-validator-type + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +Menentukan mode validasi header blok. Nilai yang mungkin: `[ecdsa, bls]`. Default: `bls`. + +--- + +####

ibft-validators-prefix-path + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +Jalur prefiks untuk direktori folder validator. Perlu ada jika bendera `ibft-validator` dihilangkan. + +--- + +####

ibft-validator + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Menentukan alamat yang diteruskan sebagai validator IBFT. Perlu ada jika bendera `ibft-validators-prefix-path` dihilangkan. +1. Jika jaringan berjalan dengan ECDSA, formatnya adalah `--ibft-validator [ADDRESS]`. +2. Jika jaringan berjalan dengan BLS, formatnya adalah `--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]`. + +--- + +####

block-gas-limit + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +Mengacu jumlah gas maksimum yang digunakan oleh semua operasi di blok. Default: `5242880`. + +--- + +####

consensus + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +Menentukan protokol konsensus. Default: `pow`. + +--- + +####

bootnode + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Multiaddr URL untuk p2p discovery bootstrap. Bendera ini dapat digunakan beberapa kali. +Alih-alih alamat IP, alamat DNS dari bootnode dapat disediakan. + +--- + +####

max-validator-count + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +Jumlah maksimum staker yang dapat bergabung dengan set validator dalam konsensus PoS. +Jumlah ini tidak boleh melebihi nilai MAX_SAFE_INTEGER (2^53 - 2). + +--- + +####

jumlah-validator-minimal + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +Jumlah minimum staker yang diperlukan untuk bergabung dengan set validator dalam konsensus PoS. +Nomor ini tidak dapat melebihi nilai max-validator-count. +Default ke 1. + +--- + +### genesis predeploy {#genesis-predeploy-flags} + +

arti path

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +Menampilkan jalur ke artefak kontrak JSON yang berisi `abi`, `bytecode`dan .`deployedBytecode` + +--- + +

chain

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +Menampilkan jalur ke `genesis.json`file yang harus diperbarui. Default `./genesis.json`. + +--- + +

constructor-args

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +Menampilkan argumen konstruktor Smart Contract jika ada. Untuk panduan rinci tentang bagaimana argumen ini harus terlihat seperti, silakan merujuk [artikel pra-penyebaran](/docs/edge/additional-features/predeployment) + +--- + +

predeploy-address

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +Menampilkan alamat untuk melakukan predeploy Default `0x0000000000000000000000000000000000001100`. + +--- + + +## Perintah Operator {#operator-commands} + +### Perintah Peer {#peer-commands} + +| **Perintah** | **Deskripsi** | +|------------------------|-------------------------------------------------------------------------------------| +| peers add | Menambahkan peer baru menggunakan alamat libp2p mereka | +| peers list | Daftar semua peer klien terhubung melalui libp2p | +| peers status | Mengembalikan status peer spesifik dari daftar peer menggunakan alamat libp2p | + +

bendera peers add

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Alamat libp2p peer dalam format multiaddr. + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +Alamat API gRPC. Default: `127.0.0.1:9632`. + +

bendera peers list

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +Alamat API gRPC. Default: `127.0.0.1:9632`. + +

bendera peers status

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +ID node libp2p dari peer tertentu dalam jaringan p2p. + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +Alamat API gRPC. Default: `127.0.0.1:9632`. + +### Perintah IBFT {#ibft-commands} + +| **Perintah** | **Deskripsi** | +|------------------------|-------------------------------------------------------------------------------------| +| ibft snapshot | Mengembalikan snapshot IBFT | +| ibft candidates | Kueri set kandidat yang diusulkan saat ini, juga kandidat yang belum disertakan | +| ibft propose | Menentukan kandidat baru untuk ditambahkan/dihapus dari set validator | +| ibft status | Mengembalikan status keseluruhan klien IBFT | +| ibft switch | Tambah konfigurasi fork ke dalam file genesis.json untuk mengganti jenis IBFT | +| ibft quorum | Menentukan nomor blok, kemudian metode ukuran kuorum optimal akan digunakan untuk konsensus | + + +

bendera ibft snapshot

+ +

number

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +Tinggi blok (nomor) untuk snapshot. + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +Alamat API gRPC. Default: `127.0.0.1:9632`. + +

bendera ibft candidates

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Alamat API gRPC. Default: `127.0.0.1:9632`. + +

bendera ibft propose

+ +

vote

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +Mengusulkan perubahan ke set validator. Nilai yang mungkin: `[auth, drop]`. + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +Alamat akun yang akan dipilih. + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +Akun Kunci Publik BLS untuk dipilih, hanya perlu dalam mode BLS. + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Alamat API gRPC. Default: `127.0.0.1:9632`. + +

bendera ibft status

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +Alamat API gRPC. Default: `127.0.0.1:9632`. + +

bendera ibft switch

+ +

chain

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +Menentukan file genesis untuk memutakhirkan. Default: `./genesis.json`. + +--- + +

Jenis

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +Menentukan tipe IBFT untuk dialihkan. Nilai yang mungkin: `[PoA, PoS]`. + +--- + +

deployment

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +Menentukan tinggi penyebaran kontrak. Hanya tersedia dengan PoS. + +--- + +

from

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +Menentukan mode validasi header blok. Nilai yang mungkin: `[ecdsa, bls]`. Default: `bls`. + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +Jalur prefiks untuk direktori validator baru. Perlu ada jika bendera `ibft-validator` dihilangkan. Hanya tersedia ketika mode IBFT adalah PoA (bendera `--pos` dihilangkan). + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Set yang diteruskan pada alamat sebagai validator IBFT akan digunakan setelah fork. Perlu ada jika bendera `ibft-validators-prefix-path` dihilangkan. Hanya tersedia dalam mode PoA. +1. Jika jaringan berjalan dengan ECDSA, formatnya adalah `--ibft-validator [ADDRESS]`. +2. Jika jaringan berjalan dengan BLS, formatnya adalah `--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]`. + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +Jumlah maksimum staker yang dapat bergabung dengan set validator dalam konsensus PoS. +Jumlah ini tidak boleh melebihi nilai MAX_SAFE_INTEGER (2^53 - 2). + +--- + +

jumlah-validator-minimal

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +Jumlah minimum staker yang diperlukan untuk bergabung dengan set validator dalam konsensus PoS. +Nomor ini tidak dapat melebihi nilai max-validator-count. +Default ke 1. + +Menentukan tinggi awal fork. + +--- + +

bendera ibft quorum

+ +

from

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +Tinggi untuk mengalihkan perhitungan quorum ke QuorumOptimal yang menggunakan formula `(2/3 * N)`, `N` menjadi nomor node validator. Harap diperhatikan bahwa ini untuk kompatibilitas mundur, yaitu hanya untuk rantai yang menggunakan perhitungan lama Quorum sampai tinggi blok tertentu. + +--- + +

chain

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +Menentukan file genesis untuk memutakhirkan. Default: `./genesis.json`. + +### Perintah Pool Transaksi {#transaction-pool-commands} + +| **Perintah** | **Deskripsi** | +|------------------------|--------------------------------------------------------------------------------------| +| txpool status | Menghasilkan jumlah transaksi di dalam pool | +| txpool subscribe | Berlangganan peristiwa dalam pool transaksi | + +

bendera txpool status

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +Alamat API gRPC. Default: `127.0.0.1:9632`. + +

bendera txpool subscribe

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +Alamat API gRPC. Default: `127.0.0.1:9632`. + +--- + +

promoted

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +Berlangganan peristiwa tx yang dipromosikan di TxPool. + +--- + +

dropped

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +Berlangganan peristiwa tx yang dikeluarkan dari TxPool + +--- + +

demoted

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +Berlangganan peristiwa tx yang diturunkan di TxPool. + +--- + +

added

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +Berlangganan peristiwa tx yang ditambahkan ke TxPool. + +--- + +

enqueued

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +Berlangganan peristiwa tx yang diantrekan di antrean akun. + +--- + +### Perintah blockchain {#blockchain-commands} + +| **Perintah** | **Deskripsi** | +|------------------------|-------------------------------------------------------------------------------------| +| status | Menampilkan status klien. Respons terperinci dapat ditemukan berikut ini | +| monitor | Berlangganan aliran peristiwa blockchain. Respons terperinci dapat ditemukan berikut ini | +| version | Mengembalikan versi klien saat ini | + +

bendera status

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +Alamat API gRPC. Default: `127.0.0.1:9632`. + +

bendera monitor

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +Alamat API gRPC. Default: `127.0.0.1:9632` + +--- +

perintah versi

+ + + + + + version + + + + +Menampilkan versi rilis git, hash commit dan waktu built. + +## Perintah Rahasia {#secrets-commands} + +| **Perintah** | **Deskripsi** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| secrets init | Menjalankan kunci privat untuk pengelola rahasia terkait | +| secrets generate | Menghasilkan file konfigurasi manajer rahasia yang dapat diurai oleh Polygon Edge | +| output rahasia | Menampilkan alamat kunci publik BLS, alamat kunci publik validator, dan node id untuk referensi | + +### bendera init rahasia {#secrets-init-flags} + +

config

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +Menentukan jalur ke file konfigurasi SecretsManager. Digunakan untuk Hashicorp Vault. Jika dihilangkan, pengelola rahasia FS lokal akan digunakan. + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +Menentukan direktori data Polygon Edge jika FS lokal digunakan. + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +Menentukan bendera yang mengindikasikan apakah akan menghasilkan kunci ECDSA. Default: `true`. + +--- + +

network

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +Menentukan bendera yang mengindikasikan apakah akan menghasilkan kunci jaringan Libp2p. Default: `true`. + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +Menentukan bendera yang mengindikasikan apakah akan menghasilkan kunci BLS. Default: `true`. + +### bendera secrets generate {#secrets-generate-flags} + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +Menentukan direktori file konfigurasi pengelola rahasia Default: `./secretsManagerConfig.json` + +--- + +

Jenis

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +Menentukan tipe pengelola rahasia [`hashicorp-vault`]. Default: `hashicorp-vault` + +--- + +

token

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +Menentukan token akses untuk layanan + +--- + +

server-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +Menentukan URL server untuk layanan + +--- + +

Nama

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +Menentukan nama node untuk arsip rekaman layanan. Default: `polygon-edge-node` + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Menentukan namespace yang digunakan untuk pengelola rahasia Hashicorp Vault. Default: `admin` + +### tanda keluaran archive {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +Menampilkan bendera yang menunjukkan apakah hanya mengeluarkan kunci publik BLS. Default: `true` + +--- + +

config

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +Menentukan jalur ke file konfigurasi SecretsManager. Jika dihilangkan, manajer rahasia FS lokal digunakan. + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +Menentukan direktori data Polygon Edge jika FS lokal digunakan. + +--- + +

node-id

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +Menampilkan bendera yang menunjukkan apakah hanya mengeluarkan node ID jaringan. Default: `true` + +--- + +

Validator

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +Menampilkan bendera yang menunjukkan apakah hanya mengeluarkan alamat validator. Default: `true` + +--- + +## Respons {#responses} + +### Respons Status {#status-response} + +Objek respons didefinisikan menggunakan Protokol Buffer. +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### Respons Monitor {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## Penggunaan {#utilities} + +### perintah whitelist {#whitelist-commands} + +| **Perintah** | **Deskripsi** | +|------------------------|-------------------------------------------------------------------------------------| +| whitelist show | Menampilkan informasi whitelist | +| whitelist deployment | Memperbarui whitelist penyebaran kontrak cerdas | + +

whitelist show

+ + + + + whitelist show + + + + +Menampilkan informasi whitelist. + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +Menentukan file genesis untuk memutakhirkan. Default: `./genesis.json`. + +--- + +

whitelist deployment

+ +

chain

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +Menentukan file genesis untuk memutakhirkan. Default: `./genesis.json`. + +--- + +

tambah

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Menambahkan alamat baru ke whitelist penyebaran kontrak. Hanya alamat di whitelist penyebaran kontrak yang dapat menyebarkan kontrak. Jika kosong, alamat apa pun dapat menjalankan penyebaran kontrak + +--- + +

remove

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Menghapus alamat dari whitelist penyebaran kontrak. Hanya alamat di whitelist penyebaran kontrak yang dapat menyebarkan kontrak. Jika kosong, alamat apa pun dapat menjalankan penyebaran kontrak + +--- + +### bendera backup {#backup-flags} + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +Alamat API gRPC. Default: `127.0.0.1:9632`. + +--- + +

out

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +Jalur file arsip yang akan disimpan. + +--- + +

from

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +Tinggi awal blok di arsip. Default: 0. + +--- + +

to

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +Tinggi akhir blok di arsip. + +--- + +## Templat Genesis {#genesis-template} +File genesis harus digunakan untuk mengatur kondisi awal blockchain (misalnya, jika beberapa akun harus memiliki saldo awal). + +File *./genesis.json* berikut dihasilkan: +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### Direktori Data {#data-directory} + +Ketika mengeksekusi bendera *data-dir*, folder **test-chain** dihasilkan. +Struktur folder terdiri dari subfolder berikut: +* **blockchain** - Menyimpan LevelDB untuk objek blockchain +* **trie** - Menyimpan LevelDB untuk pohon Merkle +* **keystore** - Menyimpan kunci privat untuk klien. Ini termasuk kunci privat libp2p dan kunci privat penyegel/validator +* **consensus** - Menyimpan informasi konsensus apa pun yang mungkin dibutuhkan klien ketika bekerja + +## Sumber daya {#resources} +* **[Buffer Protokol](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/id-edge/get-started/installation.md b/archive/edge/id-edge/get-started/installation.md new file mode 100644 index 0000000000..c426cff880 --- /dev/null +++ b/archive/edge/id-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: Instalasi +description: "Cara menginstal Polygon Edge." +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +Silakan merujuk metode instalasi yang lebih sesuai untuk Anda. + +Rekomendasi kami yakni menggunakan rilis siap pakai dan verifikasi checksum yang tersedia. + +## Rilis siap pakai {#pre-built-releases} + +Lihat halaman [Rilis GitHub](https://github.com/0xPolygon/polygon-edge/releases) untuk daftar rilisan. + +Polygon Edge dilengkapi biner AMD64/ARM64 kompilasi silang untuk Darwin dan Linux. + +--- + +## Citra Docker {#docker-image} + +Citra Docker resmi dihos di [registri hub.docker.com](https://hub.docker.com/r/0xpolygon/polygon-edge). + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## Membangun dari sumber {#building-from-source} + +Sebelum menggunakan `go install`, pastikan Anda sudah menginstal Go `>=1.18` dan telah mengonfigurasinya dengan tepat. + +Cabang stabil adalah cabang dari rilis terbaru. + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## Menggunakan `go install` + +Sebelum menggunakan `go install`, pastikan Anda sudah menginstal Go `>=1.17` dan telah mengonfigurasinya dengan tepat. + +`go install github.com/0xPolygon/polygon-edge@release/` + +biner akan tersedia dalam variabel `GOBIN`lingkungan Anda, dan akan mencakup perubahan dari rilis terbaru. Anda dapat memeriksa [Release GitHub](https://github.com/0xPolygon/polygon-edge/releases) untuk mencari tahu yang mana yang paling terbaru. diff --git a/archive/edge/id-edge/get-started/set-up-ibft-locally.md b/archive/edge/id-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..6bfb394bbf --- /dev/null +++ b/archive/edge/id-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,429 @@ +--- +id: set-up-ibft-locally +title: Pengaturan Lokal +description: "Panduan langkah-langkah pengaturan lokal." +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution Panduan ini hanya untuk pengujian + +Panduan di bawah akan mengarahkan tentang cara mengatur jaringan Polygon Edge di komputer lokal untuk pengujian +dan pengembangan. + +Prosedur ini berbeda jauh dari cara pengaturan jaringan Polygon Edge untuk skenario penggunaan nyata +a cloud: **[Cloud Setup](/docs/edge/get-started/set-up-ibft-on-the-cloud)** + +::: + + +## Persyaratan {#requirements} + +Lihat [Instalasi](/docs/edge/get-started/installation) untuk menginstal Polygon Edge. + +## Ikhtisar {#overview} + +![Pengaturan Lokal](/img/edge/ibft-setup/local.svg) + +Dalam panduan ini, tujuan kita adalah membangun jaringan blockchain `polygon-edge` yang bekerja dengan [protokol konsensus IBFT](https://github.com/ethereum/EIPs/issues/650). +Jaringan blockchain akan terdiri dari 4 node yang keempatnya merupakan node validator dan sebagai syarat untuk mengusulkan dan memvalidasi blok yang datang dari pengusul lain. +Keempat node itu akan bekerja di mesin yang sama, karena gagasan panduan ini adalah memberikan klaster IBFT yang berfungsi sepenuhnya dalam waktu singkat. + +Oleh karena itu, kami memberikan panduan melalui 4 langkah mudah: + +1. Inisialisasi direktori data akan menghasilkan kunci validator untuk setiap 4 node dan menginisialisasi direktori data blockchain kosong. Kunci validator penting karena kita perlu melakukan bootstrap blok genesis dengan pengaturan awal validator menggunakan kunci ini. +2. Menyiapkan string koneksi untuk bootnode akan menjadi informasi vital bagi setiap node yang akan kita jalankan, seperti node mana yang dihubungkan ketika memulai kali pertama. +3. Menghasilkan file `genesis.json` akan diperlukan sebagai input kunci validator yang dihasilkan langkah dalam **langkah 1** untuk pengaturan validator awal jaringan dalam blok genesis dan string koneksi bootnode dari **langkah 2**. +4. Menjalankan semua node adalah tujuan akhir dari panduan ini dan akan menjadi langkah terakhir yang kita lakukan, kita akan menginstruksikan node yang data direktorinya akan digunakan dan lokasi pencarian `genesis.json` yang melakukan bootstrap kondisi jaringan awal. + +Karena keempat node akan berjalan di host lokal, selama proses pengaturan diharapkan semua direktori data +untuk setiap node berada dalam direktori induk yang sama. + +:::info Jumlah validator + +Tidak ada jumlah node minimum dalam sebuah klaster, artinya, sebuah klaster dapat memiliki hanya 1 node validator. +Ingat bahwa dengan klaster node _tunggal_, maka **tidak ada toleransi kerusakan** dan **tidak ada jaminan BFT**. + +Jumlah node minimum yang direkomendasikan untuk bisa mendapatkan jaminan BFT adalah 4 - karena dalam sebuah klaster 4 node, kegagalan +node 1 dapat ditoleransi karena ada sisa 3 node yang berfungsi normal. + +::: + +## Langkah 1: Inisialisasi folder data untuk IBFT dan hasilkan kunci validator {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +Agar IBFT siap dioperasikan, Anda perlu menginisialisasi folder data, +satu untuk setiap node: + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +Setiap perintah ini akan mencetak kunci validator, kunci publik bls, dan [ID node](https://docs.libp2p.io/concepts/peer-id/). Anda akan membutuhkan ID Node dari node pertama untuk langkah berikutnya. + +### Menampilkan Rahasia {#outputting-secrets} +Output rahasia dapat diakses lagi, jika diperlukan. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## Langkah 2: Siapkan string koneksi multiaddr untuk bootnode {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Agar berhasil membangun konektivitas, node harus tahu server `bootnode` mana yang dihubungkan untuk mendapatkan +informasi tentang semua node yang tersisa pada jaringan. `bootnode` terkadang juga dikenal sebagai server `rendezvous` dalam jargon p2p. + +`bootnode` bukan instans khusus node polygon-edge. Setiap node polygon-edge dapat berfungsi sebagai `bootnode`, tetapi +setiap node polygon-edge perlu memiliki set bootnode yang ditentukan yang akan dihubungi untuk memberikan informasi tentang cara menghubungkan dengan +semua node yang tersisa di jaringan. + +Untuk membuat string koneksi yang menentukan bootnode, kita perlu menyesuaikan +dengan [format multiaddr](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +Dalam panduan ini, kita akan memperlakukan node pertama dan kedua sebagai bootnode untuk semua node lainnya. Yang akan terjadi dalam skenario ini +adalah semua node yang terhubung ke `node 1` atau `node 2` akan mendapatkan informasi tentang cara terhubung satu sama lain melalui +bootnode yang saling dihubungi. + +:::info Anda harus menentukan setidaknya satu bootnode untuk memulai node + +Setidaknya diperlukan **satu** bootnode, sehingga node lain yang ada dalam jaringan dapat saling menemukan. Sebaiknya menggunakan lebih banyak bootnode, karena +mereka akan memberikan daya tahan terhadap jaringan ketika terjadi gangguan. +Dalam panduan ini, kami akan mencantumkan dua node, tetapi ini dapat diubah dengan cepat tanpa berdampak pada validitas file `genesis.json`. + +::: + +Karena berjalan di localhost, bisa diasumsikan bahwa `` merupakan `127.0.0.1`. + +Untuk ``, kita akan menggunakan `10001`, karena kita akan mengatur server libp2p agar `node 1` mendengarkan di port ini nantinya. + +Terakhir, kita membutuhkan `` yang bisa didapatkan dari output perintah yang dijalankan sebelumnya, perintah `polygon-edge secrets init --data-dir test-chain-1` (yang digunakan untuk menghasilkan kunci dan direktori data untuk `node1`) + +Setelah perakitan, string koneksi multiaddr ke `node 1` yang akan kita gunakan sebagai bootnode akan terlihat seperti ini (hanya `` yang pada akhirnya harus berbeda): +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Demikian pula, kita membangun multiaddr untuk bootnode kedua seperti yang ditunjukkan di bawah +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info Nama host DNS, alih-alih ips + +Polygon Edge mendukung penggunaan nama host DNS untuk konfigurasi node. Ini fitur yang sangat membantu untuk penyebaran berbasis cloud, sebab ip node dapat berubah karena berbagai alasan. + +Format multiaddr untuk string koneksi saat menggunakan nama host DNS adalah sebagai berikut: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## Langkah 3: Menghasilkan file genesis dengan 4 node sebagai validator {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +Yang dilakukan perintah ini: + +* `--ibft-validators-prefix-path` mengatur jalur folder prefiks ke jalur folder yang ditentukan agar dapat digunakan IBFT +di Polygon Edge. Direktori ini untuk menampung folder `consensus/`, yakni tempat penyimpanan kunci privat validator. Kunci +publik validator diperlukan untuk membangun file genesis - daftar awal node bootstrap. +Bendera ini hanya dapat dimengerti ketika mengatur jaringan di localhost, seperti dalam skenario nyata, kita tidak dapat mengharapkan semua +direktori data node untuk berada di filesystem sama yang kunci publiknya dapat kita baca dengan mudah. +* `--bootnode` mengatur alamat bootnode yang akan mengaktifkan node untuk menemukan satu sama lain. +Kita akan menggunakan string multiaddr `node 1`, seperti yang disebutkan dalam **langkah 2**. + +Hasil dari perintah ini adalah `genesis.json` file yang berisi blok genesis dari blockchain baru kami, dengan set validator yang telah ditentukan sebelumnya dan konfigurasi node mana yang harus dihubungi terlebih dahulu untuk membangun konektivitas. + +:::info Ganti ke ECDSA + +BLS adalah mode validasi default dari header blok. Jika Anda ingin rantai Anda untuk dijalankan dalam mode ECDSA, Anda dapat menggunakan `—ibft-validator-type`bendera dengan argumen `ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info Saldo akun premining + +Anda mungkin ingin mengatur jaringan blockchain dengan beberapa alamat yang memiliki saldo "pratambang". + +Untuk itu, Anda harus memberikan sebanyak mungkin bendera `--premine` pada setiap alamat yang ingin diinisialisasi dengan saldo tertentu +di blockchain. + +Misalnya, jika kita ingin melakukan pratambang 1000 eth ke alamat `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` di blok genesis, maka kita perlu memberikan argumen berikut: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Perlu diperhatikan bahwa jumlah saldo pratambang dalam WEI, bukan ETH.** + +::: + +:::info Mengatur batas gas blok + +Batas gas default untuk setiap blok adalah .`5242880`. Nilai ini ditulis dalam file genesis, tetapi Anda mungkin ingin +menaikkan/menurunkannya. + +Untuk melakukan hal itu, Anda dapat menggunakan bendera `--block-gas-limit` yang diikuti dengan nilai yang diinginkan seperti yang ditunjukkan di bawah ini: + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Menentukan batas deskriptop file sistem + +Batas file deskriptor default (jumlah maksimum file terbuka) pada beberapa sistem operasi cukup kecil. +Jika node yang diharapkan memiliki throughput yang tinggi, Anda mungkin mempertimbangkan untuk menaikkan batas ini pada tingkat OS. + +Untuk distro Ubuntu, prosedurnya adalah sebagai berikut (jika Anda tidak menggunakan distro Ubuntu/Debian, lihat dokumen resmi untuk OS Anda): +- Periksa batas os saat ini (file terbuka) +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- Naikkan batas file terbuka + - Secara lokal - hanya memengaruhi sesi saat ini: + ```shell + ulimit -u 65535 + ``` + - Secara global atau per pengguna (tambah batas pada akhir file /etc/security/limits.conf): + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +Secara opsional, ubah parameter tambahan, simpan file, dan mulai ulang sistem. +Setelah memulai ulang, periksa lagi batas deskriptor file. +Itu harus diatur ke nilai yang didefinisikan dalam file limits.conf. + +::: + + +## Langkah 4: Jalankan semua klien {#step-4-run-all-the-clients} + +Karena kita berupaya menjalankan jaringan Polygon Edge yang terdiri dari 4 node yang semuanya di mesin yang sama, kita perlu berhati-hati untuk +menghindari konflik port. Inilah alasan kita akan menggunakan penalaran berikut untuk menentukan port pendengaran dari setiap node: + +- `10000` untuk server gRPC dari `node 2`, `20000` untuk server GRPC dari `node 1`, dll. +- `10001` untuk server libp2p dari `node 2`, `20001` untuk server libp2p dari `node 1`, dll. +- `10002` untuk server JSON-RPC dari `node 1`, `20002` untuk server JSON-RPC dari `node 2`, dll. + +Untuk menjalankan klien **pertama** (catat port `10001`, karena itu digunakan sebagai bagian dari libp2p multiaddr di **langkah 2** bersama Node ID node 1): + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +Untuk menjalankan klien **kedua**: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +Untuk menjalankan klien **ketiga**: + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +Untuk menjalankan klien **keempat**: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +Untuk membahas secara singkat apa yang telah dilakukan sejauh ini: + +* Direktori data klien telah ditentukan yakni **./test-chain-\*** +* Server GRPC telah dimulai pada port **10000**, **20000**, **30000**, dan **40000** untuk masing-masing node +* Server libp2p telah dimulai di port **10001**, **20001**, **30001**, dan **40001** untuk masing-masing node +* Server JSON-RPC telah dimulai pada port **10002**, **20002**, **30002**, dan **40002** untuk masing-masing node +* Bendera *seal* berarti bahwa node yang dimulai akan turut serta menyegel blok +* Bendera *chain* menentukan yang file genesis harus digunakan untuk konfigurasi rantai + +Struktur file genesis dibahas dalam bagian [Perintah CLI.](/docs/edge/get-started/cli-commands). + +Setelah menjalankan perintah sebelumnya, Anda telah mengatur jaringan Polygon Edge 4 node, mampu menyegel blok, dan memulihkan +dari kegagalan node. + +:::info Mulai klien menggunakan file konfigurasi + +Alih-alih menentukan semua parameter konfigurasi sebagai argumen CLI, Klien juga dapat mulai menggunakan file konfigurasi dengan mengeksekusi perintah berikut: + +````bash +polygon-edge server --config +```` +Contoh: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Saat ini, kami mendukung `yaml`dan `json`berbasis file konfigurasi yang dapat ditemukan **[di sini](/docs/edge/configuration/sample-config)** + +::: + +:::info Langkah-langkah untuk menjalankan node non-validator + +Node nonvalidator akan selalu menyinkronkan blok terakhir yang diterima dari node validasi, Anda dapat memulai node nonvalidator dengan menjalankan perintah berikut. + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +Misalnya, Anda dapat menambahkan klien Nonvalidator **kelima** dengan menjalankan perintah berikut: + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info Menentukan batas harga + +Node Polygon Edge dapat dimulai dengan set **batas harga** untuk transaksi masuk. + +Unit batas harga adalah `wei`. + +Mengatur batas harga berarti transaksi apa pun yang diproses oleh node saat ini harus memiliki harga gas **lebih tinggi** +kemudian batas harga ditetapkan. Jika tidak, maka tidak akan disertakan dalam blok. + +Membuat mayoritas node menghormati batas harga tertentu akan menegakkan aturan bahwa transaksi dalam jaringan +tidak boleh berada di bawah ambang batas harga tertentu. + +Nilai default batas harga adalah `0`, artinya, secara default, batas harga itu tidak diberlakukan. + +Contoh penggunaan bendera `--price-limit`: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Harap diperhatikan bahwa batas harga **diberlakukan hanya pada transaksi nonlokal**, berarti +batas harga tidak berlaku untuk transaksi yang ditambahkan secara lokal pada node. + +::: + +:::info URL WebSocket + +Secara default, ketika menjalankan Polygon Edge akan dihasilkan URL WebSocket berdasarkan lokasi rantai. +Skema URL `wss://` digunakan untuk tautan HTTPS dan `ws://` untuk HTTP. + +URL WebSocket Localhost: +````bash +ws://localhost:10002/ws +```` +Perlu diperhatikan bahwa nomor port tergantung pada port JSON-RPC yang dipilih untuk node tersebut. + +URL WebSocket Edgenet: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## Langkah 5: Berinteraksi dengan jaringan polygon-edge {#step-5-interact-with-the-polygon-edge-network} + +Karena Anda telah mengatur setidaknya 1 klien yang beroperasi, Anda dapat berinteraksi dengan blockchain menggunakan akun pratambang di atas +dan dengan menentukan URL JSON-RPC ke salah satu dari 4 node: +- Node 1: `http://localhost:10002` +- Node 2: `http://localhost:20002` +- Node 3: `http://localhost:30002` +- Node 4: `http://localhost:40002` + +Ikuti panduan ini untuk mengeluarkan perintah operator ke klaster yang baru dibangun: [Cara melakukan kueri informasi operator](/docs/edge/working-with-node/query-operator-info) (port GRPC untuk klaster yang telah dibangun adalah `10000`/`20000`/`30000`/`40000` untuk setiap node masing-masing) diff --git a/archive/edge/id-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/id-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..220dc235bc --- /dev/null +++ b/archive/edge/id-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,448 @@ +--- +id: set-up-ibft-on-the-cloud +title: Pengaturan Cloud +description: "Panduan pengaturan cloud secara bertahap." +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info Panduan ini untuk pengaturan mainnet atau testnet + +Panduan di bawah ini akan menguraikan cara menyiapkan jaringan Polygon Edge di penyedia cloud untuk penyiapan produksi testnet atau mainnet. + +Jika Anda ingin menyiapkan jaringan Polygon Edge secara lokal untuk menguji `polygon-edge` sekilas sebelum melakukan pengaturan untuk produksi, silakan lihat +**[Pengaturan](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## Persyaratan {#requirements} + +Baca [Instalasi](/docs/edge/get-started/installation) untuk menginstal Polygon Edge. + +### Menyiapkan konektivitas VM {#setting-up-the-vm-connectivity} + +Tergantung pada pilihan penyedia cloud, Anda dapat menyiapkan konektivitas dan aturan antara VM menggunakan firewall, +grup keamanan, atau daftar kontrol akses. + +Karena satu-satunya bagian dari `polygon-edge` yang perlu diekspos ke VM lainnya adalah server libp2p, maka izinkan +semua komunikasi antara VM di port `1478` libp2p default. + +## Ikhtisar {#overview} + +![Pengaturan cloud](/img/edge/ibft-setup/cloud.svg) + +Dalam panduan ini, tujuan kita adalah membangun jaringan blockchain `polygon-edge` yang bekerja dengan [protokol konsensus IBFT](https://github.com/ethereum/EIPs/issues/650). +Jaringan blockchain akan terdiri dari 4 node yang keempatnya merupakan node validator dan sebagai syarat untuk mengusulkan dan memvalidasi blok yang berasal dari proposal lain. +Masing-masing dari 4 node tersebut akan berjalan di VM masing-masing, karena gagasan dari panduan ini adalah memberikan jaringan Polygon Edge yang berfungsi sepenuhnya sekaligus menjaga kerahasiaan kunci validator guna memastikan pengaturan jaringan nirkepercayaan. + +Untuk mencapai hal tersebut, kami memandu Anda dengan 4 langkah mudah berikut: + +0. Perhatikan daftar **Persyaratan** di atas +1. Buat kunci privat untuk setiap validator dan lakukan inisialisasi pada direktori data +2. Siapkan string koneksi untuk bootnode yang akan dimasukkan ke `genesis.json` bersama +3. Buat `genesis.json` di mesin lokal dan kirim/transfer ke setiap node +4. Mulai semua node + +:::info Jumlah validator + +Tidak ada jumlah node minimum dalam sebuah klaster, artinya, sebuah klaster dapat memiliki hanya 1 node validator. +Ingat bahwa dengan klaster node _tunggal_, maka **tidak ada toleransi kerusakan** dan **tidak ada jaminan BFT**. + +Jumlah node minimum yang direkomendasikan untuk bisa mendapatkan jaminan BFT adalah 4 - karena dalam sebuah klaster 4 node, kegagalan +1 node dapat ditoleransi, dengan sisa 3 node yang berfungsi normal. + +::: + +## Langkah 1: Inisialisasi folder data dan buat kunci validator {#step-1-initialize-data-folders-and-generate-validator-keys} + +Untuk menyiapkan dan menjalankan Polygon Edge, Anda perlu menginisialisasi folder data pada setiap node: + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +Setiap perintah ini akan mencetak kunci validator, kunci publik bls, dan [ID node](https://docs.libp2p.io/concepts/peer-id/). Anda akan membutuhkan ID Node dari node pertama untuk langkah berikutnya. + +### Menampilkan Rahasia {#outputting-secrets} +Output rahasia dapat diakses lagi, jika diperlukan. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning Simpan direktori data Anda untuk diri sendiri! + +Direktori data dihasilkan di atas, selain menginisialisasi direktori untuk menyimpan kondisi blockchain, juga akan menghasilkan kunci privat validator. +**Kunci ini harus disimpan dan dirahasiakan, karena jika dicuri seseorang, orang tersebut dapat menyamar sebagai Anda untuk menjadi validator dalam jaringan!** + +::: + +## Langkah 2: Siapkan string koneksi multiaddr untuk bootnode {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Agar berhasil membangun konektivitas, node harus tahu server `bootnode` mana yang harus dihubungkan untuk mendapatkan +informasi tentang semua node yang tersisa pada jaringan. `bootnode` kadang juga dikenal sebagai server `rendezvous` dalam jargon p2p. + +`bootnode` bukan instans khusus node Polygon Edge. Setiap node Polygon Edge dapat berfungsi sebagai `bootnode` dan +setiap node Polygon Edge perlu memiliki set bootnode yang ditentukan dan akan dihubungi untuk memberikan informasi tentang cara terhubung dengan +semua node yang tersisa di jaringan. + +Untuk membuat string koneksi yang menentukan bootnode, kita perlu menyesuaikan +dengan [format multiaddr](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +Dalam panduan ini, kita akan memperlakukan node pertama dan kedua sebagai bootnode untuk semua node lainnya. Yang akan terjadi dalam skenario ini +adalah semua node yang terhubung ke `node 1` atau `node 2` akan mendapatkan informasi tentang cara terhubung satu sama lain melalui +bootnode yang saling dihubungi. + +:::info Anda harus menentukan setidaknya satu bootnode untuk memulai node + +Setidaknya diperlukan **satu** bootnode, sehingga node lain yang ada dalam jaringan dapat saling menemukan. Sebaiknya menggunakan lebih banyak bootnode, karena +mereka akan memberikan daya tahan terhadap jaringan ketika terjadi gangguan. +Dalam panduan ini kami akan mencantumkan dua node, tetapi ini dapat diubah dengan cepat tanpa berdampak pada validitas file `genesis.json`. + +::: + +Karena bagian pertama string koneksi multiaddr adalah ``, di sini Anda perlu memasukkan alamat IP yang dapat dicapai oleh node lain, tergantung pengaturan Anda, alamat tersebut bisa berupa alamat IP privat atau publik, bukan `127.0.0.1`. + +Untuk ``, kita akan menggunakan `1478`, karena itu pengaturan default untuk port libp2p. + +Terakhir, kita membutuhkan `` yang bisa didapatkan dari output perintah yang dijalankan sebelumnya, yakni perintah `polygon-edge secrets init --data-dir data-dir` (yang digunakan untuk menghasilkan kunci dan direktori data untuk `node 1`) + +Setelah perakitan, string koneksi multiaddr ke `node 1` yang akan kita gunakan sebagai bootnode akan terlihat seperti ini (hanya `` yang pada akhirnya akan berbeda): +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Demikian juga, kita membangun multiaddr untuk bootnode kedua seperti yang ditunjukkan di bawah +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info Nama host DNS, bukan ips + +Polygon Edge mendukung penggunaan nama host DNS untuk konfigurasi node. Ini fitur yang sangat membantu untuk penyebaran berbasis cloud, sebab ip node dapat berubah karena berbagai alasan. + +Format multiaddr untuk string koneksi saat menggunakan nama host DNS adalah sebagai berikut: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## Langkah 3: Menghasilkan file genesis dengan 4 node sebagai validator {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +Langkah ini dapat dijalankan di mesin lokal, tetapi Anda akan membutuhkan kunci validator untuk masing-masing dari 4 validator. + +Validator dapat dengan aman berbagi `Public key (address)` seperti yang ditunjukkan di bawah ini dalam keluaran untuk perintah `secrets init`, sehingga +Anda dapat secara aman menghasilkan genesis.json dengan validator tersebut di set validator awal, yang diidentifikasi oleh kunci publiknya: + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +Mengingat Anda telah menerima keempat kunci publik validator, maka Anda dapat menjalankan perintah berikut untuk menghasilkan `genesis.json` + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +Yang dilakukan perintah ini: + +* `--ibft-validator` menetapkan kunci publik validator yang harus dimasukkan dalam set validator awal yang ditetapkan dalam blok genesis. Jumlah validator awal bisa lebih dari satu. +* `--bootnode` mengatur alamat bootnode yang akan memungkinkan node untuk bisa saling menemukan. +`node 1`Kami akan menggunakan string multiaddr dari , seperti yang disebutkan di **langkah 2**, meskipun Anda dapat menambahkan berapa pun jumlah bootnode yang Anda inginkan, seperti yang ditunjukkan di atas. + +:::info Ganti ke ECDSA + +BLS adalah mode validasi default dari header blok. Jika Anda ingin rantai Anda untuk dijalankan dalam mode ECDSA, Anda dapat menggunakan `—ibft-validator-type`bendera dengan argumen `ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info Saldo akun premining + +Anda mungkin ingin mengatur jaringan blockchain dengan beberapa alamat yang memiliki saldo "pratambang". + +Untuk itu, Anda harus memberikan sebanyak mungkin bendera `--premine` pada setiap alamat yang ingin diinisialisasi dengan saldo tertentu +di blockchain. + +Misalnya, jika kita ingin melakukan pratambang 1000 eth ke alamat `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` di blok genesis, maka kita perlu memberikan argumen berikut: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Perlu diperhatikan bahwa jumlah saldo pratambang dalam WEI, bukan ETH.** + +::: + +:::info Mengatur batas gas blok + +Batas gas default untuk setiap blok adalah .`5242880`. Nilai ini ditulis dalam file genesis, tetapi Anda mungkin ingin +menaikkan/menurunkannya. + +Untuk melakukan hal itu, Anda dapat menggunakan bendera `--block-gas-limit` yang diikuti dengan nilai yang diinginkan seperti yang ditunjukkan di bawah ini: + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Menentukan batas deskriptop file sistem + +Batas file deskriptor default (jumlah maksimum file terbuka) pada beberapa sistem operasi cukup kecil. +Jika node yang diharapkan memiliki throughput yang tinggi, Anda mungkin mempertimbangkan untuk menaikkan batas ini pada tingkat OS. + +Untuk distro Ubuntu, prosedurnya adalah sebagai berikut (jika Anda tidak menggunakan distro Ubuntu/Debian, lihat dokumen resmi untuk OS Anda): +- Periksa batas os saat ini (file terbuka) +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- Naikkan batas file terbuka + - Secara lokal - hanya memengaruhi sesi saat ini: + ```shell + ulimit -u 65535 + ``` + - Secara global atau per pengguna (tambah batas pada akhir file /etc/security/limits.conf): + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +Secara opsional, ubah parameter tambahan, simpan file, dan mulai ulang sistem. +Setelah memulai ulang, periksa lagi batas deskriptor file. +Batas itu harus diatur ke nilai yang ditentukan dalam file limits.conf. + +::: + +Setelah menentukan: +1. Kunci publik validator yang akan dimasukkan dalam blok genesis sebagai set validator +2. String koneksi multiaddr bootnode +3. Akun dan saldo pratambang yang akan dimasukkan dalam blok genesis + +dan yang menghasilkan `genesis.json` harus disalin ke semua VM dalam jaringan. Tergantung pengaturan, Anda dapat +menyalin/menempelnya, mengirimkannya ke operator node, atau hanya melakukan SCP/FTP. + +Struktur file genesis dibahas pada bagian [Perintah CLI.](/docs/edge/get-started/cli-commands). + +## Langkah 4: Jalankan semua klien {#step-4-run-all-the-clients} + +:::note Jaringan pada Penyedia Cloud + +Kebanyakan penyedia cloud tidak mengekspos alamat IP (terutama alamat IP publik) sebagai antarmuka jaringan langsung pada VM, tetapi menyiapkan NAT proxy yang tidak terlihat. + + +Dalam kasus ini, untuk memungkinkan node saling terhubung, Anda perlu mendengarkan alamat IP `0.0.0.0` agar terikat pada semua antarmuka, tetapi Anda akan tetap perlu menentukan alamat IP atau alamat DNS yang dapat digunakan node lain untuk terhubung ke instans. Hal ini bisa dicapai dengan menggunakan argumen `--nat` atau `--dns` dengan menentukan alamat IP atau DNS eksternal. + +#### Contoh {#example} + +Alamat IP terkait yang ingin Anda dengarkan adalah `192.0.2.1`, tetapi alamat itu tidak terikat langsung ke antarmuka jaringan. + +Agar node-node tersebut dapat terhubung, Anda harus memberikan parameter berikut: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +Atau, jika Anda ingin menentukan alamat DNS `dns/example.io`, berikan parameter berikut: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +Ini akan membuat node mendengarkan semua antarmuka, tetapi juga membuatnya mengetahui bahwa klien terhubung padanya melalui alamat `--nat` atau `--dns` yang ditentukan. + +::: + +Untuk menjalankan klien **pertama**: + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Untuk menjalankan klien **kedua**: + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Untuk menjalankan klien **ketiga**: + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Untuk menjalankan klien **keempat**: + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Setelah menjalankan perintah-perintah tersebut, Anda telah selesai mengatur jaringan Polygon Edge 4 node, dapat menyegel blok, dan melakukan pemulihan +dari kegagalan node. + +:::info Mulai klien menggunakan file konfigurasi + +Alih-alih menentukan semua parameter konfigurasi sebagai argumen CLI, Klien juga dapat dimulai menggunakan file konfigurasi dengan menjalankan perintah berikut: + +````bash +polygon-edge server --config +```` +Contoh: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Saat ini, kami hanya mendukung file konfigurasi berbasis `json`, berkas konfigurasi sampel dapat ditemukan **[di sini](/docs/edge/configuration/sample-config)** + +::: + +:::info Langkah-langkah untuk menjalankan node nonvalidator + +Node nonvalidator akan selalu menyinkronkan blok terakhir yang diterima dari node validasi, Anda dapat memulai node nonvalidator dengan menjalankan perintah berikut. + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +Misalnya, Anda dapat menambahkan klien Nonvalidator **kelima** dengan menjalankan perintah berikut: + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info Menentukan batas harga + +Node Polygon Edge dapat dimulai dengan set **batas harga** untuk transaksi masuk. + +Unit batas harga adalah `wei`. + +Mengatur batas harga berarti transaksi apa pun yang diproses oleh node saat ini harus memiliki harga gas yang **lebih tinggi** +dari batas harga yang ditentukan, jika tidak, maka tidak akan dimasukkan ke dalam sebuah blok. + +Dengan membuat mayoritas node mematuhi batas harga tertentu akan memaksa berlakunya aturan bahwa transaksi dalam jaringan +tidak boleh berada di bawah ambang batas harga tertentu. + +Nilai default batas harga adalah `0`, artinya, secara default, batas harga itu tidak diberlakukan. + +Contoh penggunaan bendera `--price-limit`: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Harap diperhatikan bahwa batas harga **diberlakukan hanya pada transaksi nonlokal**, berarti +batas harga tidak berlaku untuk transaksi yang ditambahkan secara lokal pada node. + +::: + +:::info URL WebSocket + +Secara default, ketika menjalankan Polygon Edge akan dihasilkan URL WebSocket berdasarkan lokasi rantai. +Skema URL `wss://` digunakan untuk tautan HTTPS dan `ws://` untuk HTTP. + +URL WebSocket Localhost: +````bash +ws://localhost:10002/ws +```` +Perlu diperhatikan bahwa nomor port tergantung pada port JSON-RPC yang dipilih untuk node tersebut. + +URL WebSocket Edgenet: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/id-edge/get-started/terraform-aws-deployment.md b/archive/edge/id-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..cd152d542c --- /dev/null +++ b/archive/edge/id-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,176 @@ +--- +id: terraform-aws-deployment +title: Penyebaran Terraform AWS +description: "Menyebarkan jaringan Polygon Edge di penyedia cloud AWS menggunakan Terraform" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info Panduan penyebaran produksi + +Ini adalah panduan resmi untuk penyebaran AWS yang siap digunakan, dan sepenuhnya otomatis. + +Penyebaran manual ke ***[Cloud](set-up-ibft-on-the-cloud)*** atau ***[Lokal](set-up-ibft-locally)*** +direkomendasikan untuk pengujian dan/atau jika penyedia cloud Anda bukan AWS. + +::: + +:::info + +Penyebaran ini khusus PoA. +Jika mekanisme PoS diperlukan, ikuti ***[panduan](/docs/edge/consensus/migration-to-pos)*** ini sekarang untuk beralih dari PoA ke PoS. + +::: + +Panduan ini akan menjelaskan secara detail proses penyebaran jaringan blockchain Polygon Edge di penyedia cloud AWS +yang siap produksi karena node validatornya membentang di berbagai zona ketersediaan. + +## Prasyarat {#prerequisites} + +### Alat sistem {#system-tools} +* [terraform](https://www.terraform.io/) +* [aws cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [ID kunci akses dan kunci akses rahasia aws](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Variabel Terraform {#terraform-variables} +Dua variabel yang harus disediakan, sebelum menjalankan tugas: + +* `alb_ssl_certificate` - ARN sertifikat dari AWS Certificate Manager yang akan digunakan oleh ALB untuk protokol http. + Sertifikat tersebut harus dihasilkan sebelum memulai penyebaran dan harus memiliki status **Diterbitkan** +* `premine` - akun yang akan menerima mata uang asli pratambang. +Nilai harus mengikuti spesifikasi bendera [CLI](/docs/edge/get-started/cli-commands#genesis-flags) resmi + +## Informasi penyebaran {#deployment-information} +### Sumber daya yang disebarkan {#deployed-resources} +Ikhtisar tingkat tinggi tentang sumber daya yang akan disebarkan: + +* VPC Khusus +* 4 node validator (yang juga merupakan bootnode) +* 4 NAT gateway untuk memungkinkan lalu lintas internet keluar node +* Fungsi Lambda untuk menghasilkan blok (genesis) pertama dan memulai rantai +* Grup keamanan khusus dan peran IAM +* Bucket S3 untuk menyimpan file genesis.json +* Penyeimbang Beban Aplikasi yang digunakan untuk mengekspos titik akhir JSON-RPC + +### Toleransi pelanggaran {#fault-tolerance} + +Hanya wilayah yang memiliki 4 zona ketersediaan yang diperlukan untuk penyebaran ini. Setiap node disebarkan dalam AZ tunggal. + +Dengan menempatkan setiap node dalam AZ tunggal, seluruh klaster blockchain bersifat toleran-pelanggaran terhadap kegagalan node tunggal (AZ), karena Polygon Edge menerapkan konsensus IBFT +yang memungkinkan node tunggal gagal dalam klaster 4 node validator. + +### Akses baris perintah {#command-line-access} + +Node validator tidak diekspos dengan cara apa pun ke internet publik (JSON-PRC diakses hanya melalui ALB) +dan bahkan tidak memiliki alamat IP publik yang dilampirkan padanya. +Akses baris perintah node mungkin digunakan hanya melalui [AWS Systems Manager - Session Manager](https://aws.amazon.com/systems-manager/features/). + +### Peningkatan AMI dasar {#base-ami-upgrade} + +Penyebaran ini menggunakan AWS AMI`ubuntu-focal-20.04-amd64-server`. Ini **tidak** akan memicu *penyebaran ulang* EC2 jika AWS AMI mendapat pembaruan. + +Jika, karena alasan tertentu, AMI dasar diwajibkan untuk mendapatkan pembaruan, +hal ini dapat dilakukan dengan menjalankan perintah `terraform taint` untuk setiap instans, sebelum `terraform apply`. +Instans dapat dikontaminasi dengan menjalankan perintah . +`terraform taint module.instances[].aws_instance.polygon_edge_instance` + +Contoh: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info + +Dalam lingkungan produksi, `terraform taint` harus dijalankan satu persatu untuk agar jaringan blockchain tetap berfungsi. +::: + +## Prosedur penyebaran {#deployment-procedure} + +### Langkah prapenyebaran {#pre-deployment-steps} +* baca readme registri terraform [polygon-technology-edge](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) dengan cermat +* tambahkan modul `polygon-technology-edge` ke file `main.tf` menggunakan *instruksi penyediaan* pada halaman readme modul +* jalankan perintah `terraform init` untuk menginstal semua dependensi Terraform yang diperlukan +* berikan sertifikat baru dalam [AWS Certificate Manager](https://aws.amazon.com/certificate-manager/) +* pastikan sertifikat yang disediakan berada dalam status **Diterbitkan** dan catat **ARN** sertifikat tersebut +* atur pernyataan keluaran untuk mendapatkan keluaran modul dalam cli + +#### contoh `main.tf` {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### contoh `terraform.tfvars` {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### Langkah-langkah penyebaran {#deployment-steps} +* buat file `terraform.tfvars` +* atur variabel terraform yang diperlukan dalam file ini (seperti dijelaskan di atas). +:::info + +Ada variabel tidak wajib lainnya yang dapat sepenuhnya menyesuaikan penyebaran ini. +Anda dapat menimpa nilai default dengan menambahkan nilai ke file `terraform.tfvars`. + + Spesifikasi semua variabel yang tersedia dapat dilihat dalam modul ***[registri](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)*** Terraform. + +::: +* pastikan telah menyiapkan autentikasi aws cli secara tepat dengan menjalanka `aws s3 ls` - tidak boleh ada kesalahan +* sebarkan infrastruktur `terraform apply` + +### Langkah-langkah pascapenyebaran {#post-deployment-steps} +* setelah penyebaran selesai, catat nilai variabel `json_rpc_dns_name` yang dicetak dalam cli +* buat rekaman cname dns publik yang menunjuk nama domain ke nilai `json_rpc_dns_name` yang diberikan. Misalnya: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* setelah rekaman cname menyebar, periksa apakah rantai bekerja secara tepat dengan memanggil titik akhir JSON-PRC. + Dari contoh di atas: + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## Prosedur penghancuran {#destroy-procedure} +:::warning + +Prosedur berikut akan secara menghapus secara permanen seluruh infrastruktur yang disebarkan dengan skrip terraform ini. +Pastikan ada [cadangan data blockchain](docs/edge/working-with-node/backup-restore) yang tepat dan/atau yang digunakan dalam lingkungan pengujian. + +::: + +Jika perlu menghapus seluruh infrastruktur, jalankan perintah berikut `terraform destroy`. +Selain itu, Anda harus menghapus secara manual rahasia yang disimpan dalam AWS [Parameter Store](https://aws.amazon.com/systems-manager/features/) +untuk wilayah lokasi penyebaran. diff --git a/archive/edge/id-edge/overview.md b/archive/edge/id-edge/overview.md new file mode 100644 index 0000000000..b6ca3e1b72 --- /dev/null +++ b/archive/edge/id-edge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Polygon Edge +sidebar_label: What is Edge +description: "Pengantar Polygon Edge." +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +Polygon Edge adalah kerangka kerja modular dan dapat diperluas untuk membangun jaringan blockchain, rantai sisi, dan solusi penskalaan umum yang kompatibel dengan Ethereum. + +Penggunaan utamanya yaitu melakukan bootstrap pada jaringan blockchain baru sembari menyediakan kompatibilitas penuh dengan kontrak dan cerdas Ethereum. Polygon Edge menggunakan mekanisme konsensus IBFT (Istanbul Byzantine Fault Tolerant), yang didukung dalam dua jenis yakni [PoA (proof of authority)](/docs/edge/consensus/poa) dan [PoS (proof of stake)](/docs/edge/consensus/pos-stake-unstake). + +Polygon Edge juga mendukung komunikasi dengan berbagai jaringan blockchain, memungkinkan transfer token [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) dan [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721), dengan memanfaatkan [solusi jembatan tersentralisasi](/docs/edge/additional-features/chainbridge/overview). + +Dompet standar industri dapat digunakan untuk berinteraksi dengan Polygon Edge melalui titik akhir [JSON-RPC](/docs/edge/working-with-node/query-json-rpc) dan operator node dapat melakukan berbagai tindakan pada node melalui protokol [gRPC](/docs/edge/working-with-node/query-operator-info). + +Untuk mengetaui lebih banyak tentang Polygon, kunjungi [situs resminya](https://polygon.technology). + +**[Repositori GitHub](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +Ini masih dalam pengembangan sehingga perubahan arsitektur dapat terjadi di masa depan. Kode ini belum diaudit, +tetapi hubungi tim Polygon jika Anda ingin menggunakannya dalam produksi. + +::: + + + +Untuk mulai menjalankan jaringan `polygon-edge` secara lokal, baca: [Instalasi](/docs/edge/get-started/installation) dan [Penyiapan Lokal](/docs/edge/get-started/set-up-ibft-locally). diff --git a/archive/edge/id-edge/performance-reports/overview.md b/archive/edge/id-edge/performance-reports/overview.md new file mode 100644 index 0000000000..101c0ac853 --- /dev/null +++ b/archive/edge/id-edge/performance-reports/overview.md @@ -0,0 +1,32 @@ +--- +id: overview +title: Ikhtisar +description: "Pengantar pengujian Polygon Edge." +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +Perlu diperhatikan bahwa kami `loadbot`yang digunakan untuk melakukan tes ini, sekarang sudah selesai. +::: + +| Tipe | Nilai | Tautan ke pengujian | +| ---- | ----- | ------------ | +| Transfer Reguler | 1428 tps | [4 Juli 2022](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| Transfer ERC-20 | 1111 tps | [4 Juli 2022](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| Pencetakan NFT | 714 tps | [4 Juli 2022](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +Sasaran kita adalah membuat dan merawat perangkat lunak klien blockchain yang berkinerja tinggi, kaya fitur, dan mudah disiapkan. +Semua pengujian dilakukan menggunakan Polygon Edge Loadbot. +Semua laporan kinerja yang Anda akan temukan pada bagian ini telah diberi tanggal yang tepat, lingkungannya digambarkan dengan jelas, dan metode pengujian diuraikan dengan jelas. + +Sasaran pengujian kinerja ini adalah menunjukkan kinerja jaringan blockchain Polygon Edge di dunia nyata. +Siapa pun bisa mendapat hasil serupa seperti yang dicantumkan di sini, pada lingkungan yang sama, menggunakan loadbot kami. + +Semua pengujian kinerja dilakukan di platform AWS pada rantai yang terdiri dari node instans EC2. \ No newline at end of file diff --git a/archive/edge/id-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/id-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..00a01bbd35 --- /dev/null +++ b/archive/edge/id-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,132 @@ +--- +id: test-2022-01-21 +title: 21 Januari 2022 +description: "Tes kinerja dari 21 Januari." +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## 21 Januari 2022 {#january-21st-2022} + +### Ringkasan {#summary} + +:::caution +Perlu diperhatikan bahwa kami `loadbot`yang digunakan untuk melakukan tes ini, sekarang sudah selesai. +::: + +Tes ini dilakukan setelah refactor TxPool yang secara signifikan meningkatkan kinerja (dirilis di [v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0)). + +Tujuannya adalah mengatur jaringan besar yang terdiri dari 30 validator berpartisipasi aktif untuk menguji tekanan dengan benar +pada gosip konsensus dan transaksi TxPool karena semua transaksi dikirim ke JSON-RPC node. tunggal. + +Tujuan kita bukan untuk berusaha menjangkau TPS semaksimal mungkin, karena ukuran jaringan secara negatif berdampak pada kinerja +dan karena batas blok gas & waktu blok diatur ke nilai wajar yang tidak mengonsumsi banyak sumber daya sistem dan akan memungkinkan ini berjalan pada perangkat keras komoditas. + +### Hasil {#results} + +| Metrik | Nilai | +| ------ | ----- | +| Transaksi per detik | 344 | +| Transaksi gagal | 0 | +| Transaksi berhasil | 10000 | +| Total waktu operasi | 30d | + +### Lingkungan {#environment} + +
+ Konfigurasi Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Penyedia cloudAWS
Ukuran instanst2.xlarge
Jaringansubnet privat
Sistem operasiLinux Ubuntu 20.04 LTS - Focal Fossa
Batas deskriptor file65535
Proses pengguna maksimum65535
+
+
+
+
+ +
+ Konfigurasi Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Versi Polygon EdgeCommit 8377162281d1a2e4342ae27cd4e5367c4364aee2 pada pengembangan cabang
Node validator30
Node non-validator0
KonsensusIBFT PoA
Waktu blok2000md
Batas gas blok5242880
+
+
+
+
+ +
+ Konfigurasi Loadbot +
+
+ + + + + + + + + + + + + +
Transaksi Total10000
Transaksi yang dikirim per detik400
Tipe transaksiTransfer EOA ke EOA
+
+
+
+
diff --git a/archive/edge/id-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/id-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..7deb838eff --- /dev/null +++ b/archive/edge/id-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,390 @@ +--- +id: test-2022-03-02 +title: 2 Maret 2022 +description: "Tes kinerja pada 2 Maret." +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### Ringkasan {#summary} + +:::caution +Perlu diperhatikan bahwa kami `loadbot`yang digunakan untuk melakukan tes ini, sekarang sudah selesai. +::: + +Tes ini untuk mengukur transfer token SC ECR20 dan fungsi pencetakan token ERC721 dengan beban berat dan kecepatan transaksi. + +Tujuannya adalah memeriksa apakah semuanya bekerja seperti yang diharapkan selama beban berat. Itu juga menjadi alasan kami mengenalkan metrik gas di keluaran loadbot yang menunjukkan apakah blok diisi transaksi dengan benar. + +Semua transaksi dikirim ke node tunggal melalui API GRPC dan tanda terima diterima melalui API JSON-RPC. Setelah semua transaksi dilakukan, informasi gas dibaca dari setiap blok menggunakan metode eth_getBlockByNumber JSON-RPC. + +Tujuan kami bukan untuk berusaha menjangkau TPS semaksimal mungkin, +karena batas gas blok dan waktu blok diatur ke nilai wajar yang tidak mengonsumsi banyak sumber daya sistem dan akan memungkinkan ini dijalankan pada perangkat keras komoditas. + +### Hasil ERC20 {#results-erc20} + +| Metrik | Nilai | +| ------ | ----- | +| Jenis transaksi | ERC20 | +| Transaksi per detik | 65 | +| Transaksi gagal | 0 | +| Transaksi berhasil | 5000 | +| Waktu operasi transaksi ERC20 | 76,681690d | +| Waktu Sebar SC | 4,048250d | + +### Hasil ERC721 {#results-erc721} + +| Metrik | Nilai | +| ------ | ----- | +| Jenis transaksi | ERC721 | +| Transaksi per detik | 20 | +| Transaksi gagal | 0 | +| Transaksi berhasil | 2000 | +| Waktu operasi transaksi ERC721 | 97,239920d | +| Waktu Sebar SC | 3,048970d | + +### Lingkungan ERC20 {#environment-erc20} + +
+ Konfigurasi Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Penyedia cloudAWS
Ukuran instanst2.micro
Jaringansubnet privat
Sistem operasiLinux Ubuntu 20.04 LTS - Focal Fossa
Batas deskriptor file65535
Proses pengguna maksimum65535
+
+
+
+
+ +
+ Konfigurasi Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versi Polygon EdgeCommit 8a033aa1afb191abdac04636d318f83f32511f3c pada pengembangan cabang
Node validator6
Node non-validator0
KonsensusIBFT PoA
Waktu blok2d
Batas gas blok5242880
Rata-rata utilitas blok95%
+
+
+
+
+ +
+ Konfigurasi Loadbot +
+
+ + + + + + + + + + + + + +
Transaksi Total5000
Transaksi yang dikirim per detik200
Jenis transaksiTransfer ERC20 ke ERC20
+
+
+
+
+ +
+ Log loadbot + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### Lingkungan ERC721 {#environment-erc721} + +
+ Konfigurasi Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Penyedia cloudAWS
Ukuran instanst2.micro
Jaringansubnet privat
Sistem operasiLinux Ubuntu 20.04 LTS - Focal Fossa
Batas deskriptor file65535
Proses pengguna maksimum65535
+
+
+
+
+ +
+ Konfigurasi Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versi Polygon EdgeCommit 8a033aa1afb191abdac04636d318f83f32511f3c pada pengembangan cabang
Node validator6
Node non-validator0
KonsensusIBFT PoA
Waktu blok2d
Batas gas blok5242880
Rata-rata utilitas blok94
+
+
+
+
+ +
+ Konfigurasi Loadbot +
+
+ + + + + + + + + + + + + +
Transaksi Total2000
Transaksi yang dikirim per detik200
Jenis transaksiPembuatan token ERC721
+
+
+
+
+ +
+ Log loadbot + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/id-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/id-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..4fa0d009d9 --- /dev/null +++ b/archive/edge/id-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,960 @@ +--- +id: test-2022-03-23 +title: 23 Maret 2022 +description: "Tes kinerja dari tanggal 23 Maret." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### Ringkasan {#summary} + +:::caution +Perlu diperhatikan bahwa kami `loadbot`yang digunakan untuk melakukan tes ini, sekarang sudah selesai. +::: + +Tes ini dilakukan untuk menilai transfer token SC ERC20, pembuatan token SC ERC721, dan fungsionalitas transaksi EOA ke EOA dengan beban berat dan kecepatan transaksi pada node dengan sumber daya perangkat keras yang lebih tinggi. + +Tujuannya adalah memeriksa apakah semuanya bekerja seperti yang diharapkan selama beban berat. Itu juga alasan kami memperkenalkan metrik gas dalam keluaran loadbot yang menunjukkan kepada kita apakah blok sudah terisi transaksi dengan benar. + +Semua transaksi dikirim ke node tunggal melalui API GRP dan tanda terima diterima melalui API JSON-RPC. Setelah semua transaksi dilakukan, informasi gas dibaca dari setiap blok menggunakan metode eth_getBlockByNumber JSON-RPC. + +Tujuan kami adalah menjangkau TPS semaksimum mungkin pada sumber daya perangkat keras yang tersedia. +Untuk mencapai hal ini, kita telah memodifikasi batas gas blok dan parameter waktu blok untuk memberikan hasil tps yang sebaik mungkin serta menjaga integritas dan stabilitas. sistem. + +:::info Batas Gas Blok + +Batas gas blok dapat meningkat menjadi jumlah yang relatif tinggi jika transaksi menggunakan banyak gas untuk dieksekusi. +Dalam contoh yang ditunjukkan di bawah, pembuatan token ERC721 bekerja jauh lebih cepat dengan batas gas blok yang diatur menjadi 80.000.000 (bukan 20 Juta), tetapi transfer token ERC20 dengan batas gas blok 80 Juta akan membuat server rusak. + +::: + +:::info Lingkungan Produksi + +Ketika mengonfigurasi lingkungan produksi, Anda perlu berhati-hati jika Anda berusaha mencapai kinerja tinggi rantai tersebut. +Jika parameter batas gas blok diatur ke nilai tinggi, waktu blok diatur ke 1d, dan ada beban transaksi tinggi pada node tunggal node, node itu akan mengonsumsi banyak (jika tidak semua tersedia) RAM dan dapat menyebabkan kerusakan server. +Gunakan loadbot untuk menguji semua secara menyeluruh, memantau penggunaan sumber daya sistem, dan mengatur parameter konfigurasi dengan benar. + +::: + +:::info Galat Kehabisan Memori + +Beberapa distro linux akan secara otomatis menghentikan proses yang memiliki penggunaan RAM sangat tinggi (error OOM) untuk menjaga stabilitas sistem. +Keluaran log error OOM ini terlihat seperti di bawah ini. +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### Hasil transfer EOA ke EOA {#results-of-eoa-to-eoa-transfers} +| Metrik | Nilai | +| ------ | ----- | +| Jenis transaksi | EOA ke EOA | +| Transaksi per detik | 689 | +| Transaksi gagal | 0 | +| Transaksi berhasil | 20.000 | +| Total blok yang digunakan | 25 | +| Total waktu operasi | 29,921110d | + +### Hasil transfer token ERC20 {#results-of-erc20-token-transfers} + +| Metrik | Nilai | +| ------ | ----- | +| Jenis transaksi | ERC20 | +| Transaksi per detik | 500 | +| Transaksi gagal | 0 | +| Transaksi berhasil | 20.000 | +| Total blok yang digunakan | 33 | +| Waktu operasi transaksi ERC20 | 40,402900d | +| Waktu Sebar SC | 2,004140d | + +### Hasil pencetakan token ERC721 {#results-of-erc721-token-minting} + +| Metrik | Nilai | +| ------ | ----- | +| Jenis transaksi | ERC721 | +| Transaksi per detik | 157 | +| Transaksi gagal | 0 | +| Transaksi berhasil | 20.000 | +| Total blok yang digunakan | 124 | +| Waktu operasi transaksi ERC721 | 127,537340d | +| Waktu Sebar SC | 2,004420d | + + +### Hasil pencetakan token ERC721 dengan batas gas blok sangat tinggi (80 Juta) {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| Metrik | Nilai | +| ------ | ----- | +| Jenis transaksi | ERC721 | +| Transaksi per detik | 487 | +| Transaksi gagal | 0 | +| Transaksi berhasil | 20.000 | +| Total blok yang digunakan | 34 | +| Waktu operasi transaksi ERC721 | 41,098410d | +| Waktu Sebar SC | 2,004300d | + + +### Lingkungan EOA ke EOA {#environment-eoa-to-eoa} +
+ Konfigurasi Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Penyedia cloudAWS
Ukuran instansc5.2xlarge
Jaringansubnet privat
Sistem operasiAmazon Linux 2 AMI (HVM) - Kernel 5.10
Batas deskriptor file65535
Proses pengguna maksimum65535
+
+
+
+
+ +
+ Konfigurasi Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versi Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 pada pengembangan cabang
Node validator4
Node non-validator0
KonsensusIBFT PoA
Waktu blok1d
Batas gas blok20000000
Slot maksimum1.000.000
Penggunaan blok rata-rata84,00%
+
+
+
+
+ +
+ Konfigurasi Loadbot +
+
+ + + + + + + + + + + + + +
Total Transaksi20.000
Transaksi yang dikirim per detik689
Jenis transaksiTransfer EOA ke EOA
+
+
+
+
+ +
+ Log loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### Lingkungan ERC20 {#environment-erc20} +
+ Konfigurasi Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Penyedia cloudAWS
Ukuran instansc5.2xlarge
Jaringansubnet privat
Sistem operasiAmazon Linux 2 AMI (HVM) - Kernel 5.10
Batas deskriptor file65535
Proses pengguna maksimum65535
+
+
+
+
+ +
+ Konfigurasi Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versi Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 pada pengembangan cabang
Node validator4
Node non-validator0
KonsensusIBFT PoA
Waktu blok1d
Batas gas blok20000000
Slot maksimum1.000.000
Penggunaan blok rata-rata88,38%
+
+
+
+
+ +
+ Konfigurasi Loadbot +
+
+ + + + + + + + + + + + + +
Total Transaksi20.000
Transaksi yang dikirim per detik500
Jenis transaksiTransfer ERC20 ke ERC20
+
+
+
+
+ +
+ Log loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### Lingkungan ERC721 {#environment-erc721} +
+ Konfigurasi Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Penyedia cloudAWS
Ukuran instansc5.2xlarge
Jaringansubnet privat
Sistem operasiAmazon Linux 2 AMI (HVM) - Kernel 5.10
Batas deskriptor file65535
Proses pengguna maksimum65535
+
+
+
+
+ +
+ Konfigurasi Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versi Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 pada pengembangan cabang
Node validator4
Node non-validator0
KonsensusIBFT PoA
Waktu blok1d
Batas gas blok20000000
Slot maksimum1.000.000
Penggunaan blok rata-rata92,90%
+
+
+
+
+ +
+ Konfigurasi Loadbot +
+
+ + + + + + + + + + + + + +
Total Transaksi20.000
Transaksi yang dikirim per detik157
Jenis transaksiPembuatan token ERC721
+
+
+
+
+ +
+ Log loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### Lingkungan ERC20 - batas gas blok yang sangat tinggi {#environment-erc20-very-high-block-gas-limit} +
+ Konfigurasi Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Penyedia cloudAWS
Ukuran instansc5.2xlarge
Jaringansubnet privat
Sistem operasiAmazon Linux 2 AMI (HVM) - Kernel 5.10
Batas deskriptor file65535
Proses pengguna maksimum65535
+
+
+
+
+ +
+ Konfigurasi Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versi Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 pada pengembangan cabang
Node validator4
Node non-validator0
KonsensusIBFT PoA
Waktu blok1d
Batas gas blok80000000
Slot maksimum1.000.000
Penggunaan blok rata-rata---
+
+
+
+
+ +
+ Konfigurasi Loadbot +
+
+ + + + + + + + + + + + + +
Total Transaksi20.000
Transaksi yang dikirim per detik---
Jenis transaksiTransfer ERC20 ke ERC20
+
+
+
+
+ +
+ Log error OOM + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### Lingkungan ERC721 - batas gas blok yang sangat tinggi {#environment-erc721-very-high-block-gas-limit} +
+ Konfigurasi Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Penyedia cloudAWS
Ukuran instansc5.2xlarge
Jaringansubnet privat
Sistem operasiAmazon Linux 2 AMI (HVM) - Kernel 5.10
Batas deskriptor file65535
Proses pengguna maksimum65535
+
+
+
+
+ +
+ Konfigurasi Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versi Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 pada pengembangan cabang
Node validator4
Node non-validator0
KonsensusIBFT PoA
Waktu blok1d
Batas gas blok80000000
Slot maksimum1.000.000
Penggunaan blok rata-rata84,68%
+
+
+
+
+ +
+ Konfigurasi Loadbot +
+
+ + + + + + + + + + + + + +
Total Transaksi20.000
Transaksi yang dikirim per detik487
Jenis transaksiPembuatan token ERC721
+
+
+
+
+ +
+ Log loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/id-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/id-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..aed8f72be4 --- /dev/null +++ b/archive/edge/id-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,568 @@ +--- +id: test-2022-07-04 +title: 4 Juli 2022 +description: "Uji performa dari 4 Juli." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### Ringkasan {#summary} + +:::caution +Perlu diperhatikan bahwa kami `loadbot`yang digunakan untuk melakukan tes ini, sekarang sudah selesai. +::: + +Tes ini dilakukan untuk menilai transfer token SC ERC20, pembuatan token SC ERC721, dan fungsionalitas transaksi EOA ke EOA dengan beban berat dan kecepatan transaksi pada node dengan sumber daya perangkat keras yang lebih tinggi. + +Tujuannya adalah memeriksa apakah semuanya bekerja seperti yang diharapkan selama beban berat. Itu juga alasan kami memperkenalkan metrik gas dalam keluaran loadbot yang menunjukkan kepada kita apakah blok sudah terisi transaksi dengan benar. + +Semua transaksi dikirim ke node tunggal melalui API GRP dan tanda terima diterima melalui API JSON-RPC. Setelah semua transaksi dilakukan, informasi gas dibaca dari setiap blok menggunakan metode eth_getBlockByNumber JSON-RPC. + +Tujuan kami adalah menjangkau TPS semaksimum mungkin pada sumber daya perangkat keras yang tersedia. +Untuk itu, kami telah memodifikasi batas gas blok dan parameter waktu blok guna memberikan hasil tps sebaik mungkin serta menjaga integritas dan stabilitas. sistem. + + +:::info Lingkungan Produksi + +Ketika mengonfigurasi lingkungan produksi, Anda perlu berhati-hati jika Anda berusaha mencapai kinerja tinggi rantai tersebut. +Jika parameter batas gas blok diatur ke nilai tinggi, waktu blok diatur ke 1d, dan ada beban transaksi tinggi pada node tunggal node, node itu akan mengonsumsi banyak (jika tidak semua tersedia) RAM dan dapat menyebabkan kerusakan server. +Gunakan loadbot untuk menguji semua secara menyeluruh, memantau penggunaan sumber daya sistem, dan mengatur parameter konfigurasi dengan benar. + +::: + + + +### Hasil transfer EOA ke EOA {#results-of-eoa-to-eoa-transfers} +| Metrik | Nilai | +| ------ | ----- | +| Jenis transaksi | EOA ke EOA | +| Transaksi per detik | 1428 | +| Transaksi gagal | 0 | +| Transaksi berhasil | 30000 | +| Total blok yang digunakan | 15 | +| Total waktu eksekusi | 21,374620d | + +### Hasil transfer token ERC20 {#results-of-erc20-token-transfers} + +| Metrik | Nilai | +| ------ | ----- | +| Jenis transaksi | ERC20 | +| Transaksi per detik | 1111 | +| Transaksi gagal | 0 | +| Transaksi berhasil | 50000 | +| Total blok yang digunakan | 38 | +| Waktu operasi transaksi ERC20 | 45,906450d | +| Waktu Sebar SC | 2,006580d | + +### Hasil pembuatan token ERC721 {#results-of-erc721-token-minting} + +| Metrik | Nilai | +| ------ | ----- | +| Jenis transaksi | ERC721 | +| Transaksi per detik | 714 | +| Transaksi gagal | 0 | +| Transaksi berhasil | 30000 | +| Total blok yang digunakan | 39 | +| Waktu operasi transaksi ERC721 | 42,864140d | +| Waktu Sebar SC | 2,005500d | + + + + +### Lingkungan EOA ke EOA {#environment-eoa-to-eoa} +
+ Konfigurasi Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Penyedia cloudAWS EC2
Ukuran instansc6a.48xlarge
Jaringansubnet privat
Sistem operasiLinux Ubuntu 20.04 LTS - Focal Fossa
Batas deskriptor file65535
Proses pengguna maksimum65535
+
+
+
+
+ +
+ Konfigurasi Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versi Polygon EdgeRilis v0.4.1
Node validator4
Node non-validator0
KonsensusIBFT PoA
Waktu blok1d
Batas gas blok70778880
Slot maksimum276.480
Penggunaan blok rata-rata59,34%
+
+
+
+
+ +
+ Konfigurasi Loadbot +
+
+ + + + + + + + + + + + + +
Total Transaksi30000
Transaksi yang dikirim per detik1428
Tipe transaksiTransfer EOA ke EOA
+
+
+
+
+ +
+ Log loadbot + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### Lingkungan ERC20 {#environment-erc20} +
+ Konfigurasi Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Penyedia cloudAWS EC2
Ukuran instansc6a.48xlarge
Jaringansubnet privat
Sistem operasiLinux Ubuntu 20.04 LTS - Focal Fossa
Batas deskriptor file65535
Proses pengguna maksimum65535
+
+
+
+
+ +
+ Konfigurasi Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versi Polygon EdgeRilis v0.4.1
Node validator4
Node non-validator0
KonsensusIBFT PoA
Waktu blok1d
Batas gas blok47185920
Slot maksimal184.320
Penggunaan blok rata-rata81,29%
+
+
+
+
+ +
+ Konfigurasi Loadbot +
+
+ + + + + + + + + + + + + +
Total Transaksi50000
Transaksi yang dikirim per detik1111
Jenis transaksiTransfer ERC20 ke ERC20
+
+
+
+
+ +
+ Log loadbot + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### Lingkungan ERC721 {#environment-erc721} +
+ Konfigurasi Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Penyedia cloudAWS EC2
Ukuran instansc6a.48xlarge
Jaringansubnet privat
Sistem operasiLinux Ubuntu 20.04 LTS - Focal Fossa
Batas deskriptor file65535
Proses pengguna maksimum65535
+
+
+
+
+ +
+ Konfigurasi Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versi Polygon EdgeRilis v0.4.1
Node validator4
Node non-validator0
KonsensusIBFT PoA
Waktu blok1d
Batas gas blok94371840
Slot maksimal1.000.000
Penggunaan blok rata-rata93,88%
+
+
+
+
+ +
+ Konfigurasi Loadbot +
+
+ + + + + + + + + + + + + +
Total Transaksi30000
Transaksi yang dikirim per detik714
Jenis transaksiPembuatan token ERC721
+
+
+
+
+ +
+ Log loadbot + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/id-edge/troubleshooting.md b/archive/edge/id-edge/troubleshooting.md new file mode 100644 index 0000000000..391218ea91 --- /dev/null +++ b/archive/edge/id-edge/troubleshooting.md @@ -0,0 +1,70 @@ +--- +id: troubleshooting +title: Penyelesaian masalah +description: "Bagian penyelesaian masalah untuk Polygon Edge" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# Penyelesaian masalah {#troubleshooting} + +## Error `method=eth_call err="invalid signature"` {#error} + +Ketika menggunakan dompet untuk membuat transaksi Polygon Edge, pastikan pengaturan jaringan lokal dompet: + +1. `chainID` adalah yang benar. `chainID` default untuk Edge adalah `100`, tetapi ini dapat dikustomisasi menggunakan bendera genesis `--chain-id`. + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. Di "URL RPC", pastikan bidang menggunakan port RPC JSON dari node yang dihubungi. + + +## Cara mendapatkan URL Websocket {#how-to-get-a-websocket-url} + +Ketika Anda menjalankan Polygon Edge secara default, itu mengekspos titik akhir WebSocket berdasarkan lokasi rantai. +Skema URL `wss://` digunakan untuk tautan HTTPS dan `ws://` untuk HTTP. + +URL WebSocket Localhost: +````bash +ws://:/ws +```` +Perlu diperhatikan bahwa nomor port tergantung pada port JSON-RPC yang dipilih untuk node tersebut. + +URL WebSocket Edgenet: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## Error `insufficient funds` ketika mencoba menyebar kontrak {#error-when-trying-to-deploy-a-contract} + +Jika mendapatkan error ini, pastikan Anda memiliki dana yang cukup pada alamat yang diinginkan dan alamat yang digunakan sudah benar.
+Untuk menentukan saldo pratambang, Anda dapat menggunakan bendera genesis `genesis [--premine ADDRESS:VALUE]` sambil menghasilkan file genesis. +Contoh penggunaan bendera ini: +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +Pratambang 1000000000000000000000 WEI ini ke 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862. + + +## Token ERC20 tidak dirilis ketika menggunakan Chainbridge {#erc20-tokens-not-released-while-using-chainbridge} + +Jika Anda ingin mentransfer token ERC20 antara Polygon POS dan jaringan Edge lokal, token ERC20 didepositkan, dan proposal dieksekusi di relayer, tetapi token tidak dirilis di jaringan Edge, pastikan Handler ERC20 di Polygon Edge memiliki token yang cukup untuk dirilis.
+Kontrak Handler di rantai tujuan harus memiliki token yang cukup untuk dilepas untuk mode lock-release. Jika tidak memiliki token ERC20 apa pun di Handler ERC20 dari jaringan Edge lokal, cetak token baru dan transfer ke Handler ERC20. + +## `Incorrect fee supplied`error ketika menggunakan Chainbridge {#error-when-using-chainbridge} + +Anda mungkin mendapatkan error ini ketika mencoba mentransfer token ERC20 antara rantai POS Polygon Mumbai dan pengaturan Polygon Edge Polygon lokal. Error ini muncul ketika Anda mengatur biaya ketika menyebarkan menggunakan `--fee` bendera, tetapi Anda tidak mengatur nilai yang sama di transaksi setor. Anda dapat menggunakan perintah di bawah untuk mengubah biaya: +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +Anda dapat menemukan informasi lebih lanjut tentang bendera ini [di sini](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md). + + + + + diff --git a/archive/edge/id-edge/validator-hosting.md b/archive/edge/id-edge/validator-hosting.md new file mode 100644 index 0000000000..af26de109b --- /dev/null +++ b/archive/edge/id-edge/validator-hosting.md @@ -0,0 +1,264 @@ +--- +id: validator-hosting +title: Hosting Validator +description: "Persyaratan hosting untuk Polygon Edge" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +Di bawah ini adalah saran untuk mengehos node validasi dengan baik di jaringan Polygon Edge. Harap perhatikan semua item yang tercantum di bawah ini dengan saksama untuk memastikan +bahwa pengaturan validator dikonfigurasi dengan benar agar aman, stabil, dan berfungsi dengan baik. + +## Dasar pengetahuan {#knowledge-base} + +Sebelum mencoba menjalankan node validasi, baca dokumen ini sampai selesai dengan cermat. +Dokumen tambahan yang mungkin membantu adalah: + +- [Instalasi](get-started/installation) +- [Pengaturan cloud](get-started/set-up-ibft-on-the-cloud) +- [Perintah CLI](get-started/cli-commands) +- [File konfigurasi server](configuration/sample-config) +- [Kunci privat](configuration/manage-private-keys) +- [Metrik Prometheus](configuration/prometheus-metrics) +- [Pengelola rahasia](/docs/category/secret-managers) +- [Cadangan/Pemulihan](working-with-node/backup-restore) + +## Persyaratan sistem minimum {#minimum-system-requirements} + +| Tipe | Nilai | Dipengaruhi oleh | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 2 core |
  • Jumlah kueri JSON-RPC
  • Ukuran kondisi blockchain
  • Batas gas blok
  • Waktu blok
| +| RAM | 2 GB |
  • Jumlah kueri JSON-RPC
  • Ukuran kondisi blockchain
  • Batas gas blok
| +| Diska |
  • Partisi root 10 GB
  • Partisi root 30 GB dengan LVM untuk ekstensi diska
|
  • Ukuran kondisi blockchain
| + + +## Konfigurasi layanan {#service-configuration} + +Biner `polygon-edge` harus dijalankan sebagai layanan sistem secara otomatis pada konektivitas jaringan yang telah ditetapkan dan memiliki fungsi mulai / berhenti / +mulai ulang. Sebaiknya, gunakan manajer layanan seperti `systemd.` + +Contoh file konfigurasi sistem `systemd`: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### Biner {#binary} + +Dalam beban kerja produksi, biner `polygon-edge` harus boleh disebarkan dari biner rilis GitHub pre-built - bukan mengompilasi secara manual. +:::info + +Dengan melakukan kompilasi cabang GitHub `develop` secara manual, Anda dapat memperkenalkan perubahan yang dapat menyebabkan kerusakan pada lingkungan Anda. +Untuk itu, sebaiknya sbarkan biner Polygon Edge hanya dari rilisnya, karena akan mengandung +informasi tentang perubahan yang dapat menyebabkan kerusakan dan cara mengatasinya. + +::: + +Silakan lihat [Instalasi](/docs/edge/get-started/installation) untuk mendapatkan ikhtisar lengkap tentang metode instalasi. + +### Penyimpanan data {#data-storage} + +Folder `data/` yang berisi seluruh kondisi blockchain harus dimuat pada diska/volume khusus yang memungkinkan untuk +pencadangan diska otomatis, perluasan volume, dan opsi pemuatan diska/volume ke instans yang lain jika terjadi kegagalan. + + +### File log {#log-files} + +File log harus dirotasi setiap hari (dengan alat seperti `logrotate`). +:::warning + +Jika dikonfigurasi tanpa rotasi log, maka file log dapat menggunakan semua ruang diska yang tersedia dan dapat mengganggu waktu aktif validator. + +::: + +Contoh konfigurasi `logrotate`: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +Silakan lihat bagian [Pembuatan Log](#logging) di bawah ini untuk saran tentang penyimpanan log. + +### Dependensi tambahan {#additional-dependencies} + +`polygon-edge` dikompilasi secara statis dan tidak memerlukan dependensi OS host tambahan. + +## Pemeliharaan {#maintenance} + +Di bawah ini adalah praktik terbaik untuk melakukan pemeliharaan node validator aktif di jaringan Polygon Edge. + +### Cadangan {#backup} + +Ada dua jenis prosedur pencadangan yang direkomendasikan untuk node Polygon Edge. + +Anjurannya adalah menggunakan keduanya, jika memungkinkan, dengan cadangan Polygon Edge yang selalu menjadi pilihan yang tersedia. + +* ***Cadangan volume***: + Pencadangan tambahan harian volume `data/` node Polygon Edge atau VM lengkap, jika memungkinkan. + + +* ***Pencadangan Polygon Edge***: + Sebaiknya gunakan tugas CRON harian yang melakukan pencadangan Polygon Edge secara reguler dan memindahkan file `.dat` ke lokasi di luar komputer atau ke penyimpanan objek cloud yang aman. + +Idealnya, cadangan Polygon Edge tidak boleh tumpang tindih dengan cadangan volume yang dijelaskan di atas. + +Silakan lihat [Mencadangkan/memulihkan instans node](working-with-node/backup-restore) untuk mendapatkan petunjuk tentang cara melakukan pencadangan Polygon Edge. + +### Pembuatan Log {#logging} + +Log yang dihasilkan oleh node Polygon Edge harus: +- dikirim ke penyimpanan data eksternal dengan kemampuan pengindeksan dan pencarian +- memiliki periode penyimpanan log selama 30 hari + +Jika ini kali pertama Anda menyiapkan validator Polygon Edge, sebaiknya mulai node +dengan opsi `--log-level=DEBUG` untuk dapat melakukan debug dengan cepat atas setiap masalah yang mungkin dihadapi. + +:::info + +`--log-level=DEBUG` akan membuat keluaran log node ini seringkas mungkin. +Log debug akan secara drastis meningkatkan ukuran file log yang harus dipertimbangkan ketika menyiapkan +solusi rotasi log. + +::: +### Patch keamanan OS {#os-security-patches} + +Administrator harus memastikan bahwa instans validator OS selalu diperbarui dengan patch terbaru setidaknya sekali setiap bulan. + +## Metrik {#metrics} + +### Metrik sistem {#system-metrics} + +Administrator harus menyiapkan semacam monitor metrik sistem (misalnya Telegraf + InfluxDB + Grafana atau SaaS pihak ke-3). + +Metrik yang perlu dipantau dan memiliki pengaturan pemberitahuan peringatan: + +| Nama Metrik | Ambang alarm | +|-----------------------|-------------------------------| +| Penggunaan CPU (%) | > 90% untuk lebih dari 5 menit | +| Pemanfaatan RAM (%) | > 90% untuk lebih dari 5 menit | +| Pemanfaatan diska root | > 90% | +| Pemanfaatan diska data | > 90% | + +### Metrik Validator {#validator-metrics} + +Administrator harus menyiapkan koleksi metrik dari API Prometheus Polygon Edge agar dapat +memantau performa blockchain. + +Silakan lihat [metrik Prometheus](configuration/prometheus-metrics) untuk memahami metrik mana yang sedang diekspos dan cara untuk menyiapkan koleksi metrik Prometheus. + + +Perhatian ekstra harus diberikan pada metrik berikut: +- ***Waktu produksi blok*** - Jika waktu produksi blok lebih tinggi dari biasanya, ada kemungkinan terjadi masalah dengan jaringan +- ***Jumlah putaran konsensus*** - jika ada lebih dari 1 putaran, ada kemungkinan masalah dengan validator yang ditetapkan pada jaringan +- ***Jumlah peer*** - jika jumlah peer menurun, artinya ada masalah konektivitas dalam jaringan + +## Keamanan {#security} + +Di bawah ini adalah praktik terbaik untuk mengamankan node validator aktif d jaringan Polygon Edge. + +### Layanan API {#api-services} + +- ***JSON-RPC*** +Hanya layanan API yang perlu diekspos ke publik (via penyeimbang beban atau secara langsung). +API ini harus beroperasi di semua antarmuka atau pada alamat IP tertentu (contoh: `--json-rpc 0.0.0.0:8545` atau `--json-prc 192.168.1.1:8545` ). +:::info + +Karena ini API yang berhadapan dengan publik, sebaiknya Anda memiliki penyeimbang beban/proxy balik di depannya untuk memberikan keamanan dan pembatasan tarif. + +::: + + +- ***LibP2P*** - +Ini adalah API jaringan yang digunakan oleh node untuk komunikasi peer. API ini harus dijalankan di semua antarmuka atau alamat IP tertentu +(`--libp2p 0.0.0.0:1478` atau `--libp2p 192.168.1.1:1478`). API tidak boleh diekspos secara publik, +tapi harus dapat dicapai dari semua node lainnya. +:::info + +Jika dijalankan di localhost (`--libp2p 127.0.0.1:1478`), node lainnya tidak akan dapat terhubung. + +::: + + +- ***GRPC*** - +API ini hanya untuk menjalankan perintah operator dan mencatat perintah yang lain. Karena itulah, API ini harus dijalankan hanya di localhost (`--grpc-address 127.0.0.1:9632`). + +### Rahasia Polygon Edge {#polygon-edge-secrets} + +Rahasia Polygon Edge (kunci `ibft` dan kunci `libp2p`) tidak boleh disimpan di sistem file lokal. +Sebaliknya, [Pengelola Rahasia](configuration/secret-managers/set-up-aws-ssm) yang didukung harus digunakan. +Menyimpan rahasia ke sistem file lokal harus boleh digunakan di lingkungan nonproduksi. + +## Pemutakhiran {#update} + +Berikut adalah prosedur pemutakhiran yang diinginkan untuk node validasi, yang dijelaskan dengan petunjuk langkah demi langkah. + +### Prosedur pemutakhiran {#update-procedure} + +- Unduh biner Polygon Edge terbaru dari [rilis](https://github.com/0xPolygon/polygon-edge/releases) GitHub resmi +- Hentikan layanan Polygon Edge (contoh: `sudo systemctl stop polygon-edge.service`) +- Ganti biner `polygon-edge` yang ada dengan biner yang telah diunduh (contoh: `sudo mv polygon-edge /usr/local/bin/`) +- Periksa apakah versi `polygon-edge` yang benar sudah ada dengan menjalankan `polygon-edge version` - harus sesuai dengan versi rilis +- Periksa dokumentasi rilis jika ada langkah kompatibilitas mundur yang perlu dilakukan sebelum memulai layanan `polygon-edge` +- Mulai layanan `polygon-edge` (contoh: `sudo systemctl start polygon-edge.service`) +- Terakhir, periksa keluaran log `polygon-edge` dan pastikan semuanya berjalan tanpa log `[ERROR]` + +:::warning + +Ketika ada rilis yang dapat menyebabkan terjadinya kegagalan, prosedur pemutakhiran ini harus dilakukan di semua node +biner yang berjalan saat ini tidak kompatibel dengan rilis yang baru. + +Ini berarti bahwa rantai harus dihentikan selama periode waktu singkat (hingga biner `polygon-edge` diganti dan layanan dimulai) +jadi, rencanakan sesuai dengan itu. + +Anda dapat menggunakan alat seperti **[Ansible](https://www.ansible.com/)** atau beberapa skrip kustom untuk melakukan pemutakhiran secara efisien +dan meminimalkan waktu downtime rantai. +::: + +## Prosedur memulai {#startup-procedure} + +Berikut ini aliran prosedur memulai yang dikehendaki untuk validator Polygon Edge + +- Baca dokumen yang tercantum dalam bagian [Dasar Pengetahuan](#knowledge-base) +- Terapkan patch OS terbaru pada node validator +- Unduh biner `polygon-edge` terbaru dari [rilis](https://github.com/0xPolygon/polygon-edge/releases) GitHub resmi dan letakkan di instans lokal `PATH` +- Inisialisasi salah satu [pengelola rahasia](/docs/category/secret-managers) yang didukung menggunakan perintah CLI `polygon-edge secrets generate` +- Buat dan simpan rahasia menggunakan [perintah CLI](/docs/edge/get-started/cli-commands#secrets-init-flags) `polygon-edge secrets init` +- Catat nilai `NodeID` dan `Public key (address)` +- Buat file `genesis.json` seperti yang dijelaskan dalam [pengaturan cloud](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators) menggunakan [perintah CLI](/docs/edge/get-started/cli-commands#genesis-flags) `polygon-edge genesis` +- Buat file konfigurasi default menggunakan [perintah CLI](/docs/edge/configuration/sample-config) `polygon-edge server export` +- Edit file `default-config.yaml` untuk mengakomodasi lingkungan node validator lokal (file patch, dll.) +- Buat layanan Polygon Edge (`systemd` atau yang serupa) karena biner `polygon-edge` akan menjalankan server dari file `default-config.yaml` +- Mulai server Polygon Edge dengan memulai layanan (contoh: `systemctl start polygon-edge`) +- Periksa keluaran log `polygon-edge` dan pastikan blok sudah dihasilkan serta tidak ada log `[ERROR]` +- Periksa fungsi rantai dengan memanggil metode JSON-RPC seperti [`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid) diff --git a/archive/edge/id-edge/working-with-node/backup-restore.md b/archive/edge/id-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..6793b4ab5d --- /dev/null +++ b/archive/edge/id-edge/working-with-node/backup-restore.md @@ -0,0 +1,93 @@ +--- +id: backup-restore +title: Instans node pencadangan/pemulihan +description: "Cara mencadangkan dan memulihkan instans node Polygon Edge." +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## Ikhtisar {#overview} + +Panduan ini memberi perincian tentang cara mencadangkan dan memulihkan instans node Polygon Edge. +Ini mencakup folder dasar dan isinya, juga file mana yang penting untuk melakukan pencadangan dan pemulihan yang berhasil. + +## Folder dasar {#base-folders} + +Polygon Edge memanfaatkan LevelDB sebagai mesin penyimpanan. +Saat memulai node Polygon Edge, subfolder berikut dibuat di direktori kerja yang ditetapkan: +* **blockchain** - Menyimpan data blockchain +* **trie** - Menyimpan pohon Merkle (data kondisi dunia) +* **keystore** - Menyimpan kunci privat untuk klien. Ini termasuk kunci privat libp2p dan kunci privat sealing/validator +* **consensus** - Menyimpan segala informasi konsensus yang mungkin dibutuhkan klien saat bekerja. Untuk saat ini, konsensus menyimpan *kunci validator privat* dari node + +Folder-folder ini tidak boleh diubah supaya instans Polygon Edge dapat berjalan dengan lancar. + +## Buat cadangan node aktif dan pulihkan untuk node baru {#create-backup-from-a-running-node-and-restore-for-new-node} + +Bagian ini memandu pembuatan data arsip blockchain dalam node aktif dan memulihkannya di instans lain. + +### Cadangan {#backup} + +Perintah `backup` mengambil blok dari node aktif dengan gRPC dan membuat file arsip. Jika `--from` dan `--to` tidak ditentukan di dalam perintah, perintah akan mengambil blok dari awal hingga akhir. + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### Pemulihan {#restore} + +Server mengimpor blok dari arsip di awal saat memulai dengan bendera `--restore`. Pastikan ada kunci untuk setiap node baru. Untuk mencari tahu selengkapnya tentang mengimpor atau membuat kunci, kunjungi [bagian Pengelola Rahasia](/docs/edge/configuration/secret-managers/set-up-aws-ssm). + +```bash +$ polygon-edge server --restore archive.dat +``` + +## Pencadangan/Pemulihan Seluruh Data {#back-up-restore-whole-data} + +Bagian ini memandu pencadangan data termasuk data kondisi dan kunci serta memulihkan ke instans baru. + +### Langkah 1: Hentikan klien yang berjalan {#step-1-stop-the-running-client} + +Karena Polygon Edge menggunakan **LevelDB** untuk penyimpanan data, node harus dihentikan selama durasi pencadangan, +karena **LevelDB** tidak mengizinkan akses bersamaan ke file database. + +Selain itu, Polygon Edge juga melakukan pembersihan data saat menutup. + +Langkah pertama melibatkan penghentian klien yang berjalan (baik melalui manajer layanan maupun mekanisme lain yang mengirim sinyal SIGINT ke proses itu), +agar dapat memicu 2 kejadian sekaligus mematikan dengan mulus: +* Menjalankan pembersihan data pada disk +* Melepas kunci file DB oleh LevelDB + +### Langkah 2: Mencadangkan direktori {#step-2-backup-the-directory} + +Setelah klien tidak lagi berjalan, direktori data dapat dicadangkan ke media lain. +Ingatlah bahwa file dengan ekstensi `.key` memuat kunci privat yang dapat digunakan untuk meniru node saat ini +dan tidak boleh dibagikan kepada pihak ketiga/tidak dikenal. + +:::info + +Cadangkan dan pulihkan file `genesis` yang dibuat secara manual, sehingga node yang dipulihkan akan beroperasi penuh. + +::: + +## Pemulihan {#restore-1} + +### Langkah 1: Hentikan klien yang berjalan {#step-1-stop-the-running-client-1} + +Jika instans apa pun dari Polygon Edge berjalan, ini harus dihentikan supaya langkah 2 berhasil. + +### Langkah 2: Salin direktori data yang dicadangkan ke folder yang diinginkan {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +Setelah klien tidak berjalan, direktori data yang sebelumnya dicadangkan dapat disalin ke folder yang diinginkan. +Selain itu, pulihkan file `genesis` yang disalin sebelumnya. + +### Langkah 3: Jalankan klien Polygon Edge sembari menentukan direktori data yang benar {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +Supaya Polygon Edge dapat menggunakan direktor data yang dipulihkan, saat menjalankan, pengguna harus menentukan jalur ke +direktori. data. Silakan baca bagian [Perintah CLI](/docs/edge/get-started/cli-commands) untuk informasi tentang bendera `data-dir`. diff --git a/archive/edge/id-edge/working-with-node/query-json-rpc.md b/archive/edge/id-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..6615a121b4 --- /dev/null +++ b/archive/edge/id-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,93 @@ +--- +id: query-json-rpc +title: Titik Akhir Kueri JSON RPC +description: "Melakukan kueri data dan memulai rantai dengan akun pratambang." +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## Ikhtisar {#overview} + +Lapisan JSON-RPC dari Polygon Edge menyediakan fungsionalitas agar pengembang dapat berinteraksi secara mudah dengan blockchain +melalui permintaan HTTP. + +Contoh ini mencakup penggunaan peralatan seperti **curl** untuk informasi kueri, serta memulai rantai dengan akun pratambang +dan mengirim transaksi. + +## Langkah 1: Buat file genesis dengan akun pratambang {#step-1-create-a-genesis-file-with-a-premined-account} + +Untuk menghasilkan file genesis, jalankan perintah berikut: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +Bendera **premine** mengatur alamat yang harus disertakan dengan saldo awal dalam file **genesis**.
+Dalam kasus ini, alamat `0x1010101010101010101010101010101010101010` akan memiliki **saldo default** awal +`0xD3C21BCECCEDA1000000`(1 juta token mata uang asli). + +Jika kita ingin menentukan saldo alamat dan saldo dengan `:`, seperti: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +Saldonya dapat berupa nilai `hex` atau `uint256`. + +:::warning Hanya akun pratambang yang memiliki kunci privat! + +Jika Anda membuat akun pratambang dan tidak memiliki kunci privat untuk mengakses akun tersebut, saldo pratambang tidak dapat digunakan + +::: + +## Langkah 2: Mulai Polygon Edge dalam mode pengembang {#step-2-start-the-polygon-edge-in-dev-mode} + +Untuk memulai Polygon Edge dalam mode pengembang yang dijelaskan di bagian [Perintah CLI](/docs/edge/get-started/cli-commands), +jalankan berikut: +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## Langkah 3: Melakukan kueri saldo akun {#step-3-query-the-account-balance} + +Sekarang klien telah aktif dan berjalan dalam mode pengembang. Dengan menggunakan file genesis yang dihasilkan dalam **langkah 1**, kita dapat menggunakan alat seperti +**curl** untuk melakukan kueri saldo akun: +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +Perintah akan memberikan keluaran berikut: +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## Langkah 4: Kirim transaksi transfer {#step-4-send-a-transfer-transaction} + +Karena kita telah mengonfirmasi akun yang ditetapkan sebagai pratambang sudah memiliki saldo yang benar, kita dapat mentransfer beberapa ether: + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/id-edge/working-with-node/query-operator-info.md b/archive/edge/id-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..168a7552d0 --- /dev/null +++ b/archive/edge/id-edge/working-with-node/query-operator-info.md @@ -0,0 +1,85 @@ +--- +id: query-operator-info +title: Informasi operator kueri +description: "Cara melakukan kueri terhadap informasi operator." +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## Prasyarat {#prerequisites} + +Panduan ini mengasumsikan Anda telah melakukan [Penyiapan Lokal](/docs/edge/get-started/set-up-ibft-locally) atau [panduan tentang cara menyiapkan klaster IBFT di cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +Node yang berfungsi dibutuhkan untuk melakukan kueri terhadap informasi operator apa pun. + +Dengan Polygon Edge, operator node memiliki kontrol dan memahami apa yang dilakukan oleh node yang dioperasikan.
+Setiap saat, operator dapat menggunakan lapisan node, yang dibuat berdasarkan gRPC, dan mendapat informasi bermakna - tanpa harus melakukan penyisiran log. + +:::note + +Jika node tidak berjalan pada `127.0.0.1:8545`, Anda harus menambah bendera `--grpc-address ` ke perintah yang terdaftar di dalam dokumen ini. + +::: + +## Informasi peer {#peer-information} + +### Daftar peer {#peers-list} + +Untuk mendapat daftar lengkap peer yang tersambung (termasuk node berjalan), jalankan perintah berikut: +````bash +polygon-edge peers list +```` + +Ini akan memberi daftar alamat libp2p dari peer yang saat ini merupakan klien yang beroperasi. + +### Status peer {#peer-status} + +Untuk status peer tertentu, jalankan: +````bash +polygon-edge peers status --peer-id
+```` +Dengan parameter *address* yang merupakan alamat libp2p dari peer itu. + +## Info IBFT {#ibft-info} + +Umumnya, operator mungkin ingin tahu tentang kondisi node pengoperasian dalam konsensus IBFT. + +Untungnya, Polygon Edge menyediakan cara mudah untuk menemukan informasi ini. + +### Snapshot {#snapshots} + +Menjalankan perintah berikut akan memberi snapshot terbaru. +````bash +polygon-edge ibft snapshot +```` +Untuk melakukan kueri snapshot pada tinggi spesifik (nomor blok), operator dapat menjalankan: +````bash +polygon-edge ibft snapshot --num +```` + +### Kandidat {#candidates} + +Untuk mendapat info terbaru tentang kandidat, operator dapat menjalankan: +````bash +polygon-edge ibft candidates +```` +Perintah ini melakukan kueri pada set terbaru kandidat yang diusulkan, juga kandidat = yang belum disertakan + +### Status {#status} + +Perintah berikut memberi kunci validaor saat ini dari klien yang menjalankan IBFT: +````bash +polygon-edge ibft status +```` + +## Kumpulan transaksi {#transaction-pool} + +Untuk menemukan nomor transaksi saat ini di kumpulan transaksi, operator dapat menjalankan: +````bash +polygon-edge txpool status +```` diff --git a/archive/edge/it-edge/additional-features/blockscout.md b/archive/edge/it-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..39cbabeb0d --- /dev/null +++ b/archive/edge/it-edge/additional-features/blockscout.md @@ -0,0 +1,378 @@ +--- +id: blockscout +title: Blockscout +description: Come impostare un'istanza Blockscout per lavorare con Polygon Edge. +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## Panoramica {#overview} +Questa guida spiega in dettaglio come compilare e implementare un'istanza Blockscout per lavorare con Polygon-Edge. Blockscout ha la propria [documentazione](https://docs.blockscout.com/for-developers/manual-deployment), ma questa guida è composta da istruzioni passo-passo semplici ma dettagliate su come configurare l'istanza di Blockscout. + +## Ambiente {#environment} +* Sistema operativo: Ubuntu Server 20.04 LTS [link di download](https://releases.ubuntu.com/20.04/) con autorizzazioni sudo +* Server Hardware: 8CPU / 16GB RAM / 50GB HDD (LVM) +* Database server: server dedicato con 2 CPU / 4GB RAM / 100GB SSD / PostgreSQL 13.4 + +### DB server {#db-server} +Il requisito per seguire questa guida è quello di avere pronto un database server, e un database e db utente configurati. Questa guida non spiegherà in dettaglio come implementare e configurare il server PostgreSQL. Ci sono molte guide che spiegano come farlo, ad esempio la [DigitalOcean Guide](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart) + +:::info DICHIARAZIONE DI NON RESPONSABILITÀ +Questa guida ha il solo scopo di aiutarti a far funzionare Blockscout su una singola istanza, che comunque non è la configurazione ideale per la produzione. Per la produzione, sarà probabilmente necessario introdurre nell'architettura un reverse proxy, un load balancer e opzioni di scalabilità +::: + +# Procedura di implementazione di Blockscout {#blockscout-deployment-procedure} + +## Parte 1 - Installare le dipendenze {#part-1-install-dependencies} +Prima di iniziare, dobbiamo assicurarci di avere installato tutti i binari da cui dipende Blockscout. + +### Aggiornare e potenziare il sistema {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### Aggiungere il repos Erlang {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### Aggiungere il repos NodeJS {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### Installare Rust {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### Installare la versione richiesta di Erlang {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### Installare la versione richiesta di Elixir {#install-required-version-of-elixir} +La versione di Elixir deve essere `1.13`. Se proviamo ad installare questa versione dal repos ufficiale, `erlang`si aggiornerà a `Erlang/OTP 25`e noi non vogliamo che questo succeda. Per questo motivo dobbiamo installare la versione specifica precompilata `elixir` che possiamo trovare sulla pagina delle versioni rilasciate di GitHub. + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +Ora dobbiamo configurare correttamente `exlixir` i binari di sistema. +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +Controllare che `elixir` e `erlang`siano installati correttamente eseguendo `elixir -v`. L'output dovrebbe essere questo: +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning +La versione di `Erlang/OTP`deve essere `24`, e quella di `Elixir` deve essere `1.13.*`. In caso contrario, avrai problemi con la compilazione di Blockscout e/o con la sua esecuzione. +::: +:::info +Controllare la ***[pagina ufficiale dei requisiti di Blockscout](https://docs.blockscout.com/for-developers/information-and-settings/requirements)*** +::: + +### Installare NodeJS {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### Installare Cargo {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### Installare le altre dipendenze {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### Installare facoltativamente il client postgresql per controllare la tua connessione al db {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## Parte 2 - Impostare le variabili ambientali {#part-2-set-environment-variables} +Dobbiamo impostare le variabili ambientali prima di partire con la compilazione di Blockscout. In questa guida imposteremo solo il necessario per farlo funzionare. L'elenco completo delle variabili che possono essere impostate è consultabile [qui](https://docs.blockscout.com/for-developers/information-and-settings/env-variables) + +### Impostare la connessione al database come variabile ambientale {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +Ora testa la tua connessione al DB con il parametri forniti. Poiché hai fornito le variabili ambientali PG, dovresti essere in grado di connetterti al database solo eseguendo: +```bash +psql +``` + +Se il database è configurato correttamente, dovresti vedere un prompt psql: +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +In caso contrario, potresti vedere un errore come questo: +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +In questo caso, [questi documenti](https://ubuntu.com/server/docs/databases-postgresql) potrebbero esserti di aiuto. + +:::info Connessione al DB +Assicurati di aver risolto tutti i problemi di connessione al db prima di procedere alla parte successiva. +È necessario fornire i privilegi di superutente all'utente blockscout. + +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## Parte - Clonare e compilare Blockscout {#part-3-clone-and-compile-blockscout} +Ora possiamo finalmente avviare l'installazione di Blockscout. + +### Clonare il repo di Blockscout {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### Generare la chiave segreta principale per proteggere la produzione {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +All'ultima riga, dovresti vedere una lunga stringa di caratteri casuali. Questa dovrebbe essere impostata come la tua `SECRET_KEY_BASE` variabile ambientale prima del passo successivo. Ad esempio: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### Impostare la modalità di produzione {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### Compilare {#compile} +Cd nella directory del clone e inizia a compilare + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info +Se hai implementato in precedenza, rimuovi gli asset statici dal precedente build ***mix phx.digest.clean*** +::: + +### Migrare i database {#migrate-databases} +:::info +Questa parte non funzionerà se non hai configurato correttamente la tua connessione al DB, se non hai fornito o hai definito i parametri errati alla variabile ambientale DATABASE_URL. L'utente del database deve avere i privilegi di superutente. +::: +```bash +mix do ecto.create, ecto.migrate +``` + +Se è necessario abbandonare prima il database, eseguire +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### Installare le dipendenze npm e compilare i frontend asset {#install-npm-dependencies-and-compile-frontend-assets} +Devi cambiare la directory nella cartella che contiene i frontend asset. + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info Sii paziente +La compilazione di questi asset può richiedere qualche minuto e non mostrerà alcun output. Può sembrare che il processo sia bloccato, ma devi solo essere paziente. Quando il processo di compilazione è completato, dovresti vedere qualcosa come: `webpack 5.69.1 compiled with 3 warnings in 104942 ms` +::: + +### Costruire gli asset statici {#build-static-assets} +Per questo passo devi tornare al root della tua cartella del clone Blockscout. +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### Generare i certificati autofirmati {#generate-self-signed-certificates} +:::info +Puoi saltare questo passo se non utilizzerai `https`. +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## Parte 4 - Creare ed eseguire servizi Blockscout {#part-4-create-and-run-blockscout-service} +In questa parte dobbiamo configurare un sistema di servizi poiché vogliamo che Blockscout continui ad essere in esecuzione in background dopo il riavvio del sistema. + +### Creare i file servizio {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### Modificare i file di servizio {#edit-service-file} +Usa il tuo editor di testo linux preferito per modificare file e configurare il servizio. +```bash +sudo vi /etc/systemd/system/explorer.service +``` +Il contenuto del file explorer.service dovrebbe essere simile a questo: +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### Abilita l'avvio del servizio all'avvio del sistema {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### Sposta la tua cartella clone di Blockscout in una posizione system-wide {#move-your-blockscout-clone-folder-to-system-wide-location} +Il servizio Blockscout deve avere accesso alla cartella che hai clonato dal repo di Blockscout e che ha compilato tutte le risorse. +```bash +sudo mv ~/blockscout /usr/local +``` + +### Creare il file delle variabili ambientali che sarà utilizzato dal servizio Blockscout. {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info +Usa `SECRET_KEY_BASE` che hai generato nella parte 3. +:::Salva il file ed esci. + +### Infine, avvia il servizio Blockscout {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## Parte 5 - Testa la funzionalità della tua istanza Blockscout {#part-5-test-out-the-functionality-of-your-blockscout-instance} +Ora tutto ciò che devi fare è controllare se il servizio Blockscout è in esecuzione. Controllare lo stato del servizio con: +```bash +sudo systemctl status explorer.service +``` + +Per controllare l'output del servizio +```bash +sudo journalctl -u explorer.service -f +``` + +Puoi controllare se ci sono nuove porte in ascolto: +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +Dovresti ottenere una lista di porte in ascolto e nella lista dovresti trovare qualcosa come: +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +Il servizio web Blockscout esegue la porta e il protocollo definito nei file ambientali. In questo esempio viene eseguito su `4000` (http). Se è tutto ok, dovresti essere in grado di accedere al portale web Blockscout con `http://:4000`. + +## Considerazioni {#considerations} +Per ottenere prestazioni ottimali, è consigliabile avere un nodo non validatore dell'archivio `polygon-edge`completo dedicato/locale che sarà utilizzato esclusivamente per le richieste Blockscout. `json-rpc`L'API di questo nodo non deve essere esposto pubblicamente, poiché Blockscout esegue tutte le richieste dal backend. + + +## Considerazioni finali {#final-thoughts} +Abbiamo appena implementato una singola istanza Blockscout, che funziona bene, ma per la produzione dovresti considerare di mettere questa istanza dietro un reverse proxy come Nginx. Dovresti anche fare attenzione al database e alla scalabilità dell'istanza, a seconda del tuo utilizzo. + +Dovresti sicuramente controllare la [documentazione ufficiale Blockscout](https://docs.blockscout.com/) poiché ci sono molte opzioni di personalizzazione. \ No newline at end of file diff --git a/archive/edge/it-edge/additional-features/chainbridge/definitions.md b/archive/edge/it-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..5c42f3ae1f --- /dev/null +++ b/archive/edge/it-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,218 @@ +--- +id: definitions +title: Definizioni generali +description: Definizioni generali per i termini utilizzati nella chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## Relayer {#relayer} +Chainbridge è un bridge di tipo relayer. Il ruolo di un relayer è votare per l'esecuzione di una richiesta (ad esempio, quanti token da bruciare/rilasciare). +Monitora gli eventi da ogni chain, e vota una proposta nel contratto bridge della chain di destinazione quando riceverà un `Deposit` evento da una chain. Un relayer chiama un metodo nel contratto bridge per eseguire la proposta dopo che il numero di voti richiesto sia stato inviato. Il bridge delega l'esecuzione al contratto Handler. + + +## Tipi di contratti {#types-of-contracts} +In ChainBridge, ci sono tre tipi di contratto su ciascuna chain, chiamati Bridge/Handler/Target. + +| **Tipo** | **Descrizione** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Contratto bridge | Un contratto bridge che gestisce le richieste, i voti e le esecuzioni deve essere implementato in ogni chain. Gli utenti chiameranno `deposit` in Bridge per avviare il trasferimento, e Bridge delega il processo al contratto Handler corrispondente al contratto Target. Una volta che il contratto Handler è riuscito a chiamare il contratto Target, il contratto Bridge emette un evento `Deposit` per avvisare i relayer. | +| Contratto Handler | Questo contratto interagisce con il contratto Target per effettuare un deposito o una proposta. Convalida la richiesta dell'utente, chiama il contratto Target e fornisce aiuto con alcune impostazioni per il contratto Target. Ci sono alcuni contratti Handler per chiamare ciascun contratto Target che presentano un'interfaccia diversa. Le chiamate indirette effettuate dal contratto Handler fanno il bridge per consentire il trasferimento di qualsiasi tipo di asset o dato. Attualmente, esistono tre tipi di contratti Handler implementati da ChainBridge: ERC20Handler, ERC721Handler e GenericHandler. | +| Contratto Target | Un contratto che gestisce gli asset da scambiare o i messaggi che vengono trasferiti tra le chain. L'interazione con questo contratto verrà effettuata da ogni lato del bridge. | + +
+ +![Architettura di ChainBridge](/img/edge/chainbridge/architecture.svg) +*Architettura di ChainBridge* + +
+ +
+ +![Flusso di lavoro del trasferimento di token ERC20](/img/edge/chainbridge/erc20-workflow.svg) +*es. Flusso di lavoro di un trasferimento di token ERC20* + +
+ +## Tipi di account {#types-of-accounts} + +Assicurati che gli account dispongano di token nativi sufficienti per creare transazioni prima di iniziare. In Polygon Edge, puoi assegnare saldi preminati agli account durante la generazione del blocco di genesi. + +| **Tipo** | **Descrizione** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Amministratore | A questo account verrà assegnato per default il ruolo di amministratore. | +| Utente | L'account del mittente/destinatario che invia/riceve gli asset. L'account del mittente paga le gas fee quando approva i trasferimenti dei token e chiama il deposito nel contratto Bridge per avviare un trasferimento. | + +:::info Il ruolo di amministratore +Alcune azioni possono essere eseguite solo dall'account del ruolo di amministratore. Di default, l'implementatore del contratto Bridge ha il ruolo di amministratore. Qui di seguito viene indicato come concedere il ruolo di amministratore a un altro account oppure rimuoverlo. + +### Aggiungi il ruolo di amministratore {#add-admin-role} + +Aggiunge un amministratore + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### Revoca il ruolo di amministratore {#revoke-admin-role} + +Rimuove un amministratore + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## Le operazioni consentite dall'account `admin` sono le seguenti. {#account-are-as-below} + +### Impostare la risorsa {#set-resource} + +Registrare un ID risorsa con un indirizzo di contratto per un handler. + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Rendere il contratto burnable/mintable (bruciabile/coniabile) {#make-contract-burnable-mintable} + +Impostare un contratto token come mintable/burnable in un handler. + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Annullare la proposta {#cancel-proposal} + +Annullare la proposta di esecuzione + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### Sospendere/Riattivare {#pause-unpause} + +Sospendere temporaneamente i depositi, la creazione delle proposte, le votazioni e l'esecuzione dei depositi. + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### Modificare la commissione {#change-fee} + +Modificare la commissione che verrà pagata al contratto Bridge + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### Aggiungere/Rimuovere un relayer {#add-remove-a-relayer} + +Aggiungere un account come nuovo relayer o rimuovere un account dai relayer + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### Modificare la soglia del relayer {#change-relayer-threshold} + +Modificare il numero di voti richiesti per l'esecuzione di una proposta + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## ID della chain {#chain-id} + +Il Chainbridge `chainId` è un valore arbitrario utilizzato nel bridge per operare una differenziazione tra le reti blockchain, e deve essere compreso nell'intervallo di uint8. Da non confondere con l'ID della chain della rete, non sono la stessa cosa. Questo valore deve essere univoco, ma non deve essere lo stesso dell'ID della rete. + +In questo esempio, impostiamo `99` in `chainId`, perché l'ID della chain della Mumbai testnet è `80001`, che non può essere rappresentato con un uint8. + +## ID delle risorse {#resource-id} + +Un ID di risorsa è un valore univoco di 32 byte in un ambiente cross-chain, associato a un certo asset (risorsa) che viene trasferito tra le reti. + +L'ID di una risorsa è arbitrario, ma, come convenzione, di solito l'ultimo byte contiene l'ID della chain sorgente (la rete da cui proveniva questo asset). + +## URL JSON-RPC per Polygon PoS {#json-rpc-url-for-polygon-pos} + +Per questa guida utilizzeremo https://rpc-mumbai.matic.today, un URL JSON-RPC pubblico fornito da Polygon che può avere dei limiti di traffico o di rete. Questo URL verrà utilizzato solo per connettersi alla Polygon Mumbai testnet. Ti consigliamo di ottenere il tuo URL JSON-RPC da un servizio esterno come Infura perché l'implementazione dei contratti invierà molte query/richieste al JSON-RPC. + +## Modalità di elaborazione del trasferimento di token {#ways-of-processing-the-transfer-of-tokens} +Durante il trasferimento tra le chain, i token ERC20 possono essere elaborati in due modalità diverse: + +### Modalità di blocco/rilascio {#lock-release-mode} +Chain di origine: I token che stai inviando saranno bloccati nel contratto Handler.
Chain di destinazione: La stessa quantità di token che hai inviato nella chain di origine verrà sbloccata e trasferita dal contratto Handler all'account del destinatario nella chain di destinazione. + +### Modalità brucia/conia {#burn-mint-mode} +Chain di origine: I token che stai inviando verranno bruciati.
Chain di destinazione: La stessa quantità di token che hai inviato e bruciato nella chain di origine verrà coniata nella chain di destinazione e inviata all'account del destinatario. + +Puoi utilizzare diverse modalità su ciascuna chain. Questo significa che puoi bloccare un token nella chain principale durante il mining di un token nella subchain per il trasferimento. Ad esempio, può avere senso bloccare/rilasciare i token se la fornitura totale o il programma di conio è controllato. Se il contratto nella subchain deve seguire la fornitura nella chain principale, i token verrebbero coniati/bruciati. + +La modalità predefinita è la modalità blocco/rilascio. Se vuoi rendere i tuoi token mintable/burnable, devi chiamare il metodo `adminSetBurnable`. Se vuoi coniare i token all'esecuzione, dovrai concedere un ruolo `minter` al contratto Handler ERC20. + + diff --git a/archive/edge/it-edge/additional-features/chainbridge/overview.md b/archive/edge/it-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..26edf75b94 --- /dev/null +++ b/archive/edge/it-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Panoramica +description: Panoramica su ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Cos'è ChainBridge? {#what-is-chainbridge} + +ChainBridge è un bridge blockchain multidirezionale modulare che supporta catene compatibili con EVM e Substrate, costruito da ChainSafe. Consente agli utenti di trasferire tutti i tipi di asset o messaggi tra due catene diverse. + +Per maggiori informazioni su ChainBridge, consulta prima i [documenti ufficiali](https://chainbridge.chainsafe.io/) forniti dai suoi sviluppatori. + +Questa guida ha lo scopo di aiutare ad integrare Chainbridge in Polygon Edge. Passa attraverso la configurazione di un bridge tra un PoS di Polygon (Mumbai testnet) in esecuzione e una rete di Polygon Edge locale. + +## Requisiti {#requirements} + +In questa guida eseguirai dei nodi Polygon Edge e un relayer ChainBridge (puoi trovare ulteriori informazioni [qui](/docs/edge/additional-features/chainbridge/definitions)), e lo strumento cb-sol-cli, che è uno strumento CLI utile ad implementare i contratti localmente, a registrare risorse e a modificare le impostazioni per il bridge (puoi consultare anche [questo articolo](https://chainbridge.chainsafe.io/cli-options/#cli-options)). Prima di avviare la configurazione, sono necessari i seguenti ambienti: + +* Go: >= 1.17 +* Node.js >= 16.13.0 +* Git + + +Inoltre, dovrai clonare i seguenti repository con le versioni per eseguire alcune applicazioni. + +* [Polygon Edge](https://github.com/0xPolygon/polygon-edge): sul `develop` ramo +* [ChainBridge](https://github.com/ChainSafe/ChainBridge): v1.1.5 +* [Strumenti di implementazione di ChainBridge](https://github.com/ChainSafe/chainbridge-deploy): `f2aa093` sul `main` ramo + + +Devi configurare una rete Polygon Edge prima di procedere alla sezione successiva. Controlla le [impostazioni locali](/docs/edge/get-started/set-up-ibft-locally) o le [impostazioni del Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) per ulteriori dettagli. \ No newline at end of file diff --git a/archive/edge/it-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/it-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..2a74b112c5 --- /dev/null +++ b/archive/edge/it-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,142 @@ +--- +id: setup-erc20-transfer +title: Trasferimento di token ERC20 +description: Come configurare un trasferimento ERC-20 in chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Finora, abbiamo creato un bridge per lo scambio di asset/dati tra Polygon PoS e la catena Polygon Edge. Questa sezione ti guiderà nella configurazione di un bridge ERC20 e invierà token tra le diverse blockchain. + +## Passaggio 1: Registra un ID di risorsa {#step-1-register-resource-id} + +In primo luogo, registrerai un ID di risorsa che associa le risorse in un ambiente cross-chain. Un ID di risorsa è un valore di 32 byte che deve essere univoco per la risorsa che stiamo trasferendo tra queste blockchain. Gli ID di risorsa sono arbitrari, ma possono avere l'ID catena della catena home nell'ultimo byte, come convenzione (catena home che si riferisce alla rete su cui queste risorse avevano origine). + +Per registrare un ID di risorsa, puoi utilizzare il comando `cb-sol-cli bridge register-resource`. Dovrai fornire la chiave privata dell'account `admin`. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (Facoltativo) Rendere i contratti mintable/burnable (creabili/bruciabili) {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## Passaggio 2: Trasferire un token ERC20 {#step-2-transfer-erc20-token} + +Invieremo i token ERC20 dalla catena PoS Polygon alla catena Polygon Edge. + +In primo luogo, riceverai i token con il minting. Un account con il ruolo `minter` può creare nuovi token. L'account che ha implementato il contratto ERC20 ha il ruolo `minter` di default. Per specificare altri account come membri del ruolo `minter`, devi eseguire il comando `cb-sol-cli erc20 add-minter`. + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +Per controllare il saldo attuale, puoi utilizzare il comando `cb-sol-cli erc20 balance`. + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +Successivamente, devi approvare il trasferimento del token ERC20 dall'account tramite l'handler ERC20 + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +Per trasferire i token alla catena Polygon Edge, chiamerai `deposit`. + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Dopo che la transazione di deposito è riuscita, il relayer riceverà l'evento e voterà la proposta. Esegue una transazione per inviare i token all'account del destinatario nella catena Polygn Edge dopo che è stato inviato il numero di voti richiesto. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Una volta che la transazione di esecuzione è riuscita, riceverai i token nella catena Polygon Edge. + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/it-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/it-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..d299b7eccd --- /dev/null +++ b/archive/edge/it-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,134 @@ +--- +id: setup-erc721-transfer +title: Trasferimento di NFT ERC721 +description: Come configurare un trasferimento ERC721 in chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Questa sezione ti guida attraverso la configurazione di un bridge ERC721 e l'invio di NFT tra reti blockchain. + +## Passaggio 1: Registra un ID di risorsa {#step-1-register-resource-id} + +Dovrai prima registrare l'ID di risorsa per il token ERC721 nei contratti bridge su entrambe le chain. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (Facoltativo): Rendi i contratti mintable/burnable (coniabili/bruciabili) {#optional-make-contracts-mintable-burnable} + +Per rendere i token mintable/burnable, dovrai chiamare i seguenti comandi: + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## Passaggio 2: Trasferisci gli NFT {#step-2-transfer-nft} + +In primo luogo, creerai un NFT se ne hai bisogno. + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Per controllare il proprietario degli NFT, puoi utilizzare `cb-sol-cli erc721 owner` + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +In seguito, approverai un trasferimento del NFT da parte dell'handler ERC721 + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Infine, avvierai il trasferimento + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +Il relayer riceverà l'evento e voterà la proposta. Esegue una transazione per inviare gli NFT all'account del destinatario nella catena Polygon Edge dopo che è stato inviato il numero di voti richiesto. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Puoi verificare il proprietario dell'NFT sulla rete Polygon Edge al termine dell'esecuzione. + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/it-edge/additional-features/chainbridge/setup.md b/archive/edge/it-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..8a509ba59d --- /dev/null +++ b/archive/edge/it-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,197 @@ +--- +id: setup +title: Configurazione +description: Come configurare chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Implementazione dei contratti {#contracts-deployment} + +In questa sezione implementerai i contratti richiesti alla catena Polygon PoS e Polygon Edge con`cb-sol-cli` . + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +In primo luogo, implementeremo i contratti alla catena Polygon PoS con il comando `cb-sol-cli deploy`. Il flag `--all`fa sì che il comando implementi tutti i contratti, compresi Bridge, ERC20 Handler, ERC721 Handler, Generic Handler, ERC20 e ERC721. Inoltre, imposterà l'indirizzo dell'account del relayer predefinito e la soglia + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +Scopri di più su chainID e JSON-RPC URL [qui](/docs/edge/additional-features/chainbridge/definitions) + +:::caution + +Il prezzo del gas predefinito in `cb-sol-cli` è `20000000` (`0.02 Gwei`). Per impostare il corretto prezzo del gas in una transazione si prega di impostare il valore utilizzando l'argomento `--gasPrice`. + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +Il contratto Bridge richiede circa 0x3f97b8 (4167608) per essere implementato. Assicurati che i blocchi generati abbiano un limite di gas del blocco sufficiente a contenere la transazione per la creazione del contratto. Per ulteriori informazioni sulla modifica del limite del gas del blocco in Polygon Edge, visitare il [Setup locale](/docs/edge/get-started/set-up-ibft-locally) + +::: + +Una volta implementati i contratti, si otterrà il seguente risultato: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +Ora possiamo implementare i contratti alla catena Polygon Edge. + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Salva gli output del terminale con gli indirizzi degli smart contract implementati, perché ci serviranno per il prossimo passo. + +## Configurazione del relayer {#relayer-setup} + +In questa sezione, avvieremo un relayer per lo scambio di dati tra 2 catene. + +Per prima cosa, dobbiamo clonare e costruire il repository ChainBridge. + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +Poi devi creare `config.json`e impostare gli URL JSON-RPC, l'indirizzo relayer e l'indirizzo dei contratti per ogni catena. + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +Per avviare un relayer, è necessario importare la chiave privata corrispondente all'indirizzo dell'account del relayer. Dovrai inserire la password quando importi la chiave privata. Una volta che l'importazione è andata a buon fine, la chiave verrà memorizzata sotto `keys/
.key`. + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +A questo punto, è possibile avviare il relayer. Dovrai inserire la stessa password che hai scelto all'inizio per la memorizzazione della chiave. + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +Una volta avviato, il relayer inizierà a osservare i nuovi blocchi di ogni catena. diff --git a/archive/edge/it-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/it-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..953c89be31 --- /dev/null +++ b/archive/edge/it-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,255 @@ +--- +id: use-case-erc20-bridge +title: Caso d'uso - ERC20 Bridge +description: Caso per contratto bridge ERC20 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +Questa sezione ha lo scopo di fornire un flusso di configurazione di ERC20 Bridge per un esempio d'uso pratico. + +In questa guida utilizzerai la testnet Mumbai di Polygon PoS e la chain locale di Polygon Edge. Assicurati di avere l'endpoint JSON-RPC per Mumbai e di aver configurato Polygon Edge nell'ambiente locale. Fai riferimento a [Configurazione locale](/docs/edge/get-started/set-up-ibft-locally) o [Configurazione Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) per maggiori dettagli. + +## Scenario {#scenario} + +Questo scenario prevede la creazione di un bridge per il token ERC20 che è già stato implementato nella catena pubblica (Polygon PoS) al fine di consentire il trasferimento a basso costo in una catena privata (Polygon Edge) per gli utenti in un caso normale. In questo caso, la fornitura totale di token è stata definita nella catena pubblica e solo la quantità di token che è stata trasferita dalla catena pubblica alla catena privata deve esistere nella catena privata. Per questo motivo dovrai utilizzare la modalità blocco/rilascio nella catena pubblica e la modalità brucia/conia nella catena privata. + +Quando si inviano token dalla catena pubblica alla catena privata, il token viene bloccato nel contratto ERC20 Handler della catena pubblica e la stessa quantità di token viene coniata nella catena privata. Invece, in caso di trasferimento dalla catena privata alla catena pubblica, il token della catena privata verrà bruciato e la stessa quantità di token verrà rilasciata dal contratto ERC20 Handler nella catena pubblica. + +## Contratti {#contracts} + +Spiegare con un semplice contratto ERC20 invece del contratto sviluppato da ChainBridge. Per la modalità brucia/conia, il contratto ERC20 deve avere metodi `mint`e `burnFrom`in aggiunta ai metodi per ERC20 come questo: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +Tutti i codici e gli script sono in Github Repo [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Passo 1: implementazione dei contratti Bridge e ERC20 Handler {#step1-deploy-bridge-and-erc20-handler-contracts} + +In primo luogo, si distribuiscono i contratti Bridge e ERC20Handler utilizzando `cb-sol-cli` in entrambe le catene. + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Si otterranno indirizzi di contratto Bridge e ERC20Handler come questo: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Passo 2: implementazione del contratto ERC20 {#step2-deploy-your-erc20-contract} + +Implementerai il contratto ERC20. Questo esempio ti guida con il progetto hardhat [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Crea il file `.env` e imposta i seguenti valori. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Poi dovrai implementare il contratto ERC20 in entrambe le catene. + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +Dopo che l'implementazione sarà riuscita, otterrai un indirizzo del contratto come questo: + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## Passo 3: Registra l'ID risorsa nel Bridge {#step3-register-resource-id-in-bridge} + +Dovrai registrare un ID risorsa che associa la risorsa in un ambiente cross-chain. È necessario impostare lo stesso ID risorsa in entrambe le catene. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## Passo 4: imposta la modalità Conia/Brucia nel bridge ERC20 dell'Edge {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +Bridge prevede di lavorare come modalità di brucia/conia in Polygon Edge. La modalità brucia/conia va impostata usando `cb-sol-cli`. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +Inoltre, è necessario assegnare un ruolo di minatore e bruciatore al contratto ERC20 Handler. + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Passo 5: coniare token {#step5-mint-token} + +I nuovi token ERC20 saranno coniati nella catena Mumbai. + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +Una volta che la transazione è andata a buon fine, l'account avrà il token coniato. + +## Paaso 6: avvia il trasferimento di ERC20 {#step6-start-erc20-transfer} + +Prima di iniziare questo passo assicurati di aver avviato un relayer. SI prega di controllare la [Configurazione](/docs/edge/additional-features/chainbridge/setup) per maggiori dettagli. + +Durante il trasferimento dei token da Mumbai a Edge, il contratto ERC20 Handler di Mumbai preleva i token dal tuo account. Chiamerai l'approvazione prima del trasferimento. + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +Infine, inizierai a trasferire token da Mumbai a Edge utilizzando `cb-sol-cli`. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Dopo che la transazione del deposito è andata a buon fine, il relayer riceverà l'evento e voterà la proposta. Esegue una transazione per inviare i token all'account del destinatario nella Polygn Edge chain dopo che è stato inviato il numero di voti richiesto. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Una volta che la transazione dell'esecuzione sarà andata a buon fine, riceverai i token nella catena Polygon Edge. diff --git a/archive/edge/it-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/it-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..5ca1003cfd --- /dev/null +++ b/archive/edge/it-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,308 @@ +--- +id: use-case-erc721-bridge +title: Caso d'uso - Bridge ERC721 +description: Esempio per il bridge del contratto ERC721 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +Questa sezione mira a fornirti un flusso di installazione di bridge ERC271 per un caso d'uso pratico. + +In questa guida utilizzerai la testnet Mumbai di Polygon PoS e la chain locale di Polygon Edge. Assicurati di avere l'endpoint JSON-RPC per Mumbai e di aver configurato Polygon Edge nell'ambiente locale. Fai riferimento a [Configurazione locale](/docs/edge/get-started/set-up-ibft-locally) o [Configurazione Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) per maggiori dettagli. + +## Scenario {#scenario} + +Questo scenario consiste nell'impostare un bridge per l'NFT ERC721 che è già stato implementato nella catena pubblica (PoS di Polygon) per abilitare il trasferimento a basso costo in una catena privata (edge di Polygon) per utenti in un caso normale. In tal caso, i metadati originali sono stati definiti nella catena pubblica e gli unici NFT che sono stati trasferiti dalla catena pubblica possono esistere nella catena privata. Per questo motivo dovrai utilizzare la modalità blocco/rilascio nella catena pubblica e la modalità brucia/conia nella catena privata. + +Quando si invia un NFT dalla catena pubblica alla catena privata, l'NFT verrà bloccato nel contratto handler ERC271 nella catena pubblica e lo stesso NFT verrà coniato nella catena privata. D'altra parte, in caso di trasferimento dalla catena privata alla catena pubblica, l'NFT nella catena privata verrà bruciato e lo stesso NFT verrà rilasciato dal contratto handler ERC721 nella catena pubblica. + +## Contratti {#contracts} + +Spiegazione con un contratto ERC721 semplice invece del contratto sviluppato da ChainBridge. Per la modalità burn/mint, il contratto ERC721 deve avere i metodi `mint` e `burn` in aggiunta ai metodi definiti in ERC721 come questo: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +Tutti i codici e gli script sono in Github Repo [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Passaggio 1: Implementa il bridge e i contratti handler ERC721 {#step1-deploy-bridge-and-erc721-handler-contracts} + +In primo luogo, dovrai implementare il bridge e i contratti Handler ERC721 utilizzando `cb-sol-cli` in entrambe le catene. + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Otterrai gli indirizzi del bridge e del contratto handler ERC721 come questo: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Passaggio 2: Implementa il tuo contratto ERC721 {#step2-deploy-your-erc721-contract} + +Dovrai implementare il tuo contratto ERC721. Questo esempio ti guida con il progetto hardhat [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Crea il file `.env` e imposta i seguenti valori. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Poi dovrai implementare il contratto ERC721 in entrambe le catene. + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +Dopo che l'implementazione è riuscita, otterrai un indirizzo del contratto come questo: + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## Passaggio 3: Registra l'ID risorsa nel Bridge {#step3-register-resource-id-in-bridge} + +Dovrai registrare un ID risorsa che associa le risorse in un ambiente cross-chain. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## Passaggio 4: Imposta la modalità Mint/Burn nel bridge ERC721 dell'edge {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +Bridge prevede di funzionare come modalità burn/mint in Edge. Dovrai impostare la modalità burn/mint. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +E devi concedere un ruolo minatore e bruciatore al contratto handler ERC721. + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Passaggio 5: Crea l'NFT {#step5-mint-nft} + +Creerai il nuovo NFT ERC721 nella Mumbai chain. + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +Una volta che la transazione è andata a buon fine, l'account avrà l'NFT coniato. + +## Passaggio 6: Avvia il trasferimento ERC721 {#step6-start-erc721-transfer} + +Prima di iniziare questo passaggio, assicurati di aver avviato il relayer. SI prega di controllare la [Configurazione](/docs/edge/additional-features/chainbridge/setup) per maggiori dettagli. + +Durante il trasferimento dell'NFT da Mumbai a Edge, il contratto handler ERC721 in Mumbai preleva l'NFT dal tuo account. Chiamerai l'approvazione prima del trasferimento. + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +Infine, avvierai il trasferimento di NFT da Mumbai a Edge. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +Dopo che la transazione del deposito è andata a buon fine, il relayer riceverà l'evento e voterà la proposta. +Esegue una transazione per inviare l'NFT all'account del destinatario nella Polygon Edge chain dopo che è stato inviato il numero di voti richiesto. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Una volta che la transazione dell'esecuzione è andata a buon fine, riceverai l'NFT nella Polygon Edge chain. diff --git a/archive/edge/it-edge/additional-features/permission-contract-deployment.md b/archive/edge/it-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..65d0347c18 --- /dev/null +++ b/archive/edge/it-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,85 @@ +--- +id: permission-contract-deployment +title: Autorizzazione all'implementazione di smart contract +description: Come aggiungere l'implementazione di smart contract di autorizzazione. +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## Panoramica {#overview} + +Questa guida affronta nel dettaglio il modo in cui gli indirizzi whitelist possono implementare gli smart contract. A volte gli operatori della rete desiderano impedire agli utenti l'implementazione di smart contract non inerenti allo scopo della rete. Gli operatori della rete possono: + +1. Indirizzi Whitelist per l'implementazione di smart contract +2. Rimuovere gli indirizzi dalla whitelist per l'implementazione di smart contract + +## Presentazione video {#video-presentation} + +[![concessione del contratto - video](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## Come usarla? {#how-to-use-it} + + +Puoi trovare tutti i comandi cli relativi alla lista di implementazione nella pagina dei [comandi CLI](/docs/edge/get-started/cli-commands#whitelist-commands) . + +* `whitelist show`: Visualizza informazioni sulla whitelist +* `whitelist deployment --add`: Aggiunge un nuovo indirizzo alla whitelist di implementazione del contratto +* `whitelist deployment --remove`: Rimuove un nuovo indirizzo dalla whitelist di implementazione del contratto + +#### Mostra tutti gli indirizzi nella whitelist di implementazione {#show-all-addresses-in-the-deployment-whitelist} + +Ci sono 2 modi per trovare gli indirizzi dalla whitelist di implementazione. +1. Guardare `genesis.json` dove sono salvate le whitelist +2. Eseguire `whitelist show`, che stampa tutte le whitelist supportate da Polygon Edge + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### Aggiungi un indirizzo alla whitelist di implementazione {#add-an-address-to-the-deployment-whitelist} + +Per aggiungere un nuovo indirizzo alla whitelist di implementazione, esegui il comando CLI `whitelist deployment --add [ADDRESS]`. Non c'è limite al numero di indirizzi presenti nella whitelist. Solo gli indirizzi che esistono nella whitelist di implementazione del contratto possono implementare i contratti. Se la whitelist è vuota, qualsiasi indirizzo può eseguire l'implementazione + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### Rimuovere un indirizzo dalla whitelist di implementazione {#remove-an-address-from-the-deployment-whitelist} + +Per rimuovere un indirizzo dalla whitelist di implementazione, esegui il comando CLI `whitelist deployment --remove [ADDRESS]`. Solo gli indirizzi che esistono nella whitelist di implementazione del contratto possono implementare i contratti. Se la whitelist è vuota, qualsiasi indirizzo può eseguire l'implementazione + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/it-edge/architecture/modules/blockchain.md b/archive/edge/it-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..47f38a9263 --- /dev/null +++ b/archive/edge/it-edge/architecture/modules/blockchain.md @@ -0,0 +1,156 @@ +--- +id: blockchain +title: Blockchain +description: Spiegazione dei moduli blockchain e state di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## Panoramica {#overview} + +Alcuni dei moduli principali di Polygon Edge sono **Blockchain** e **State**.
+ +**Blockchain** è il motore che si occupa delle riorganizzazioni dei blocchi. Ciò significa che si occupa di tutta la logica che si verifica quando un nuovo blocco viene inserito nella blockchain. + +**State** rappresenta l'oggetto *transizione di stato*. Si occupa di come cambia lo stato quando viene inserito un nuovo blocco.
Tra le altre cose, **State** si occupa di: +* Eseguire le transazioni +* Eseguire l'EVM +* Cambiare gli alberi di Merkle +* Molto altro che è discusso nella corrispondente sezione **State** 🙂 + +La chiave di lettura è che queste due parti sono molto collegate e lavorano insieme per il funzionamento del client.
Ad esempio, quando il livello **Blockchain** riceve un nuovo blocco (e non è avvenuta alcuna riorganizzazione), chiama lo **State** per eseguire una transizione di stato. + +**La blockchain** deve anche occuparsi di alcune parti relative al consenso (es. *questo ethHash è corretto?*, *questa PoW è corretta?*)
. In una frase, **è il nucleo principale della logica attraverso cui vengono inclusi tutti i blocchi**. + +## *WriteBlocks* + +Una delle parti più importanti che riguardano il **Blockchain** layer è il metodo *WriteBlocks*: + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +Il metodo *WriteBlocks* è il punto di ingresso per scrivere blocchi nella blockchain. Come parametro, accetta un intervallo di blocchi.
In primo luogo, i blocchi vengono convalidati. Dopo di che, vengono scritti nella catena. + +La *transizione di stato* vera e propria viene eseguita richiamando il metodo *processBlock* all'interno di *WriteBlocks*. + +Vale la pena ricordare che, essendo il punto di ingresso per la scrittura dei blocchi nella blockchain, altri moduli (come il **Sealer**) utilizzano questo metodo. + +## Sottoscrizioni nella blockchain {#blockchain-subscriptions} + +È necessario un modo per monitorare le modifiche relative alla blockchain.
È qui che entrano in gioco le **Sottoscrizioni**. + +Le sottoscrizioni sono un modo per attingere ai flussi di eventi della blockchain e ricevere istantaneamente dati significativi. + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +Gli **Eventi Blockchain** contengono informazioni relative a qualsiasi modifica apportata alla catena attuale. Questo include le riorganizzazioni, nonché i nuovi blocchi: + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip Aggiornamento +Ricordi quando abbiamo menzionato il comando ***monitor*** nella sezione [Comandi CLI](/docs/edge/get-started/cli-commands)? + +Gli eventi Blockchain sono gli eventi originali che si verificano in Polygon Edge e vengono successivamente mappati in un formato di messaggio Protocol Buffers per facilitarne il trasferimento. +::: \ No newline at end of file diff --git a/archive/edge/it-edge/architecture/modules/consensus.md b/archive/edge/it-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..990392950a --- /dev/null +++ b/archive/edge/it-edge/architecture/modules/consensus.md @@ -0,0 +1,494 @@ +--- +id: consensus +title: Consenso +description: Spiegazione del modulo di consenso di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## Panoramica {#overview} + +Il modulo **Consenso** fornisce un'interfaccia per i meccanismi di consenso. + +Attualmente sono disponibili i seguenti motori di consenso: +* **IBFT PoA** +* **IBFT PoS** + +Polygon Edge vuole mantenere uno stato di modularità e collegabilità.
Questo è il motivo per cui la logica di base del consenso è stata resa astratta, in modo che nuovi meccanismi di consenso possano essere costruiti su di essa, senza compromettere la semplicità d'uso e le possibilità di utilizzo.. + +## Interfaccia Consenso {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + +L'interfaccia di ***Consenso*** è il nucleo dell'astrazione citata.
+* Il metodo **VerifyHeader** rappresenta una funzione di supporto che il layer di consenso espone al layer della **blockchain** Serve a gestire la verifica delle intestazioni +* Il metodo **Start** avvia semplicemente il processo di consenso e tutto ciò che vi è associato. Questo include la sincronizzazione, la sigillatura e tutto quello che deve essere fatto +* Il metodo **Chiudi** chiude la connessione di consenso + +## Configurazione Consenso {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +Può capitare che si voglia passare una posizione personalizzata per il protocollo di consenso per memorizzare i dati, o forse una mappa chiave-valore personalizzata da utilizzare per il meccanismo di consenso. Questo può essere ottenuto tramite la struttura ***Config***, che viene letta quando viene creata una nuova istanza di consenso. + +## IBFT {#ibft} + +### ExtraData {#extradata} + +L'oggetto intestazione della blockchain, tra gli altri campi, ne ha uno chiamato **ExtraData**. + +L'IBFT utilizza questo campo aggiuntivo per memorizzare informazioni operative relative al blocco, rispondendo a domande come: +* "Chi ha firmato questo blocco?" +* "Chi sono i validatori di questo blocco?" + +Questi campi aggiuntivi per l'IBFT sono definiti come segue: +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### Dati sulla firma {#signing-data} + +Per firmare le informazioni in IBFT, il nodo utilizza il metodo *signHash*: +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +Un altro metodo degno di nota è il metodo *VerifyCommittedFields*, che verifica che i sigilli impegnati provengano da validatori: +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### Istantanee {#snapshots} + +Le istantanee, come dice il nome, servono a fornire un'*istantanea*, ovvero lo *stato* di un sistema a qualsiasi altezza del blocco (numero). + +Le istantanee contengono un insieme di nodi che sono validatori, nonché informazioni di voto (i validatori possono votare per altri validatori). I validatori includono le informazioni di voto nell'intestazione del **Minatore** e modificano il valore del **nonce**: +* Il nonce è **tutto 1s** se il nodo vuole rimuovere un validatore +* Il nonce è **tutto 0s**, se il nodo vuole aggiungere un validatore + +Le istantanee vengono calcolate con il metodo ***processHeaders***: + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +Questo metodo viene solitamente chiamato con 1 intestazione, ma il flusso è lo stesso anche con intestazioni multiple.
Per ogni intestazione passata, IBFT deve verificare che il proponente dell'intestazione sia il validatore. Questo può essere fatto facilmente prendendo l'ultima istantanea e controllando se il nodo è nel set di validatori. + +Successivamente, il nonce viene controllato. Il voto viene incluso e conteggiato e, se ci sono abbastanza voti, un nodo viene aggiunto/rimosso dall'insieme di validatori, dopo di che viene salvata la nuova istantanea. + +#### Archivio delle istantanee {#snapshot-store} + +Il servizio delle istantanee gestisce e aggiorna un'entità chiamata **snapshotStore**, che memorizza l'elenco di tutte le istantanee disponibili. Grazie ad esso, il servizio è in grado di capire rapidamente quale istantanea è associata a quale altezza del blocco. +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### Avviamento di IBFT {#ibft-startup} + +Per avviare IBFT, Polygon Edge deve innanzitutto impostare il trasporto IBFT: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +Crea essenzialmente un nuovo argomento con il proto IBFT, con un nuovo messaggio proto buff.
I messaggi sono destinati a essere utilizzati dai validatori. Polygon Edge si iscrive quindi all'argomento e gestisce i messaggi di conseguenza. + +#### MessageReq {#messagereq} + +Il messaggio scambiato dai validatori: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +Il campo **View** del **MessageReq** rappresenta la posizione corrente del nodo all'interno della catena. Ha un attributo *round* e uno *sequence*. +* **round** rappresenta il tempo necessario proposto per l'altezza +* **sequence** rappresenta altezza della blockchain + +Il file *msgQueue* dell'implementazione IBFT ha lo scopo di memorizzare le richieste di messaggi. Ordina i messaggi per *View* (prima per sequenza, poi per round). L'implementazione IBFT possiede anche code diverse per i diversi stati del sistema. + +### Stati IBFT {#ibft-states} + +Dopo che il meccanismo di consenso è stato avviato con il metodo **Start**, entra in un ciclo infinito che simula una macchina a stati: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### SyncState {#syncstate} + +Tutti i nodi iniziano nello stato **Sync**. + +Questo perché i dati recenti devono essere recuperati dalla blockchain. Il client deve scoprire se è il validatore, ha trovato l'istantanea attuale. Questo stato risolve eventuali blocchi in sospeso. + +Dopo che la sincronizzazione è terminata e il client ha stabilito che si tratta effettivamente di un validatore, deve passare ad **AcceptState**. Se il client **non** è un validatore, continuerà la sincronizzazione e rimarrà in **SyncState** + +#### AcceptState {#acceptstate} + +Lo stato **Accept** controlla sempre l'istantanea e l'insieme dei validatori. Se il nodo attuale non è nell'insieme dei validatori, +torna allo stato **Sync**. + +Se invece il nodo **è** un validatore, calcola il proponente. Se si scopre che il nodo corrente è il proponente, costruisce blocco e invia i messaggi preprepare e poi prepare. + +* Messaggi preprepare - messaggi inviati dai proponenti ai validatori, per avvisarli della proposta +* Messaggi prepare - messaggi in cui i validatori concordano su una proposta. Tutti i nodi ricevono tutti i messaggi prepare +* Messaggi di Commit - messaggi contenenti informazioni di commit per la proposta + +Se il nodo corrente **non è** un validatore, utilizza il metodo *getNextMessage* per leggere un messaggio dalla coda precedentemente mostrata.
Attende i messaggi preprepare Una volta confermato che tutto è corretto, il nodo passa allo stato **Validate**. + +#### ValidateState {#validatestate} + +Lo stato **Validate** è piuttosto semplice: tutto ciò che i nodi fanno in questo stato è leggere i messaggi e aggiungerli allo stato della loro istantanea locale. diff --git a/archive/edge/it-edge/architecture/modules/json-rpc.md b/archive/edge/it-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..b9c3c54d3c --- /dev/null +++ b/archive/edge/it-edge/architecture/modules/json-rpc.md @@ -0,0 +1,180 @@ +--- +id: json-rpc +title: JSON RPC +description: Spiegazione per il modulo JSON RPC di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## Panoramica {#overview} + +Il modulo **JSON RPC** implementa il **layer API JSON RPC**, una cosa che gli sviluppatori di dApp usano per interagire con la blockchain. + +Include il supporto per **[gli endpoint standard json-rpc](https://eth.wiki/json-rpc/API)** e anche quello degli endpoint websocket. + +## Interfaccia blockchain {#blockchain-interface} + +Polygon Edge usa l'***interfaccia blockchain*** per definire tutti i metodi che il modulo JSON RPC deve utilizzare, per fornire i suoi endpoint. + +L'interfaccia blockchain è implementata dal server **[Minimal](/docs/edge/architecture/modules/minimal)**. È l'implementazione base che è passata nel layer RPC JSON. + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## Endpoint ETH {#eth-endpoints} + +Tutti gli endpoint standard JSON RPC sono implementati in: + + + +````bash +jsonrpc/eth_endpoint.go +```` + +## Gestione Filtro + + {#filter-manager} + +La **Gestione del Filtro** è un servizio che viene eseguito insieme al server JSON RPC. + +Fornisce il supporto per il filtraggio dei blocchi sulla blockchain.
In particolare, include sia un filtro a livello di **log** che **di blocco**. + +La Gestione del Filtro si basa molto sugli eventi di sottoscrizione, menzionati + nella sezione [Blockchain](blockchain#blockchain-subscriptions) + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +Gli eventi della Gestione del Filtro vengono distribuiti nel metodo *Esegui*: + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## 📜 Risorse {#resources} +* **[Ethereum JSON-RPC](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/it-edge/architecture/modules/minimal.md b/archive/edge/it-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..4fef5971c7 --- /dev/null +++ b/archive/edge/it-edge/architecture/modules/minimal.md @@ -0,0 +1,119 @@ +--- +id: minimal +title: Minimal +description: Spiegazione per il modulo minimal di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## Panoramica {#overview} + +Come già detto, Polygon Edge è un insieme di moduli diversi, tutti collegati tra di loro.
+La **Blockchain** è collegata allo **Stato** o, ad esempio, alla **Sincronizzazione**, che convoglia nuovi blocchi nella **Blockchain**. + +**Minimal** è il caposaldo di questi moduli interconnessi.
+Esso agisce come un hub centrale per tutti i servizi in esecuzione su Polygon Edge. + +## Avvia Magic {#startup-magic} + +Tra l'altro, Minimal si occupa di: +* Configurare le directory di dati +* Creare un keystore per la comunicazione libp2p +* Creare l'archiviazione +* Configurare il consensus +* Configurare l'oggetto della blockchain con GRPC, JSON RPC e Synchronization + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/it-edge/architecture/modules/networking.md b/archive/edge/it-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..cf1117924a --- /dev/null +++ b/archive/edge/it-edge/architecture/modules/networking.md @@ -0,0 +1,78 @@ +--- +id: networking +title: Rete +description: Spiegazione per il modulo di rete di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## Panoramica {#overview} + +Un nodo deve comunicare con altri nodi sulla rete per scambiare informazioni utili.
+Per realizzare questo compito, il Polygon Edge sfrutta il framework **libp2p** testato sul campo. + +La scelta di utilizzare **libp2p** si focalizza principalmente su: +* La **velocità** - libp2p ha un significativo miglioramento delle prestazioni su devp2p (utilizzato in GETH e altri client) +* **Extensibility** - serve come un ottimo fondamento per altre caratteristiche del sistema +* **Modularity** - libp2p è modulare di natura, proprio come Polygon Edge. Questo offre una maggiore flessibilità, soprattutto quando parti di Polygon Edge devono essere scambiabili + +## GRPC {#grpc} + +Oltre a **libp2p**, Polygon Edge usa il protocollo **GRPC** .
Tecnicamente, Polygon Edge utilizza diversi protocolli GRPC, che saranno trattati in seguito. + +Il layer di GRPC aiuta a rendere astratti tutti i protocolli di richiesta/risposta e semplifica i protocolli di streaming necessari per il funzionamento di Polygon Edge. + +GRPC si basa sui **Protocol Buffer** per definire i *servizi* e le *strutture dei messaggi*.
+I servizi e le strutture sono definiti nei file *.proto* , che sono compilati e indipendenti dal linguaggio. + +In precedenza, abbiamo detto che Polygon Edge sfrutta diversi protocolli GRPC.
+Questo è stato fatto per potenziare l'esperienza utente complessiva per l'operatore del nodo, cosa che spesso è in ritardo rispetto a client come GETH e Parity. + +L'operatore del nodo ha una panoramica migliore di quanto sta accadendo con il sistema chiamando il servizio GRPC, invece di passare al setaccio i log per trovare le informazioni che sta cercando. + +### GRPC per gli operatori del nodo {#grpc-for-node-operators} + +La seguente sezione potrebbe sembrare familiare perché è stata trattata brevemente nella sezione [Comandi CLI](/docs/edge/get-started/cli-commands). + +Il servizio GRPC destinato ad essere utilizzato dagli **operatori del nodo** viene definito in questo modo: +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip +I comandi CLI chiamano effettivamente le implementazioni di questi metodi di servizio. + +Questi metodi vengono implementati in ***minimal/system_service.go***. + +::: + +### GRPC per altri nodi {#grpc-for-other-nodes} + +Polygon Edge implementa anche diversi metodi di servizio utilizzati da altri nodi sulla rete.
+Il servizio citato viene descritto nella sezione **[Protocollo](docs/edge/architecture/modules/consensus)**. + +## 📜 Risorse {#resources} +* **[I buffer di protocollo](https://developers.google.com/protocol-buffers)** +* **[libp2p](https://libp2p.io/)** +* **[gRPC](https://grpc.io/)** diff --git a/archive/edge/it-edge/architecture/modules/other-modules.md b/archive/edge/it-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..e720f0f1d6 --- /dev/null +++ b/archive/edge/it-edge/architecture/modules/other-modules.md @@ -0,0 +1,36 @@ +--- +id: other-modules +title: Altri moduli +description: Spiegazione riguardo alcuni moduli di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## Crypto {#crypto} + +Il modulo **Crypto** contiene funzioni di utilità crypto. + +## Chain {#chain} + +Il modulo **Chain** contiene dei parametri della catena (fork attivi, motore di consensus, etc.) + +* **catene**- Configurazioni predefinite della catena (mainnet, goerli, ibft) + +## Supporto {#helper} + +Il modulo **Supporto** contiene pacchetti di supporto. + +* **dao** - Programmi di utilità di Dao +* **enode** - Funzione di codifica/decodifica di Enode +* **hex** - Funzioni di codifica/decodifica di Hex +* **ipc** - Funzioni di connessione IPC +* **keccak** - Funzioni Keccak +* **rlputil** - Funzione di supporto per la codifica/decodifica di Rlp + +## Comando {#command} + +Il modulo di **Comando** contiene interfacce per i comandi CLI. \ No newline at end of file diff --git a/archive/edge/it-edge/architecture/modules/sealer.md b/archive/edge/it-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..b495dc5838 --- /dev/null +++ b/archive/edge/it-edge/architecture/modules/sealer.md @@ -0,0 +1,70 @@ +--- +id: sealer +title: Sealer +description: Spiegazione del modulo Sealer di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## Panoramica {#overview} + +Il **Sealer** è un'entità che raccoglie le transazioni e crea un blocco
nuovo. Poi, il blocco viene inviato al modulo **Consensus** perché venga sigillato. + +La logica di sigillatura finale si trova all'interno del modulo **Consensus**. + +## Metodo di esecuzione {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution Lavoro in corso +I moduli **Sealer** e **Consensus** saranno riuniti in un'unica entità nel prossimo futuro. + +Il nuovo modulo incorporerà una logica modulare per diversi tipi di meccanismi di consenso, che richiedono diverse implementazioni di sigillatura: +* **PoS** (Proof of Stake) +* **PoA** (Proof of Authority) + +Attualmente, i moduli **Sealer** e **Consensus** funzionano con PoW (Proof of Work). +::: \ No newline at end of file diff --git a/archive/edge/it-edge/architecture/modules/state.md b/archive/edge/it-edge/architecture/modules/state.md new file mode 100644 index 0000000000..bca1f3a52c --- /dev/null +++ b/archive/edge/it-edge/architecture/modules/state.md @@ -0,0 +1,245 @@ +--- +id: state +title: Stato +description: Spiegazione per il modulo di stato di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +Per capire veramente come funziona lo **Stato** devi capire alcuni concetti di base di Ethereum.
+ +Ti consigliamo vivamente di leggere **[Lo Stato nella guida di Ethereum](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)**. + +## Panoramica {#overview} + +Ora che abbiamo preso dimestichezza con i concetti di base di Ethereum, la prossima panoramica dovrebbe risultare semplice. + +Abbiamo detto che il **trie di stato mondiale** ha tutti gli account Ethereum esistenti.
+Questi account sono le foglie del Merkle trie. Ogni foglia ha codificato informazioni di **Stato dell'account**. + +Questo consente a Polygon Edge di ottenere un specifico Merkle trie, per un momento specifico.
+Ad esempio, possiamo ottenere l'hash dello stato al blocco 10. + +Il Merkle trie, in qualsiasi momento, viene chiamato ***Snapshot***. + +Possiamo avere degli ***Snapshot*** per il **trie di stato**, o per il **trie di archiviazione** - sostanzialmente sono gli stessi.
+L'unica differenza sta in quello che le foglie rappresentano: + +* Nel caso del trie di archiviazione, le foglie contengono uno stato arbitrario, che non possiamo elaborare o sapere cosa c'è dentro. +* Nel caso del trie di stato, le foglie rappresentano gli account + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + +L'interfaccia **Snapshot** viene definita come: + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +Le informazioni che possono essere impegnate vengono definite dalla *Struttura dell'oggetto*: + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +L'implementazione per il Merkle trie è nella cartella *trie di stato/immutabile*.
+*state/immutable-trie/state.go* implementa l'interfaccia dello **Stato** . + +*state/immutable-trie/trie.go* è il principale oggetto del Merkle trie. Rappresenta una versione ottimizzata del Merkle trie, che riutilizza quanta più memoria possibile. + +## Esecutore {#executor} + +*state/executor.go* include tutte le informazioni necessarie affinché Polygon Edge decida come un blocco possa cambiare lo stato +corrente. L'implementazione del *ProcessBlock* si trova qui. + +Il metodo *apply* esegue la transizione dello stato corrente. L'esecutore chiama l'EVM. + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## Runtime {#runtime} + +Quando viene eseguita una transizione di stato, il modulo principale che esegue tale transizione è l'EVM (situato in state/runtime/evm). + +La **tabella di spedizione** fa una corrispondenza tra il**codice operativo** e l'istruzione. + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +La logica di base che alimenta l'EVM è il ciclo di *Esecuzione*.
+ +Questo è il punto di ingresso principale per l'EVM. Fa un ciclo e controlla il codice operativo corrente, prende l'istruzione, controlla se può essere eseguita, consuma gas ed esegue l'istruzione finché non fallisce o si arresta. + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/it-edge/architecture/modules/storage.md b/archive/edge/it-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..6dbfe758cd --- /dev/null +++ b/archive/edge/it-edge/architecture/modules/storage.md @@ -0,0 +1,116 @@ +--- +id: storage +title: Archiviazione +description: Spiegazione del modulo di archiviazione di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## Panoramica {#overview} + +Polygon Edge utilizza attualmente **LevelDB** per l'archiviazione dei dati, oltre a un archivio dati **in-memory**. + +In Polygon Edge, quando i moduli devono interagire con l'archivio dati sottostante, non hanno bisogno di sapere con quale motore DB o servizio stanno comunicando. + +Il livello DB è astratto da un modulo chiamato **Storage**, il quale esporta interfacce che vengono ricercate dai moduli. + +Ogni livello del DB, per ora solo **LevelDB**, implementa questi metodi separatamente, assicurandosi che si adattino alla propria implementazione. + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### Prefissi {#prefixes} + +Per rendere deterministica la ricerca dell'archivio LevelDB e per evitare conflitti tra gli archivi di chiavi, Polygon Edge fa leva su prefissi e sottoprefissi durante l'archiviazione dei dati. + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## Piani futuri {#future-plans} + +I piani per il prossimo futuro prevedono l'aggiunta di alcune delle soluzioni DB più popolari, come: +* PostgreSQL +* MySQL + + +## 📜 Risorse {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/it-edge/architecture/modules/syncer.md b/archive/edge/it-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..39f8763aa7 --- /dev/null +++ b/archive/edge/it-edge/architecture/modules/syncer.md @@ -0,0 +1,67 @@ +--- +id: syncer +title: Syncer +description: Spiegazione del modulo syncer di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## Panoramica {#overview} + +Questo modulo contiene la logica del protocollo di sincronizzazione. Viene utilizzato per sincronizzare un nuovo nodo con la rete in esecuzione o per convalidare/inserire nuovi blocchi per i nodi che non partecipano al consenso (non validatori). + +Polygon Edge utilizza **libp2p** come livello di rete e in aggiunta esegue **gRPC**. + +Esistono essenzialmente 2 tipi di sincronizzazione in Polygon Edge: +* Bulk Sync - sincronizza una vasta gamma di blocchi alla volta +* Watch Sync - sincronizza su base per-blocco. + +### Bulk Sync {#bulk-sync} + +I passaggi per la sincronizzazione in massa sono piuttosto semplici per soddisfare l'obiettivo di Bulk Sync - sincronizzare il maggior numero possibile di blocchi (disponibili) dall'altro peer per rimettersi al passo il più rapidamente possibile. + + +Questo è il flusso del processo di Bulk Sync: + +1. ** Determinare se il nodo ha bisogno di Bulk Sync ** - In questa fase, il nodo controlla la mappa dei peer per vedere se c'è qualcuno che ha un numero di blocco maggiore di quello che il nodo ha localmente. +2. ** Trovare il miglior peer (usando la mappa dei peer di sincronizzazione) ** - In questa fase il nodo trova il miglior peer con cui sincronizzarsi in base ai criteri menzionati nell'esempio precedente. +3. ** Aprire un flusso di sincronizzazione in massa ** - In questa fase il nodo apre un flusso gRPC verso il miglior peer per sincronizzare in massa i blocchi dal numero di blocco comune. +4. ** Il miglior peer chiude il flusso quando ha terminato l'invio di massa ** - In questa fase il miglior peer con cui il nodo si sta sincronizzando chiuderà il flusso non appena avrà inviato tutti i blocchi disponibili che possiede. +5. ** Al termine della sincronizzazione in massa, verificare se il nodo è un validatore ** - In questa fase, il flusso viene chiuso dal miglior peer e il nodo deve verificare se è un validatore dopo la sincronizzazione in massa. + * Se lo è, esce dallo stato di sincronizzazione e inizia a partecipare al consenso. + * In caso contrario, continuano a ** Watch Sync ** + +### Watch Sync {#watch-sync} + +:::info +Il passaggio per Watch Syncing viene eseguito solo se il nodo non è un validatore, ma un normale nodo non validatore della rete che si limita ad ascoltare i blocchi in arrivo. +::: + +Il comportamento di Watch Sync è piuttosto semplice: il nodo è già sincronizzato con il resto della rete e deve solo analizzare i nuovi blocchi in arrivo. + +Questo è il flusso del processo di Watch Sync: + +1. ** Aggiungere un nuovo blocco quando lo stato di un peer viene aggiornato ** - In questa fase i nodi ascoltano gli eventi di un nuovo blocco, quando hanno un nuovo blocco eseguono una chiamata di funzione gRPC, ottengono il blocco e aggiornano lo stato locale. +2. ** Verifica se il nodo è un validatore dopo la sincronizzazione dell'ultimo blocco ** + + * Se lo è, esce dallo stato di sincronizzazione + * In caso contrario, continua ad ascoltare gli eventi dei nuovi blocchi + +## Rapporto sulla performance {#perfomance-report} + +:::info + +Le prestazioni sono state misurate su una macchina locale sincronizzando un milione di blocchi. +::: + +| Nome | Risultato | +|----------------------|----------------| +| Sincronizzazione di 1 milione di blocchi | ~ 25 min | +| Trasferimento di 1 milione di blocchi | ~ 1 min | +| Numero di chiamate GRPC | 2 | +| Copertura test | ~ 93% | \ No newline at end of file diff --git a/archive/edge/it-edge/architecture/modules/txpool.md b/archive/edge/it-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..39f40cd7b2 --- /dev/null +++ b/archive/edge/it-edge/architecture/modules/txpool.md @@ -0,0 +1,228 @@ +--- +id: txpool +title: TxPool +description: Spiegazione per il modulo TxPool di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## Panoramica {#overview} + +Il modulo TxPool rappresenta l'implementazione del pool della transazione, dove vengono aggiunte transazioni da diverse parti del sistema. Il modulo espone anche diverse funzionalità utili per gli operatori del nodo, che vengono trattate di seguito. + +## Comandi dell'operatore {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +Gli operatori del nodo possono richiedere questi endpoint del GRPC, come descritto nella sezione **[Comandi CLI](/docs/edge/get-started/cli-commands#transaction-pool-commands)**. + +## Elaborazione delle transazioni {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +Il metodo ***addImpl*** è il pane quotidiano del modulo **TxPool**. +È il luogo centrale dove vengono aggiunte le transazioni nel sistema, chiamate dal servizio GRPC, dagli endpoint JSON RPC, +e ogni volta che il client riceve una transazione attraverso il protocollo di **gossip**. + +Prende come argomento **ctx**, che denota semplicemente il contesto da cui vengono aggiunte le transazioni (GRPC, JSON RPC...).
+L'altro parametro è la lista delle transazioni da aggiungere al pool. + +La cosa principale da notare qui è il controllo del campo **Da** all'interno della transazione: +* Se il campo **Da** è **vuoto**, viene considerata come una transazione non crittografata/non firmata. Questi tipi di transazioni sono accettate solo in modalità sviluppo +* Se il campo **Da** **non è vuoto**, significa che si tratta di una transazione firmata, perciò viene eseguita la verifica della firma + +Dopo tutte queste convalide, le transazioni vengono considerate valide. + +## Strutture dei dati {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +I campi nell'oggetto TxPool che possono creare confusione sono la **coda** e le liste **ordinate**. +* **coda** - Implementazione heap di una lista ordinata di transazioni dell'account (per nonce) +* **ordinata**- Lista ordinata per tutte le transazioni promosse in corso (tutte le transazioni eseguibili). Ordinata per prezzo del gas + +## Gestione degli errori di limite del gas {#gas-limit-error-management} + +Ogni volta che invii una transazione, ci sono tre modi per elaborarla dal TxPool. + +1. Tutte le transazioni in sospeso possono rientrare in un blocco +2. Una o più transazioni in sospeso non può rientrare in un blocco +3. Una o più transazioni in sospeso non rientrerà mai in un blocco + +Qui, la parola **_rientrare_** significa che transazione ha un limite di gas inferiore a quello gas rimanente nel TxPool. + +Il primo scenario non produce alcun errore. + +### Secondo scenario {#second-scenario} + +- Il gas rimanente del TxPool viene impostato al limite del gas dell'ultimo blocco, diciamo **5000** +- Una prima transazione viene elaborata e consuma **3000** unità di gas del TxPool + - Il gas rimanente del TxPool è ora **2000** +- Viene inviata una seconda transazione, che è uguale alla prima poiché consumano entrambe 3000 unità di gas +- Poiché il gas rimanente del TxPool è **inferiore** al gas della transazione, non può essere elaborato nel blocco +corrente + - Viene rimesso in una coda delle transazioni in sospeso in modo che possa essere elaborato nel blocco successivo +- Viene scritto il primo blocco, chiamiamolo **blocco #1** +- Il gas rimanente del TxPool viene impostato sul blocco genitore - limite di gas del **blocco #1** +- La transazione che è stata reinserita nella coda delle transazioni in sospeso di TxPool viene ora elaborata e scritta nel blocco + - Il gas rimanente del TxPool è ora **2000** +- Viene scritto il secondo blocco +- ... + +![Scenario di errore di TxPool #1](/img/edge/txpool-error-1.png) + +### Terzo scenario {#third-scenario} +- Il gas rimanente del TxPool viene impostato al limite del gas dell'ultimo blocco, diciamo **5000** +- Una prima transazione viene elaborata e consuma **3000** unità di gas del TxPool + - Il gas rimanente del TxPool è ora **2000** +- Viene presentata una seconda transazione, con un campo gas impostato a **6000** +- Poiché il limite di gas del blocco è **inferiore** al gas della transazione, tale transazione viene scartata + - Non sarà mai in grado di rientrare in un blocco +- Viene scritto il primo blocco +- ... + + +![Scenario errore TxPool #2](/img/edge/txpool-error-2.png) + +> Questo avviene ogni volta che si ottiene il seguente errore: +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## Target per il gas del blocco {#block-gas-target} + +Ci sono situazioni in cui i nodi vogliono mantenere il limite di gas del blocco al di sotto o in corrispondenza di un determinato target su una catena di esecuzione. + +L'operatore del nodo può impostare il limite di gas target su un nodo specifico, che cercherà di applicare questo limite ai blocchi di nuova creazione. Se anche la maggior parte degli altri nodi ha impostato un limite di gas target simile (o uguale), allora il limite di gas del blocco si sposterà sempre +intorno a quel target di gas del blocco, procedendo lentamente verso di esso (al massimo `1/1024 * parent block gas limit`) man mano che vengono creati i nuovi blocchi. + +### Scenario di esempio {#example-scenario} + +* L'operatore del nodo imposta il limite di gas del blocco per un singolo nodo su `5000` +* Anche altri nodi sono configurati su `5000`, tranne un singolo nodo che è configurato su `7000` +* Quando i nodi che hanno il target del gas impostato su `5000` diventano dei proponenti, verificheranno se il limite del gas ha già raggiunto il target +* Se il limite del gas non è al target (è maggiore/inferiore), il nodo proponente imposterà il target del gas del blocco al massimo (1/1024 * limite del gas madre) nella direzione del target + 1. Es.: `parentGasLimit = 4500` e `blockGasTarget = 5000`, il proponente calcolerà il limite del gas per il nuovo blocco a `4504.39453125` (`4500/1024 + 4500`) + 2. Es.: `parentGasLimit = 5500` e `blockGasTarget = 5000`, il proponente calcolerà il limite del gas per il nuovo blocco a `5494.62890625` (`5500 - 5500/1024`) +* Ciò garantisce che il limite del gas del blocco nella catena verrà mantenuto al target, perché il singolo proponente che ha il target configurato a `7000`non può avanzare di molto il limite e la maggioranza +dei nodi che l'ha impostato a `5000` cercherà sempre di tenerlo lì \ No newline at end of file diff --git a/archive/edge/it-edge/architecture/modules/types.md b/archive/edge/it-edge/architecture/modules/types.md new file mode 100644 index 0000000000..e2647955e9 --- /dev/null +++ b/archive/edge/it-edge/architecture/modules/types.md @@ -0,0 +1,40 @@ +--- +id: types +title: Types +description: Spiegazione del modulo Types di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## Panoramica {#overview} + +Il modulo ****Types implementa tipi di oggetti fondamentali, come: + +* **Indirizzo** +* **Hash** +* **Header** +* molte funzioni di aiuto + +## Codifica/decodifica RLP {#rlp-encoding-decoding} + +A differenza di client come GETH, Polygon Edge non utilizza la riflessione per la
codifica. La preferenza è stata quella di non utilizzare la riflessione, perché introduce nuovi problemi, come la degradazione delle prestazioni e una scalabilità più difficile. + + +Il modulo ****Types fornisce un'interfaccia facile da usare per il marshaling e l'unmarshalling di RLP, utilizzando il pacchetto FastRLP. + +Il marshaling è eseguito attraverso i metodi *MarshalRLPWith* e *MarshalRLPTo*. Gli stessi metodi esistono per l'unmarshalling. + +Definendo manualmente questi metodi, non è necessario che Polygon Edge utilizzi la riflessione. In *rlp_marshal.go* puoi trovare metodi per il marshaling: + +* **Corpi** +* **Blocchi** +* **Header** +* **Ricevute** +* **Registri** +* **Transazioni** \ No newline at end of file diff --git a/archive/edge/it-edge/architecture/overview.md b/archive/edge/it-edge/architecture/overview.md new file mode 100644 index 0000000000..b3198362c8 --- /dev/null +++ b/archive/edge/it-edge/architecture/overview.md @@ -0,0 +1,59 @@ +--- +id: overview +title: Panoramica sull'architettura +sidebar_label: Overview +description: Introduzione all'architettura di Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +Abbiamo iniziato con l'idea di creare un software *modulare*. + +Questo aspetto è presente in quasi tutte le parti del Polygon Edge. Di seguito troverete una breve panoramica dell'architettura costruita e della sua stratificazione. + +## Stratificazione di Polygon Edge {#polygon-edge-layering} + +![Architettura di Polygon Edge](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +Tutto inizia dal layer di networking di base che utilizza **libp2p**. Abbiamo deciso di utilizzare questa tecnologia perché sposa la filosofia di progettazione di Polygon Edge. Libp2p è: + +- Modulare +- Estensibile +- Veloce + +Soprattutto, fornisce un'ottima base per funzioni più avanzate, che tratteremo più avanti. + + +## Sincronizzazione e Consenso {#synchronization-consensus} +La separazione dei protocolli di sincronizzazione e consenso consente la modularità e l'implementazione di meccanismi di sincronizzazione e consenso **personalizzati**, a seconda di come viene eseguito il client. + +Polygon Edge è stato progettato per offrire algoritmi di consenso collegabili in modo autonomo. + +Elenco attuale degli algoritmi di consenso supportati: + +* IBFT PoA +* IBFT PoS + +## Blockchain {#blockchain} +Il layer Blockchain è il livello centrale che coordina tutto nel sistema Polygon Edge. Viene trattata in modo approfondito nella corrispondente sezione *Moduli*. + +## Stato {#state} +Il layer interno di State contiene la logica di transizione di stato. Si occupa di come cambia lo stato quando viene inserito un nuovo blocco. Viene trattata in modo approfondito nella corrispondente sezione *Moduli*. + +## JSON RPC {#json-rpc} +Il layer JSON RPC è un layer API che gli sviluppatori di dApp utilizzano per interagire con la blockchain. Viene trattata in modo approfondito nella corrispondente sezione *Moduli*. + +## TxPool {#txpool} +Il layer TxPool rappresenta il pool di transazioni ed è strettamente collegato agli altri moduli del sistema, poiché le transazioni possono essere aggiunte da più punti di ingresso. + +## grpc {#grpc} +gRPC o Google Remote Procedure Call, è un robusto framework open source che Google inizialmente ha creato per costruire API scalabili e veloci. Il layer GRPC è fondamentale per le interazioni dell'operatore. Attraverso di esso, gli operatori dei nodi possono interagire facilmente con il cliente, offrendo una piacevole Esperienza Utente. diff --git a/archive/edge/it-edge/community/propose-new-feature.md b/archive/edge/it-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..9470369f90 --- /dev/null +++ b/archive/edge/it-edge/community/propose-new-feature.md @@ -0,0 +1,59 @@ +--- +id: propose-new-feature +title: Proporre una nuova funzionalità +description: "Modello di PR e istruzioni per la proposta di una nuova funzionalità." +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## Panoramica {#overview} + +Se desideri includere una correzione, o semplicemente contribuire al codice, ti consigliamo vivamente di contattare prima il team.
Polygon Edge utilizza un modello di proposta di funzionalità relativamente semplice, che è conciso ed efficace. + +## Modello di PR {#pr-template} + +### Descrizione {#description} + +Fornire una descrizione dettagliata di ciò che è stato fatto in questo PR + +### Le modifiche includono {#changes-include} + +- [ ] Bugfix (modifica non di interruzione che risolve un problema) +- [ ] Hotfix (modifica che risolve un problema urgente, e richiede attenzione immediata) +- [ ] Nuova funzionalità (modifica di non interruzione che aggiunge funzionalità) +- [ ] Modifica di interruzione (modifica che non è compatibile con le versioni precedenti e/o modifica la funzionalità corrente) + +### Modifiche di interruzione {#breaking-changes} + +Completa questa sezione se sono state effettuate modifiche di interruzione, altrimenti eliminala + +### Lista di controllo {#checklist} + +- [ ] Ho assegnato questo PR a me stesso +- [ ] Ho aggiunto almeno un revisore +- [ ] Ho aggiunto le etichette pertinenti +- [ ] Ho aggiornato la documentazione ufficiale +- [ ] Ho aggiunto sufficiente documentazione nel codice + +### Test {#testing} + +- [ ] Ho testato questo codice con la suite del test ufficiale +- [ ] Ho testato questo codice manualmente + +## Test manuali {#manual-tests} + +Completa questa sezione se esegui dei test manuali per questa funzionalità, altrimenti eliminala + +### Aggiornamento della documentazione {#documentation-update} + +Collega il PR dell'aggiornamento della documentazione in questa sezione se presente, altrimenti eliminala + +### Commenti aggiuntivi {#additional-comments} + +Invia ulteriori commenti in questa sezione se li hai, altrimenti eliminala \ No newline at end of file diff --git a/archive/edge/it-edge/community/report-bug.md b/archive/edge/it-edge/community/report-bug.md new file mode 100644 index 0000000000..c42c53268e --- /dev/null +++ b/archive/edge/it-edge/community/report-bug.md @@ -0,0 +1,53 @@ +--- +id: report-bug +title: Segnalare un problema +description: Modello e istruzioni per la segnalazione di un problema di Polygon Edge. +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## Panoramica {#overview} + +A volte le cose si rompono.
È sempre meglio informare il team di qualsiasi problema che si possa incontrare.
Sulla pagina GitHub di Polygon Edge, è possibile inserire un nuovo problema e iniziare a discuterne con il team. + +## Template per i problemi {#issue-template} + +## [Oggetto del problema] + +### Descrizione {#description} + +Descrivi il tuo problema nel modo più dettagliato possibile + +### Il tuo ambiente {#your-environment} + +* Sistema operativo e versione +* versione del ramo di Polygon Edge +* che causa il problema + +### Passaggi da riprodurre {#steps-to-reproduce} + +* Dicci come riprodurre questo problema
+* Dove si trova il problema, se lo sai
+* Eventuali comandi che hanno causato il problema + +### Comportamento previsto {#expected-behaviour} + +Dicci cosa dovrebbe accadere + +### Comportamento effettivo {#actual-behaviour} + +Dicci cosa succede invece + +### Log {#logs} + +Si prega di incollare qui gli eventuali log che dimostrano il problema + +### Soluzione proposta {#proposed-solution} + +Se hai un'idea su come risolvere questo problema, scrivila qui, così possiamo iniziare a discuterne. \ No newline at end of file diff --git a/archive/edge/it-edge/configuration/manage-private-keys.md b/archive/edge/it-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..7d0a6ec2c4 --- /dev/null +++ b/archive/edge/it-edge/configuration/manage-private-keys.md @@ -0,0 +1,74 @@ +--- +id: manage-private-keys +title: Gestisci le chiavi private +description: "Come gestire le chiavi private e quali tipi di chiavi ci sono." +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## Panoramica {#overview} + +Polygon Edge ha due tipi di chiavi private che gestisce direttamente: + +* **Chiave privata utilizzata per il meccanismo di consensus** +* **Chiave privata utilizzata per il networking da libp2p** +* **(Facoltativo) Chiave privata BLS utilizzata per il meccanismo di consensus per aggregare le firme dei validatori** + +Attualmente, Polygon Edge non offre il supporto per la gestione diretta dell'account. + +Basato sulla struttura delle directory delineata nella [guida Backup e ripristino](/docs/edge/working-with-node/backup-restore), +Polygon Edge memorizza i file chiave menzionati in due directory distinte - **consensus** e **keystore**. + +## Formato della chiave {#key-format} + +Le chiavi private sono memorizzate in un semplice **formato Base64**, in modo che possano essere leggibili dall'uomo e portabili. + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info Tipo di chiave + +Tutti i file di chiavi private generati e utilizzati all'interno di Polygon Edge si basano su ECDSA con la curva [secp256k1](https://en.bitcoin.it/wiki/Secp256k1). + +Poiché la curva non è standard, non può essere codificata e memorizzata in alcun formato PEM standardizzato. L'importazione di chiavi che non sono conformi a questo tipo di chiave non è supportata. +::: +## Chiave privata di consensus {#consensus-private-key} + +Il file della chiave privata menzionato come *chiave privata di consensus* viene anche chiamato **chiave privata del validatore**. Questa chiave privata viene utilizzata quando il nodo agisce come validatore della rete e deve firmare nuovi dati. + +Il file di chiave privata è situato in `consensus/validator.key`, e aderisce al [formato chiave](/docs/edge/configuration/manage-private-keys#key-format) menzionato. + +:::warning +La chiave privata del validatore è univoca per ogni nodo validatore. La stessa chiave non deve essere condivisa in tutti i validatori, in quanto ciò può compromettere la sicurezza della tua catena. + +::: + +## Chiave privata di rete {#networking-private-key} + +Il file della chiave privata menzionato per il networking viene utilizzato da libp2p per generare il PeerID corrispondente e consentire al nodo di partecipare alla rete. + +Si trova in `keystore/libp2p.key`, e aderisce al [formato chiave](/docs/edge/configuration/manage-private-keys#key-format) menzionato. + +## Chiave segreta BLS {#bls-secret-key} + +Il file chiave segreta BLS viene utilizzato per aggregare i sigilli impegnati nel layer di consensus. La dimensione dei sigilli impegnati aggregati da BLS è inferiore alle firme ECDSA impegnate serializzate. + +La funzionalità BLS è facoltativa e si può scegliere se utilizzare o meno BLS. Consultare [BLS](/docs/edge/consensus/bls) per ulteriori dettagli. + +## Importazione / Esportazione {#import-export} + +Poiché i file chiave vengono memorizzati in un semplice Base64 sul disco, può esserne facilmente eseguito il backup o l'importazione. + +:::caution Modificare i file chiave +Qualsiasi modifica effettuata ai file chiave su una rete già impostata/in esecuzione può portare a gravi interruzioni di rete/consensus. +poiché i meccanismi di consensus e peer discovery archiviano i dati derivati da queste chiavi nella memoria specifica del nodo e fanno affidamento su questi dati +per avviare connessioni ed eseguire la logica del consensus + +::: \ No newline at end of file diff --git a/archive/edge/it-edge/configuration/prometheus-metrics.md b/archive/edge/it-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..ea60ce5f8e --- /dev/null +++ b/archive/edge/it-edge/configuration/prometheus-metrics.md @@ -0,0 +1,35 @@ +--- +id: prometheus-metrics +title: Metriche Prometheus +description: "Come abilitare le metriche Prometheus per Polygon Edge." +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## Panoramica {#overview} + +Polygon Edge può segnalare e servire le metriche Prometheus, che a loro volta possono essere consumate utilizzando il collettore o i collettori Prometheus. + +Le metriche Prometheus sono disabilitate di default. Può essere attivato specificando l'indirizzo dell'ascoltatore utilizzando `--prometheus` il flag o `Telemetry.prometheus` il campo nel file di configurazione. +Le metriche verranno servite sotto `/metrics` sull'indirizzo specificato. + +## Metriche disponibili {#available-metrics} + +Sono disponibili le seguenti metriche: + +| **Nome** | **Tipo** | **Descrizione** | +|-----------------------------------------------|---------------|-------------------------------------------------| +| txpool_pending_transactions | Gauge | Numero di transazioni in attesa in TxPool | +| consensus_validators | Gauge | Numero di validatori | +| consensus_rounds | Gauge | Numero di round | +| consensus_num_txs | Gauge | Numero di transazioni nell'ultimo blocco | +| consensus_block_interval | Gauge | Tempo tra questo e l'ultimo blocco in secondi | +| network_peers | Gauge | Numero di peer collegati | +| network_outbound_connections_count | Gauge | Numero di connessioni in uscita | +| network_inbound_connections_count | Gauge | Numero di connessioni in entrata | +| network_pending_outbound_connections_count | Gauge | Numero di connessioni in uscita in attesa | +| network_pending_inbound_connections_count | Gauge | Numero di connessioni in entrata in sospeso | \ No newline at end of file diff --git a/archive/edge/it-edge/configuration/sample-config.md b/archive/edge/it-edge/configuration/sample-config.md new file mode 100644 index 0000000000..4d50dc26a6 --- /dev/null +++ b/archive/edge/it-edge/configuration/sample-config.md @@ -0,0 +1,150 @@ +--- +id: sample-config +title: File di configurazione del server +description: "Avvia il server Polygon Edge utilizzando un file di configurazione." +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# File di configurazione del server {#server-configuration-file} +L'avvio del server con varie opzioni di configurazione può essere eseguito utilizzando un file di configurazione anziché utilizzare solo i flag. Il comando utilizzato per avviare il server con un file di configurazione: `polygon-edge server --config ` + +## Esporta il file di configurazione con la configurazione predefinita {#export-config-file-with-default-configuration} +La configurazione con le impostazioni predefinite per il server Polygon Edge può essere esportata in un file di configurazione in formato `yaml` o `json`. +Questo file può essere utilizzato come modello per l'esecuzione del server utilizzando un file di configurazione. + +### YAML {#yaml} +Per generare il file di configurazione in formato `yaml`: +```bash +polygon-edge server export --type yaml +``` +oppure solo +```bash +polygon-edge server export +``` +il file di configurazione denominato `default-config.yaml` verrà creato nella stessa directory da cui è stato eseguito questo comando. + +Esempio di file: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +Per generare il file di configurazione in formato `json`: +```bash +polygon-edge server export --type json +``` +il file di configurazione denominato `default-config.json` verrà creato nella stessa directory da cui è stato eseguito questo comando. + +Esempio di file: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +Consulta la sezione [Comandi CLI](/docs/edge/get-started/cli-commands) per ottenere informazioni su come utilizzare questi parametri. + +### Schema di TypeScript {#typescript-schema} + +Di seguito è riportato il formato del campione per il file di configurazione. È scritto in TypeScript per esprimere i tipi di proprietà (`string`, `number`, `boolean`), da esso si potrebbe ricavare la configurazione. Vale la pena ricordare che il type `PartialDeep` da `type-fest` viene utilizzato per esprimere che tutte le proprietà sono facoltative. + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/it-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/it-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..d1cfbd81c0 --- /dev/null +++ b/archive/edge/it-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,126 @@ +--- +id: set-up-aws-ssm +title: Configurazione di AWS SSM (Systems Manager) +description: "Configurare AWS SSM (Systems Manager) per Polygon Edge." +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## Panoramica {#overview} + +Attualmente, Polygon Edge si occupa di mantenere due importanti segreti di runtime: +* La **chiave privata del validatore** utilizzata dal nodo, se il nodo è un validatore. +* La **chiave privata di rete** utilizzata da libp2p, per partecipare e comunicare con altri peer. + + +Per ulteriori informazioni, leggere la [Guida alla gestione delle chiavi private](/docs/edge/configuration/manage-private-keys). + +I moduli di Polygon Edge **non devono sapere come mantenere i segreti**. In definitiva, a un modulo non dovrebbe interessare se un segreto è memorizzato su un server lontano o localmente sul disco del nodo. + +Tutto ciò che un modulo deve sapere sulla gestione dei segreti è **sapere come usare il segreto**, **sapere quali segreti ottenere e quali salvare**. I dettagli più fini dell'implementazione di queste operazioni sono delegati a `SecretsManager`, che ovviamente è un'astrazione. + +L'operatore del nodo che sta avviando Polygon Edge può ora specificare quale gestore di segreti desidera utilizzare e non appena il gestore dei segreti corretto è istanziato, i moduli si occupano dei segreti attraverso l'interfaccia menzionata - senza preoccuparsi se i segreti sono memorizzati su un disco o su un server. + +Questo articolo illustra in dettaglio i passaggi necessari per rendere operativo Polygon Edge con le guide precedenti di [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) + +:::info . +Prima di leggere questo articolo,** si consiglia di** leggere gli articoli sulla [**Configurazione locale**](/docs/edge/get-started/set-up-ibft-locally) e [**la Configurazione del Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud). +::: + + +## Prerequisiti {#prerequisites} +### Policy IAM {#iam-policy} +L'utente deve creare un criterio IAM che consenta operazioni di lettura/scrittura per AWS Systems Manager Parameter Store. Dopo aver creato con successo il criterio IAM, l'utente deve collegarlo all'istanza EC2 che esegue il server Polygon Edge. La policy IAM dovrebbe avere un aspetto simile a questo: +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +Ulteriori informazioni sui ruoli IAM di AWS SSM sono disponibili nei [documenti di AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html). + +Informazioni necessarie prima di continuare: +* **Regione** (regione in cui risiedono Systems Manager e ii nodi) +* **Percorso del parametro** (percorso arbitrario in cui verrà inserito il segreto, ad esempio `/polygon-edge/nodes`) + +## Passo 1 - Generare la configurazione del gestore dei segreti {#step-1-generate-the-secrets-manager-configuration} + +Affinché Polygon Edge sia in grado di comunicare senza problemi con l'SSM di AWS, deve analizzare un file di configurazione già generato, che contenga tutte le informazioni necessarie per la memorizzazione segreta su AWS SSM. + +Per generare la configurazione, eseguire il seguente comando: + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +Parametri presenti: +* `PATH`è il percorso in cui esportare il file di configurazione. Predefinito `./secretsManagerConfig.json` +* `NODE_NAME`è il nome del nodo corrente per il quale si sta impostando la configurazione di AWS SSM. Può essere un valore arbitrario. Predefinito `polygon-edge-node` +* `REGION`è la regione in cui risiede l'AWS SSM. Questa deve essere la stessa regione del nodo che utilizza AWS SSM. +* `SSM_PARAM_PATH`è il nome del percorso in cui verrà memorizzato il segreto. Ad esempio se `--name node1` e `ssm-parameter-path=/polygon-edge/nodes` +sono specificati, il segreto verrà memorizzato come `/polygon-edge/nodes/node1/` + +:::caution Nomi del nodo +Fai attenzione quando specifici i nomi del nodo. + +Polygon Edge utilizza il nome del nodo specificato per tenere traccia dei segreti che genera e utilizza su SSM AWS. Specificare un nome di nodo esistente può avere come conseguenza la mancata scrittura del segreto in AWS SSM. + +I segreti sono memorizzati nel seguente percorso di base: `SSM_PARAM_PATH/NODE_NAME` +::: + +## Passo 2 - Inizializzare le chiavi segrete utilizzando la configurazione {#step-2-initialize-secret-keys-using-the-configuration} + +Ora che il file di configurazione è presente, si possono inizializzare le chiavi segrete richieste con il +file di configurazione impostato nel Passo 1, utilizzando `--config`: + +```bash +polygon-edge secrets init --config +``` + +Il parametro `PATH` è la posizione del parametro del gestore dei segreti generato in precedenza dal Passo 1. + + +:::info Policy IAM + +Questo passaggio fallirà se il criterio IAM che consente operazioni di lettura/scrittura non è configurato correttamente e/o non è collegato all'istanza EC2 che esegue il comando. +::: + +## Passo 3 - Generare il file genesi {#step-3-generate-the-genesis-file} + +Il file genesi deve essere generato in modo simile a quello delle guide [**Configurazione locale**](/docs/edge/get-started/set-up-ibft-locally) +e [**Configurazione del Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud), con modifiche minime. + +Poiché viene utilizzato AWS SSM invece del file system locale, gli indirizzi dei validatori devono essere aggiunti tramite il flag `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Passo 4 - Avviare il client Polygon Edge {#step-4-start-the-polygon-edge-client} + +Ora che le chiavi sono state impostate e il file genesi è stato generato, l'ultimo passo di questo processo è l'avvio di Polygon Edge con il comando `server`. + +Il comando `server`viene utilizzato nello stesso modo delle guide precedenti, con una piccola aggiunta - il flag `--secrets-config`: + +```bash +polygon-edge server --secrets-config ... +``` + +Il parametro `PATH` è la posizione del parametro del secrets manager generato in precedenza dal Passo 1. \ No newline at end of file diff --git a/archive/edge/it-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/it-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..a94d17d186 --- /dev/null +++ b/archive/edge/it-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,107 @@ +--- +id: set-up-gcp-secrets-manager +title: Configurazione di GCP Secrets Manager +description: "Configurazione del Gestore di segreti GCP per Polygon Edge." +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## Panoramica {#overview} + +Attualmente, Polygon Edge si occupa di mantenere due importanti segreti di runtime: +* La **chiave privata del validatore** utilizzata dal nodo, se il nodo è un validatore. +* La **chiave privata di rete** utilizzata da libp2p, per partecipare e comunicare con altri peer. + + +Per ulteriori informazioni, leggere la [Guida alla gestione delle chiavi private](/docs/edge/configuration/manage-private-keys). + +I moduli di Polygon Edge **non devono sapere come mantenere i segreti**. In definitiva, a un modulo non dovrebbe interessare se un segreto è memorizzato su un server lontano o localmente sul disco del nodo. + +Tutto ciò che un modulo deve sapere sulla gestione dei segreti è **sapere come usare il segreto**, **sapere quali segreti ottenere e quali salvare**. I dettagli più fini dell'implementazione di queste operazioni sono delegati a `SecretsManager`, che ovviamente è un'astrazione. + +L'operatore del nodo che sta avviando Polygon Edge può ora specificare quale gestore di segreti desidera utilizzare e non appena il gestore dei segreti corretto è istanziato, i moduli si occupano dei segreti attraverso l'interfaccia menzionata - senza preoccuparsi se i segreti sono memorizzati su un disco o su un server. + +Questo articolo illustra in dettaglio i passaggi necessari per rendere operativo Polygon Edge con [GCP Secret Manager](https://cloud.google.com/secret-manager). + +:::info Guide precedenti +Prima di leggere questo articolo,** si consiglia di** leggere gli articoli sulla [**Configurazione locale**](/docs/edge/get-started/set-up-ibft-locally) e [**la Configurazione del Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud). +::: + + +## Prerequisiti {#prerequisites} +### Account di fatturazione GCP Billing Account {#gcp-billing-account} +Per utilizzare GCP Secrets Manager, l'utente deve avere l'[account di fatturazione](https://console.cloud.google.com/) abilitato sul portale GCP. +I nuovi account Google sulla piattaforma GCP vengono forniti con dei fondi per iniziare, come una sorta di prova gratuita. Maggiori informazioni sui [documenti GCP](https://cloud.google.com/free) + +### API di Secrets Manager {#secrets-manager-api} +L'utente dovrà abilitare le API di GCP Secrets Manager prima di poterlo utilizzare. Si può procedere all'abilitazione tramite il [portale delle API di Secrets Manager](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com). Maggiori informazioni: [Configurazione di Secret Manager](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + +### Credenziali per GCP {#gcp-credentials} +Infine, l'utente deve generare delle nuove credenziali che verranno utilizzate per l'autenticazione. Lo si può fare seguendo le istruzioni riportate [qui](https://cloud.google.com/secret-manager/docs/reference/libraries). +Il file json generato contenente le credenziali deve essere trasferito ad ogni nodo che deve utilizzare GCP Secrets Manager. + +Informazioni necessarie prima di continuare: +* **ID di progetto** (l'id di progetto definito sulla piattaforma GCP) +* **Posizione del file con le credenziali** (il percorso del file json contenente le credenziali) + +## Passo 1 - Generare la configurazione di Secrets manager {#step-1-generate-the-secrets-manager-configuration} + +Affinché Polygon Edge sia in grado di comunicare senza problemi con GCP SM, deve analizzare un file di configurazione già generato, che contenga tutte le informazioni necessarie per la memorizzazione segreta su GCP SM. + +Per generare la configurazione, eseguire il seguente comando: + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +Parametri presenti: +* `PATH`è il percorso in cui esportare il file di configurazione. Predefinito `./secretsManagerConfig.json` +* `NODE_NAME` è il nome del nodo corrente per il quale si sta impostando la configurazione di GCP SM. Può essere un valore arbitrario. Predefinito `polygon-edge-node` +* `PROJECT_ID`è l'ID del progetto che l'utente ha definito nella console GCP durante la configurazione dell'account e l'attivazione delle API di Secrets Manager. +* `GCP_CREDS_FILE` è il percorso del file json contenente le credenziali che consentiranno l'accesso in lettura/scrittura a Secrets Manager. + +:::caution Nomi del nodo +Fai attenzione quando specifichi i nomi dei nodi. + +Polygon Edge utilizza il nome del nodo specificato per tenere traccia dei segreti che genera e utilizza su SSM GCP. Specificare un nome di nodo esistente può avere come conseguenza il non riuscire a scrivere il segreto a GCP SM. + +I segreti sono memorizzati nel seguente percorso di base: `projects/PROJECT_ID/NODE_NAME` +::: + +## Passo 2 - Inizializzare le chiavi segrete utilizzando la configurazione {#step-2-initialize-secret-keys-using-the-configuration} + +Ora che il file di configurazione è presente, si possono inizializzare le chiavi segrete richieste con il +file di configurazione impostato nel Passo 1, utilizzando `--config`: + +```bash +polygon-edge secrets init --config +``` + +Il parametro `PATH` è la posizione del parametro del secrets manager generato in precedenza dal Passo 1. + +## Passo 3 - Generare il file genesi {#step-3-generate-the-genesis-file} + +Il file genesi deve essere generato in modo simile a quello delle guide [**Configurazione locale**](/docs/edge/get-started/set-up-ibft-locally) +e [**Configurazione del Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud), con modifiche minime. + +Poiché viene utilizzato GCP SM invece del file system locale, gli indirizzi dei validatori devono essere aggiunti tramite il flag `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Passo 4 - Avviare il client Polygon Edge {#step-4-start-the-polygon-edge-client} + +Ora che le chiavi sono state impostate e il file genesi è stato generato, l'ultimo passo di questo processo è l'avvio di Polygon Edge con il comando `server`. + +Il comando `server`viene utilizzato nello stesso modo delle guide precedenti, con una piccola aggiunta - il flag `--secrets-config`: + +```bash +polygon-edge server --secrets-config ... +``` + +Il parametro `PATH` è la posizione del parametro del secrets manager generato in precedenza dal Passo 1. \ No newline at end of file diff --git a/archive/edge/it-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/it-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..bb37b36048 --- /dev/null +++ b/archive/edge/it-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,109 @@ +--- +id: set-up-hashicorp-vault +title: Configura Hashicorp Vault +description: "Configura Hashicorp Vault per Polygon Edge." +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## Panoramica {#overview} + +Attualmente, Polygon Edge si occupa di mantenere due importanti segreti di runtime: +* La **chiave privata del validatore** utilizzata dal nodo, se il nodo è un validatore. +* La **chiave privata di rete** utilizzata da libp2p, per partecipare e comunicare con altri peer. + + +:::warning +La chiave privata del validatore è univoca per ogni nodo validatore. La stessa chiave non deve essere condivisa in tutti i validatori, in quanto ciò può compromettere la sicurezza della tua catena. + +::: + +Per ulteriori informazioni, leggere la [Guida alla gestione delle chiavi private](/docs/edge/configuration/manage-private-keys). + +I moduli di Polygon Edge **non devono sapere come mantenere i segreti**. In definitiva, a un modulo non dovrebbe interessare se un segreto è memorizzato su un server lontano o localmente sul disco del nodo. + +Tutto ciò che un modulo deve sapere sulla gestione dei segreti è **sapere come usare il segreto**, **sapere quali segreti ottenere e quali salvare**. I dettagli più fini dell'implementazione di queste operazioni sono delegati a `SecretsManager`, che ovviamente è un'astrazione. + +L'operatore del nodo che sta avviando Polygon Edge può ora specificare quale gestore di segreti desidera utilizzare e non appena il gestore dei segreti corretto è istanziato, i moduli si occupano dei segreti attraverso l'interfaccia menzionata - senza preoccuparsi se i segreti sono memorizzati su un disco o su un server. + +Questo articolo illustra in dettaglio i passaggi necessari per rendere operativo Polygon Edge con un server [Hashicorp Vault](https://www.vaultproject.io/). + +:::info Guide precedenti +Prima di leggere questo articolo,** si consiglia di** leggere gli articoli sulla [**Configurazione locale**](/docs/edge/get-started/set-up-ibft-locally) e [**la Configurazione del Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud). +::: + + +## Prerequisiti {#prerequisites} + +Questo articolo presuppone che un'istanza funzionante del server Hashicorp Vault **sia già impostata**. + +Inoltre, è necessario che il server Hashicorp Vault utilizzato per Polygon Edge abbia **abilitato lo storage KV**. + +Informazioni necessarie prima di continuare: +* **L'URL del server** (URL dell'API del server Hashicorp Vault) +* **Token** (token di accesso usato per accedere allo storage engine KV) + +## Passo 1 - Generare la configurazione di Secrets manager {#step-1-generate-the-secrets-manager-configuration} + +Affinché Polygon Edge sia in grado di comunicare senza problemi con il server del Vault, deve analizzare un file di configurazione già generato, che contenga tutte le informazioni necessarie per la memorizzazione segreta sul Vault. + +Per generare la configurazione, eseguire il seguente comando: + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +Parametri presenti: +* `PATH`è il percorso in cui esportare il file di configurazione. Predefinito `./secretsManagerConfig.json` +* `TOKEN` è il token di accesso precedentemente menzionato nella [sezione dei prerequisiti](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `SERVER_URL` è l'URL dell'API per il server Vault, menzionato anche nella [sezione dei prerequisiti](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `NODE_NAME`è il nome del nodo corrente per cui viene impostata la configurazione del Vault. Può essere un valore arbitrario. Predefinito `polygon-edge-node` + +:::caution Nomi del nodo + +Fai attenzione quando specifichi i nomi dei nodi. + +Polygon Edge utilizza il nome del nodo specificato per tenere traccia dei segreti che genera e utilizza sull'istanza del Vault. +La specifica di un nome nodo esistente può avere conseguenze sulla sovrascrittura dei dati sul server del Vault. + +I segreti sono memorizzati nel seguente percorso di base: `secrets/node_name` +::: + +## Passo 2 - Inizializzare le chiavi segrete utilizzando la configurazione {#step-2-initialize-secret-keys-using-the-configuration} + +Ora che il file di configurazione è presente, si possono inizializzare le chiavi segrete richieste con il +file di configurazione impostato nel Passo 1, utilizzando `--config`: + +```bash +polygon-edge secrets init --config +``` + +Il parametro `PATH` è la posizione del parametro del secrets manager generato in precedenza dal Passo 1. + +## Passo 3 - Generare il file genesi {#step-3-generate-the-genesis-file} + +Il file genesi deve essere generato in modo simile a quello delle guide [**Configurazione locale**](/docs/edge/get-started/set-up-ibft-locally) +e [**Configurazione del Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud), con modifiche minime. + +Poiché viene utilizzato Hashicorp Vault invece del file system locale, gli indirizzi dei validatori devono essere aggiunti tramite il flag `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Passo 4 - Avviare il client Polygon Edge {#step-4-start-the-polygon-edge-client} + +Ora che le chiavi sono state impostate e il file genesi è stato generato, l'ultimo passo di questo processo è l'avvio di Polygon Edge con il comando `server`. + +Il comando `server`viene utilizzato nello stesso modo delle guide precedenti, con una piccola aggiunta - il flag `--secrets-config`: + +```bash +polygon-edge server --secrets-config ... +``` + +Il parametro `PATH` è la posizione del parametro del secrets manager generato in precedenza dal Passo 1. \ No newline at end of file diff --git a/archive/edge/it-edge/consensus/bls.md b/archive/edge/it-edge/consensus/bls.md new file mode 100644 index 0000000000..011c9cec60 --- /dev/null +++ b/archive/edge/it-edge/consensus/bls.md @@ -0,0 +1,144 @@ +--- +id: bls +title: BLS +description: "Spiegazione e istruzioni relative alla modalità BLS." +keywords: + - docs + - polygon + - edge + - bls +--- + +## Panoramica {#overview} + +BLS è uno schema di firma crittografica che permette a un utente di verificare che un firmatario sia autentico. È uno schema di firma che può aggregare più firme. In Polygon Edge, BLS è utilizzato per impostazione predefinita per garantire una maggiore sicurezza nella modalità di consenso IBFT. BLS può aggregare le firme in un singolo array di byte e ridurre la dimensione dell'intestazione del blocco. Ogni catena può scegliere se utilizzare o meno BLS. La chiave ECDSA viene utilizzata indipendentemente dal fatto che la modalità BLS sia abilitata o meno. + +## Presentazione video {#video-presentation} + +[![bls - video](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## Come configurare una catena con BLS {#how-to-setup-a-new-chain-using-bls} + +Per istruzioni dettagliate sulla configurazione, consultare le sezioni [Configurazione locale](/docs/edge/get-started/set-up-ibft-locally) / [Configurazione cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +## Come migrare da una catena PoA ECDSA esistente a una catena PoA BLS {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +Questa sezione descrive come utilizzare la modalità BLS in una catena PoA esistente. Per abilitare il BLS in una catena PoA sono necessari i seguenti passaggi. + +1. Interrompere tutti i nodi +2. Generare le chiavi BLS per i validatori +3. Aggiungere un'impostazione di fork in genesis.json +4. Riavviare tutti i nodi + +### 1. Arrestare di tutti i nodi {#1-stop-all-nodes} + +Terminare tutti i processi dei validatori premendo Ctrl + c (Control + c). Ricordare l'ultima altezza del blocco (il numero di sequenza più alto nel registro dei blocchi impegnati). + +### 2. Generare la chiave BLS {#2-generate-the-bls-key} + +`secrets init`con il `--bls`genera una chiave BLS. Per mantenere la chiave ECDSA e la chiave di rete esistente e aggiungere una nuova chiave BLS, `--ecdsa`e `--network`devono essere disabilitati. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Aggiungere l'impostazione di fork + {#3-add-fork-setting} + +`ibft switch`aggiunge un'impostazione di fork, che abilita il BLS nella catena esistente, in `genesis.json`. + +Per le reti PoA, i validatori devono essere indicati nel comando. Come per il modo di `genesis`comando, è possibile utilizzare i flag `--ibft-validators-prefix-path` o `--ibft-validator`per specificare il validatore. + +Specificare l'altezza da cui parte la catena usando BLS con il flag `--from`. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. Riavviare tutti i nodi {#4-restart-all-nodes} + +Riavviare tutti i nodi con il comando `server`. Dopo la creazione del blocco al punto `from`specificato nel passaggio precedente, la catena abilita il BLS e mostra i log come di seguito: + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +Inoltre, i log mostrano quale modalità di verifica è stata utilizzata per generare ciascun blocco dopo la sua creazione. + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## Come migrare da una catena ECDSA PoS esistente a una catena BLS PoS {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +Questa sezione descrive come utilizzare la modalità BLS in una catena PoS esistente. +Per abilitare il BLS nella catena PoS sono necessari i seguenti passaggi. + +1. Interrompere tutti i nodi +2. Generare le chiavi BLS per i validatori +3. Aggiungere un'impostazione di fork in genesis.json +4. Chiamare il contratto di staking per registrare la chiave pubblica di BLS. + +5. Riavviare tutti i nodi + +### 1. Arrestare di tutti i nodi {#1-stop-all-nodes-1} + +Terminare tutti i processi dei validatori premendo Ctrl + c (Control + c). Ricordare l'ultima altezza del blocco (il numero di sequenza più alto nel registro dei blocchi impegnati). + +### 2. Generare la chiave BLS {#2-generate-the-bls-key-1} + +`secrets init`con il flag `--bls`genera la chiave BLS. Per mantenere la chiave ECDSA e la chiave di rete esistente e aggiungere una nuova chiave BLS, `--ecdsa`e `--network`devono essere disabilitati. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Aggiungere l'impostazione di fork + {#3-add-fork-setting-1} + +Il comando `ibft switch`aggiunge un'impostazione di fork, che abilita il BLS dal centro della catena, in `genesis.json`. + +Specificare l'altezza da cui parte la catena utilizzando la modalità BLS con il flag `from` e l'altezza a cui viene aggiornato il contratto con il flag `development`. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. Registrare la chiave pubblica BLS nel contratto di staking {#4-register-bls-public-key-in-staking-contract} + +Dopo l'aggiunta del fork e il riavvio dei validatori, ogni validatore deve richiamare `registerBLSPublicKey` nel contratto di staking per registrare la chiave pubblica BLS. Questo deve essere fatto dopo l'altezza specificata in `--deployment` prima dell'altezza specificata in `--from`. + +Lo script per registrare la chiave pubblica BLS è definito nel [repo Staking Smart Contract](https://github.com/0xPolygon/staking-contracts). + +Impostazione `BLS_PUBLIC_KEY`da registrare nel file `.env`. Per maggiori dettagli sugli altri parametri, consultare [pos-stake-unstake](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts). + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +Il comando seguente registra la chiave pubblica BLS inserita `.env` nel contratto. + +```bash +npm run register-blskey +``` + +:::warning I validatori devono registrare manualmente la chiave pubblica BLS +In modalità BLS, i validatori devono avere il proprio indirizzo e la chiave pubblica BLS. Il livello di consenso ignora i validatori che non hanno registrato la chiave pubblica BLS nel contratto quando il consenso recupera le informazioni sui validatori dal contratto. +::: + +### 5. Riavviare tutti i nodi {#5-restart-all-nodes} + +Riavviare tutti i nodi con il comando `server`. La catena abilita il BLS dopo la creazione del blocco al punto `from`specificato nel passaggio precedente. diff --git a/archive/edge/it-edge/consensus/migration-to-pos.md b/archive/edge/it-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..7b2f7fb6f4 --- /dev/null +++ b/archive/edge/it-edge/consensus/migration-to-pos.md @@ -0,0 +1,39 @@ +--- +id: migration-to-pos +title: Migrazione da PoA a PoS +description: "Come migrare dalla modalità PoA a PoS IBFT e viceversa." +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## Panoramica {#overview} + +Questa sezione guida alla migrazione dalla modalità PoA a quella PoS IBFT, e viceversa, per un cluster in funzione, senza la necessità di resettare la blockchain. + +## Come migrare a PoS {#how-to-migrate-to-pos} + +È necessario arrestare tutti i nodi, aggiungere la configurazione di fork in genesis.json con il comando `ibft switch`e riavviare i nodi. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution Switching durante l'utilizzo di ECDSA +Quando si utilizza ECDSA, la `--ibft-validator-type`bandiera deve essere aggiunta allo switch, menzionando che the viene utilizzata. Se non incluso, Edge verrà automaticamente commutato a BLS. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::Per passare a PoS, dovrai specificare 2 altezza di blocco: `deployment`e . `from`è `deployment`l'altezza per distribuire il contratto di staking ed è l'altezza `from`dell'inizio di PoS. Il contratto di staking sarà implementato all'indirizzo `0x0000000000000000000000000000000000001001`al `deployment`, come nel caso del contratto pre-implementato. + +Si prega di controllare [Proof of Stake](/docs/edge/consensus/pos-concepts) per maggiori dettagli sul contratto di Staking. + +:::warning I validatori devono fare stake manualmente +Ogni validatore deve fare stake dopo che il contratto è stato implementato a `deployment`e prima di `from`per essere un validatore all'inizio del PoS. Ogni validatore aggiornerà il proprio set di validatori in base a quello impostato nel contratto di staking all'inizio del PoS. + +Per saperne di più su Staking, visita il **[Set up e utilizza la Proof of Stake](/docs/edge/consensus/pos-stake-unstake)**. +::: diff --git a/archive/edge/it-edge/consensus/poa.md b/archive/edge/it-edge/consensus/poa.md new file mode 100644 index 0000000000..6e9fae200c --- /dev/null +++ b/archive/edge/it-edge/consensus/poa.md @@ -0,0 +1,104 @@ +--- +id: poa +title: Proof of Authority (PoA) +description: "Spiegazione e istruzioni riguardanti la Proof of Autority." +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## Panoramica {#overview} + +L'IBFT PoA è il meccanismo di consenso predefinito nel Polygon Edge. Nella PoA, i validatori sono i responsabili della creazione dei blocchi e della loro aggiunta in serie alla blockchain. + +Tutti i validatori costituiscono un insieme dinamico di validatori, dove questi ultimi possono essere aggiunti o rimossi dall'insieme utilizzando un meccanismo di voto. Ciò significa che i validatori possono essere votati per entrare/uscire dall'insieme dei validatori se la maggioranza (51%) dei nodi validatori vota per aggiungere/rimuovere un determinato validatore dall'insieme. In questo modo, i validatori malintenzionati possono essere riconosciuti e rimossi dalla rete, mentre nuovi validatori affidabili possono essere aggiunti. + +Tutti i validatori propongono a turno il blocco successivo (round-robin) e, affinché il blocco venga convalidato/inserito nella blockchain, una supermaggioranza (più di 2/3) dei validatori deve approvarlo. + +Oltre ai validatori, ci sono i non validatori che non partecipano alla creazione del blocco ma partecipano al processo di convalida del blocco. + +## Aggiungere un validatore all'insieme di validatori {#adding-a-validator-to-the-validator-set} + +Questa guida descrive come aggiungere un nuovo nodo validatore a una rete IBFT attiva con 4 nodi validatori. Se hai bisogno di aiuto a impostare la rete si riferimento alle sezioni [di Configurazione](/edge/get-started/set-up-ibft-locally.md) [locale/Configurazione](/edge/get-started/set-up-ibft-on-the-cloud.md) Cloud. + +### Passo 1: inizializzare le cartelle dati per IBFT e generare le chiavi di validazione per il nuovo nodo + {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +Per essere operativi con IBFT sul nuovo nodo, occorre innanzitutto inizializzare le cartelle di dati e generare le chiavi: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +Questo comando stamperà la chiave del validatore (indirizzo) e l'ID del nodo. La chiave di convalida (indirizzo) è necessaria per il passaggio successivo. + +### Passo 2: proporre un nuovo candidato da altri nodi validatori {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +Affinché un nuovo nodo diventi validatore, deve essere proposto da almeno il 51% dei validatori. + +Esempio di come proporre un nuovo validatore (`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`) dal nodo validatore esistente sull'indirizzo grpc: 127.0.0.1:1000: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +La struttura dei comandi IBFT è stata affrontata nella sezione [Comandi CLI](/docs/edge/get-started/cli-commands). + +:::info Chiave pubblica BLS +La chiave pubblica BLS è necessaria solo se la rete funziona con BLS, per la rete che non funziona in modalità BLS `--bls` non è necessaria. +::: + +### Passo 3: eseguire il nodo client {#step-3-run-the-client-node} + +Poiché in questo esempio stiamo cercando di eseguire una rete in cui tutti i nodi si trovano sulla stessa macchina, dobbiamo fare attenzione a evitare conflitti delle porte. + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +Dopo aver recuperato tutti i blocchi, nella console si noterà che un nuovo nodo sta partecipando alla validazione + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info Promuovere un non validatore a validatore +`--seal`Naturalmente, un non validatore può diventare un validatore attraverso il processo di voto, ma per essere incluso con successo nell'insieme dei validatori dopo il processo di voto, il nodo deve essere riavviato con il flag. +::: + +## Rimuovere un validatore dall'insieme di validatori {#removing-a-validator-from-the-validator-set} + +Questa operazione è abbastanza semplice. Per rimuovere un nodo validatore dall'insieme dei validatori, questo comando deve essere eseguito per la maggior parte dei nodi validatori. + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info Chiave pubblica BLS +La chiave pubblica BLS è necessaria solo se la rete funziona con BLS, per la rete che non funziona in modalità BLS `--bls` non è necessaria. +::: + +Dopo aver eseguito i comandi, si osserva che il numero di validatori è diminuito (in questo esempio di log da 4 a 3). + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/it-edge/consensus/pos-concepts.md b/archive/edge/it-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..e66b16172d --- /dev/null +++ b/archive/edge/it-edge/consensus/pos-concepts.md @@ -0,0 +1,110 @@ +--- +id: pos-concepts +title: Proof-of-Stake +description: "Spiegazione e istruzioni riguardanti la Proof of Stake." +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## Panoramica {#overview} + +Questa sezione mira a fornire una migliore panoramica di alcuni concetti attualmente presenti nella Proof of Stake (PoS). Implementazione di Polygon Edge. + +L'implementazione della Proof of Stake (PoS) di Polygon Edge vuole essere un'alternativa all'implementazione PoA IBFT esistente, per offrire agli operatori dei nodi la possibilità di scegliere facilmente tra le due quando avviano una catena. + +## Caratteristiche della PoS {#pos-features} + +La logica alla base dell'implementazione di Proof of Stake è situata all'interno dello lo **[Smart Contract](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)**. + +Questo contratto viene implementato in anticipo ogni volta che viene inizializzata una catena Polygon Edge con meccanismo PoS ed è disponibile all'indirizzo +`0x0000000000000000000000000000000000001001` dal blocco `0`. + +### Epoche {#epochs} + +Le epoche sono un concetto introdotto con l'aggiunta della PoS al Polygon Edge. + +Le epoche sono considerate un lasso di tempo speciale (in blocchi) in cui un certo insieme di validatori può produrre blocchi. Le loro lunghezze sono modificabili, il che significa che gli operatori dei nodi possono configurare la lunghezza di un'epoca durante la generazione del file genesi. + + +Alla fine di ogni epoca, viene creato un _blocco di epoca_ e dopo questo evento inizia una nuova epoca. Per saperne di più sui blocchi delle epoche, vedere la sezione [Blocchi dell'epoca](/docs/edge/consensus/pos-concepts#epoch-blocks). + +I set di validatori vengono aggiornati alla fine di ogni epoca. I nodi interrogano il set di validatori dallo Staking Smart Contract durante la creazione del blocco epoca e salvano i dati ottenuti nella memoria locale. Questo ciclo di interrogazione e salvataggio viene ripetuto alla fine di ogni epoca. + +In sostanza, garantisce che lo Staking Smart Contract abbia il pieno controllo sugli indirizzi dell'insieme di validatori, e +lascia ai nodi una sola responsabilità - interrogare il contratto una volta sola durante un'epoca per recuperare le informazioni più recenti sul set di validatori. + Questo alleggerisce la responsabilità dei singoli nodi di occuparsi degli insiemi di validatori. + +### Staking {#staking} + +Gli indirizzi possono metter in staking fondi sullo Staking Smart Contract invocando il `stake`metodo e specificando un valore per +l'importo messo in staking nella transazione: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +Mettendo in staking i fondi sullo Staking Smart Contract, gli indirizzi possono entrare nell'insieme dei validatori e quindi partecipare al +processo di produzione dei blocchi. + +:::info Soglia per lo staking + +Attualmente, la soglia minima per entrare nell'insieme dei validatori è mettere in staking `1 ETH` +::: + +### Togliere dallo staking {#unstaking} + +Gli indirizzi che hanno messo in staking dei fondi possono **ritirare tutti i loro fondi in una sola volta**. + + +Ritirare dallo staking può essere fatto con il metodo `unstake`nello Staking Smart Contract: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +Dopo aver ritirato i propri fondi, gli indirizzi vengono rimossi dall'insieme di validatori impostato sullo Staking Smart Contract e non saranno considerati validatori durante l'epoca successiva. + +## Blocchi dell'epoca {#epoch-blocks} + +I **blocchi dell'epoca** sono un concetto introdotto nell'implementazione della PoS di IBFT in Polygon Edge. + +In sostanza, i blocchi dell'epoca sono blocchi speciali che **non contengono transazioni** e si verificano solo alla **fine di un epoca**. + Ad esempio, se la **dimensione** dell'epoca è impostata per `50`blocchi, i blocchi di epoch sarebbero considerati blocchi `50`, `100``150`e così via. + +Vengono utilizzati per eseguire una logica aggiuntiva che non dovrebbe verificarsi durante la normale produzione di blocchi. + +Soprattutto, sono un'indicazione per il nodo che **ha bisogno di recuperare le informazioni più recenti sul set di validatori** dallo Staking Smart Contract. + +Dopo l'aggiornamento dell'insieme di validatori al blocco dell'epoca, l'insieme di validatori (modificato o invariato) +viene utilizzato per i `epochSize - 1`blocchi successivi, fino a quando non viene nuovamente aggiornato prelevando le informazioni più recenti dallo Staking Smart Contract. + +Le lunghezze dell'epoca (in blocchi) sono modificabili durante la generazione del file genesi, utilizzando uno speciale flag `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +La dimensione predefinita di un'epoca è costituita da `100000`blocchi in Polygon Edge. + +## Pre-implementazione del contratto + {#contract-pre-deployment} + +Polygon Edge _pre-implementa_ lo [Staking Smart Contract](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol) durante **la generazione di genesi** all'indirizzo `0x0000000000000000000000000000000000001001`. + +Lo fa senza un EVM in funzione, modificando direttamente lo stato della blockchain dello Smart Contract, utilizzando i valori di configurazione passati al comando genesi. diff --git a/archive/edge/it-edge/consensus/pos-stake-unstake.md b/archive/edge/it-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..938cdbdad6 --- /dev/null +++ b/archive/edge/it-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,164 @@ +--- +id: pos-stake-unstake +title: Impostazione e utilizzo di Proof of Stake (PoS) +description: "Mettere in staking, ritirare dallo staking e altre istruzioni relative al staking." +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## Panoramica {#overview} + +Questa guida spiega in dettaglio come configurare una rete Proof of Stake con Polygon Edge, come mettere in staking i fondi per i nodi per diventare validatori e come togliere fondi dallo staking. + +È **fortemente incoraggiato** a leggere e passare attraverso le sezioni [Configurazione locale](/docs/edge/get-started/set-up-ibft-locally) / [Configurazione del cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud), prima di continuare +con questa guida PoS. Queste sezioni illustrano i passi necessari per avviare un cluster Proof of Authority (PoA) con il sistema di gestione dei dati +Polygon Edge. + +Attualmente, non vi è alcun limite al numero di validatori che possono puntare fondi sullo Staking Smart Contract. + +## Staking Smart Contract {#staking-smart-contract} + +Il repo dello Staking Smart Contract si trova [qui](https://github.com/0xPolygon/staking-contracts). + + +Contiene gli script di test necessari, i file ABI e soprattutto lo Staking Smart Contract stesso. + +## Configurazione di un cluster di N nodi {#setting-up-an-n-node-cluster} + +La configurazione di una rete con Polygon Edge è trattata nelle le sezioni [Configurazione locale](/docs/edge/get-started/set-up-ibft-locally) e [Configurazione del Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +L'**unica differenza** tra la creazione di un cluster PoS e PoA è nella parte di generazione del file genesi. + +**Quando si genera il file genesi per un cluster PoS, è necessario un flag aggiuntivo`--pos`** : + +```bash +polygon-edge genesis --pos ... +``` + +## Impostazione della lunghezza di un'epoca {#setting-the-length-of-an-epoch} + +Le epoche sono trattate in dettaglio nella sezione [Blocchi dell'epoca](/docs/edge/consensus/pos-concepts#epoch-blocks). + + +Per impostare la dimensione di un'epoca per un cluster (in blocchi), quando si genera il file di genesi, un flag aggiuntivo +va specificato `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +Questo valore specifica nel file di genesi che la dimensione dell'epoca deve essere di `50`blocchi. + +Il valore predefinito per la dimensione di un'epoca (in blocchi) è `100000`. + +:::info Diminuire la lunghezza dell'epoca +Come indicato nella sezione [Blocchi dell'epoca](/docs/edge/consensus/pos-concepts#epoch-blocks), + i blocchi dell'epoca vengono utilizzati per aggiornare i set di validatori per i nodi. + +La lunghezza predefinita dell'epoca in blocchi (`100000`) può richiedere molto tempo per gli aggiornamenti dei set di validatori. Considerando che i nuovi blocchi vengono aggiunti ~2 s, ci vorrebbero ~55.5 h per l'insieme di validatori per un eventuale cambio. + +L'impostazione di un valore più basso per la lunghezza dell'epoca garantisce un aggiornamento più frequente del set di validatori. +::: + +## Utilizzo degli script dello Staking Smart Contract {#using-the-staking-smart-contract-scripts} + +### Prerequisiti {#prerequisites} + +Il repo di Staking Smart Contract è un progetto Hardhat, che richiede NPM. + +Per inizializzarlo correttamente, nella directory principale eseguire: + +```bash +npm install +```` + +### Configurazione degli script di aiuto forniti {#setting-up-the-provided-helper-scripts} + +Gli script per interagire con lo Smart Contract Staking distribuito si trovano sulla [repo Staking Smart Contract](https://github.com/0xPolygon/staking-contracts). + +Creare un `.env`file con i seguenti parametri nella posizione del repo Smart Contracts: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +Dove sono i parametri: + +* **JSONRPC_URL** - l'endpoint JSON-RPC per il nodo in esecuzione +* **PRIVATE_KEYS** - chiavi provate dell'indirizzo dello staker. +* **STAKING_CONTRACT_ADDRESS** - l'indirizzo dello staking smart contract ( +default `0x0000000000000000000000000000000000001001`) +* **BLS_PUBLIC_KEY** - chiave pubblica BLS dello staker. Necessaria solo se la rete è in esecuzione con BLS + +### Fondi staking {#staking-funds} + +:::info Indirizzo staking +Lo Staking Smart Contract è pre-implementato all' indirizzo `0x0000000000000000000000000000000000001001`. + +Qualsiasi tipo di interazione con il meccanismo di staking avviene attraverso lo Staking Smart Contract all'indirizzo specificato. + +Per saperne di più sullo Staking Smart Contract, visitare lo **[Staking Smart Contract](/docs/edge/consensus/pos-concepts#contract-pre-deployment)** . + +::: + +Per entrare a far parte del set di validatori, un indirizzo deve metter in staking una certa quantità di fondi al di sopra di una soglia. + +Attualmente, la soglia predefinita per entrare a far parte del set di validatori è `1 ETH`. + +Lo staking può essere avviato chiamando il `stake`metodo dello Staking Smart Contract e specificando un valore `>= 1 ETH`. + +Dopo che il `.env`file menzionato nella +[sezione precedente](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) è stato impostato e una +catena è stata avviata in modalità PoS, è possibile effettuare lo staking con il seguente comando nella repo Staking Smart Contract: + +```bash +npm run stake +``` + +Lo script `stake`Hardhat fissa una quantità predefinita di `1 ETH`, che può essere cambiata modificando il file `scripts/stake.ts`. + +Se i fondi che vengono in staking sono `>= 1 ETH`, il validatore impostato sullo Staking Smart Contract viene aggiornato e l'indirizzo farà parte dell'insieme dei validatori a partire dall'epoca successiva. + +:::info Registrazione delle chiavi BLS + +Se la rete funziona in modalità BLS, per diventare validatori i nodi devono registrare le loro chiavi pubbliche BLS dopo lo staking + +Questo può essere fatto con il seguente comando: + +```bash +npm run register-blskey +``` +::: + +### Rimuovere i fondi dallo staking {#unstaking-funds} + +Gli indirizzi che hanno fondi in staking possono **ritirare tutti i loro fondi** in una sola volta. + +Dopo che il `.env`file menzionato nella +[sezione precedente](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) è stato configurato e una catena è stata avviata in modalità PoS, il ritiro dallo staking può essere effettuato con il seguente comando nel file +repo dello Staking Smart Contract: + +```bash +npm run unstake +``` + +### Recuperare l'elenco degli stakers {#fetching-the-list-of-stakers} + +Tutti gli indirizzi che hanno fondi in staking vengono salvati nello Staking Smart Contract. + +Dopo che il `.env`file menzionato nella +[sezione precedente](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) è stato configurato e una catena è stata avviata in modalità PoS, la ricerca dell'elenco dei validatori può essere effettuata con il +seguente comando nella repo dello Staking Smart Contract: + +```bash +npm run info +``` diff --git a/archive/edge/it-edge/faq/Contracts.md b/archive/edge/it-edge/faq/Contracts.md new file mode 100644 index 0000000000..d18877cb2f --- /dev/null +++ b/archive/edge/it-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: Domande frequenti sugli Smart Contract +description: "Domande frequenti sugli Smart Contract di Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## Polygon Edge supporta gli Smart Contract? {#does-polygon-edge-support-smart-contracts} + +Sì. Le reti Polygon Edge sono blockchain compatibili con Ethereum, quindi gli Smart Contract che sono implementabili su Ethereum sono implementabili anche sulle catene Polygon Edge. + +## È possibile aggiornare la logica del contratto di staking per la PoS dopo la distribuzione? {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +Per il momento, dopo aver avviato la rete PoS, non è possibile modificare la logica del contratto di staking, poiché fa parte del file genesis. Quindi non è possibile, ad esempio, modificare il numero minimo/massimo di validatori. È possibile mettere in stake o smettere di fare staking, aggiungere o rimuovere i validatori. + + + diff --git a/archive/edge/it-edge/faq/Gas.md b/archive/edge/it-edge/faq/Gas.md new file mode 100644 index 0000000000..2148bdca45 --- /dev/null +++ b/archive/edge/it-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: Domande frequenti sul gas +description: "Domande frequenti sul gas per Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Come applicare un prezzo del gas minimo? {#how-to-enforce-a-minimum-gas-price} +Puoi utilizzare il `--price-limit`flag fornito sul comando del server. In questo modo il nodo accetterà solo le transazioni che hanno un prezzo del gas superiore o uguale al limite impostato. Per essere certi che sia applicato all'intera rete, è necessario assicurarsi che tutti i nodi abbiano lo stesso limite di prezzo. + + +## È possibile effettuare transazioni con commissioni del gas pari a 0? {#can-you-have-transactions-with-0-gas-fees} +Sì, è possibile. Il limite di prezzo predefinito che i nodi applicano è `0`, ovvero i nodi accetteranno transazioni con un prezzo del gas impostato su `0`. + +## Come impostare l'offerta totale del token gas(nativo)? {#how-to-set-the-gas-native-token-total-supply} + +È possibile impostare un saldo preminato sugli account (indirizzi) utilizzando il `--premine flag`. Si prega di notare che questa è una configurazione del file genesis e non può essere modificata in seguito. + +Esempio su come utilizzare `--premine flag`: + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +Questo imposta un saldo preminato di 1000 ETH a 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862 (l'importo dell'argomento è in wei). + +L'importo preminato del token gas sarà l'offerta totale. Nessun'altra quantità della valuta nativa (token gas) può essere coniata in seguito. + +## Edge supporta ERC-20 come token gas? {#does-edge-support-erc-20-as-a-gas-token} + +Edge non supporta il token ERC-20 come token gas. Per il gas è supportata solo la valuta nativa di Edge. + +## Come aumentare il limite di gas? {#how-to-increase-the-gas-limit} + +Ci sono due opzioni per aumentare il limite di gas in Polygon Edge: +1. Wiping la catena e aumentando `block-gas-limit`al massimo valore uint64 nel file genesis +2. Usa la `--block-gas-target`bandiera con un alto valore per aumentare il limite di gas di tutti i nodi. Questo richiede il reboot nodo. Spiegazione dettagliata [qui](/docs/edge/architecture/modules/txpool/#block-gas-target). \ No newline at end of file diff --git a/archive/edge/it-edge/faq/Tokens.md b/archive/edge/it-edge/faq/Tokens.md new file mode 100644 index 0000000000..0ffe060348 --- /dev/null +++ b/archive/edge/it-edge/faq/Tokens.md @@ -0,0 +1,23 @@ +--- +id: tokens +title: Domande frequenti sui token +description: "Domande frequenti sui token di Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## Polygon Edge supporta EIP-1559? {#does-polygon-edge-support-eip-1559} +Al momento, Polygon Edge non supporta EIP-1559. + +## Come impostare il simbolo della valuta (token)? {#how-to-set-the-currency-token-symbol} + +Il simbolo del token è solo un elemento dell'interfaccia utente, quindi non può essere configurato o codificato in modo fisso in nessuna parte della rete. +Puoi comunque cambiarlo quando aggiungi la rete al wallet, come Metamask, ad esempio. + +## Cosa succede alle transazioni quando una catena si arresta? {#what-happens-to-transactions-when-a-chain-halts} + +Tutte le transazioni che non sono state elaborate sono all'interno della TxPool (incise o promosse coda). Se la catena si arresta (tutte le blocco di produzione), queste transazioni non saranno mai in blocco.
Questo non è solo il caso in cui la catena si arresta. Se i nodi vengono arrestati o riavviati, tutte le transazioni che non sono state eseguite e che sono ancora in TxPool, verranno silenziosamente rimosse.
La stessa cosa accadrà alle transazioni quando viene introdotta una modifica di rottura, in quanto è necessario che i nodi vengano riavviati. diff --git a/archive/edge/it-edge/faq/Validators.md b/archive/edge/it-edge/faq/Validators.md new file mode 100644 index 0000000000..635d3d6e26 --- /dev/null +++ b/archive/edge/it-edge/faq/Validators.md @@ -0,0 +1,83 @@ +--- +id: validators +title: Domande frequenti sui validatori +description: "Domande frequenti sui validatori di Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Come aggiungere/rimuovere un validatore? {#how-to-add-remove-a-validator} + +### Poa {#poa} +L'aggiunta/rimozione dei validatori viene effettuata votando. [Qui](/docs/edge/consensus/poa) puoi trovare una guida completa sull'argomento. + +### PoS {#pos} +[Qui](/docs/edge/consensus/pos-stake-unstake) puoi trovare una guida su come fare lo staking di fondi, in modo che un nodo possa diventare un validatore, e su come annullare lo staking (rimuovere il validatore). + +Nota che: +- Puoi utilizzare il flag di genesi `--max-validator-count` per impostare un numero massimo di staker che possono unirsi al set di validatori. +- Puoi utilizzare il flag della genesi `--min-validator-count ` per impostare il numero minimo di staker necessari per unirsi al set di validatori (`1` di default). +- Quando viene raggiunto il numero massimo di validatori, non puoi aggiungere un altro validatore fino a quando non ne rimuovi uno esistente dal set (non importa se l'importo messo in staking del nuovo è più alto). Se rimuovi un validatore, il numero di validatori rimanenti non può essere inferiore a `--min-validator-count`. +- Esiste una soglia predefinita di `1` unità di valuta della rete (gas) nativa per diventare un validatore. + + + +## Quanto spazio su disco è consigliato per un validatore? {#how-much-disk-space-is-recommended-for-a-validator} + +Consigliamo di iniziare con 100G come pista stimata in modo prudente, e di assicurarsi che sia possibile ridimensionare il disco in seguito. + + +## Esiste un limite al numero di validatori? {#is-there-a-limit-to-the-number-of-validators} + +Se parliamo di limitazioni tecniche, Polygon Edge non ha esplicitamente un limite al numero di nodi che puoi avere in una rete. Puoi impostare i limiti di connessione (conteggi di connessioni in entrata/in uscita) su base per nodo. + +Se parliamo di limitazioni pratiche, vedrai una performance più degradata con un cluster di 100 nodi rispetto a un cluster di 10 nodi: Aumentando il numero di nodi nel tuo cluster, aumenti la complessità delle comunicazioni e solo il sovraccarico di rete in generale. Tutto dipende dal tipo di rete in esecuzione, e dal tipo di topologia di rete che hai. + +## Come passare da PoA a PoS? {#how-to-switch-from-poa-to-pos} + +PoA è il meccanismo di consensus predefinito. Nel caso di un nuovo cluster, per passare a PoS, dovrai aggiungere il flag `--pos` quando generi il file di genesi. Se hai un cluster in esecuzione, puoi trovare [qui](/docs/edge/consensus/migration-to-pos) come effettuare il passaggio. Tutte le informazioni di cui hai bisogno sui nostri meccanismi di consensus e sulla configurazione sono disponibili nella nostra [sezione sul consensus](/docs/edge/consensus/poa). + +## Come faccio ad aggiornare i miei nodi quando c'è una modifica sostanziale? {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +[Qui](/docs/edge/validator-hosting#update) puoi trovare una guida dettagliata su come eseguire questa procedura. + +## L'importo di staking minimo è configurabile per PoS Edge? {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +Di default l'importo di staking minimo è `1 ETH`, e non è configurabile. + +## Perché i comandi JSON RPC `eth_getBlockByNumber` e `eth_getBlockByHash` non restituiscono l'indirizzo del minatore? {#not-return-the-miner-s-address} + +Il consensus utilizzato attualmente in Polygon Edge è IBFT 2.0, che, a sua volta, si basa sul meccanismo di voto spiegato in Clique PoA: [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225). + +Guardando all'EIP-225 (Clique PoA), questa è la parte rilevante che spiega per cosa viene utilizzato `miner` (alias `beneficiary`): + +
Riutilizziamo i campi di intestazione ethash come segue:
    +
  • beneficiario / minatore: Indirizzo a cui proporre la modifica dell'elenco dei firmatari autorizzati.
  • +
      +
    • Deve essere riempito normalmente con degli zeri, modificato solo durante la votazione.
    • +
    • Tuttavia i valori arbitrari sono consentiti (anche quelli senza senso, come la votazione dei non firmatari) per evitare una complessità extra nelle implementazioni intorno alla meccanica di voto.
    • +
    • Deve essere riempito con degli zeri sui blocchi di checkpoint (cioè transizione di epoca).
    • +
    + +
+ +
+ +Così, il campo `miner` viene utilizzato per proporre un voto per un indirizzo specifico, non per mostrare il proponente del blocco. + +Le informazioni sul proponente del blocco possono essere trovate recuperando la pubkey dal campo Seal del campo dati extra Istanbul codificato RLP nelle intestazioni del blocco. + +## Quali parti e valori di Genesis possono essere modificate in modo sicuro? {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +Assicurati di creare una copia manuale del file genesis.json esistente prima di tentare di modificarlo. Inoltre, l'intera catena deve essere fermata prima di modificare il file genesis.json. Una volta che il file di genesis viene modificato, la nuova versione di esso deve distribuire in tutti i nodi non validatore e valdiator + +::: + +**Solo la sezione degli bootnodes del file genesis può essere modificata in modo sicuro**, dove è possibile aggiungere o rimuovere gli bootnodes dall'elenco. \ No newline at end of file diff --git a/archive/edge/it-edge/get-started/cli-commands.md b/archive/edge/it-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..b209915302 --- /dev/null +++ b/archive/edge/it-edge/get-started/cli-commands.md @@ -0,0 +1,2221 @@ +--- +id: cli-commands +title: Comandi CLI +description: "Elenco dei comandi CLI e dei flag di comando per Polygon Edge." +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +Questa sezione illustra i comandi presenti, i flag di comando in Polygon Edge e il loro utilizzo. + +:::tip Supporto per l'output JSON + +Il flag `--json` è supportato da alcuni comandi. Questo flag indica al comando di stampare l'output nel formato JSON + +::: + +## Comandi di avvio {#startup-commands} + +| **Comando** | **Descrizione** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| server | Il comando predefinito che avvia il client della blockchain, avviando tutti i moduli insieme | +| genesi | Genera un file *genesis.json*, usato per impostare uno stato di catena predefinito prima di avviare il client. La struttura del file genesi è descritta a seguito del | +| genesis predeploy | Predeploys uno Smart Contract per le nuove reti | + +### flag del server {#server-flags} + + +| **Tutte le bandiere del server** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [prometheus](/docs/edge/get-started/cli-commands#prometheus) | [block-gas-target](/docs/edge/get-started/cli-commands#block-gas-target) | +| [max-peers](/docs/edge/get-started/cli-commands#max-peers) | [max-inbound-peers](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [max-outbound-peers](/docs/edge/get-started/cli-commands#max-outbound-peers) | [max-enqueued](/docs/edge/get-started/cli-commands#max-enqueued) | +| [log-level](/docs/edge/get-started/cli-commands#log-level) | [log-to](/docs/edge/get-started/cli-commands#log-to) | +| [catena](/docs/edge/get-started/cli-commands#chain) | [join](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [limite di prezzo](/docs/edge/get-started/cli-commands#price-limit) | [max-slots](/docs/edge/get-started/cli-commands#max-slots) | +| [Configurazione](/docs/edge/get-started/cli-commands#config) | [secrets-config](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-interval](/docs/edge/get-started/cli-commands#dev-interval) | +| [no-discover](/docs/edge/get-started/cli-commands#no-discover) | [restore](/docs/edge/get-started/cli-commands#restore) | +| [block-time](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +Consente di specificare la directory dei dati utilizzata per memorizzare i dati del client Polygon Edge. Predefinito: `./test-chain`. + + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +Imposta l'indirizzo e la porta per il servizio JSON-RPC `address:port` +Se viene definita solo la porta, `:10001`il binding verrà effettuato su tutte le `0.0.0.0:10001` interfacce. Se viene omesso, il servizio si legherà al `address:port`predefinito. Indirizzo predefinito `0.0.0.0:8545`. + +--- + +####

json-rpc-block-range-limit + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +Imposta l'intervallo massimo di blocchi da considerare quando si eseguono richieste json-rpc che includono i valori fromBlock/toBlock (ad esempio eth_getLogs). Predefinito:`1000` + +--- + +####

json-rpc-batch-request-limit + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +Imposta la lunghezza massima da considerare quando si gestiscono le richieste batch json-rpc. Predefinito: `20` + +--- + +####

grpc + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +Imposta l'indirizzo e la porta per il servizio gRPC `address:port`. +Indirizzo predefinito `127.0.0.1:9632`. + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +Imposta l'indirizzo e la porta per il servizio libp2p `address:port`. +Indirizzo predefinito `127.0.0.1:1478`. + +--- + +####

prometheus + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +Imposta l'indirizzo e la porta per il server Prometheus `address:port` +Se viene definita solo la porta, `:5001`il servizio si legherà a tutte le interfacce `0.0.0.0:5001`. +Se omesso, il servizio non verrà avviato. + +--- + +####

block-gas-target + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +Imposta il limite di gas del blocco target per la catena. Predefinito (non eseguito): `0`. + +Per una spiegazione più dettagliata del target del gas del blocco, consultare la [sezione TxPool](/docs/edge/architecture/modules/txpool#block-gas-target). + +--- + +####

max-peers + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +Imposta il numero massimo di peer del client. Predefinito: `40` + +Il limite del peer deve essere specificato utilizzando `max-peers` o il flag `max-inbound/outbound-peers`. + +--- + +####

max-inbound-peers + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +Imposta il numero massimo di peer in entrata del client. Se `max-peers`è impostato, il limite max-inbound-peer viene calcolato con le seguenti formule. + +`max-inbound-peer = InboundRatio * max-peers`, dov'`InboundRatio`è il `0.8`. + +--- + +####

max-outbound-peers + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +Imposta il numero massimo di peer in uscita del client. Se `max-peers`è impostato, il numero max-outbound-peer viene calcolato utilizzando le seguenti formule. + +`max-outbound-peer = OutboundRatio * max-peers`, dov'`OutboundRatio`è il `0.2`. + +--- + +####

max-enqueued + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +Imposta il numero massimo di transazioni in attesa per account. Predefinito:`128` + +--- + +####

log-level + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +Imposta il livello di log per l'output della console. Predefinito: `INFO` + +--- + +####

log-to + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +Definisce il nome del file di log che conterrà tutti i risultati del comando del server. +Per impostazione predefinita, tutti i log del server vengono inviati alla console (stdout), +ma se il flag è impostato, non ci sarà alcun output sulla console quando si esegue il comando del server. + +--- + +####

catena + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +Specifica il file genesi usato per avviare la catena. Predefinito: `./genesis.json` + +--- + +####

join + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Specifica l'indirizzo del peer da unire. + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +Imposta l'indirizzo IP esterno senza la porta, come può essere visto dai peer. + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +Imposta l'indirizzo DNS dell'host. Può essere utilizzato per pubblicizzare un DNS esterno. Supporta `dns`,`dns4`,`dns6`. + +--- + +####

limite di prezzo + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +Imposta il limite minimo di prezzo del gas da applicare per l'accettazione nel pool. Predefinito: `1` + +--- + +####

max-slots + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +Imposta il numero massimo di slot nel pool. Predefinito: `4096` + +--- + +####

Configurazione + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +Specifica il percorso della configurazione della CLI. Supporti `.json`. + +--- + +####

secrets-config + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +Imposta il percorso del file di configurazione di SecretsManager. Utilizzato per Hashicorp Vault, AWS SSM e GCP Secrets Manager. Se omesso, viene utilizzato il secrets manager FS locale. + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +Imposta il client in modalità dev. Predefinita: `false`. In modalità dev, la scoperta peer è disabilitata per impostazione predefinita. + +--- + +####

dev-interval + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +Imposta l'intervallo di notifica dev del client in secondi. Predefinito: `0` + +--- + +####

no-discover + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +Impedisce al client di scoprire altri peer. Predefinito: `false` + +--- + +####

restore + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +Ripristina i blocchi dal file di archivio specificato + +--- + +####

block-time + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +Imposta il tempo di produzione dei blocchi in secondi. Predefinito: `2` + +--- + +####

access-control-allow-origins + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +Imposta i domini autorizzati a condividere le risposte alle richieste JSON-RPC. +Aggiungere più flag `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"`per autorizzare più domini. Se omesso l'intestazione Access-Control-Allow-Origins sarà impostata su `*`e tutti i domini saranno autorizzati. + +--- + +### flag genesis {#genesis-flags} +| **Tutte le bandiere di genesi** | +|---------------------------------------|---------------------------------------------| +| [dir](/docs/edge/get-started/cli-commands#dir) | [Nome](/docs/edge/get-started/cli-commands#name) | +| [pos](/docs/edge/get-started/cli-commands#pos) | [epoch-size](/docs/edge/get-started/cli-commands#epoch-size) | +| [premine](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [ibft-validator-type](/docs/edge/get-started/cli-commands#ibft-validator-type) | [ibft-validators-prefix-path](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [ibft-validator](/docs/edge/get-started/cli-commands#ibft-validator) | [block-gas-limit](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [consensus](/docs/edge/get-started/cli-commands#consensus) | [bootnode](/docs/edge/get-started/cli-commands#bootnode) | +| [max-validator-count](/docs/edge/get-started/cli-commands#max-validator-count) | [min-validator-count](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

dir + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +Imposta la directory per i dati della genesi di Polygon Edge. Predefinito: `./genesis.json`. + +--- + +####

Nome + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +Imposta il nome della catena. Predefinito: `polygon-edge` + +--- + +####

pos + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +Imposta il flag che indica che il cliente deve utilizzare la Proof of Stake IBFT. +Si imposta in maniera predefinita su Proof of Authority se il flag non viene fornito o `false`. + +--- + +####

epoch-size + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +Imposta la dimensione dell'epoca per la catena. Predefinito `100000`. + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +Imposta gli account e i saldi predefiniti nel formato `address:amount`. +L'importo può essere in formato decimale o esadecimale. +Bilancio preminato: `0xD3C21BCECCEDA1000000`(1 milione di gettoni di valuta nativa). + +--- + +####

chainid + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +Imposta l'ID della catena. Predefinito: `100` + +--- + +####

ibft-validator-type + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +Specifica la modalità di convalida delle intestazioni di blocco. Valori possibili: `[ecdsa, bls]`. Predefinito: `bls` + +--- + +####

ibft-validators-prefix-path + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +Percorso del prefisso per la cartella del validatore. Deve essere presente se il flag `ibft-validator`viene omesso. + +--- + +####

ibft-validator + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Imposta gli indirizzi passati come validatori IBF. Deve essere presente se il flag `ibft-validators-prefix-path`viene omesso. +1. Se la rete funziona con ECDSA, il formato è `--ibft-validator [ADDRESS]`. +2. Se la rete funziona con BLS, il formato è `--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]`. + +--- + +####

block-gas-limit + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +Si riferisce alla quantità massima di gas utilizzata da tutte le operazioni in un blocco. Predefinito: `5242880` + +--- + +####

consensus + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +Imposta il protocollo di consenso. Predefinito: `pow` + +--- + +####

bootnode + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +URL multiddr per il bootstrap della scoperta p2p. Questo flag può essere utilizzato più volte. +Invece di un indirizzo IP, è possibile fornire l'indirizzo DNS del bootnode. + +--- + +####

max-validator-count + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +Il numero massimo di staker in grado di unirsi al set di validatori in un consenso PoS. Questo numero non può superare il valore di MAX_SAFE_INTEGER (2^53 - 2). + +--- + +####

min-validator-count + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +Il numero minimo di staker necessari per unirsi al set di validatori in un consenso PoS. Questo numero non può superare il valore di max-validator-count. +Predefinito a 1. + +--- + +### genesis predeploy le bandiere {#genesis-predeploy-flags} + +

percorso artefatto-

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +Imposta il percorso degli artefatti del contratto JSON che contiene il `abi`, `bytecode`e .`deployedBytecode` + +--- + +

catena

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +Imposta il percorso del `genesis.json`file che dovrebbe essere aggiornato. Predefinito `./genesis.json`. + +--- + +

constructor-args

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +Impostare gli argomenti costruttori dello Smart Contract se presente. Per una guida dettagliata su come queste argomentazioni dovrebbero essere presentate, si prega di fare riferimento [all'articolo di predeployment](/docs/edge/additional-features/predeployment). + +--- + +

predeploy-address

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +Imposta l'indirizzo a cui predeploy Predefinito `0x0000000000000000000000000000000000001100`. + +--- + + +## Comandi dell'operatore {#operator-commands} + +### Comandi dei peer {#peer-commands} + +| **Comando** | **Descrizione** | +|------------------------|-------------------------------------------------------------------------------------| +| aggiunta peer | Aggiunge un nuovo peer utilizzando il suo indirizzo libp2p | +| elenco peer | Elenca tutti i peer a cui il client è connesso tramite libp2p | +| stato peer | Restituisce lo stato di uno specifico peer dall'elenco dei peer, utilizzando l'indirizzo libp2p | + +

flag aggiungi peer

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Indirizzo libp2p del peer nel formato multiaddr. + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +Indirizzo dell'API gRPC. Predefinito: `127.0.0.1:9632` + +

flag elenco peer

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +Indirizzo dell'API gRPC. Predefinito: `127.0.0.1:9632` + +

flag stato peer

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +ID del nodo Libp2p di uno specifico peer all'interno della rete p2p. + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +Indirizzo dell'API gRPC. Predefinito: `127.0.0.1:9632` + +### Comandi IBFT {#ibft-commands} + +| **Comando** | **Descrizione** | +|------------------------|-------------------------------------------------------------------------------------| +| istantanea ibft | Restituisce l'istantanea IBFT | +| candidati ibft | Interroga l'insieme attuale dei candidati proposti e i candidati che non sono ancora stati inclusi. | +| proponi ibft | Propone un nuovo candidato da aggiungere/rimuovere dal set di validatori. | +| stato ibft | Restituisce lo stato generale del client IBFT | +| interruttore ibft | Aggiungere configurazioni di fork nel file genesis.json per cambiare il tipo di IBFT | +| quorum ibft | Specifica il numero di blocchi dopo il quale verrà utilizzato il metodo della dimensione ottimale del quorum per raggiungere il consenso. | + + +

flag istantanea ibft

+ +

numero

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +L'altezza del blocco (numero) per l'istantanea. + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +Indirizzo dell'API gRPC. Predefinito: `127.0.0.1:9632` + +

flag candidati ibft

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Indirizzo dell'API gRPC. Predefinito: `127.0.0.1:9632` + +

ibft propone flags

+ +

vote

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +Propone una modifica al set di validatori. Valori possibili: `[auth, drop]`. + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +Indirizzo dell'account da votare. + + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +Chiave pubblica BLS dell'account da votare, necessaria solo in modalità BLS. + + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Indirizzo dell'API gRPC. Predefinito: `127.0.0.1:9632` + +

flag di stato ibft

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +Indirizzo dell'API gRPC. Predefinito: `127.0.0.1:9632` + +

flag interruttore ibft

+ +

catena

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +Specifica il file genesi da aggiornare. Predefinito: `./genesis.json` + +--- + +

Tipo

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +Specifica il tipo di IBFT da commutare. Valori possibili: `[PoA, PoS]`. + +--- + +

implementazione

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +Specifica l'altezza della distribuzione del contratto. Disponibile solo con PoS. + +--- + +

da

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +Specifica la modalità di convalida delle intestazioni di blocco. Valori possibili: `[ecdsa, bls]`. Predefinito: `bls` + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +Percorso del prefisso per le directory dei nuovi validatori. Deve essere presente se il flag `ibft-validator`è omesso. Disponibile solo quando la modalità IBFT è PoA (il flag `--pos` è omesso). + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Imposta gli indirizzi passati come validatori IBFT utilizzati dopo il fork. Deve essere presente se il flag `ibft-validators-prefix-path`è omesso. Disponibile solo in modalità PoA. +1. Se la rete funziona con ECDSA, il formato è `--ibft-validator [ADDRESS]`. +2. Se la rete funziona con BLS, il formato è `--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]`. + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +Il numero massimo di staker in grado di unirsi al set di validatori in un consenso PoS. Questo numero non può superare il valore di MAX_SAFE_INTEGER (2^53 - 2). + +--- + +

min-validator-count

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +Il numero minimo di staker necessari per unirsi al set di validatori in un consenso PoS. Questo numero non può superare il valore di max-validator-count. +Predefinito a 1. + +Specifica l'altezza di inizio del fork. + +--- + +

flag quorum ibft

+ +

da

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +L'altezza per passare il calcolo del quorum a QuorumOptimal, che utilizza la formula `(2/3 * N)`, con il numero di nodi validatori `N`. Si noti che questo è per la compatibilità all'indietro, cioè solo per le catene che utilizzavano un calcolo Quorum legacy fino a una certa altezza del blocco. + +--- + +

catena

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +Specifica il file genesi da aggiornare. Predefinito: `./genesis.json` + +### Comandi Transazione Pool {#transaction-pool-commands} + +| **Comando** | **Descrizione** | +|------------------------|--------------------------------------------------------------------------------------| +| stato txpool | Restituisce il numero di transazioni nel pool | +| sottoscrizione txpool | Si iscrive agli eventi del pool di transazioni | + +

flag stato txpool

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +Indirizzo dell'API gRPC. Predefinito: `127.0.0.1:9632` + +

flag abbonamento txpool

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +Indirizzo dell'API gRPC. Predefinito: `127.0.0.1:9632` + +--- + +

promosso

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +Si iscrive agli eventi tx promossi nel TxPool. + +--- + +

dropped

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +Si iscrive agli eventi tx abbandonati nel TxPool. + +--- + +

retrocesso

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +Si iscrive agli eventi tx retrocessi nel TxPool. + +--- + +

aggiunto

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +Si iscrive agli eventi tx aggiunti al TxPool. + +--- + +

in coda

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +Si iscrive agli eventi tx in coda nell'account + +--- + +### Comandi blockchain {#blockchain-commands} + +| **Comando** | **Descrizione** | +|------------------------|-------------------------------------------------------------------------------------| +| stato | Restituisce lo stato del client La risposta dettagliata può essere visualizzata sotto | +| monitor | Si iscrive a un flusso di eventi della blockchain. La risposta dettagliata può essere visualizzata sotto | +| versione | Restituisce la versione corrente del client | + +

flag stato

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +Indirizzo dell'API gRPC. Predefinito: `127.0.0.1:9632` + +

flag monitor

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +Indirizzo dell'API gRPC. Predefinito: `127.0.0.1:9632` + +--- +

comando della versione

+ + + + + + version + + + + +Visualizza la versione di rilascio, il git branch, commit hash e il tempo di costruzione. + +## Comandi segreti {#secrets-commands} + +| **Comando** | **Descrizione** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| segreti init | Inizializza le chiavi private al gestore di segreti corrispondenti | +| genera segreti | Genera un file di configurazione del gestore dei segreti che può essere analizzato da Polygon Edge | +| segreti di uscita | Stampare l'indirizzo di chiave pubblica BLS, l'indirizzo di chiave pubblica del validatore e il nodo id per riferimento | + +### flag segreti init {#secrets-init-flags} + +

Configurazione

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +Imposta il percorso del file di configurazione di SecretsManager. Usato per Hashicorp Vault. Se omesso, viene utilizzato il gestore dei segreti FS locale. + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +Imposta la directory per i dati di Polygon Edge se si usa il FS locale. + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +Imposta il flag che indica se generare una chiave ECDSA. Predefinito: `true` + +--- + +

network

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +Imposta il flag che indica se generare una chiave di rete Libp2p. Predefinito: `true` + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +Imposta il flag che indica se generare una chiave BLS. Predefinito: `true` + +### flag genera segreti {#secrets-generate-flags} + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +Imposta la directory per il file di configurazione del gestore dei segreti Predefinito: `./secretsManagerConfig.json` + +--- + +

Tipo

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +Specifica il tipo di gestore dei segreti [`hashicorp-vault`]. Predefinito: `hashicorp-vault` + +--- + +

token

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +Specifica il token di accesso per il servizio + +--- + +

server-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +Specifica l'URL del server per il servizio + +--- + +

Nome

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +Specifica il nome del nodo per la registrazione on-service. Predefinito: `polygon-edge-node` + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Specifica lo spazio dei nomi utilizzato per il gestore dei segreti di Hashicorp Vault. Predefinito: `admin` + +### segreti bandiere di uscita {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +Imposta la bandiera che indica se produrre solo la chiave pubblica BLS. Predefinito: `true` + +--- + +

Configurazione

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +Imposta il percorso del file di configurazione di SecretsManager. Se omesso, viene utilizzato il secrets manager FS locale. + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +Imposta la directory per i dati di Polygon Edge se si usa il FS locale. + +--- + +

node-id

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +Imposta la bandiera che indica se produrre solo il nodo di rete ID. Predefinito: `true` + +--- + +

Validatore

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +Imposta la bandiera che indica se produrre solo l'indirizzo del validatore. Predefinito: `true` + +--- + +## Risposte {#responses} + +### Stato delle risposte {#status-response} + +L'oggetto della risposta è definito utilizzando i buffer di protocollo. +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### Monitor risposte {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## Utilità {#utilities} + +### comandi lista bianca {#whitelist-commands} + +| **Comando** | **Descrizione** | +|------------------------|-------------------------------------------------------------------------------------| +| mostra lista bianca | Mostra le informazioni della lista bianca | +| implementazione lista bianca | Aggiorna la lista bianca di implementazione degli smart contract + | + +

mostra lista bianca

+ + + + + whitelist show + + + + +Mostra le informazioni della lista bianca. + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +Specifica il file genesi da aggiornare. Predefinito: `./genesis.json` + +--- + +

implementazione lista bianca

+ +

catena

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +Specifica il file genesi da aggiornare. Predefinito: `./genesis.json` + +--- + +

aggiungi

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Aggiunge un nuovo indirizzo alla lista bianca di implementazione del contratto. Solo gli indirizzi presenti nella lista bianca di implementazione dei contratti possono implementare i contratti. +Se vuota, qualsiasi indirizzo può eseguire l'implementazione del contratto + +--- + +

rimuovi

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Rimuove un indirizzo dalla lista bianca dell'implementazione del contratto. +Solo gli indirizzi presenti nella lista bianca di implementazione dei contratti possono implementare i contratti. +Se vuota, qualsiasi indirizzo può eseguire l'implementazione del contratto + +--- + +### flag di backup {#backup-flags} + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +Indirizzo dell'API gRPC. Predefinito: `127.0.0.1:9632` + +--- + +

out

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +Percorso del file di archivio da salvare. + +--- + +

da

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +L'altezza iniziale dei blocchi nell'archivo. Predefinito: 0. + +--- + +

a

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +L'altezza finale dei blocchi nell'archivo. + +--- + +## Modello genesi {#genesis-template} +Il file genesi deve essere utilizzato per impostare lo stato iniziale della blockchain (ad esempio, se alcuni account devono avere un saldo iniziale). + +Viene generato il seguente file *./genesis.json*: +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### Data Directory {#data-directory} + +Quando si esegue il flag *data-dir*, viene generata una cartella **della catena di prova**. La struttura della cartella è composta dalle seguenti sottocartelle: +* **blockchain** - Memorizza il LevelDB per gli oggetti della blockchain +* **trie** - Memorizza il LevelDB per i tentativi Merkle +* **keystore** - Memorizza le chiavi private del client. Questo include la chiave privata di libp2p e la chiave privata del sigillatore/validatore. +* **consensus** - Memorizza tutte le informazioni sul consenso di cui il client potrebbe avere bisogno durante il lavoro + +## Risorse {#resources} +* **[I buffer di protocollo](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/it-edge/get-started/installation.md b/archive/edge/it-edge/get-started/installation.md new file mode 100644 index 0000000000..6a17a1ac74 --- /dev/null +++ b/archive/edge/it-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: Installazione +description: "Come installare Polygon Edge." +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +Fai riferimento al metodo di installazione che meglio ti si addice. + +Il nostro consiglio è di utilizzare le versioni predefinite e di verificare i checksum forniti. + +## Versioni predefinite {#pre-built-releases} + +Fai riferimento alla pagina [Versioni di GitHub](https://github.com/0xPolygon/polygon-edge/releases)per un elenco di versioni. + +Polygon Edge viene fornito con binari AMD64/ARM64 cross-compilati per Darwin e Linux. + +--- + +## Immagine Docker {#docker-image} + +Le immagini Docker ufficiali sono ospitate nel [registro hub.docker.com](https://hub.docker.com/r/0xpolygon/polygon-edge). + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## Costruire dalla sorgente {#building-from-source} + +Prima di utilizzare `go install` assicurati di avere Go `>=1.18` installato e configurato correttamente. + +La ramo stabile è la ranca dell'ultima release. + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## Uso di `go install` + +Prima di utilizzare `go install` assicurati di avere Go `>=1.17` installato e configurato correttamente. + +`go install github.com/0xPolygon/polygon-edge@release/` + +La binaria sarà disponibile nella tua variabile di `GOBIN`ambiente e includerà le modifiche dell'ultima release. Puoi checkout [GitHub](https://github.com/0xPolygon/polygon-edge/releases) Rilasciare per scoprire quale sia l'ultimo. diff --git a/archive/edge/it-edge/get-started/set-up-ibft-locally.md b/archive/edge/it-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..b28e5a32e0 --- /dev/null +++ b/archive/edge/it-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,411 @@ +--- +id: set-up-ibft-locally +title: Configurazione locale +description: "Guida alla configurazione locale passo dopo passo." +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution Questa guida è solo a scopo di test + +La seguente guida ti spiega come configurare una rete Polygon Edge sul tuo computer locale per scopi di test e sviluppo. + +La procedura differisce notevolmente dal modo in cui si dovrebbe impostare la rete Polygon Edge per uno scenario di utilizzo reale. un provider di cloud **[Cloud Setup](/docs/edge/get-started/set-up-ibft-on-the-cloud)** + +::: + + +## Requisiti {#requirements} + +Per installare Polygon Edge, consultare la sezione [Installazione](/docs/edge/get-started/installation). + +## Panoramica {#overview} + +![Configurazione locale](/img/edge/ibft-setup/local.svg) + +In questa guida, il nostro obiettivo è stabilire una rete `polygon-edge`blockchain funzionante con [il protocollo di consenso IBFT](https://github.com/ethereum/EIPs/issues/650). +La rete blockchain sarà composta da 4 nodi, di cui tutti e 4 sono nodi validatori, e come tali sono idonei sia a proporre blocchi, sia a validare blocchi provenienti da altri proponenti. Tutti e 4 i nodi funzioneranno sulla stessa macchina, poiché l'idea di questa guida è di fornire un cluster IBFT completamente funzionale nel minor tempo possibile. + +Per raggiungere questo obiettivo, ti guideremo attraverso 4 semplici passi: + +1. L'inizializzazione delle directory di dati genererà le chiavi del validatore per ciascuno dei 4 nodi e inizializzerà le directory di dati della blockchain vuote. Le chiavi dei validatori sono importanti, perché dobbiamo avviare il blocco genesi con l'insieme iniziale di validatori, utilizzando queste chiavi. +2. La preparazione della stringa di connessione per il bootnode sarà l'informazione vitale per ogni nodo che verrà eseguito per sapere a quale nodo connettersi al primo avvio. +3. La generazione del `genesis.json`file richiederà come input sia le chiavi dei validatori generate nel **passo 1**, utilizzate per impostare i validatori iniziali della rete nel blocco genesi, sia la stringa di connessione del bootnode dal **passo 2**. +4. L'esecuzione di tutti i nodi è l'obiettivo finale di questa guida e sarà l'ultimo passo che faremo, istruiremo i nodi su quale directory di dati utilizzare e dove trovare il `genesis.json`che avvia lo stato iniziale della rete. + +Poiché tutti e quattro i nodi saranno in esecuzione su localhost, durante il processo di configurazione si prevede che tutte le directory di dati per ciascuno dei nodi si trovino nella stessa directory madre. + +:::info Numero di validatori + +Non esiste un numero minimo di nodi in un cluster, il che significa che sono possibili cluster con un solo nodo validatore. Tieni presente che con un cluster _a singolo_ nodo non c'è **tolleranza agli arresti** anomali né **garanzia di BFT**. + +Il numero minimo di nodi consigliato per ottenere una garanzia BFT è 4, poiché in un cluster di 4 nodi, il guasto di 1 nodo può essere tollerato, con i rimanenti 3 nodi che funzionano normalmente. + +::: + +## Passo 1: inizializzare le cartelle dati per IBFT e generare le chiavi del validatore {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +Per essere operativi con IBFT, è necessario inizializzare le cartelle dati, una per ogni nodo: + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +Ciascuno di questi comandi stamperà la chiave del validatore, la chiave pubblica bls e l'[ID del nodo](https://docs.libp2p.io/concepts/peer-id/). Per il passaggio successivo avrai bisogno dell'ID nodo del primo nodo. + +### Output {#outputting-secrets} +L'uscita dei segreti può essere recuperata di nuovo, se necessario. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## Passo 2: preparare la stringa di connessione multiaddr per il bootnode {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Affinché un nodo stabilisca con successo la connettività, deve sapere a quale `bootnode`server connettersi per ottenere informazioni su tutti i nodi rimanenti sulla rete. Nel gergo del p2p, il server `bootnode`è talvolta noto anche come server `rendezvous`. + +`bootnode`non è un'istanza speciale del nodo Polygon Edge. Ogni nodo di Polygon Edge può fungere da `bootnode`, ma +ogni nodo di Polygon-Edge deve avere un insieme di bootnodes specificati che saranno contattati per fornire informazioni su come connettersi a tutti i nodi rimanenti nella rete. + +Per creare la stringa di connessione per specificare il bootnode, occorre conformarsi al [formato multiaddr](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +In questa guida, tratteremo il primo e il secondo nodo come nodi di avvio per tutti gli altri nodi. Ciò che accadrà in questo caso + è che i nodi che si connettono a `node 1` o `node 2` riceveranno informazioni su come connettersi l'uno all'altro tramite il +bootnode contattato reciprocamente. + +:::info È necessario specificare almeno un bootnode per avviare un nodo + +È richiesto almeno **un** bootnode, in modo che gli altri nodi della rete possano scoprirsi a vicenda. Si raccomanda un numero maggiore di bootnodes, in quanto forniscono resilienza alla rete in caso di interruzioni. In questa guida elencheremo due nodi, ma questo può essere cambiato all'istante, senza alcun impatto sulla validità del `genesis.json`file. +::: + +Poiché siamo in esecuzione su localhost, è lecito supporre che ``sia`127.0.0.1`. + + +Per la porta ``utilizzeremo, `10001`poiché in seguito configureremo il server libp2p perché`node 1` ascolti questa porta. + +Infine, abbiamo bisogno di ``che possiamo ricavare dall'output del comando `polygon-edge secrets init --data-dir test-chain-1`eseguito in precedenza (che è stato usato per generare le chiavi e le directory dei dati per il `node1`). + + +Dopo l'assemblaggio, la stringa di connessione multiaddr al `node 1`che useremo come bootnode avrà un aspetto simile a questo (solo il ``che si trova alla fine dovrebbe essere diverso): +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Allo stesso modo, si costruisce il multiddr per il secondo bootnode come mostrato di seguito +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info Nomi di host DNS al posto degli ip + +Polygon Edge supporta l'uso di nomi host DNS per la configurazione dei nodi. Si tratta di una funzione molto utile per le distribuzioni basate sul cloud, dato che l'ip del nodo può cambiare per vari motivi. + +Il formato mult +iddr per la stringa di connessione quando si utilizzano nomi di host DNS è il seguente: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## Passo 3: generare il file genesi con i 4 nodi come validatori {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +Cosa fa questo comando: + +* `--ibft-validators-prefix-path`imposta il percorso della cartella del prefisso a quello specificato che IBFT in Polygon Edge può +utilizzare. Questa directory è utilizzata per ospitare la cartella `consensus/`in cui è conservata la chiave privata del validatore. La +chiave pubblica del validatore è necessaria per costruire il file genesi - l'elenco iniziale dei nodi di avvio. + Questo flag ha senso solo quando si configura la rete su localhost, poiché in uno scenario reale non ci si può aspettare che tutte le directory dei dati dei nodi si trovino sullo stesso filesystem da cui si possono leggere facilmente le loro chiavi pubbliche. +* Il `--bootnode`imposta l'indirizzo del bootnode che consentirà ai nodi di trovarsi a vicenda. + Utilizzeremo la stringa multiaddr del `node 1`, come indicato nel **passo 2**. + + +Il risultato di questo comando è il file `genesis.json` che contiene il blocco genesi della nostra nuova blockchain, con il validatore predefinito e la configurazione del nodo da contattare per primo per stabilire la connettività. + +:::info Passare a ECDSA + +BLS è la modalità di convalida predefinita delle intestazioni di blocco. Se vuoi che la tua catena venga eseguita in modalità ECDSA, puoi utilizzare la bandiera `—ibft-validator-type`, con la discussione `ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info Saldi account che preminano + +Probabilmente vorrai impostare la tua rete blockchain con alcuni indirizzi che hanno saldi "preminati". + +Per fare ciò, si passano tutti i flag `--premine`che si vogliono per ogni indirizzo che si vuole inizializzare con un certo saldo + sulla blockchain. + +Ad esempio, se vogliamo preminare 1000 ETH all'indirizzo `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862`nel nostro blocco genesi, dobbiamo fornire il seguente argomento: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Si noti che l'importo preminato è in WEI, non in ETH.** + +::: + +:::info Imposta il limite gas del blocco + +Il limite di gas predefinito per ogni blocco è `5242880`. Questo valore è scritto nel file genesi, ma puoi + aumentarlo / abbassarlo. + +Per farlo, è possibile utilizzare il flag `--block-gas-limit`seguito dal valore desiderato come di seguito indicato : + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Impostare il limite dei descrittori di file di sistema + +Il limite predefinito del descrittore di file (numero massimo di file aperti) su alcuni sistemi operativi è piuttosto ridotto. Se si prevede che i nodi abbiano un throughput elevato, si potrebbe considerare di aumentare questo limite a livello di sistema operativo. + +Per la distribuzione Ubuntu la procedura è la seguente (se non si utilizza la distribuzione Ubuntu/Debian, controllare i documenti ufficiali del proprio sistema operativo) : +- Controllare i limiti attuali del sistema operativo (file aperti) +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- Aumentare il limite dei file aperti + - Localmente - influenza solo la sessione corrente: + ```shell + ulimit -u 65535 + ``` + - Globalmente o per utente (aggiunge i limiti alla fine del file /etc/security/limits.conf): + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +In alternativa, è possibile modificare altri parametri, salvare il file e riavviare il sistema. Dopo il riavvio, controllare nuovamente il limite del descrittore di file. Deve essere impostato sul valore definito nel file limits.conf. + +::: + + +## Passo 4: eseguire tutti i client {#step-4-run-all-the-clients} + +Poiché si sta tentando di eseguire una rete Polygon Edge composta da 4 nodi tutti sulla stessa macchina, è necessario prestare attenzione a +evitare conflitti tra le porte. Per questo motivo utilizzeremo il seguente ragionamento per determinare le porte di ascolto di ciascun server di un nodo: + +- `10000`per il server gRPC di `node 1`, `20000`per il server GRPC di `node 2`, ecc. +- `10001`per il server libp2p di `node 1`, `20001`per il server libp2p di `node 2`, ecc. +- `10002`per il server JSON-RPC di `node 1`, `20002`per il server JSON-RPC di `node 2`, ecc.. + +Per eseguire il **primo** client (notare la porta, `10001`poiché è stata usata come parte del multiaddr di libp2p nel **passo 2** insieme all'ID del nodo 1): + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +Per eseguire il **secondo** client: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +Per eseguire il **terzo** client: + + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +Per eseguire il **quarto** client: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +Ripercorriamo brevemente ciò che è stato fatto finora: + +* La directory per i dati del client è stata specificata come **./test-chain-\*** +* I server GRPC sono stati avviati sulle porte **10000**, **20000**, **30000** e **40000**, rispettivamente per ogni nodo. +* I server libp2p sono stati avviati sulle porte **10001**, **20001**, **30001** e **40001**, rispettivamente per ogni nodo. +* I server JSON-RPC sono stati avviati sulle porte **10002**, **20002**, **30002** e **40002**, rispettivamente per ogni nodo. +* Il flag *sigillo* indica che il nodo avviato parteciperà alla sigillatura dei blocchi. +* Il flag *catena* specifica quale file di genesi deve essere usato per la configurazione della catena. + +La struttura del file genesi è descritta nella sezione [Comandi CLI](/docs/edge/get-started/cli-commands). + +Dopo aver eseguito i comandi precedenti, è stata configurata una rete Polygon Edge a 4 nodi, in grado di sigillare i blocchi e di riprendersi +dal guasto di un nodo. + +:::info Avvia il client utilizzando il file di configurazione + +Invece di specificare tutti i parametri di configurazione come argomenti della CLI, il Client può essere avviato anche utilizzando un file di configurazione, eseguendo il seguente comando: + +````bash +polygon-edge server --config +```` +Esempio: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Attualmente, supportiamo `yaml`e `json`basiamo i file di configurazione, campioni i file di config possono essere trovati **[qui](/docs/edge/configuration/sample-config)** + +::: + +:::info Passaggi per eseguire un nodo non validatore + +Un nodo non validatore sincronizzerà sempre gli ultimi blocchi ricevuti dal nodo validatore; è possibile avviare un nodo non validatore eseguendo il seguente comando. + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +Ad esempio, è possibile aggiungere il **quinto** client Non-validatore eseguendo il seguente comando: + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info Specificare il limite di prezzo + +Un nodo Polygon Edge può essere avviato con un **limite di prezzo** impostato per le transazioni in entrata. + +L'unità per il limite di prezzo è `wei`. + +L'impostazione di un limite di prezzo significa che qualsiasi transazione elaborata dal nodo corrente dovrà avere un prezzo del gas **superiore** al limite di prezzo impostato, altrimenti non sarà inclusa in un blocco. + +Se la maggioranza dei nodi rispetta un certo limite di prezzo, viene applicata la regola che le transazioni nella rete non possono essere inferiori a una certa soglia di prezzo. + +Il valore predefinito per il limite di prezzo è `0`, il che significa che per impostazione predefinita non viene applicato. + +Esempio di utilizzo del flag `--price-limit`: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Vale la pena notare che i limiti di prezzo **vengono applicati solo alle transazioni non locali**, il che significa +che il limite di prezzo non si applica alle transazioni aggiunte localmente sul nodo. +::: + +:::info URL WebSocket +Per impostazione predefinita, quando si esegue Polygon Edge, viene generato un URL WebSocket basato sulla posizione della catena. Lo schema URL `wss://`viene utilizzato per i collegamenti HTTPS e `ws://`per HTTP. + +URL Localhost WebSocket: +````bash +ws://localhost:10002/ws +```` +Notare che il numero di porta dipende dalla porta JSON-RPC scelta per il nodo. + +URL Edgenet WebSocket: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## Passo 5: interagire con la rete di Polygon Edge {#step-5-interact-with-the-polygon-edge-network} + +Ora che hai configurato almeno un client funzionante, puoi interagire con la blockchain usando l'account che hai preimpostato sopra e specificando l'URL JSON-PRC a uno qualsiasi dei 4 nodi: +- Nodo 1: `http://localhost:10002` +- Nodo 2: `http://localhost:20002` +- Nodo 3: `http://localhost:30002` +- Nodo 4: `http://localhost:40002` + +Segui questa guida per impartire i comandi dell'operatore al cluster appena costruito: [Come ricercare le informazioni sull'operatore ](/docs/edge/working-with-node/query-operator-info) (le porte GRPC per il cluster che abbiamo costruito sono rispettivamente `10000`/`20000`/`30000`/`40000` per ogni nodo) diff --git a/archive/edge/it-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/it-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..f837035f2b --- /dev/null +++ b/archive/edge/it-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,430 @@ +--- +id: set-up-ibft-on-the-cloud +title: Configurazione del cloud +description: "Guida alla configurazione del cloud step-by-step." +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info Questa guida è per le configurazioni mainnet o testnet + +La guida seguente ti spiegherà come configurare una rete Polygon Edge su un provider cloud per una configurazione di produzione della tua testnet o mainnet. + +Se desideri configurare una rete Polygon Edge localmente per testare rapidamente `polygon-edge` prima di effettuare una configurazione simile alla produzione, fare riferimento a +**[Configurazione locale](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## Requisiti {#requirements} + +Per installare Polygon Edge, consultare la sezione [Installazione](/docs/edge/get-started/installation). + +### Configurazione della connettività VM {#setting-up-the-vm-connectivity} + +A seconda della scelta del provider cloud, puoi configurare la connettività e le regole tra le VM utilizzando un firewall, gruppi di sicurezza o elenchi di controllo degli accessi. + +Poiché l'unica parte di `polygon-edge` che deve essere esposta ad altre VM è il server libp2p, è sufficiente consentire semplicemente +tutte le comunicazioni tra VM sulla porta libp2p predefinita `1478`. + +## Panoramica {#overview} + +![Configurazione del cloud](/img/edge/ibft-setup/cloud.svg) + +In questa guida, il nostro obiettivo è stabilire una rete `polygon-edge`blockchain funzionante con [il protocollo di consenso IBFT](https://github.com/ethereum/EIPs/issues/650). +La rete blockchain sarà composta da 4 nodi, di cui tutti e 4 sono nodi validatori, e come tali sono idonei sia a proporre blocchi, sia a validare blocchi provenienti da altri proponenti. Ciascuno dei 4 nodi verrà eseguito sulla propria VM, poiché l'idea di questa guida è quella di fornire una rete Polygon Edge completamente funzionale mantenendo private le chiavi del validatore per garantire una configurazione di rete affidabile. + +Per raggiungere questo obiettivo, ti guideremo attraverso 4 semplici passi: + +0. Dai un'occhiata all'elenco dei **Requisiti** sopra +1. Genera le chiavi private per ciascuno dei validatori e inizializza la directory dei dati +2. Prepara la stringa di connessione per il bootnode da inserire nel `genesis.json` condiviso +3. Crea il `genesis.json` sulla tua macchina locale e invialo/trasferiscilo a ciascuno dei nodi +4. Avvia tutti i nodi + +:::info Numero di validatori + +Non esiste un numero minimo di nodi in un cluster, il che significa che sono possibili cluster con un solo nodo validatore. Tieni presente che con un cluster _a singolo_ nodo non c'è **tolleranza agli arresti** anomali né **garanzia di BFT**. + +Il numero minimo di nodi consigliato per ottenere una garanzia BFT è 4, poiché in un cluster di 4 nodi, il guasto di 1 nodo può essere tollerato, con i rimanenti 3 nodi che funzionano normalmente. + +::: + +## Passo 1: Inizializzare le cartelle di dati e generare le chiavi del validatore {#step-1-initialize-data-folders-and-generate-validator-keys} + +Per iniziare ad utilizzare Polygon Edge, è necessario inizializzare le cartelle di dati, su ciascun nodo: + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +Ciascuno di questi comandi stamperà la chiave del validatore, la chiave pubblica bls e l'[ID del nodo](https://docs.libp2p.io/concepts/peer-id/). Per il passaggio successivo avrai bisogno dell'ID nodo del primo nodo. + +### Output {#outputting-secrets} +L'uscita dei segreti può essere recuperata di nuovo, se necessario. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning Tieni per te la directory dei tuoi dati! + +Le directory di dati generate sopra, oltre a inizializzare le directory per la gestione dello stato della blockchain, genereranno anche le chiavi private del tuo validatore. **Questa chiave deve essere mantenuta segreta, poiché se qualcuno te la rubasse sarebbe in grado di impersonarti come validatore nella rete!** + +::: + +## Passo 2: preparare la stringa di connessione multiaddr per il bootnode {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Affinché un nodo stabilisca con successo la connettività, deve sapere a quale server `bootnode` connettersi per ottenere +informazioni su tutti i nodi rimanenti sulla rete. Nel gergo del p2p, il `bootnode`è talvolta noto anche come server `rendezvous`. + +`bootnode` non è un'istanza speciale di un nodo Polygon Edge. Ogni nodo Polygon Edge può fungere da `bootnode` e +ogni nodo Polygon Edge deve avere un set di bootnodes specificato che verrà contattato per fornire informazioni su come connettersi con tutti i nodi rimanenti nella rete. + +Per creare la stringa di connessione per specificare il bootnode, occorre conformarsi al [formato multiaddr](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +In questa guida, tratteremo il primo e il secondo nodo come nodi di avvio per tutti gli altri nodi. Ciò che accadrà in questo caso + è che i nodi che si connettono a `node 1` o `node 2` riceveranno informazioni su come connettersi l'uno all'altro tramite il +bootnode contattato reciprocamente. + +:::info È necessario specificare almeno un bootnode per avviare un nodo + +È richiesto almeno **un** bootnode, in modo che gli altri nodi della rete possano scoprirsi a vicenda. Si raccomanda un numero maggiore di bootnodes, in quanto forniscono resilienza alla rete in caso di interruzioni. In questa guida elencheremo due nodi, ma questo può essere modificato all'istante, senza alcun impatto sulla validità del file `genesis.json`. +::: + +Poiché la prima parte della stringa di connessione multiaddr è ``, qui dovrai inserire l'indirizzo IP come raggiungibile da altri nodi; a seconda della tua configurazione, potrebbe essere un indirizzo IP privato o pubblico, non `127.0.0.1`. + +Per `` utilizzeremo `1478`, poiché è la porta libp2p predefinita. + +Infine, abbiamo bisogno di ``che possiamo ricavare dall'output del comando `polygon-edge secrets init --data-dir data-dir`eseguito in precedenza (che è stato usato per generare le chiavi e le directory dei dati per il `node 1`) + +Dopo l'assemblaggio, la stringa di connessione multiaddr al `node 1`che useremo come bootnode avrà un aspetto simile a questo (solo il ``che si trova alla fine dovrebbe essere diverso): +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Allo stesso modo, si costruisce il multiddr per il secondo bootnode come mostrato di seguito +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info Nomi di host DNS al posto degli ip + +Polygon Edge supporta l'uso di nomi host DNS per la configurazione dei nodi. Si tratta di una funzione molto utile per le distribuzioni basate sul cloud, dato che l'ip del nodo può cambiare per vari motivi. + +Il formato mult +iddr per la stringa di connessione quando si utilizzano nomi di host DNS è il seguente: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## Passo 3: generare il file genesi con i 4 nodi come validatori {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +Questo passaggio può essere eseguito sulla tua macchina locale, ma avrai bisogno delle chiavi pubbliche del validatore per ciascuno dei 4 validatori. + +I validatori possono condividere in modo sicuro il `Public key (address)` come mostrato di seguito nell'output ai loro comandi `secrets init`, in modo +da poter generare in modo sicuro il genesis.json con quei validatori nel set di validatori iniziale, identificati dalle loro chiavi pubbliche: + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +Dato che hai ricevuto tutte e 4 le chiavi pubbliche dei validatori, puoi eseguire il seguente comando per generare il `genesis.json` + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +Cosa fa questo comando: + +* Il `--ibft-validator` imposta la chiave pubblica del validatore che dovrebbe essere inclusa nel set di validazione iniziale nel blocco di genesi. Ci possono essere molti validatori iniziali. +* Il `--bootnode`imposta l'indirizzo del bootnode che consentirà ai nodi di trovarsi a vicenda. + Useremo la stringa multiaddr di `node 1`, come indicato nel **passo 2**, anche se aggiungi tutti i bootnodes che vuoi, come mostrato sopra. + +:::info Passare a ECDSA + +BLS è la modalità di convalida predefinita delle intestazioni di blocco. Se vuoi che la tua catena venga eseguita in modalità ECDSA, puoi utilizzare la bandiera `—ibft-validator-type`, con la discussione `ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info Saldi account che preminano + +Probabilmente vorrai impostare la tua rete blockchain con alcuni indirizzi che hanno saldi "preminati". + +Per fare ciò, si passano tutti i flag `--premine`che si vogliono per ogni indirizzo che si vuole inizializzare con un certo saldo + sulla blockchain. + +Ad esempio, se vogliamo preminare 1000 ETH all'indirizzo `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862`nel nostro blocco genesi, dobbiamo fornire il seguente argomento: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Si noti che l'importo preminato è in WEI, non in ETH.** + +::: + +:::info Imposta il limite gas del blocco + +Il limite di gas predefinito per ogni blocco è `5242880`. Questo valore è scritto nel file genesi, ma puoi + aumentarlo / abbassarlo. + +Per farlo, è possibile utilizzare il flag `--block-gas-limit`seguito dal valore desiderato come di seguito indicato : + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Impostare il limite dei descrittori di file di sistema + +Il limite predefinito del descrittore di file (numero massimo di file aperti) su alcuni sistemi operativi è piuttosto ridotto. Se si prevede che i nodi abbiano un throughput elevato, si potrebbe considerare di aumentare questo limite a livello di sistema operativo. + +Per la distribuzione Ubuntu la procedura è la seguente (se non si utilizza la distribuzione Ubuntu/Debian, controllare i documenti ufficiali del proprio sistema operativo) : +- Controllare i limiti attuali del sistema operativo (file aperti) +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- Aumentare il limite dei file aperti + - Localmente - influenza solo la sessione corrente: + ```shell + ulimit -u 65535 + ``` + - Globalmente o per utente (aggiunge i limiti alla fine del file /etc/security/limits.conf): + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +In alternativa, è possibile modificare altri parametri, salvare il file e riavviare il sistema. Dopo il riavvio, controllare nuovamente il limite del descrittore di file. Deve essere impostato sul valore definito nel file limits.conf. + +::: + +Dopo aver specificato ciò che segue: +1. Chiavi pubbliche dei validatori da includere nel blocco di genesi come set di validatori +2. Stringhe di connessione multiaddr Bootnode +3. Conti e saldi pre-minati da includere nel blocco di genesi + +e generare `genesis.json`, dovresti copiarlo su tutte le VM della rete. A seconda della tua configurazione, puoi copiarlo/incollarlo, inviarlo all'operatore del nodo o semplicemente procedere al SCP/FTP. + +La struttura del file genesi è descritta nella sezione [Comandi CLI](/docs/edge/get-started/cli-commands). + +## Passo 4: eseguire tutti i client {#step-4-run-all-the-clients} + +:::note Networking sui provider di cloud + +La maggior parte dei provider di cloud non espone gli indirizzi IP (specialmente quelli pubblici) come interfaccia di rete diretta sulla tua VM, ma piuttosto configura un proxy NAT invisibile. + + +Per consentire ai nodi di connettersi tra loro in questo caso dovresti ascoltare l'indirizzo IP `0.0.0.0` per associare tutte le interfacce, ma dovresti comunque specificare l'indirizzo IP o l'indirizzo DNS che altri nodi possono utilizzare per connettersi alla tua istanza. Ciò si ottiene utilizzando l'argomento `--nat` o `--dns` in cui è possibile specificare rispettivamente l'indirizzo IP o DNS esterno. + +#### Esempio {#example} + +L'indirizzo IP associato su cui desideri ascoltare è `192.0.2.1`, ma non è direttamente collegato a nessuna delle tue interfacce di rete. + +Per consentire ai nodi di connettersi, devi passare i seguenti parametri: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +Oppure, se desideri specificare un indirizzo DNS `dns/example.io`, passa i seguenti parametri: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +Ciò renderebbe il tuo nodo in ascolto su tutte le interfacce, ma lo renderebbe anche consapevole che i client si stanno connettendo ad esso tramite l'indirizzo `--nat` o `--dns` specificato. + +::: + +Per eseguire il **primo** client: + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Per eseguire il **secondo** client: + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Per eseguire il **terzo** client: + + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Per eseguire il **quarto** client: + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Dopo aver eseguito i comandi precedenti, è stata configurata una rete Polygon Edge a 4 nodi, in grado di sigillare i blocchi e di riprendersi dal guasto di un nodo. + +:::info Avvia il client utilizzando il file di configurazione + +Invece di specificare tutti i parametri di configurazione come argomenti della CLI, il Client può essere avviato anche utilizzando un file di configurazione, eseguendo il seguente comando: + +````bash +polygon-edge server --config +```` +Esempio: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Attualmente, supportiamo solo il file di configurazione `json`basato, il file di config può essere trovato **[qui](/docs/edge/configuration/sample-config)** + +::: + +:::info Passaggi per eseguire un nodo non validatore + +Un nodo non validatore sincronizzerà sempre gli ultimi blocchi ricevuti dal nodo validatore; è possibile avviare un nodo non validatore eseguendo il seguente comando. + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +Ad esempio, è possibile aggiungere il **quinto** client Non-validatore eseguendo il seguente comando: + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info Specificare il limite di prezzo + +Un nodo Polygon Edge può essere avviato con un **limite di prezzo** impostato per le transazioni in entrata. + +L'unità per il limite di prezzo è `wei`. + +L'impostazione di un limite di prezzo significa che qualsiasi transazione elaborata dal nodo corrente dovrà avere un gas price **superiore** al limite di prezzo impostato, altrimenti non verrà inserito in un blocco. + +Se la maggioranza dei nodi rispetta un certo limite di prezzo, viene applicata la regola che le transazioni nella rete non possono essere inferiori a una certa soglia di prezzo. + +Il valore predefinito per il limite di prezzo è `0`, il che significa che per impostazione predefinita non viene applicato. + +Esempio di utilizzo del flag `--price-limit`: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Vale la pena notare che i limiti di prezzo **vengono applicati solo alle transazioni non locali**, il che significa +che il limite di prezzo non si applica alle transazioni aggiunte localmente sul nodo. +::: + +:::info URL WebSocket +Per impostazione predefinita, quando si esegue Polygon Edge, viene generato un URL WebSocket basato sulla posizione della catena. Lo schema URL `wss://`viene utilizzato per i collegamenti HTTPS e `ws://`per HTTP. + +URL Localhost WebSocket: +````bash +ws://localhost:10002/ws +```` +Notare che il numero di porta dipende dalla porta JSON-RPC scelta per il nodo. + +URL Edgenet WebSocket: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/it-edge/get-started/terraform-aws-deployment.md b/archive/edge/it-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..a2a8b9d048 --- /dev/null +++ b/archive/edge/it-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,168 @@ +--- +id: terraform-aws-deployment +title: Implementazione di AWS Terraform +description: "Implementa la rete Polygon Edge sul provider cloud AWS utilizzando Terraform" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info Guida all'implementazione della produzione +Questa è la guida all'implementazione di AWS ufficiale, pronta per la produzione e completamente automatizzata. + +Sono consigliate implementazioni del manuale sul ***[Cloud](set-up-ibft-on-the-cloud)*** o ***[Locali](set-up-ibft-locally)*** per i test e/o se il tuo provider cloud non è AWS. +::: + +:::info + +Questa implementazione è solo PoA. +Se è necessario il meccanismo PoS, basta che segui questa ***[guida](/docs/edge/consensus/migration-to-pos)*** per passare ora da PoA a PoS. + +::: + +Questa guida descriverà in dettaglio il processo di implementazione di una rete di blockchain Polygon Edge sul provider di servizi cloud AWS, che è pronto per la produzione poiché i nodi del validatore sono distribuiti su più zone di disponibilità. + +## Prerequisiti {#prerequisites} + +### Strumenti di sistema {#system-tools} +* [terraform](https://www.terraform.io/) +* [aws cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [ID della chiave di accesso aws e chiave di accesso segreta](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Variabili Terraform {#terraform-variables} +Due variabili che devono essere fornite, prima di eseguire la distribuzione: + +* `alb_ssl_certificate` - l'ARN del certificato dal Certificate Manager AWS che deve essere utilizzato da ALB per il protocollo https. + Il certificato deve essere generato prima di avviare l'implementazione, e deve avere lo stato di **Emesso** +* `premine` - l'account che riceverà valuta nativa preminata. +Il valore deve seguire la specifica ufficiale del flag [CLI](/docs/edge/get-started/cli-commands#genesis-flags) + +## Informazioni sull'implementazione {#deployment-information} +### Risorse implementate {#deployed-resources} +Panoramica di alto livello delle risorse che verranno implementate: + +* VPC dedicato +* 4 nodi validatore (che sono anche nodi di avvio) +* 4 gateway NAT per consentire ai nodi il traffico internet in uscita +* Funzione Lambda utilizzata per generare il primo blocco (genesi) e avviare la catena +* Gruppi di sicurezza dedicati e ruoli IAM +* Bucket S3 utilizzato per archiviare il file genesis.json +* Application Load Balancer utilizzato per esporre l'endpoint JSON-RPC + +### Tolleranza ai guasti {#fault-tolerance} + +Per questa implementazione sono necessarie solo le regioni che dispongono di 4 zone di disponibilità. Ogni nodo viene implementato in una singola zona di disponibilità. + +Posizionando ogni nodo in una singola zona di disponibilità AZ, l'intero cluster blockchain è tollerante ai guasti di un singolo nodo (AZ), poiché Polygon Edge implementa il consensus IBFT che consente a un singolo nodo di fallire in un cluster di 4 nodi del validatore. + +### Accesso alla linea di comando {#command-line-access} + +I nodi del validatore non sono esposti in alcun modo alla rete internet pubblica (JSON-PRC è accessibile solo tramite ALB) non hanno neppure indirizzi IP pubblici collegati. +L'accesso alla linea di comando del nodo è possibile solo tramite [AWS Systems Manager - Session Manager](https://aws.amazon.com/systems-manager/features/). + +### Aggiornamento dell'AMI di base {#base-ami-upgrade} + +Questa implementazione utilizza `ubuntu-focal-20.04-amd64-server` l'AMI AWS. **Non ** attiverà la *reimplementazione di EC2* se l'AMI AWS viene aggiornata. + +Se, per qualche ragione, è necessario che l'AMI base venga aggiornata, si può ottenere eseguendo prima il `terraform taint` comando per ogni istanza `terraform apply`. +Le istanze possono essere contaminate eseguendo il +`terraform taint module.instances[].aws_instance.polygon_edge_instance` comando. + +Esempio: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info + +In un ambiente di produzione `terraform taint` dovrebbe essere eseguito uno per uno per mantenere funzionale la rete blockchain. + +::: + +## Procedura di implementazione {#deployment-procedure} + +### Passi preliminari all'implementazione {#pre-deployment-steps} +* leggi il file readme del registro terraform [polygon-technology-edge](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) +* aggiungi il modulo `polygon-technology-edge` al tuo `main.tf` file utilizzando *le istruzioni di fornitura* sulla pagina readme dei moduli +* esegui il comando `terraform init` per installare tutte le dipendenze Terraform necessarie +* fornisci un nuovo certificato in [AWS Certificate Manager](https://aws.amazon.com/certificate-manager/) +* assicurati che il certificato fornito sia nello stato **Emesso** e annota l'**ARN** del certificato +* imposta la tua dichiarazione di output per ottenere l'output dei moduli nel cli + +#### `main.tf` esempio {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### `terraform.tfvars` esempio {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### Passi per l'implementazione {#deployment-steps} +* crea il `terraform.tfvars` file +* imposta le variabili del terraform richieste in questo file (come spiegato sopra). +:::info +Ci sono altre variabili non obbligatorie che possono personalizzare completamente questa implementazione. Puoi ignorare i valori predefiniti aggiungendo il tuo al file `terraform.tfvars`. + + La specifica di tutte le variabili disponibili si trova nel ***[registro](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)*** Terraform dei moduli + +::: +* assicurati di aver impostato correttamente un'autenticazione aws cli eseguendo `aws s3 ls` - non dovrebbero esserci errori +* implementa l'infrastruttura `terraform apply` + +### Passi post-implementazione {#post-deployment-steps} +* una volta terminata l'implementazione, prendi nota del `json_rpc_dns_name` valore variabile stampato nel cli +* crea un record cname dns pubblico che punta il tuo nome di dominio al valore `json_rpc_dns_name` fornito. Ad esempio: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* una volta che il record cname si è propagato, controlla se la catena funziona correttamente chiamando il tuo endpoint JSON-PRC. + Dall'esempio sopra: + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## Procedura di distruzione {#destroy-procedure} +:::warning + +La seguente procedura eliminerà in modo permanente l'intera infrastruttura implementata con questi script terraform. +Assicurati di avere [backup di dati blockchain](docs/edge/working-with-node/backup-restore) corretti e/o di lavorare con un ambiente di test. + +::: + +Se è necessario rimuovere l'intera infrastruttura, esegui il seguente comando `terraform destroy`. +Inoltre, dovrai rimuovere manualmente i segreti memorizzati in AWS [Parameter Store](https://aws.amazon.com/systems-manager/features/) +per la regione dove è avvenuta l'implementazione. diff --git a/archive/edge/it-edge/overview.md b/archive/edge/it-edge/overview.md new file mode 100644 index 0000000000..cc5049c7a4 --- /dev/null +++ b/archive/edge/it-edge/overview.md @@ -0,0 +1,35 @@ +--- +id: overview +title: Polygon Edge +sidebar_label: What is Edge +description: "Un'introduzione a Polygon Edge" +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +Polygon Edge è un framework modulare ed estensibile per costruire reti blockchain, sidechain e soluzioni di scalabilità generali compatibili con Ethereum. + +Il suo utilizzo primario è quello di avviare una nuova rete blockchain fornendo al contempo la piena compatibilità con contratti e transazioni intelligenti di Ethereum. Utilizza il meccanismo di consensus IBFT (Istanbul Byzantine Fault Tolerant), supportato in due versioni come [PoA (proof of authority)](/docs/edge/consensus/poa) e [PoS (proof of stake)](/docs/edge/consensus/pos-stake-unstake). + +Polygon Edge supporta anche la comunicazione con reti blockchain multiple, consentendo trasferimenti di token [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) e [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) utilizzando la [soluzione bridge centralizzata](/docs/edge/additional-features/chainbridge/overview). + +I portafogli standard di settore possono essere utilizzati per interagire con Polygon Edge attraverso di endpoint [JSON-RPC](/docs/edge/working-with-node/query-json-rpc) e gli operatori dei nodi possono eseguire varie azioni sui nodi tramite il protocollo [gRPC](/docs/edge/working-with-node/query-operator-info). + +Per saperne di più su Polygon, visita il [sito ufficiale](https://polygon.technology). + +**[Repository di GitHub](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +Questo è un lavoro in corso, quindi in futuro potrebbero verificarsi modifiche architettoniche. Il codice non è stato ancora verificato, quindi ti preghiamo di contattare il team Polygon se vuoi usarlo in produzione. + +::: + + + +Per iniziare eseguendo una rete `polygon-edge` localmente, leggi: [Installazione](/docs/edge/get-started/installation) e [Impostazioni locali](/docs/edge/get-started/set-up-ibft-locally). diff --git a/archive/edge/it-edge/performance-reports/overview.md b/archive/edge/it-edge/performance-reports/overview.md new file mode 100644 index 0000000000..668557eedd --- /dev/null +++ b/archive/edge/it-edge/performance-reports/overview.md @@ -0,0 +1,29 @@ +--- +id: overview +title: Panoramica +description: "Introduzione ai test di Polygon Edge." +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +Si prega di notare che il nostro , `loadbot`utilizzato per eseguire questi test, è ora deprezzato. +::: + +| Tipo | Valore | Link al test | +| ---- | ----- | ------------ | +| Transfer regolari | 1428 tps | [4 luglio 2022](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| Trasferimenti ERC-20 | 1111 tps | [4 luglio 2022](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| Minting di NFT | 714 tps | [4 luglio 2022](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +Il nostro obiettivo è di rendere un software client di blockchain altamente performante, ricco di funzionalità e facile da configurare e mantenere. Tutti i test sono stati effettuati utilizzando Loadbot di Polygon Edge. Ogni report sulle prestazioni che troverai in questa sezione è correttamente datato, l'ambiente chiaramente descritto e il metodo di test chiaramente spiegato. + +L'obiettivo di questi test sulle prestazioni è mostrare una performance mondiale reale della rete blockchain Polygon Edge. Chiunque dovrebbe essere in grado di ottenere gli stessi risultati riportati qui, sullo stesso ambiente, utilizzando il nostro loadbot. + +Tutti i test delle prestazioni sono stati condotti sulla piattaforma AWS su una catena costituita dai nodi di istanza EC2. \ No newline at end of file diff --git a/archive/edge/it-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/it-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..7fda9598dd --- /dev/null +++ b/archive/edge/it-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,130 @@ +--- +id: test-2022-01-21 +title: 21 gennaio 2022 +description: "Test di performance del 21 gennaio." +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## 21 gennaio 2022 {#january-21st-2022} + +### Riepilogo {#summary} + +:::caution +Si prega di notare che il nostro , `loadbot`utilizzato per eseguire questi test, è ora deprezzato. +::: + +Il test è stato eseguito dopo il refactoring di TxPool che ha notevolmente migliorato le prestazioni (rilasciato in [v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0)). + +L'obiettivo era quello di creare un'ampia rete composta da 30 validatori attivamente partecipanti al fine di testare adeguatamente il consenso e il gossip delle transazioni di TxPool, poiché tutte le transazioni sono state inviate al JSON-RPC di un singolo nodo. + +Il nostro obiettivo non era quello di raggiungere il più alto numero di TPS possibile, poiché la dimensione della rete influisce negativamente sulle prestazioni, e dal momento che il limite di gas del blocco e il tempo del blocco sono impostati su valori adeguati che non consumano molte risorse di sistema e ne consentono l'esecuzione su hardware di base. + +### Risultati {#results} + +| Valore | metrico | +| ------ | ----- | +| Transazioni al secondo | 344 | +| Transazioni fallite | 0 | +| Transazioni effettuate con successo | 10000 | +| Tempo di esecuzione totale | 30 s | + +### Ambiente {#environment} + +
+ Configurazione host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornitore cloudAWS
Dimensione istanzat2.xlarge
ReteSubnet privato
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Limite del descrittore di file65535
Numero massimo di processi utente65535
+
+
+
+
+ +
+ Configurazione blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Versione Polygon EdgeCommit 8377162281d1a2e4342ae27cd4e5367c4364aee2 su develop branch
Nodi validatori30
Nodi non validatori0
ConsensusIBFT PoA
Tempo di blocco2000 ms
Limite gas del blocco5242880
+
+
+
+
+ +
+ Configurazione Loadbot +
+
+ + + + + + + + + + + + + +
Transazioni totali10000
Transazioni inviate al secondo400
Tipo di transazioniTrasferimenti EOA a EOA
+
+
+
+
diff --git a/archive/edge/it-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/it-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..ca00150b26 --- /dev/null +++ b/archive/edge/it-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,389 @@ +--- +id: test-2022-03-02 +title: 2 marzo 2022 +description: "Test della performance dal 2 marzo.\n" +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### Riepilogo {#summary} + +:::caution +Si prega di notare che il nostro , `loadbot`utilizzato per eseguire questi test, è ora deprezzato. +::: + +Questo test è stato eseguito per misurare i trasferimenti di token SC ERC20 e la funzionalità di minting di token SC ERC721 con carichi pesanti e la velocità delle transazioni. + +L'obiettivo era quello di verificare se tutto avesse funzionato come previsto nei momenti con carichi pesanti. Questo è anche il motivo per cui abbiamo introdotto le metriche gas nell'output del loadbot, che ci mostrano se i blocchi sono riempiti correttamente con le transazioni. + +Tutte le transazioni sono state inviate al singolo nodo tramite API GRPC e le ricevute sono state ricevute tramite API JSON-RPC. Al termine di tutte le transazioni, le informazioni sul gas sono state lette da ciascun blocco, utilizzando il metodo eth_getBlockByNumber JSON-RPC. + +Il nostro obiettivo non era quello di raggiungere il massimo TPS possibile, dal momento che il limite di gas del blocco e il tempo del blocco sono impostati su valori adeguati che non consumano molte risorse di sistema e ne consentono l'esecuzione su hardware di base. + +### Risultati ERC20 {#results-erc20} + +| Valore | metrico | +| ------ | ----- | +| Tipo di transazione | ERC20 | +| Transazioni al secondo | 65 | +| Transazioni fallite | 0 | +| Transazioni effettuate con successo | 5000 | +| Tempo di esecuzione della transazione ERC20 | 76.681690s | +| Tempo di implementazione SC | 4.048250 s | + +### Risultati ERC721 {#results-erc721} + +| Valore | metrico | +| ------ | ----- | +| Tipo di transazione | ERC721 | +| Transazioni al secondo | 20 | +| Transazioni fallite | 0 | +| Transazioni effettuate con successo | 2000 | +| Tempo di esecuzione della transazione ERC721 | 97.239920 s | +| Tempo di implementazione SC | 3.048970 s | + +### Ambiente ERC20 {#environment-erc20} + +
+ Configurazione host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornitore cloudAWS
Dimensione istanzat2.micro
ReteSubnet privato
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Limite del descrittore di file65535
Numero massimo di processi utente65535
+
+
+
+
+ +
+ Configurazione blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versione Polygon EdgeCommit 8a033aa1afb191abdac04636d318f83f32511f3c su develop branch
Nodi validatori6
Nodi non validatori0
ConsensusIBFT PoA
Tempo di blocco2 s
Limite gas del blocco5242880
Utilizzo medio del blocco95%
+
+
+
+
+ +
+ Configurazione Loadbot +
+
+ + + + + + + + + + + + + +
Transazioni totali5000
Transazioni inviate al secondo200
Tipo di transazioniTrasferimenti da ERC20 a ERC20
+
+
+
+
+ +
+ Log Loadbot + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### Ambiente ERC721 {#environment-erc721} + +
+ Configurazione host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornitore cloudAWS
Dimensione istanzat2.micro
ReteSubnet privato
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Limite del descrittore di file65535
Numero massimo di processi utente65535
+
+
+
+
+ +
+ Configurazione blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versione Polygon EdgeCommit 8a033aa1afb191abdac04636d318f83f32511f3c su develop branch
Nodi validatori6
Nodi non validatori0
ConsensusIBFT PoA
Tempo di blocco2 s
Limite gas del blocco5242880
Utilizzo medio del blocco94%
+
+
+
+
+ +
+ Configurazione Loadbot +
+
+ + + + + + + + + + + + + +
Transazioni totali2000
Transazioni inviate al secondo200
Tipo di transazioniConio di token ERC721
+
+
+
+
+ +
+ Log Loadbot + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/it-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/it-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..51a1e46409 --- /dev/null +++ b/archive/edge/it-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,956 @@ +--- +id: test-2022-03-23 +title: 23 marzo 2022 +description: "Test di performance dal 23 marzo." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### Riepilogo {#summary} + +:::caution +Si prega di notare che il nostro , `loadbot`utilizzato per eseguire questi test, è ora deprezzato. +::: + +Questo test è stato effettuato per misurare i trasferimenti di token SC ERC20, il minting di token SC ERC721, la funzionalità delle transazioni da EOA a EOA con carichi pesanti e la velocità delle transazioni sui nodi con risorse hardware superiori. + +L'obiettivo era quello di verificare se tutto funzioni come previsto nei momenti con carichi pesanti. Questo è anche il motivo per cui abbiamo introdotto le metriche gas nell'output del loadbot, che ci mostrano se i blocchi sono riempiti correttamente con le transazioni. + +Tutte le transazioni sono state inviate al singolo nodo tramite API GRPC e le ricevute sono state ricevute tramite API JSON-RPC. Al termine di tutte le transazioni, le informazioni sul gas sono state lette da ciascun blocco, utilizzando il metodo eth_getBlockByNumber JSON-RPC. + +Il nostro obiettivo era quello di raggiungere il più alto numero di TPS possibile con le risorse hardware disponibili. Per ottenere questo risultato, abbiamo modificato il limite gas del blocco e i parametri del tempo del blocco, per ottenere i migliori risultati possibili in termini di TPS e mantenere l'integrità e la stabilità del sistema. + +:::info Limite Gas del blocco + +Il limite di gas del blocco può essere aumentato a un numero relativamente alto se le transazioni utilizzano molto gas per l'esecuzione. +Nell'esempio riportato di seguito, il minting dei token ERC721 ha funzionato molto più velocemente con un limite di gas del blocco impostato a 80.000.000 (invece di 20 milioni), ma con i trasferimenti di token ERC20 con un limite di gas del blocco di 80 milioni, il server si è bloccato. + +::: + +:::info Ambienti di produzione + +Quando si configura un ambiente di produzione, è necessario prestare attenzione se si vogliono ottenere prestazioni elevate della catena. Se il parametro limite del gas del blocco è impostato su un valore elevato, il tempo del blocco è impostato su 1 s e c'è un carico elevato di transazioni su un singolo nodo, questo nodo consumerà molta (se non tutta la RAM disponibile) e potrà causare un crash del server. +Usa il loadbot per testare tutto a fondo, monitorare l'utilizzo delle risorse del sistema e impostare i parametri di configurazione di conseguenza. +::: + +:::info Errori di memoria esaurita + +Alcune distribuzioni Linux eliminano automaticamente i processi che hanno un utilizzo molto elevato della RAM (errore OOM), al fine di preservare la stabilità del sistema. L'output del log di questo errore OOM è simile al seguente. +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### Risultati dei trasferimenti da EOA a EOA {#results-of-eoa-to-eoa-transfers} +| Valore | metrico | +| ------ | ----- | +| Tipo di transazione | EOA a EOA | +| Transazioni al secondo | 689 | +| Transazioni fallite | 0 | +| Transazioni effettuate con successo | 20000 | +| Totale blocchi usati | 25 | +| Tempo di esecuzione totale | 29,921110 s | + +### Risultati del trasferimento dei token ERC20 {#results-of-erc20-token-transfers} + +| Valore | metrico | +| ------ | ----- | +| Tipo di transazione | ERC20 | +| Transazioni al secondo | 500 | +| Transazioni fallite | 0 | +| Transazioni effettuate con successo | 20000 | +| Totale blocchi usati | 33 | +| Tempo di esecuzione della transazione ERC20 | 40,402900 s | +| Tempo di implementazione SC | 2,004140 s | + +### Risultati del minting di token ERC721 {#results-of-erc721-token-minting} + +| Valore | metrico | +| ------ | ----- | +| Tipo di transazione | ERC721 | +| Transazioni al secondo | 157 | +| Transazioni fallite | 0 | +| Transazioni effettuate con successo | 20000 | +| Totale blocchi usati | 124 | +| Tempo di esecuzione della transazione ERC721 | 127537340 s | +| Tempo di implementazione SC | 2,004420 s | + + +### Risultati del conio del gettone ERC721 con un limite di gas di blocco molto alto (80 milioni) {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| Valore | metrico | +| ------ | ----- | +| Tipo di transazione | ERC721 | +| Transazioni al secondo | 487 | +| Transazioni fallite | 0 | +| Transazioni effettuate con successo | 20000 | +| Totale blocchi usati | 34 | +| Tempo di esecuzione della transazione ERC721 | 41,098410 s | +| Tempo di implementazione SC | 2.004300 s | + + +### Ambiente da EOA a EOA {#environment-eoa-to-eoa} +
+ Configurazione host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornitore cloudAWS
Dimensione istanzac5.2xlarge
ReteSubnet privato
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite del descrittore di file65535
Numero massimo di processi utente65535
+
+
+
+
+ +
+ Configurazione blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versione Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 su develop branch
Nodi validatori4
Nodi non validatori0
ConsensusIBFT PoA
Tempo di blocco1 s
Limite gas del blocco20000000
Slot massimi1000000
Utilizzo medio del blocco84,00%
+
+
+
+
+ +
+ Configurazione Loadbot +
+
+ + + + + + + + + + + + + +
Transazioni totali20000
Transazioni inviate al secondo689
Tipo di transazioniTrasferimenti EOA a EOA
+
+
+
+
+ +
+ Log Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### Ambiente ERC20 {#environment-erc20} +
+ Configurazione host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornitore cloudAWS
Dimensione istanzac5.2xlarge
ReteSubnet privato
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite del descrittore di file65535
Numero massimo di processi utente65535
+
+
+
+
+ +
+ Configurazione blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versione Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 su develop branch
Nodi validatori4
Nodi non validatori0
ConsensusIBFT PoA
Tempo di blocco1 s
Limite gas del blocco20000000
Slot massimi1000000
Utilizzo medio del blocco88,38%
+
+
+
+
+ +
+ Configurazione Loadbot +
+
+ + + + + + + + + + + + + +
Transazioni totali20000
Transazioni inviate al secondo500
Tipo di transazioniTrasferimenti da ERC20 a ERC20
+
+
+
+
+ +
+ Log Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### Ambiente ERC721 {#environment-erc721} +
+ Configurazione host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornitore cloudAWS
Dimensione istanzac5.2xlarge
ReteSubnet privato
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite del descrittore di file65535
Numero massimo di processi utente65535
+
+
+
+
+ +
+ Configurazione blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versione Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 su develop branch
Nodi validatori4
Nodi non validatori0
ConsensusIBFT PoA
Tempo di blocco1 s
Limite gas del blocco20000000
Slot massimi1000000
Utilizzo medio del blocco92,90%
+
+
+
+
+ +
+ Configurazione Loadbot +
+
+ + + + + + + + + + + + + +
Transazioni totali20000
Transazioni inviate al secondo157
Tipo di transazioniConio di token ERC721
+
+
+
+
+ +
+ Log Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### Ambiente ERC20 - limite gas del blocco molto alto {#environment-erc20-very-high-block-gas-limit} +
+ Configurazione host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornitore cloudAWS
Dimensione istanzac5.2xlarge
ReteSubnet privato
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite del descrittore di file65535
Numero massimo di processi utente65535
+
+
+
+
+ +
+ Configurazione blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versione Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 su develop branch
Nodi validatori4
Nodi non validatori0
ConsensusIBFT PoA
Tempo di blocco1 s
Limite gas del blocco80000000
Slot massimi1000000
Utilizzo medio del blocco---
+
+
+
+
+ +
+ Configurazione Loadbot +
+
+ + + + + + + + + + + + + +
Transazioni totali20000
Transazioni inviate al secondo---
Tipo di transazioniTrasferimenti da ERC20 a ERC20
+
+
+
+
+ +
+ Log errore OOM + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### Ambiente ERC721 - limite gas del blocco molto alto {#environment-erc721-very-high-block-gas-limit} +
+ Configurazione host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornitore cloudAWS
Dimensione istanzac5.2xlarge
ReteSubnet privato
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite del descrittore di file65535
Numero massimo di processi utente65535
+
+
+
+
+ +
+ Configurazione blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versione Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 su develop branch
Nodi validatori4
Nodi non validatori0
ConsensusIBFT PoA
Tempo di blocco1 s
Limite gas del blocco80000000
Slot massimi1000000
Utilizzo medio del blocco84,68%
+
+
+
+
+ +
+ Configurazione Loadbot +
+
+ + + + + + + + + + + + + +
Transazioni totali20000
Transazioni inviate al secondo487
Tipo di transazioniConio di token ERC721
+
+
+
+
+ +
+ Log Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/it-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/it-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..32ac71c6ff --- /dev/null +++ b/archive/edge/it-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,565 @@ +--- +id: test-2022-07-04 +title: 4 luglio 2022 +description: "Test delle prestazioni dal 4 luglio." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### Riepilogo {#summary} + +:::caution +Si prega di notare che il nostro , `loadbot`utilizzato per eseguire questi test, è ora deprezzato. +::: + +Questo test è stato effettuato per misurare i trasferimenti di token SC ERC20, il minting di token SC ERC721, la funzionalità delle transazioni da EOA a EOA con carichi pesanti e la velocità delle transazioni sui nodi con risorse hardware superiori. + +L'obiettivo era quello di verificare se tutto funzioni come previsto nei momenti con carichi pesanti. Questo è anche il motivo per cui abbiamo introdotto le metriche gas nell'output del loadbot, che ci mostrano se i blocchi sono riempiti correttamente con le transazioni. + +Tutte le transazioni sono state inviate al singolo nodo tramite API GRPC e le ricevute sono state ricevute tramite API JSON-RPC. Al termine di tutte le transazioni, le informazioni sul gas sono state lette da ciascun blocco, utilizzando il metodo eth_getBlockByNumber JSON-RPC. + +Il nostro obiettivo era quello di raggiungere il più alto numero di TPS possibile con le risorse hardware disponibili. Per ottenere questo risultato, abbiamo modificato il limite gas del blocco e i parametri del tempo del blocco, per ottenere i migliori risultati possibili in termini di TPS e mantenere l'integrità e la stabilità del sistema. + + +:::info Ambienti di produzione + +Quando si configura un ambiente di produzione, è necessario prestare attenzione se si vogliono ottenere prestazioni elevate della catena. Se il parametro limite del gas del blocco è impostato su un valore elevato, il tempo del blocco è impostato su 1 s e c'è un carico elevato di transazioni su un singolo nodo, questo nodo consumerà molta (se non tutta la RAM disponibile) e potrà causare un crash del server. +Usa il loadbot per testare tutto a fondo, monitorare l'utilizzo delle risorse del sistema e impostare i parametri di configurazione di conseguenza. +::: + + + +### Risultati dei trasferimenti da EOA a EOA {#results-of-eoa-to-eoa-transfers} +| Valore | metrico | +| ------ | ----- | +| Tipo di transazione | EOA a EOA | +| Transazioni al secondo | 1428 | +| Transazioni fallite | 0 | +| Transazioni effettuate con successo | 30000 | +| Totale blocchi usati | 15 | +| Tempo di esecuzione totale | 21,374620 s | + +### Risultati del trasferimento dei token ERC20 {#results-of-erc20-token-transfers} + +| Valore | metrico | +| ------ | ----- | +| Tipo di transazione | ERC20 | +| Transazioni al secondo | 1111 | +| Transazioni fallite | 0 | +| Transazioni effettuate con successo | 50000 | +| Totale blocchi usati | 38 | +| Tempo di esecuzione della transazione ERC20 | 45,906450 s | +| Tempo di implementazione SC | 2,006580 s | + +### Risultati del minting di token ERC721 {#results-of-erc721-token-minting} + +| Valore | metrico | +| ------ | ----- | +| Tipo di transazione | ERC721 | +| Transazioni al secondo | 714 | +| Transazioni fallite | 0 | +| Transazioni effettuate con successo | 30000 | +| Totale blocchi usati | 39 | +| Tempo di esecuzione della transazione ERC721 | 42,864140 s | +| Tempo di implementazione SC | 2,005500 s | + + + + +### Ambiente da EOA a EOA {#environment-eoa-to-eoa} +
+ Configurazione host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornitore cloudAWS EC2
Dimensione istanzac6a.48xlarge
ReteSubnet privato
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Limite del descrittore di file65535
Numero massimo di processi utente65535
+
+
+
+
+ +
+ Configurazione blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versione Polygon EdgeRilascio v0.4.1
Nodi validatori4
Nodi non validatori0
ConsensusIBFT PoA
Tempo di blocco1 s
Limite gas del blocco7077880
Slot massimi276480
Utilizzo medio del blocco59,34%
+
+
+
+
+ +
+ Configurazione del Loadbot +
+
+ + + + + + + + + + + + + +
Transazioni totali30000
Transazioni inviate al secondo1428
Tipo di transazioniTrasferimenti EOA a EOA
+
+
+
+
+ +
+ Log Loadbot + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### Ambiente ERC20 {#environment-erc20} +
+ Configurazione host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornitore cloudAWS EC2
Dimensione istanzac6a.48xlarge
ReteSubnet privato
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Limite del descrittore di file65535
Numero massimo di processi utente65535
+
+
+
+
+ +
+ Configurazione blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versione Polygon EdgeRilascio v0.4.1
Nodi validatori4
Nodi non validatori0
ConsensusIBFT PoA
Tempo di blocco1 s
Limite gas del blocco47185920
Slot massimi184320
Utilizzo medio del blocco81,29%
+
+
+
+
+ +
+ Configurazione del Loadbot +
+
+ + + + + + + + + + + + + +
Transazioni totali50000
Transazioni inviate al secondo1111
Tipo di transazioniTrasferimenti da ERC20 a ERC20
+
+
+
+
+ +
+ Log Loadbot + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### Ambiente ERC721 {#environment-erc721} +
+ Configurazione host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornitore cloudAWS EC2
Dimensione istanzac6a.48xlarge
ReteSubnet privato
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Limite del descrittore di file65535
Numero massimo di processi utente65535
+
+
+
+
+ +
+ Configurazione blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versione Polygon EdgeRilascio v0.4.1
Nodi validatori4
Nodi non validatori0
ConsensusIBFT PoA
Tempo di blocco1 s
Limite gas del blocco94371840
Slot massimi1000000
Utilizzo medio del blocco93,88%
+
+
+
+
+ +
+ Configurazione del Loadbot +
+
+ + + + + + + + + + + + + +
Transazioni totali30000
Transazioni inviate al secondo714
Tipo di transazioniConio di token ERC721
+
+
+
+
+ +
+ Log Loadbot + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/it-edge/troubleshooting.md b/archive/edge/it-edge/troubleshooting.md new file mode 100644 index 0000000000..1e7ec71f50 --- /dev/null +++ b/archive/edge/it-edge/troubleshooting.md @@ -0,0 +1,67 @@ +--- +id: troubleshooting +title: Risoluzione dei problemi +description: "Sezione Risoluzione dei problemi per Polygon Edge" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# Risoluzione dei problemi {#troubleshooting} + +## `method=eth_call err="invalid signature"` errore {#error} + +Quando si utilizza un wallet per effettuare una transazione con Polygon Edge, assicurarsi che nell'impostazione della rete locale del proprio wallet: + +1. Il `chainID`sia quello giusto. L'impostazione predefinita `chainID`per Edge è `100`, ma può essere personalizzata utilizzando il flag genesi`--chain-id` . + + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. Assicurarsi che, nel campo "RPC URL", si utilizzi la porta JSON RPC del nodo a cui ci si connette. + + +## Come ottenere un URL WebSocket {#how-to-get-a-websocket-url} + +Per impostazione predefinita, quando si esegue Polygon Edge, viene esposto un endpoint WebSocket basato sulla posizione della catena. Lo schema URL `wss://`viene utilizzato per i collegamenti HTTPS e `ws://`per HTTP. + +URL Localhost WebSocket: +````bash +ws://:/ws +```` +Notare che il numero di porta dipende dalla porta JSON-RPC scelta per il nodo. + +URL Edgenet WebSocket: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## `insufficient funds`errore durante il tentativo di implementazione di un contratto {#error-when-trying-to-deploy-a-contract} + +Se si verifica questo errore, assicurarsi di avere fondi sufficienti sull'indirizzo desiderato e che l'indirizzo utilizzato sia quello corretto.
Per impostare il saldo preminato, è possibile utilizzare il flag genesi `genesis [--premine ADDRESS:VALUE]`durante la generazione del file genesi. Esempio di utilizzo di questo flag: +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +Questo premina 1000000000000000000000 WEI su 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862. + + +## I token ERC20 non vengono rilasciati mentre si usa Chainbridge {#erc20-tokens-not-released-while-using-chainbridge} + +Se si tenta di trasferire token ERC20 tra Polygon POS e una rete Edge locale, e i token ERC20 vengono depositati, anche la proposta viene eseguita al relayer, ma i token non vengono rilasciati nella rete Edge, assicurarsi che l'Handler ERC20 nella catena Polygon Edge abbia abbastanza token da
rilasciare. Il contratto Handler nella catena di destinazione deve avere abbastanza token da rilasciare per la modalità lock-release. Se non sono presenti token ERC20 nell'Handler ERC20 della rete Edge locale, si prega di coniare nuovi token e trasferirli all'Handler ERC20. + +## `Incorrect fee supplied` errore durante l'utilizzo di Chainbridge {#error-when-using-chainbridge} + +È possibile che si verifichi questo errore quando si tenta di trasferire i token ERC20 tra la catena Mumbai Polygon POS e una configurazione Polygon Edge locale. Questo errore compare quando si imposta la commissione al momento della distribuzione utilizzando il `--fee`flag, ma non si imposta lo stesso valore nella transazione di deposito. È possibile utilizzare il comando seguente per modificare la commissione: +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +Qui puoi trovare altre informazioni su questa [bandiera](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md). + + + + + diff --git a/archive/edge/it-edge/validator-hosting.md b/archive/edge/it-edge/validator-hosting.md new file mode 100644 index 0000000000..119ea38d9c --- /dev/null +++ b/archive/edge/it-edge/validator-hosting.md @@ -0,0 +1,249 @@ +--- +id: validator-hosting +title: Hosting validatore +description: "Requisiti di hosting per Polygon Edge" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +Di seguito sono riportati i suggerimenti per ospitare correttamente un nodo validatore in una rete Polygon Edge. Fai attenzione a tutti gli articoli elencati di seguito per assicurarti che la configurazione del tuo validatore sia stata eseguita correttamente per essere sicura, stabile e performante. + +## Conoscenze di base {#knowledge-base} + +Prima di provare ad eseguire il nodo validatore, leggi attentamente questo documento. +Documenti aggiuntivi che potrebbero essere utili sono: + +- [Installazione](get-started/installation) +- [Configurazione del cloud](get-started/set-up-ibft-on-the-cloud) +- [Comandi CLI](get-started/cli-commands) +- [File di configurazione del server](configuration/sample-config) +- [Chiavi private](configuration/manage-private-keys) +- [Metriche Prometheus](configuration/prometheus-metrics) +- [Secret managers](/docs/category/secret-managers) +- [Backup/Ripristino](working-with-node/backup-restore) + +## Requisiti di sistema minimi {#minimum-system-requirements} + +| Tipo | Valore | Influenzato da | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 2 core |
  • Numero di query JSON-RPC
  • Dimensione dello stato della blockchain
  • Limite gas del blocco
  • Tempo di blocco
| +| RAM | 2 GB |
  • Numero di query JSON-RPC
  • Dimensione dello stato della blockchain
  • Limite gas del blocco
| +| Disco |
  • Partizione di root da 10 GB
  • Partizione di root da 30 GB con LVM per l'estensione del disco
|
  • Dimensione dello stato della blockchain
| + + +## Configurazione del servizio {#service-configuration} + +Il binario `polygon-edge` deve essere eseguito automaticamente come servizio di sistema dopo aver stabilito la connettività di rete e avere funzionalità di +avvio/arresto/riavvio. Consigliamo di utilizzare un gestore di servizi come `systemd.` + +Esempio di file di configurazione del sistema `systemd`: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### Binario {#binary} + +Nei carichi di lavoro di produzione il binario `polygon-edge` deve essere implementato solo da binari di rilascio GitHub predefiniti, non compilandolo manualmente. +:::info + +Compilando manualmente il `develop` ramo GitHub, potresti introdurre modifiche sostanziali al tuo ambiente. +Per questo motivo si consiglia di implementare il binario Polygon Edge esclusivamente dalle versioni, in quanto conterrà informazioni sulle modifiche sostanziali e su come superarle. +::: + +Consultare l'[Installazione](/docs/edge/get-started/installation) per una panoramica completa del metodo di installazione. + +### Archivio dati {#data-storage} + +La cartella `data/` contenente l'intero stato della blockchain deve essere montata su un disco/volume dedicato consentendo +backup automatici del disco, estensione del volume e montaggio facoltativo del disco/volume su un'altra istanza in caso di errore. + + +### File di log {#log-files} + +I file di log devono essere ruotati su base giornaliera (con uno strumento come `logrotate`). +:::warning +Se configurati senza rotazione del log, i file di log potrebbero esaurire tutto lo spazio su disco disponibile, il che potrebbe interrompere il tempo di attività del validatore +::: + +Esempio di configurazione `logrotate`: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +Consultare la sezione [Logging](#logging) di seguito per consigli sull'archiviazione dei log. + +### Dipendenze aggiuntive {#additional-dependencies} + +`polygon-edge` è compilato in modo statico, senza richiedere ulteriori dipendenze del sistema operativo host. + +## Manutenzione {#maintenance} + +Di seguito sono riportate le procedure consigliate per la gestione di un nodo validatore in esecuzione di una rete Polygon Edge. + +### Backup {#backup} + +Per i nodi Polygon Edge sono consigliati due tipi di procedure di backup. + +Il suggerimento è di utilizzare entrambi, quando possibile, con il backup Polygon Edge che è un'opzione sempre disponibile. + +* ***Backup del volume***: +Backup incrementale giornaliero del volume `data/` del nodo Polygon Edge o della VM completa, se possibile. + + +* ***Backup di Polygon Edge***: + Si consiglia un lavoro CRON giornaliero che esegue backup regolari di Polygon Edge e sposta i file `.dat` in una posizione fuori sede o in un archivio di oggetti cloud sicuro. + +Il backup Polygon Edge idealmente non dovrebbe sovrapporsi al backup del volume descritto sopra. + +Consultare l'[istanza del nodo di backup/ripristino](working-with-node/backup-restore) per istruzioni su come eseguire i backup di Polygon Edge. + +### Logging {#logging} + +I log generati dai nodi Polygon Edge dovrebbero: +- essere inviati a un archivio dati esterno con funzionalità di indicizzazione e ricerca +- avere un periodo di conservazione del log di 30 giorni + +Se è la prima volta che configuri un validatore Polygon Edge, ti consigliamo di avviare il nodo con l'opzione `--log-level=DEBUG` per essere in grado di eseguire rapidamente il debug di eventuali problemi che potresti incontrare. + +:::info + +Il `--log-level=DEBUG` renderà l'output del log del nodo il più dettagliato possibile. +I log del debug aumenteranno drasticamente la dimensione del file di log da tenere in considerazione durante l'impostazione della soluzione di rotazione del log. +::: +### Le patch di sicurezza del sistema operativo {#os-security-patches} + +Gli amministratori devono assicurarsi che il sistema operativo dell'istanza del validatore sia sempre aggiornato con le patch più recenti almeno una volta al mese. + +## Metriche {#metrics} + +### Metriche di sistema {#system-metrics} + +Gli amministratori devono configurare una sorta di monitoraggio delle metriche di sistema, (ad es. Telegraf + InfluxDB + Grafana o un SaaS di terze parti). + +Metriche che devono essere monitorate e per le quali è necessario configurare le notifiche di allarme: + +| Nome della metrica | Soglia di allarme | +|-----------------------|-------------------------------| +| Utilizzo della CPU (%) | > 90% per più di 5 minuti | +| Utilizzo della RAM (%) | > 90% per più di 5 minuti | +| Utilizzo del disco di root | > 90% | +| Utilizzo del disco dati | > 90% | + +### Metriche del validatore {#validator-metrics} + +Gli amministratori devono configurare la raccolta di metriche dall'API Prometheus di Polygon Edge per poter monitorare le prestazioni della blockchain. + +Consulta le [metriche di Prometheus](configuration/prometheus-metrics) per capire quali metriche vengono esposte e come configurare la raccolta di metriche di Prometheus. + + +È necessario prestare un'attenzione supplementare alle seguenti metriche: +- ***Tempo di produzione del blocco*** - se il tempo di produzione del blocco è superiore al normale, esiste un potenziale problema con la rete +- ***Numero di round di consensus*** - se c'è più di 1 round, c'è un potenziale problema con il validatore impostato nella rete +- ***Numero di peer*** - se il numero di peer diminuisce, c'è un problema di connettività nella rete + +## Sicurezza {#security} + +Di seguito sono riportate le procedure consigliate per la protezione di un nodo validatore in esecuzione di una rete Polygon Edge. + +### Servizi API {#api-services} + +- ***JSON-RPC*** - +Solo il servizio API che deve essere esposto al pubblico (tramite bilanciatore del carico o direttamente). +Questa API dovrebbe essere eseguita su tutte le interfacce o su un indirizzo IP specifico (esempio: `--json-rpc 0.0.0.0:8545` o `--json-prc 192.168.1.1:8545` ). +:::info +Poiché si tratta di un'API pubblica, si consiglia di disporre di un bilanciatore di carico/proxy inverso di fronte ad essa per fornire sicurezza e limitazione della velocità. +::: + + +- ***LibP2P*** - +Questa è l'API di networking utilizzata dai nodi per la comunicazione peer. Deve essere eseguita su tutte le interfacce o su un indirizzo ip specifico ( `--libp2p 0.0.0.0:1478` o `--libp2p 192.168.1.1:1478` ). Questa API non deve essere esposta pubblicamente, ma dovrebbe essere raggiungibile da tutti gli altri nodi. +:::info + +Se eseguito su localhost ( `--libp2p 127.0.0.1:1478` ) altri nodi non saranno in grado di connettersi. + +::: + + +- ***GRPC*** - +Questa API viene utilizzata solo per eseguire i comandi dell'operatore e annotare altro. In quanto tale dovrebbe funzionare esclusivamente su localhost ( `--grpc-address 127.0.0.1:9632` ). + +### Segreti di Polygon Edge {#polygon-edge-secrets} + +I segreti di Polygon Edge ( `ibft` e `libp2p` le chiavi) devono essere memorizzati su un file system locale. +Invece, dovrebbe essere utilizzato un [Secret Manager](configuration/secret-managers/set-up-aws-ssm) supportato. +La memorizzazione dei segreti nel file system locale deve essere utilizzata solo in ambienti non di produzione. + +## Aggiornamento {#update} + +Di seguito è riportata la procedura di aggiornamento desiderata per i nodi validatori, descritta come istruzioni step-by-step. + +### Procedura di aggiornamento {#update-procedure} + +- Scarica l'ultimo binario Polygon Edge dalle [versioni](https://github.com/0xPolygon/polygon-edge/releases)ufficiali di GitHub +- Arresta il servizio Polygon Edge (esempio: `sudo systemctl stop polygon-edge.service` ) +- Sostituisci il `polygon-edge` binario esistente con il binario scaricato (esempio: `sudo mv polygon-edge /usr/local/bin/` ) +- Verifica se è disponibile la versione `polygon-edge` corretta eseguendo `polygon-edge version` - dovrebbe corrispondere alla versione di rilascio +- Controlla la documentazione di rilascio se sono necessari dei passaggi per la compatibilità con le versioni precedenti prima di avviare il servizio `polygon-edge` +- Avvia il servizio `polygon-edge` (esempio: `sudo systemctl start polygon-edge.service` ) +- Infine, controlla `polygon-edge` l'output del log e assicurati che tutto sia in esecuzione senza alcun log `[ERROR]` + +:::warning +Quando è presente una versione di interruzione, questa procedura di aggiornamento deve essere eseguita su tutti i nodi poiché il binario attualmente in esecuzione non è compatibile con la nuova versione. + +Ciò significa che la catena deve essere interrotta per un breve periodo di tempo (fino alla sostituzione dei binari `polygon-edge` e al riavvio del servizio) +quindi pianifica di conseguenza. + +È possibile utilizzare strumenti come **[Ansible](https://www.ansible.com/)** o alcuni script personalizzati per eseguire l'aggiornamento in modo efficiente +e minimizzare i tempi di inattività della catena. +::: + +## Procedura di avvio {#startup-procedure} + +Di seguito è riportato il flusso desiderato della procedura di avvio per il validatore Polygon Edge + +- Leggi i documenti elencati nella sezione [Conoscenze di base](#knowledge-base) +- Applica le più recenti patch del sistema operativo sul nodo validatore +- Scarica l'ultimo binario `polygon-edge` dalle [versioni](https://github.com/0xPolygon/polygon-edge/releases) ufficiali di GitHub e inseriscilo nell'istanza locale `PATH` +- Inizializza uno dei [secrets manager](/docs/category/secret-managers) supportati utilizzando il `polygon-edge secrets generate` comando CLI +- Genera e memorizza i segreti utilizzando il `polygon-edge secrets init` [comando CLI](/docs/edge/get-started/cli-commands#secrets-init-flags) +- Prendi nota dei valori `NodeID` e `Public key (address)` +- Genera `genesis.json` file come descritto nella [configurazione cloud](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators) utilizzando il`polygon-edge genesis` [comando CLI](/docs/edge/get-started/cli-commands#genesis-flags) +- Genera il file di configurazione di predefinito utilizzando il `polygon-edge server export` [comando CLI](/docs/edge/configuration/sample-config) +- Modifica il file `default-config.yaml` perché si adatti all'ambiente del nodo validatore locale (percorsi di file, ecc.) +- Crea un servizio Polygon Edge ( `systemd` o simile ) dove il binario `polygon-edge` eseguirà il server da un file `default-config.yaml` +- Avvia il server Polygon Edge avviando il servizio (esempio: `systemctl start polygon-edge` ) +- Controlla `polygon-edge` l'output del log e assicurati che i blocchi vengano generati e che non ci siano log `[ERROR]` +- Controlla la funzionalità della catena chiamando un metodo JSON-RPC come [`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid) diff --git a/archive/edge/it-edge/working-with-node/backup-restore.md b/archive/edge/it-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..b51a9f69df --- /dev/null +++ b/archive/edge/it-edge/working-with-node/backup-restore.md @@ -0,0 +1,86 @@ +--- +id: backup-restore +title: Backup/ripristino dell'istanza del nodo +description: "Come eseguire il backup e ripristinare un'istanza del nodo Polygon Edge." +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## Panoramica {#overview} + +Questa guida illustra in dettaglio come eseguire il backup e il ripristino di un'istanza del nodo Polygon Edge. Tratta le cartelle di base e quello che contengono, così come quali file sono fondamentali per l'esecuzione di un backup e di un ripristino di successo. + +## Cartelle di base {#base-folders} + +Polygon Edge sfrutta LevelDB come suo motore di archiviazione. Quando si avvia un nodo Polygon Edge, vengono create le seguenti sotto-cartelle nella directory di lavoro specificata: +* **blockchain** - Memorizza i dati blockchain +* **trie** - Memorizza i trie di Merkle (dati sullo stato mondiale) +* **keystore** - Memorizza le chiavi private del client. Questo include la chiave privata di libp2p e la chiave privata del sigillatore/validatore +* **consensus** - Memorizza tutte le informazioni sul consenso di cui il client potrebbe avere bisogno durante il lavoro. Per ora, memorizza la *chiave privata del validatore* del nodo + +È fondamentale che queste cartelle vengano conservate affinché l'istanza Polygon Edge funzioni senza problemi. + +## Crea il backup da un nodo in esecuzione e ripristina il nuovo nodo {#create-backup-from-a-running-node-and-restore-for-new-node} + +Questa sezione ti guida attraverso la creazione di dati di archivio della blockchain in un nodo in esecuzione e il ripristino in un'altra istanza. + +### Backup {#backup} + +Il comando `backup` recupera i blocchi da un nodo in esecuzione tramite gRPC e genera un file di archivio. Se `--from` e `--to` non vengono forniti nel comando, questo comando recupererà i blocchi dalla genesi all'ultimo. + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### Ripristina {#restore} + +Un server importa i blocchi da un archivio all'inizio quando si parte con il flag `--restore`. Assicurati che ci sia una chiave per un nodo nuovo. Per saperne di più sull'importazione o la generazione di chiavi, visita la [sezione Secret Managers](/docs/edge/configuration/secret-managers/set-up-aws-ssm). + +```bash +$ polygon-edge server --restore archive.dat +``` + +## Backup/ripristino di dati interi {#back-up-restore-whole-data} + +Questa sezione ti guida attraverso il backup dei dati, inclusi i dati di stato e la chiave, e il ripristino nella nuova istanza. + +### Passo 1: Ferma l'esecuzione del client {#step-1-stop-the-running-client} + +Poiché Polygon Edge utilizza **LevelDB** per la memorizzazione dei dati, il nodo deve essere fermato per la durata del backup, poiché **LevelDB** non consente l'accesso simultaneo ai suoi file di database. + +Inoltre, Polygon Edge esegue anche lo svuotamento dei dati alla chiusura. + +Il primo passo prevede l'arresto del client in esecuzione (tramite un gestore di servizi o altro meccanismo che invia un segnale SIGINT al processo), quindi può attivare 2 eventi mentre si spegne adeguatamente: +* Esecuzione dello scaricamento di dati sul disco +* Rilascio del blocco dei file DB da parte di LevelDB + +### Passo 2: Backup della directory {#step-2-backup-the-directory} + +Ora che il client non è in esecuzione, la directory dei dati può essere supportata su un altro mezzo. +Tieni presente che i file con estensione `.key` contengono i dati della chiave privata che si possono utilizzare per impersonare il nodo corrente, +e non dovrebbero mai essere condivisi con terzi/sconosciuti. + +:::info + +Esegui il backup e il ripristino manuale del file `genesis` generato, di modo che il nodo ripristinato sia completamente operativo. +::: + +## Ripristina {#restore-1} + +### Passo 1: Ferma l'esecuzione del client {#step-1-stop-the-running-client-1} + +Se è in esecuzione un'istanza di Polygon Edge, è necessario interromperla affinché il passaggio 2 abbia esito positivo. + +### Passo 2: copia la directory dei dati di backup nella cartella desiderata {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +Quando il client non è in esecuzione, la directory dei dati di cui è stato eseguito il backup in precedenza può essere copiata nella cartella desiderata. Inoltre, ripristina il file `genesis` copiato in precedenza. + +### Passo 3: esegui il client Polygon Edge specificando la directory dei dati corretta {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +Affinché Polygon Edge utilizzi la directory dei dati ripristinata, all'avvio, l'utente deve specificare il percorso della directory dei dati. Consulta la sezione [Comandi CLI](/docs/edge/get-started/cli-commands) sulle informazioni relative al flag `data-dir`. diff --git a/archive/edge/it-edge/working-with-node/query-json-rpc.md b/archive/edge/it-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..d5cda953db --- /dev/null +++ b/archive/edge/it-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,86 @@ +--- +id: query-json-rpc +title: Richiesta endpoint JSON RPC +description: "Richiedere i dati e avviare la catena con un account preminato." +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## Panoramica {#overview} + +Il layer JSON-RPC di Polygon Edge fornisce agli sviluppatori la funzionalità di interagire facilmente con la blockchain, tramite richieste HTTP. + +Questo esempio riguarda l'uso di strumenti come "**curl**" per richiedere le informazioni, nonché avviare la catena con un account preminato e inviare una transazione. + +## Passo 1: Creare un file genesis con un account preminato {#step-1-create-a-genesis-file-with-a-premined-account} + +Per generare un file genesis, eseguire il seguente comando: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +La bandiera **premina** imposta l'indirizzo che dovrebbe essere incluso con un saldo iniziale nel file **genesis**
. In questo caso, l'indirizzo `0x1010101010101010101010101010101010101010` avrà un saldo iniziale **predefinito** di`0xD3C21BCECCEDA1000000` (1 milione di gettoni di valuta nativa). + +Se si volesse specificare un saldo, si possono separare il saldo e l'indirizzo con un `:`, come: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +Il saldo può essere un valore `hex`o `uint256`. + +:::warning Preminare solo account per i quali si dispone di una chiave privata! + +Se si preminano account e non si dispone di una chiave privata per accedervi, il saldo preminato non sarà utilizzabile. +::: + +## Passo 2: avviare Polygon Edge in modalità dev {#step-2-start-the-polygon-edge-in-dev-mode} + +Per avviare Polygon Edge in modalità dev, come spiegato nella sezione [CLI Commands](/docs/edge/get-started/cli-commands), eseguire quanto segue: +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## Passo 3: richiedere il saldo dell'account {#step-3-query-the-account-balance} + +Ora che il client è attivo e funzionante in modalità dev, usando il file genesis generato nel **Passo 1**, possiamo usare uno strumento come **curl** per richiedere il saldo dell'account: +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +Il comando dovrebbe produrre il seguente risultato: +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## Passo 4: inviare una transazione di trasferimento {#step-4-send-a-transfer-transaction} + +Ora che abbiamo confermato che l'account che abbiamo impostato come preminato ha il saldo corretto, possiamo trasferire un po' di ether: + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/it-edge/working-with-node/query-operator-info.md b/archive/edge/it-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..aeb8299e35 --- /dev/null +++ b/archive/edge/it-edge/working-with-node/query-operator-info.md @@ -0,0 +1,85 @@ +--- +id: query-operator-info +title: Richiedere informazioni sull'operatore +description: "Come richiedere informazioni sull'operatore." +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## Prerequisiti {#prerequisites} + +Questa guida presuppone che tu abbia seguito l'[Installazione locale](/docs/edge/get-started/set-up-ibft-locally) o la guida [ su come configurare un cluster IBFT sul cloud2](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +È necessario un nodo funzionante per richiedere qualsiasi tipo di informazione sull'operatore. + +Con polygon edge, gli operatori del nodo hanno il controllo e sono informati su cosa sta facendo il nodo che stanno operando.
+In qualsiasi momento, possono utilizzare il layer di informazioni sui nodi, basato su gRPC, e ottenere informazioni significative, senza necessità di setacciare i log. + +:::note + +Se il tuo nodo non è in esecuzione su `127.0.0.1:8545` aggiungi un flag `--grpc-address ` ai comandi elencati in questo documento. + +::: + +## Informazioni sui peer {#peer-information} + +### Elenco dei peer {#peers-list} + +Per ottenere un elenco completo dei peer connessi (compreso lo stesso nodo in esecuzione), esegui il seguente comando: +````bash +polygon-edge peers list +```` + +Questo restituirà un elenco di indirizzi libp2p che sono attualmente peer del client in esecuzione. + +### Stato dei peer {#peer-status} + +Per lo stato di un peer specifico, esegui: +````bash +polygon-edge peers status --peer-id
+```` +Dove il parametro *indirizzo* è l'indirizzo libp2p del peer. + +## Informazioni su IBFT {#ibft-info} + +Molte volte, un operatore potrebbe voler conoscere lo stato del nodo operativo nel consensus IBFT. + +Fortunatamente, Polygon Edge fornisce un modo facile per trovare queste informazioni. + +### Istantanee {#snapshots} + +L'esecuzione del seguente comando restituisce lo snapshot più recente. +````bash +polygon-edge ibft snapshot +```` +Per interrogare lo snapshot a un'altezza specifica (numero di blocco), l'operatore può eseguire: +````bash +polygon-edge ibft snapshot --num +```` + +### Candidati {#candidates} + +Per ottenere le informazioni più recenti sui candidati, l'operatore può eseguire: +````bash +polygon-edge ibft candidates +```` +Questo comando interroga l'attuale set di candidati proposti, nonché i candidati che non sono ancora stati inclusi + +### Stato {#status} + +Il seguente comando restituisce la chiave validatore corrente del client IBFT in esecuzione: +````bash +polygon-edge ibft status +```` + +## Pool di transazioni {#transaction-pool} + +Per trovare il numero corrente di transazioni nel pool di transazioni, l'operatore può eseguire: +````bash +polygon-edge txpool status +```` diff --git a/archive/edge/ja-edge/additional-features/blockscout.md b/archive/edge/ja-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..ace01dc9e0 --- /dev/null +++ b/archive/edge/ja-edge/additional-features/blockscout.md @@ -0,0 +1,408 @@ +--- +id: blockscout +title: Blockscout +description: Polygon Edgeで動作するようにBlockscoutインスタンスを設定する方法。 +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## 概要 {#overview} +このガイドでは、Polygon Edgeで動作するようにBlockscoutインスタンスをコンパイル、デプロイする方法を詳しく説明します。 +Blockscoutには独自の[ドキュメント](https://docs.blockscout.com/for-developers/manual-deployment)がありますが、このガイドではBlockscoutインスタンスを設定する簡単かつ詳細なステップバイステップの手順に焦点を当てています。 + +## 環境 {#environment} +* オペレーティングシステム: Ubuntu Server 20.04 LTS[ダウンロードリンク](https://releases.ubuntu.com/20.04/)とsudo権限 +* サーバーハードウェア: 8CPU / 16GB RAM / 50GB HDD(LVM) +* データベースサーバ:2 CPU / 4GB RAM / 100GB SSD / PostgreSQL 13.4の専用サーバ + +### DBサーバ {#db-server} +このガイドに従うための要件はデータベースサーバーを準備し、データベースとdbユーザーを設定することです。 +ガイドでは、PostgreSQLサーバーのデプロイと設定の方法は詳しく説明しません。 +この方法については現在多数のガイドがあります。たとえば[DigitalOceanガイド](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart)です。 + +:::info 免責事項 + +ガイドはシングルインスタンスでのBlockscoutの起動、実行を支援することだけを目的にしており、これは理想的な実稼働用の設定ではありません。 +実稼働用の運用では、おそらくアーキテクチャにリバースプロキシ、ロードバランサ―、拡張性オプションなどを導入する方が良いでしょう。 +::: + +# Blockscoutデプロイメント手順 {#blockscout-deployment-procedure} + +## パート1 - インストール依存関係 {#part-1-install-dependencies} +始める前に、blockscoutが依存しているすべてのバイナリがインストールされていることを確認する必要があります。 + +### アップデートとアップグレードシステム {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### erlangレポジトリを追加する {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### NodeJSレポジトリを追加する {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### Rustをインストールする {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### Erlangの対応バージョンをインストールする {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### Elixirの対応バージョンをインストールする {#install-required-version-of-elixir} +Elixirのバージョンは`1.13`でなくてはなりません。公式レポジトリからこのバージョンを試し、インストールしようとする場合、 +`erlang`は`Erlang/OTP 25`に更新されますが、それは望ましくありません。 +このため、GitHubのリリースページから特別にプリコンパイルされた`elixir`バージョンをインストールする必要があります。 + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +ここで`exlixir`システムバイナリを適切に設定する必要があります。 +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +`elixir`と`erlang`が適切にインストールされているか`elixir -v`を実行して確認してください。 +下記が出力されるはずです: +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning + +`Erlang/OTP`はバージョン`24`および`Elixir`はバージョン`1.13.*`である必要があります。 +こうなっていない場合、Blockscoutのコンパイルおよび/または実行に問題が生じることになります。 +::: +:::info + +公式の***[Blockscout要件ページ](https://docs.blockscout.com/for-developers/information-and-settings/requirements)***を確認してください + +::: + +### NodeJSをインストールする {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### Cargoをインストールする {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### 他の依存関係をインストールする {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### オプションとしてpostgresqlクライアントをインストールしてdb接続を確認する {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## パート2 - 環境変数を設定する {#part-2-set-environment-variables} +Blockscoutのコンパイルを始める前に環境変数を設定する必要があります。ガイドでは機能するための最小限の基本のみを設定します。設定できる変数の完全なリストは[ここ](https://docs.blockscout.com/for-developers/information-and-settings/env-variables)にあります + +### データベース接続を環境変数として設定する {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +提供されたパラメータでDB接続をテストしましょう。 +PG環境変数を提供したため、実行するだけでデータベースに接続できるはずです: +```bash +psql +``` + +データベースが正しく設定されていれば、psqlプロンプトが表示されます: +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +そうでなければ、次のようにエラーが表示される可能性があります: +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +この場合は[これらのドキュメント](https://ubuntu.com/server/docs/databases-postgresql)が助けになるかもしれません。 + +:::info DB接続 + +db接続の問題をすべて解決してから次の部分に進むことを確認してください。Blockscoutユーザーにスーパーユーザー権限を付与する際に必要になります。 + +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## パート3 - Blockscoutをクローン、コンパイルする {#part-3-clone-and-compile-blockscout} +ここでついにBlockscoutのインストールを開始できるようになりました。 + +### Blockscoutレポジトリをクローンする {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### 運用ビルドを保護するために秘密鍵ベースを生成する {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +最後の行では、ランダムな文字の長い文字列が表示されます。 +これを`SECRET_KEY_BASE`環境変数として設定してから、次のステップへと進みます。 +例: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### 運用モードを設定する {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### コンパイル {#compile} +cdコマンドでクローンディレクトリに移動して、コンパイルを開始する + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info + +以前にデプロイしている場合、***mix phx.digest.clean***で、以前のビルドから静的アセットを削除します。 + +::: + +### データベースを移行する {#migrate-databases} +:::info + +この部分はDB接続を適切に設定していない場合や、DATABASE_URL環境変数でパラメータを提供しなかったまたは誤ったものを定義した場合に失敗します。データベースユーザーはスーパーユーザー権限を有する必要があります。 + +::: +```bash +mix do ecto.create, ecto.migrate +``` + +最初にデータベースをドロップする必要がある場合、実行する +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### npm依存関係をインストールし、フロントエンドアセットをコンパイルする {#install-npm-dependencies-and-compile-frontend-assets} +フロントエンドアセットを含むフォルダへとディレクトリを変更する必要があります。 + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info 辛抱強く + +これらのアセットのコンパイルには数分間かかり、なおかつ出力は表示されません。 +プロセスがスタックしたかのように見えることがありますが、辛抱してください。コンパイルプロセスが完了すると、次のような出力があります:`webpack 5.69.1 compiled with 3 warnings in 104942 ms` + +::: + +### 静的アセットをビルドする {#build-static-assets} +このステップではBlockscoutクローンフォルダのルートに戻る必要があります。 +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### 自己署名証明書を生成する {#generate-self-signed-certificates} +:::info + +`https`を使用しない場合はこのステップを省略することができます。 + +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## パート4 - Blockscoutサービスの作成と実行 {#part-4-create-and-run-blockscout-service} +このパートでは、Blockscoutがバックグラウンドで実行し、システム再起動後に継続するようにシステムサービスを設定する必要があります。 + +### サービスファイルを作成する {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### サービスファイルを編集する {#edit-service-file} +お気に入りのLinuxテキストエディタを使用してこのファイルを編集し、サービスを設定します。 +```bash +sudo vi /etc/systemd/system/explorer.service +``` +explorer.serviceファイルの内容は次のようになるべきです: +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### システムブートでサービス開始を有効化する {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### Blockscoutクローンフォルダをシステム全体の場所に移動する {#move-your-blockscout-clone-folder-to-system-wide-location} +BlockscoutサービスはBlockscoutレポジトリからクローンしたフォルダとコンパイルしたすべてのアセットにアクセスする必要があります。 +```bash +sudo mv ~/blockscout /usr/local +``` + +### Blockscoutサービスで使用される環境変数ファイルを作成する {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info + +パート3で生成した`SECRET_KEY_BASE`を使用します。 + +::: +ファイルを保存し、終了します。 + +### 最後に、Blockscoutサービスをスタートする {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## パート5 - Blockscoutインスタンスの機能をテストする {#part-5-test-out-the-functionality-of-your-blockscout-instance} +ここで、残っているのはBlockscoutサービスが実行されているか確認することです。 +以下でサービスステータスを確認します: +```bash +sudo systemctl status explorer.service +``` + +サービス出力を確認するには: +```bash +sudo journalctl -u explorer.service -f +``` + +新しいリスニングポートがあるか確認することができます: +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +リスニングポートのリストを取得すべきであり、そのリストには次のようなものになるはずです: +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +Blockscout webサービスは環境ファイルで定義されたポートとプロトコルを実行します。この例では `4000`(http)で実行されます。 +すべてがうまくいけば、`http://:4000`でBlockscout webポータルにアクセスできるはずです。 + +## 考慮事項 {#considerations} +最高のパフォーマンスのためには、専門/ローカルの`polygon-edge`フルアーカイブのノンバリデータのノードを持ち、それをBlockscoutクエリ専用に使用することをお勧めします。 +このノードの`json-rpc`APIは公表する必要はありません。Blockscoutがすべてのクエリをバックエンドから実行するためです。 + + +## 最後に {#final-thoughts} +これまでシングルBlockscoutインスタンスをデプロイし、これはうまく動作しますが、運用のためにはこのインスタンスをNginxなどのリバースプロキシの背後に置くことを検討すべきです。また、ユースケースに応じてデータベースやインスタンスの拡張性について考慮する必要があります。 + +多くのカスタマイズオプションがあるため、公式[Blockscoutドキュメント](https://docs.blockscout.com/)は必ずチェックすべきでしょう。 \ No newline at end of file diff --git a/archive/edge/ja-edge/additional-features/chainbridge/definitions.md b/archive/edge/ja-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..230adb35df --- /dev/null +++ b/archive/edge/ja-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,220 @@ +--- +id: definitions +title: 一般定義 +description: chainBridgeで使用する用語の一般定義 +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## リレイヤー {#relayer} +Chainbridgeはリレイヤータイプのブリッジです。リレイヤーの役割は、リクエストの実行(例:バーン/リリースするトークン数)に投票することです。これは、すべてのチェーンのイベントを監視し、チェーンから`Deposit`イベントを受信した際に宛先チェーンのブリッジコントラクトで提案を投票します。リレイヤーは、必要な投票数が送信された後に、提案を実行するためにブリッジコントラクトでメソッドを呼び出します。ブリッジは実行をハンドラーコントラクトに委任します。 + + +## コントラクトの種類 {#types-of-contracts} +ChainBridgeでは、各チェーンに3つのコントラクトタイプ、ブリッジ/ハンドラー/ターゲットがあります。 + +| **タイプ** | **説明** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| ブリッジコントラクト | リクエスト、投票、実行を管理するブリッジコントラクトを各チェーンにデプロイする必要があります。ユーザーは、ブリッジで`deposit`を呼び出し、転送を開始し、ブリッジは、プロセスをターゲットコントラクトに対応するハンドラーコントラクトに委任します。ハンドラーコントラクトがターゲットコントラクトを呼び出すのに成功すると、ブリッジコントラクトはリレイヤーに通知するために`Deposit`イベントを出します。 | +| ハンドラーコントラクト | このコントラクトはターゲットコントラクトとやりとりし、デポジットまたは提案を実行します。これはユーザーのリクエストを検証し、ターゲットコントラクトを呼び出し、ターゲットコントラクトの一部の設定のサポートを行います。さまざまなインターフェースを持つ各ターゲットコントラクトを呼び出すハンドラーコントラクトがあります。ハンドラーコントラクトによる間接的な呼び出しにより、ブリッジは、どのような種類のアセットまたはデータでも転送が可能になります。現在、ChainBridgeによって実装されているハンドラーコントラクトは3種類あります:ERC20Handler、ERC721Handler、GenericHandler。 | +| ターゲットコントラクト | チェーン間で交換されるアセットまたは転送されるメッセージを管理するコントラクト。このコントラクトとのやり取りは、ブリッジの各サイドから行われます。 | + +
+ +![ChainBridgeアーキテクチャ](/img/edge/chainbridge/architecture.svg) +*ChainBridgeアーキテクチャ* + +
+ +
+ +![ERC20トークン転送のワークフロー](/img/edge/chainbridge/erc20-workflow.svg) +*例:ERC20トークン転送のワークフロー* + +
+ +## アカウントの種類 {#types-of-accounts} + +アカウントに、起動前にトランザクションの作成するのに十分なネイティブトークンがあることを確認してください。Polygon Edgeでは、ジェネシスブロックを生成する際に、前払い残高をアカウントに割り当てることができます。 + +| **タイプ** | **説明** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| 管理者 | このアカウントは、管理者の役割をデフォルトで与えられます。 | +| ユーザー | アセットを送信/受信する送信者/受信者アカウント。送信者アカウントは、トークンの転送を承認し、転送を開始するためにブリッジコントラクトでデポジットを呼び出す際にガス代を支払います。 | + +:::info 管理者の役割 + +特定のアクションは、管理者のアカウントでしか実行できません。デフォルトでは、ブリッジコントラクトをデプロイした人に管理者の役割が割り当てられます。管理者の役割を他のアカウントに付与したり削除する方法については下記をご確認ください。 + +### 管理者の役割を追加 {#add-admin-role} + +管理者の追加 + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### 管理者の役割を取り消す {#revoke-admin-role} + +管理者の削除 + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## `admin`アカウントで許可されている操作は、以下の通りです。 {#account-are-as-below} + +### リソースの設定 {#set-resource} + +ハンドラーのコントラクトアドレスでリソースIDを登録します。 + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### コントラクトをバーン/ミント可能にする {#make-contract-burnable-mintable} + +トークンコントラクトをハンドラーでミント/バーン可能に設定します。 + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### 提案のキャンセル {#cancel-proposal} + +実行の提案をキャンセル + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### 一時停止/一時停止解除 {#pause-unpause} + +デポジット、提案の作成、投票、デポジットの実行を一時的に停止します。 + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### 手数料の変更 {#change-fee} + +ブリッジコントラクトに支払われる手数料を変更します + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### リレイヤーの追加/削除 {#add-remove-a-relayer} + +新しいリレイヤーとしてアカウントを追加するか、リレイヤーからアカウントを削除します。 + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### リレイヤーのしきい値を変更する {#change-relayer-threshold} + +提案の実行に必要な投票数を変更する + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## チェーンID {#chain-id} + +Chainbridgeの`chainId`は、ブロックチェーンネットワークを区別するためにブリッジで使用される任意の値であり、それはuint8の範囲でなければなりません。ネットワークのチェーンIDと混同しないでください。それらは同じものではありません。この値は固有である必要がありますが、ネットワークのIDと同じである必要はありません。 + +この例では、MumbaiテストネットのチェーンIDが`80001`であるため、`99`を`chainId`に設定し、それはuint8では表現することはできません。 + +## リソースID {#resource-id} + +リソースIDは、クロスチェーン環境の固有の32バイト値であり、ネットワーク間で転送されている特定のアセット(リソース)に関連付けられています。 + +リソースIDは任意ですが、通常、最後のバイトにはソースチェーン(このアセットが最初に発生したネットワーク)のチェーンIDを含みます。 + +## Polygon PoSのJSON-RPC URL {#json-rpc-url-for-polygon-pos} + +このガイドでは、トラフィックまたはレート制限があるPolygonが提供する公開JSON-RPC URL、https://rpc-mumbai.matic.todayを使用します。これはPolygon Mumbaiテストネットとの接続にのみ使用されます。コントラクトをデプロイすると、JSON-RPCに多くのクエリ/リクエストを送信するため、Infuraなどの外部サービスでJSON-RPC URLを取得することを推奨します。 + +## トークンの転送を処理する方法 {#ways-of-processing-the-transfer-of-tokens} +チェーン間でERC20トークンを転送する際、次の2つの異なるモードで処理することができます: + +### ロック/リリースモード {#lock-release-mode} +ソースチェーン:送信するトークンはハンドラーコントラクトでロックされます。
+送信先チェーン:ソースチェーンで送信されたのと同額のトークンがロック解除され、ハンドラーコントラクトから送信先チェーン内の受信アカウントに転送されます。 + +### バーン/ミントモード {#burn-mint-mode} +ソースチェーン:送信するトークンがバーンされます
。 +送信先チェーン:ソースチェーンで送信およびバーンしたのと同額のトークンが送信先チェーンでミントされ、受信アカウントに送信されます。 + +チェーンごとに異なるモードを使用することができます。つまり、転送のためにサブチェーンでトークンをミントしながらメインチェーンでトークンをロックすることができます。たとえば、総供給量またはミントスケジュールが制御されている場合、トークンをロック/リリースすることは理にかなっています。サブチェーンのコントラクトがメインチェーン内の供給に従う必要がある場合、トークンがミント/バーンされます。 + +デフォルトモードはロック/リリースモードです。トークンをミント/バーン可能にする場合は、`adminSetBurnable`メソッドを呼び出す必要があります。実行時にトークンをミントする場合は、ERC20ハンドラーコントラクトに`minter`の役割を付与する必要があります。 + + diff --git a/archive/edge/ja-edge/additional-features/chainbridge/overview.md b/archive/edge/ja-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..ee3f59c446 --- /dev/null +++ b/archive/edge/ja-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: 概要 +description: ChainBridgeの概要 +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## ChainBridgeとは {#what-is-chainbridge} + +ChainBridgeは、ChainSafeによって構築されたEVMとSubstrateの互換性のあるチェーンをサポートするモジュラー多方向ブロックチェーンブリッジです。これにより、ユーザーは2つの異なるチェーン間であらゆる種類のアセットまたはメッセージを転送することができます。 + +ChainBridgeの詳細については、まず開発者が提供する[公式ドキュメント](https://chainbridge.chainsafe.io/)をご覧ください。 + +このガイドはPolygon EdgeにChainbridgeを統合するサポートになることを意図しています。実行中のPolygon PoS(Mumbaiテストネット)とローカルのPolygon Edgeネットワーク間のブリッジの設定について説明します。 + +## 要件 {#requirements} + +このガイドでは、Polygon Edgeノード、ChainBridgeリレイヤー(詳細については[こちら](/docs/edge/additional-features/chainbridge/definitions))、およびローカルにコントラクトをデプロイし、リソースの登録、ブリッジの設定を変更するためのCLIツールであるcb-sol-cliツールを実行します([こちら](https://chainbridge.chainsafe.io/cli-options/#cli-options)も確認できます)。設定を開始する前に、次の環境が必要です: + +* Go: >= 1.17 +* Node.js >= 16.13.0 +* Git + + +さらに、いくつかのアプリケーションを実行するためにこのバージョンで次のリポジトリをクローンする必要があります。 + +* [Polygon Edge](https://github.com/0xPolygon/polygon-edge):`develop`ブランチ上 +* [ChainBridge](https://github.com/ChainSafe/ChainBridge):v1.1.5 +* [ChainBridgeデプロイツール](https://github.com/ChainSafe/chainbridge-deploy):`main`ブランチ上の`f2aa093` + + +次のセクションに進む前にPolygon Edgeネットワークを設定する必要があります。詳細については、[ローカル設定](/docs/edge/get-started/set-up-ibft-locally)または[クラウド設定](/docs/edge/get-started/set-up-ibft-on-the-cloud)をご覧ください。 \ No newline at end of file diff --git a/archive/edge/ja-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/ja-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..c70291d025 --- /dev/null +++ b/archive/edge/ja-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,142 @@ +--- +id: setup-erc20-transfer +title: ERC20トークン転送 +description: ChainBridgeでERC20の転送を設定する方法 +keywords: + - docs + - polygon + - edge + - Bridge +--- + +ここまでにPolygon PoSとPolygon Edgeチェーン間でアセット/データを取引するブリッジを設定しました。このセクションではERC20ブリッジを設定し、異なるブロックチェーン間でトークンを送信する方法について説明します。 + +## ステップ1:リソースIDを登録する {#step-1-register-resource-id} + +まず、クロスチェーン環境でリソースを関連付けるリソースIDを登録します。リソースIDは、32バイト値で、これらのブロックチェーン間で転送するリソースに固有のものでなければなりません。リソースIDは任意ですが、慣例的に最後のバイトにホームチェーンのチェーンIDを含む可能性があります(これらのリソースが生成された元のネットワークを参照するホームチェーン)。 + +リソースIDを登録するには、`cb-sol-cli bridge register-resource`コマンドを使用することができます。`admin`アカウントの秘密鍵を提供する必要があります。 + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (オプション)コントラクトをミント/バーン可能にする {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## ステップ2:ERC20トークンの転送 {#step-2-transfer-erc20-token} + +Polygon PoSチェーンからPolygon EdgeチェーンにERC20トークンを送信します。 + +まず、ミントすることでトークンを取得します。`minter`の役割を持つアカウントは、新しいトークンをミントすることができます。ERC20コントラクトをデプロイしたアカウントは、デフォルトで`minter`の役割があります。`minter`の役割のメンバーとして他のアカウントを指定するには、`cb-sol-cli erc20 add-minter`コマンドを実行する必要があります。 + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +現在の残高をチェックするには、`cb-sol-cli erc20 balance`コマンドを使用することができます。 + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +次に、ERC20ハンドラーによってアカウントからERC20トークンの転送を承認する必要があります。 + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +Polygon Edgeチェーンにトークンを転送するには、`deposit`を呼び出します。 + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +デポジットトランザクションが成功した後、リレイヤーがイベントを獲得し、提案に投票します。必要な票数が送信された後、Polygon Edgeチェーン内の受信者アカウントにトークンを送信するトランザクションを実行します。 + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +実行トランザクションが成功すると、Polygon Edgeチェーンでトークンが取得されます。 + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/ja-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/ja-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..ae5e32483f --- /dev/null +++ b/archive/edge/ja-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,134 @@ +--- +id: setup-erc721-transfer +title: ERC721NFTの転送 +description: ChainBridgeでERC721の転送を設定する方法 +keywords: + - docs + - polygon + - edge + - Bridge +--- + +このセクションではERC721ブリッジを設定し、ブロックチェーンネットワーク間でNFTを送信する方法について説明します。 + +## ステップ1:リソースIDを登録する {#step-1-register-resource-id} + +まず、双方のチェーン上にあるブリッジコントラクトにERC721トークンのリソースIDを登録する必要があります。 + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (オプション):コントラクトをミント/バーン可能にする {#optional-make-contracts-mintable-burnable} + +トークンをミント/バーン可能にするには、次のコマンドを呼び出す必要があります: + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## ステップ2:NFTを転送する {#step-2-transfer-nft} + +まず、必要に応じてNFTをミントします。 + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +NFTの所有者をチェックするには、`cb-sol-cli erc721 owner`を使用してください。 + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +次に、ERC721ハンドラーによってNFTの転送を承認します。 + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +最後に、転送を開始します。 + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +リレイヤーはイベントを取得し、提案に投票します。必要な票数が送信された後、Polygon Edgeチェーン内の受信者アカウントにNFTを送信するトランザクションを実行します。 + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +実行が完了した後、Polygon EdgeネットワークでNFTの所有者をチェックすることができます。 + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/ja-edge/additional-features/chainbridge/setup.md b/archive/edge/ja-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..8b8b30164c --- /dev/null +++ b/archive/edge/ja-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,198 @@ +--- +id: setup +title: 設定 +description: ChainBridgeの設定方法 +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## コントラクトのデプロイメント {#contracts-deployment} + +このセクションでは、Polygon PoSとPolygon Edgeチェーンに`cb-sol-cli`で必要なコントラクトをデプロイします。 + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +まず、Polygon PoSチェーンに`cb-sol-cli deploy`コマンドでコントラクトをデプロイします。`--all`フラグによりコマンドがブリッジ、ERC20ハンドラー、ERC721ハンドラー、ジェネリックハンドラー、ERC20、ERC721コントラクトを含むすべてのコントラクトをデプロイします。さらに、これはデフォルトのリレイヤーアカウントアドレスとそのしきい値を設定します + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +チェーンIDとJSON-RPC URLについて[ここ](/docs/edge/additional-features/chainbridge/definitions)で学びましょう + +:::caution + +`cb-sol-cli`のデフォルトのガス価格は`20000000`(`0.02 Gwei`)です。トランザクションの適切なガス価格を設定するには、`--gasPrice`引数を使用して値を設定してください。 + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +ブリッジコントラクトのデプロイには約0x3f97b8(4167608)ガスかかります。生成しているブロックがコントラクト作成トランザクションを含むために十分なブロックガス制限を持つことを確認してください。Polygon Edgeのブロックガス制限の変更について詳細を学ぶには、 +[ローカル設定](/docs/edge/get-started/set-up-ibft-locally)を参照してください。 + +::: + +いったんコントラクトがデプロイされると、次の結果が得られます: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +これでコントラクトをPolygon Edgeチェーンにデプロイすることができます。 + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +デプロイされたスマートコントラクトアドレスを持つターミナル出力を保存しましょう、次のステップで必要になります。 + +## リレイヤー設定 {#relayer-setup} + +このセクションでは、2つのチェーン間のデータ交換のためにリレイヤーをスタートします。 + +まず、ChainBridgeレポジトリをクローン、ビルドする必要があります。 + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +次に、`config.json`を作成して、チェーンごとにJSON-RPC URL、リレイヤーアドレス、コントラクトアドレスを設定する必要があります。 + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +リレイヤーをスタートするには、リレイヤーアカウントアドレスに対応する秘密鍵をインポートする必要があります。秘密鍵をインポートする際にパスワードを入力する必要があります。インポートが成功すると、鍵は`keys/
.key`の下に保存されます。 + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +その後、リレイヤーをスタートすることができます。最初に鍵を保存するために選択したのと同じパスワードを入力する必要があります。 + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +リレイヤーはいったん開始されると各チェーン上の新しいブロックの監視をスタートします。 diff --git a/archive/edge/ja-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/ja-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..603678fa84 --- /dev/null +++ b/archive/edge/ja-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,255 @@ +--- +id: use-case-erc20-bridge +title: ユースケース - ERC20ブリッジ +description: ERC20コントラクトブリッジの例 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +このセクションでは実用的なユースケース用のERC20ブリッジの設定フローを提供することを目的としています。 + +このガイドでは、Mumbai Polygon PoSテストネットとPolygon Edgeローカルチェーンを使用します。Mumbai用にJSON-RPCエンドポイントがあり、ローカル環境にPolygon Edgeを設定していることを確認してください。詳細は[ローカル設定](/docs/edge/get-started/set-up-ibft-locally)または[クラウド設定](/docs/edge/get-started/set-up-ibft-on-the-cloud)を参照してください。 + +## シナリオ {#scenario} + +このシナリオは、通常のケースにおいてユーザーにプライベートチェーン(Polygon Edge)内での低コストの転送を可能にするためにすでにパブリックチェーン(Polygon PoS)にデプロイされたERC20トークン用のブリッジを設定するものです。こうした場合、トークンの総供給はパブリックチェーンで定義されており、パブリックチェーンからプライベートチェーンに転送されたトークンの額だけがプライベートチェーンに存在する必要があります。そのため、パブリックチェーンのロック/リリースモードとプライベートチェーンのバーン/ミントモードを使用する必要があります。 + +パブリックチェーンからプライベートチェーンにトークンを送信する時、トークンはパブリックチェーンのERC20ハンドラーコントラクトにロックされ、同じ額のトークンがプライベートチェーンにミントされます。一方、プライベートチェーンからパブリックチェーンに転送する場合、プライベートチェーンのトークンがバーンされ、パブリックチェーンのERC20ハンドラーコントラクトから同じ額のトークンがリリースされます。 + +## コントラクト {#contracts} + +ChainBridgeが開発したコントラクトではなく簡単なERC20コントラクトで説明します。バーン/ミントモードでは、ERC20コントラクトは次のようなERC20のメソッドに加え、`mint`および`burnFrom`メソッドを持っている必要があります: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +すべてのコードとスクリプトはGithubレポジトリ[Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example)にあります。 + +## ステップ1:ブリッジおよびERC20ハンドラーコントラクトをデプロイする {#step1-deploy-bridge-and-erc20-handler-contracts} + +まず、両方のチェーンで`cb-sol-cli`を使用してブリッジとERC20ハンドラーコントラクトをデプロイします。 + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +ブリッジとERC20ハンドラーコントラクトアドレスは次のようになります: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## ステップ2:ERC20コントラクトをデプロイする {#step2-deploy-your-erc20-contract} + +ERC20コントラクトをデプロイします。この例ではハードハットプロジェクト[Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example)で説明します。 + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +`.env`ファイルを作成し、次の値を設定してください。 + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +次に、両方のチェーンにERC20コントラクトをデプロイします。 + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +デプロイに成功すると、次のようなコントラクトアドレスが得られます: + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## ステップ3:ブリッジにリソースIDを登録する {#step3-register-resource-id-in-bridge} + +クロスチェーン環境でリソースを関連付けるリソースIDを登録します。両方のチェーンに同じリソースIDを設定する必要があります。 + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## ステップ4:EdgeのERC20ブリッジでミント/バーンモードを設定する {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +ブリッジはPolygon Edgeでバーン/ミントモードとして動作することを予定しています。バーン/ミントモードは`cb-sol-cli`を使用して設定します。 + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +そしてERC20ハンドラーコントラクトにミンターとバーナーの役割を付与する必要があります。 + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## ステップ5:トークンをミントする {#step5-mint-token} + +Mumbaiチェーンに新しいERC20トークンをミントします。 + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +トランザクションが成功した後、アカウントはミントされたトークンを持つようになります。 + +## ステップ6:ERC20転送のスタート {#step6-start-erc20-transfer} + +このステップを始める前に、リレイヤーを起動したことを確認してください。詳細については[設定](/docs/edge/additional-features/chainbridge/setup)を確認してください。 + +MumbaiからEdgeへとトークンを転送する際に、MumbaiのERC20ハンドラーコントラクトはアカウントからトークンを引き出します。転送する前に承認を呼び出します。 + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +最後に、MumbaiからEdgeへのトークン転送を`cb-sol-cli`を使用して開始します。 + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +デポジットトランザクションが成功した後、リレイヤーはイベントを取得し、提案に投票します。必要な票数が送信された後、Polygon Edgeチェーン内の受信者アカウントにトークンを送信するトランザクションを実行します。 + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +実行トランザクションが成功すると、Polygon Edgeチェーンでトークンが取得されます。 diff --git a/archive/edge/ja-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/ja-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..f059ed11aa --- /dev/null +++ b/archive/edge/ja-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,308 @@ +--- +id: use-case-erc721-bridge +title: ユースケース - ERC721ブリッジ +description: ERC721コントラクトブリッジの例 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +このセクションでは実用的なユースケース用のERC721ブリッジの設定フローを提供することを目的としています。 + +このガイドでは、Mumbai Polygon PoSテストネットとPolygon Edgeローカルチェーンを使用します。Mumbai用にJSON-RPCエンドポイントがあり、ローカル環境にPolygon Edgeを設定していることを確認してください。詳細は[ローカル設定](/docs/edge/get-started/set-up-ibft-locally)または[クラウド設定](/docs/edge/get-started/set-up-ibft-on-the-cloud)を参照してください。 + +## シナリオ {#scenario} + +このシナリオでは、通常のケースでユーザに対してプライベートチェーン(Polygon Edge)での低コスト転送を可能にするために、パブリックチェーン(Polygon PoS)にすでにデプロイされているERC721NFT用のブリッジを設定します。このような場合、元のメタデータはパブリックチェーンに定義され、パブリックチェーンから転送されたNFTだけがプライベートチェーンに存在することができます。そのため、パブリックチェーンではロック/リリースモード、プライベートチェーンではバーン/ミントモードを使用する必要があります。 + +パブリックチェーンからプライベートチェーンにNFTを送信する場合、NFTはパブリックチェーンのERC721ハンドラーコントラクトにロックされ、同じNFTがプライベートチェーンにミントされます。一方、プライベートチェーンからパブリックチェーンに転送する場合、プライベートチェーンのNFTがバーンされ、パブリックチェーンのERC721ハンドラーコントラクトから同じNFTがリリースされます。 + +## コントラクト {#contracts} + +ChainBridgeが開発したコントラクトではなく、簡単なERC721コントラクトで説明します。バーン/ミントモードの場合、ERC721コントラクトには、次のようにERC721に定義されている方法に加えて、`mint`と`burn`メソッドが必要です: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +すべてのコードとスクリプトはGithubレポジトリ[Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example)にあります。 + +## ステップ1:ブリッジおよびERC721ハンドラーコントラクトをデプロイする {#step1-deploy-bridge-and-erc721-handler-contracts} + +最初に、両方のチェーンで`cb-sol-cli`を使用して、ブリッジとERC721ハンドラーコントラクトをデプロイします。 + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +ブリッジとERC721ハンドラーコントラクトアドレスは次のようになります: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## ステップ2:ERC721コントラクトをデプロイする {#step2-deploy-your-erc721-contract} + +ERC721コントラクトをデプロイします。この例では、ハードハットプロジェクト[Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example)を使用して説明します。 + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +`.env`ファイルを作成し、以下の値を設定してください。 + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +次に、両方のチェーンにERC721コントラクトをデプロイします。 + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +デプロイに成功すると、次のようなコントラクトアドレスが得られます: + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## ステップ3:ブリッジでリソースIDを登録する {#step3-register-resource-id-in-bridge} + +クロスチェーン環境でリソースを関連付けるリソースIDを登録します。 + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## ステップ4:EdgeのERC721ブリッジでミント/バーンモードを設定する {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +ブリッジはEdgeでバーン/ミントモードとして動作することを想定しています。バーン/ミントモードを設定します。 + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +また、ERC721ハンドラーコントラクトにミンターとバーナーの役割を付与する必要があります。 + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## ステップ5:NFTをミントする {#step5-mint-nft} + +Mumbaiチェーンに新しいERC721 NFTをミントします。 + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +トランザクションが成功すると、そのアカウントはミントされたNFTを持ちます。 + +## ステップ6:ERC721転送をスタートする {#step6-start-erc721-transfer} + +このステップの開始前に、リレイヤーを開始したことを確認してください。詳細については、[セットアップ](/docs/edge/additional-features/chainbridge/setup)を確認してください。 + +MumbaiからEdgeへのNFT転送中に、MumbaiのERC721ハンドラーコントラクトがアカウントからNFTを引き出します。転送する前に承認を呼び出します。 + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +最後にMumbaiからEdgeへのNFT転送をスタートします。 + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +デポジットトランザクションが成功した後、リレイヤーがイベントを獲得し、提案に投票します。 +必要な数の投票が送信された後、Polygon Edgeチェーンの受信者アカウントにNFTを送信するトランザクションを実行します。 + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +実行トランザクションが成功すると、Polygon EdgeチェーンにNFTが取得されます。 diff --git a/archive/edge/ja-edge/additional-features/permission-contract-deployment.md b/archive/edge/ja-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..db99defec2 --- /dev/null +++ b/archive/edge/ja-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,85 @@ +--- +id: permission-contract-deployment +title: スマートコントラクトデプロイメント許可 +description: スマートコントラクトデプロイメント許可を追加する方法。 +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## 概要 {#overview} + +このガイドでは、スマートコントラクトをデプロイできるアドレスをホワイトリストにする方法について詳しく説明します。ネットワークオペレータは、ユーザがネットワークの目的と無関係なスマートコントラクトをデプロイしないようにしたい場合があります。ネットワークオペレータは次のことが可能です: + +1. スマートコントラクトデプロイメント用のアドレスをホワイトリストする +2. スマートコントラクトデプロイメントのためのホワイトリストからアドレスを削除する + +## ビデオプレゼンテーション {#video-presentation} + +[![許可契約の展開 - ビデオ](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## 使用方法 {#how-to-use-it} + + +デプロイメントホワイトリストに関連するすべてのCLIコマンドは、[CLIコマンド](/docs/edge/get-started/cli-commands#whitelist-commands)ページにあります。 + +* `whitelist show`: ホワイトリスト情報を表示する +* `whitelist deployment --add`: コントラクトデプロイメントホワイトリストに新しいアドレスを追加する +* `whitelist deployment --remove`:コントラクトデプロイメントホワイトリストから新しいアドレスを削除する + +#### デプロイメントホワイトリストのすべてのアドレスを表示する {#show-all-addresses-in-the-deployment-whitelist} + +デプロイメントホワイトリストでアドレスを検索するには、2つの方法があります。 +1. ホワイトリストが保存されている`genesis.json`を確認します +2. ますPolygon Edgeでサポートされているすべてのホワイトリストの情報を出力する`whitelist show`を実行します + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### デプロイメントホワイトリストにアドレスを追加する {#add-an-address-to-the-deployment-whitelist} + +デプロイメントホワイトリストに新しいアドレスを追加するには、`whitelist deployment --add [ADDRESS]`CLIコマンドを実行します。ホワイトリストに存在するアドレスの数に制限はありません。コントラクトデプロイメントホワイトリストに存在するアドレスだけがコントラクトをデプロイできます。ホワイトリストが空の場合、すべてのアドレスがデプロイメントを実行できます + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### デプロイメントホワイトリストからアドレスを削除する {#remove-an-address-from-the-deployment-whitelist} + +デプロイメントホワイトリストからアドレスを削除するには、`whitelist deployment --remove [ADDRESS]`CLIコマンドを実行します。コントラクトデプロイメントホワイトリストに存在するアドレスだけがコントラクトをデプロイできます。ホワイトリストが空の場合、すべてのアドレスがデプロイメントを実行できます + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/ja-edge/architecture/modules/blockchain.md b/archive/edge/ja-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..8ea22a0215 --- /dev/null +++ b/archive/edge/ja-edge/architecture/modules/blockchain.md @@ -0,0 +1,159 @@ +--- +id: blockchain +title: ブロックチェーン +description: ブロックチェーンとPolygon Edgeのステートモジュールに関する説明。 +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## 概要 {#overview} + +Polygon Edgeのメインモジュールの1つは**ブロックチェーン**と**ステート**です。
+ +**ブロックチェーン**はブロック再編に対応する原動力です。つまり新しいブロックがブロックチェーンに含まれる時に発生するすべてのロジックを扱うことを意味します。 + +**ステート**は*ステート移行*オブジェクトを表します。新しいブロックが含まれる時にステートがどのように変化するかを扱います。
他のことと共に、**ステート**が扱うのは: +* トランザクションの実行 +* EVMの実行 +* Merkleトライの変更 +* 他にも多数ありますが、これは次の**ステート**セクションでカバーされています 🙂 + +主な要点は、これら2つの部分にかなり関連しており、クライアントが機能するために緊密に連携するということです。
たとえば、**ブロックチェーン**レイヤーが新しいブロックを受信する(そして再編成が発生していない)場合、**ステート**を呼び出してステート移行を行います。 + +**ブロックチェーン**はまた、コンセンサス(例、*このethHashは正しいか?*、*このPoWは正しいか?*)関連の部分を扱う必要があります。
1文にまとめると、**これはすべてのブロックが含まれるロジックのメインコアです**。 + +## *WriteBlocks* + +**ブロックチェーン**レイヤーに関連する最も重要な部分の1つは *WriteBlocks*メソッドです: + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +*WriteBlocks*メソッドはブロックをブロックチェーンに書き込むエントリーポイントです。パラメータとして、これはブロックの範囲を含めます。
+まず、ブロックは検証されます。その後、これはチェーンに書き込まれます。 + +実際の*ステートの移行*は*processBlock*メソッドを*WriteBlock*内で呼び出すことで実行されます。 + +ここで触れるべきことは、これがブロックチェーンにブロックを記述する際のエントリーポイントになるために、他のモジュール(**シーラー**など)がこのメソッドを使用することです。 + +## ブロックチェーンのサブスクリプション {#blockchain-subscriptions} + +ブロックチェーン関連の変更を監視する方法が必要となります。
+これが**サブスクリプション**が必要になるところです。 + +サブスクリプションはブロックチェーンのイベントストリームをタップし、即座に有意義なデータを受け取る方法です。 + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +**ブロックチェーンイベント**は実際のチェーンへの変更に関する情報を含んでいます。これには再編成や新しいブロックが含まれます: + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip 気分を変えて + +***モニター***コマンドについて[CLIコマンド](/docs/edge/get-started/cli-commands)で述べた時を覚えていますか? + +ブロックチェーンイベントはPolygon Edgeで起こる独自のイベントであり、その後は転送を簡単にするためにプロトコルバッファーメッセージ形式にマッピングされたものです。 +::: \ No newline at end of file diff --git a/archive/edge/ja-edge/architecture/modules/consensus.md b/archive/edge/ja-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..9792658242 --- /dev/null +++ b/archive/edge/ja-edge/architecture/modules/consensus.md @@ -0,0 +1,500 @@ +--- +id: consensus +title: コンセンサス +description: Polygon Edgeのコンセンサスモジュールに関する説明。 +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## 概要 {#overview} + +**コンセンサス**モジュールはコンセンサスメカニズムのためのインターフェースを提供します。 + +現在、以下のコンセンサスエンジンが利用できます: +* **IBFT PoA** +* **IBFT PoS** + +Polygon Edgeはモジュール性とプラグビリティの状態を維持したいと考えています。
+これがコンセンサスロジックが抽象化された理由であり、利便性や使いやすさを犠牲にせずに新しいコンセンサスメカニズムを構築できるようになりました。 + +## コンセンサスインターフェース {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + + ***コンセンサス***インターフェースは前述の抽象化の中心です。
+* **VerifyHeader**メソッドはコンセンサスレイヤーが**ブロックチェーン**レイヤーに露出するヘルパー機能を表します。そこでヘッダー検証を処理します。 +* **スタート**メソッドは単純にコンセンサスプロセスとそれに伴うすべてのものをスタートさせます。これには同期化、シーリング、必要なすべてのものを含みます。 +* **クローズ**メソッドはコンセンサス接続を閉じます + +## コンセンサス設定 {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +コンセンサスプロトコルがデータを格納するためのカスタムの場所や、またはコンセンサスメカニズムにおいて使用するカスタムのキーバリューマップを渡したい時もあります。これは ***設定***ストラクチャを通じて、このストラクチャが新しいコンセンサスインスタンスが作成される時読み取られることで達成することができます。 + +## IBFT {#ibft} + +### ExtraData {#extradata} + +ブロックチェーンヘッダオブジェクトは、他のフィールドとともに**ExtraData**と呼ばれるフィールドを持っています。 + +IBFTはこの追加のフィールドを使用してブロックに関する操作情報を保存し、次のような質問に答えます: +* 「誰がこのブロックに署名したのか?」 +* 「このブロックのバリデータは誰か?」 + +これらのIBFT用の追加フィールドは次のように定義されます: +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### 署名データ {#signing-data} + +ノードがIBFTで情報に署名するためには、*signHash*メソッドを活用します: +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +もう1つの注目されるメソッドは*VerifyCommittedFields*メソッドで、これはコミットされたシールが有効なバリデータからのものであることを検証します: +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### スナップショット {#snapshots} + +スナップショットは名前が示すように、あらゆるブロックの高さ(数字)での*スナップショット*、またはシステムの*状態*を提供するためにそこにあります。 + +スナップショットにはバリデータであるノードのセットや投票情報(バリデータは他のバリデータに投票できる)が含まれています。バリデータには**Miner**ヘッダにファイルされた投票情報が含まれ、**ノンス**の値を変更します: +* ノードがバリデータを削除したい場合は、ノンスはすべて**1**です +* ノードがバリデータを追加したい場合は、ノンスはすべて**0**です + +スナップショットは***processHeaders***メソッドを使用して計算されます: + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +このメソッドは通常は1ヘッダで呼び出されますが、複数のヘッダでもフローは同じです。
+各渡されたヘッダについて、IBFTはヘッダの提案者がバリデータであることを検証する必要があります。これは簡単にできるもので +最新のスナップショットを取得し、ノードがバリデータセットにいるかチェックします。 + +次にノンスがチェックされます。投票は含まれ、集計されます - そして十分な票がある場合はノードがバリデータセットから追加/削除され、その後新しいスナップショットが保存されます。 + +#### スナップショットストア {#snapshot-store} + +スナップショットサービスは**snapshotStore**というエンティティを管理、更新します。これは使用可能なすべてのスナップショットのリストを格納します。それを使用すると、サービスはどのスナップショットがどのブロックの高さと関連付けられているかをすみやかに把握できます。 +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### IBFTスタートアップ {#ibft-startup} + +IBFTをスタートアップするためには、Polygon Edgeは最初にIBFTトランスポートを設定する必要があります。 +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +これは実質的に新しいトピックをIBFTプロトと新しいプロトバフメッセージで作成します。
+メッセージはバリデータに使用されることを意図しています。Polygon Edgeはその後トピックにサブスクライブし、それに応じてメッセージを処理します。 + +#### MessageReq {#messagereq} + +バリデータによって交換されるメッセージ: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +**MessageReq**の**View**フィールドは、チェーン内の現在のノードの位置を表します。 +これは*ラウンド*と*シーケンス*の属性を持っています。 +* **ラウンド**は高さのプロポーザラウンドを表します +* **シーケンス**はブロックチェーンの高さを表します + +IBFT実装にファイルされた*msgQueue*にはメッセージ要求を格納する目的があります。メッセージへの命令は +*View*(最初にシーケンス、次にラウンド)により行われます。IBFT実装はシステム内の異なるステートに異なるキューを保有しています。 + +### IBFTステート {#ibft-states} + +コンセンサスメカニズムが**Start**メソッドを使用して開始した後は、ステートマシンをシミュレートする無限ループへと実行します: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### SyncState {#syncstate} + +すべてのノードは**Sync**状態でスタートします。 + +これはブロックチェーンから新しいデータを取得する必要があるためです。クライアントはそれがバリデータであるかどうかを調べ、現在のスナップショットを見つけるる必要があります。このステートはあらゆる保留中のブロックを解決します。 + +同期が終了し、クライアントが実際にバリデータであると判断した後、これを**AcceptState**に転送する必要があります。クライアントがバリデータで**ない**場合、同期を続けて、**SyncState**に留まります。 + +#### AcceptState {#acceptstate} + +**Accept**ステートは常にスナップショットとバリデータセットをチェックします。現在のノードがバリデータセットにない場合は、**Sync**ステートに戻ります。 + +一方、ノードがバリデータで**ある**場合は、プロポーザーを計算します。現在のノードがプロポーザーであると判明した場合は、ブロックを構築し、プリプリペアメッセージを送信し、その後プリペアメッセージを送信します。 + +* プリプリペアメッセージ - プロポーザーがバリデータに送信し、提案について知らせるメッセージ +* プリペアメッセージ - バリデータが提案に同意するメッセージすべてのノードがすべてのプリペアメッセージを受信します。 +* コミットメッセージ - 提案のコミット情報を含むメッセージ + +現在のノードがバリデータで**ない**場合、*getNextMessage*メソッドを使用して以前に表示されたキューからメッセージを読み取ります。
+プリプリペアメッセージを待っています。すべてが正しいことを確認すると、ノードは**Validate**ステートに移動します。 + +#### ValidateState {#validatestate} + +**Validate**ステートはかなりシンプルです - このステートでノードがすべきことはメッセージを読み、これをローカルなスナップショットステートに追加することです。 diff --git a/archive/edge/ja-edge/architecture/modules/json-rpc.md b/archive/edge/ja-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..2cb5114c59 --- /dev/null +++ b/archive/edge/ja-edge/architecture/modules/json-rpc.md @@ -0,0 +1,176 @@ +--- +id: json-rpc +title: JSON RPC +description: Polygon EdgeのJSON RPCモジュールについて説明します。 +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## 概要 {#overview} + +**JSON RPC**モジュールは**JSON RPC APIレイヤー**を実行しますが、これはdApp開発者がブロックチェーンとやり取りするために使用します。 + +これには標準の**[json-rpcエンドポイント](https://eth.wiki/json-rpc/API)**とwebsocketのエンドポイントが含まれます。 + +## ブロックチェーンインターフェース {#blockchain-interface} + +Polygon Edgeは***ブロックチェーンインターフェース***を使用してJSON RPCモジュールが使用するのに必要なすべてのメソッドを定義することで、そのエンドポイントを提供します。 + +ブロックチェーンインターフェースは**[Minimal](/docs/edge/architecture/modules/minimal)**サーバーによって実装されます。これは基本の実装でありJSON RPCレイヤーに伝送されます。 + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## ETHエンドポイント {#eth-endpoints} + +すべての標準JSON RPCエンドポイントは次に実装されます: + +````bash +jsonrpc/eth_endpoint.go +```` + +## フィルタマネージャ {#filter-manager} + +**フィルタマネージャ**はJSON RPCサーバーと並行して実行されるサービスです。 + +ブロックチェーン上にブロックをフィルタリングするサポートを提供します。
+具体的には、**ログ**と**ブロック**レベルフィルタの両方が含まれます。 + +フィルタマネージャはサブスクリプションイベントに大きく依存しており、これは[ブロックチェーン](blockchain#blockchain-subscriptions)セクションで述べられています。 + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +フィルタマネージャイベントは*実行*メソッドで発生します: + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## 📜 リソース {#resources} +* **[Ethereum JSON-RPC](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/ja-edge/architecture/modules/minimal.md b/archive/edge/ja-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..588796f171 --- /dev/null +++ b/archive/edge/ja-edge/architecture/modules/minimal.md @@ -0,0 +1,119 @@ +--- +id: minimal +title: Minimal(最小) +description: Polygon EdgeのMinimalモジュールについて説明します。 +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## 概要 {#overview} + +前述したようにPolygon Edgeは、相互に接続されている異なるモジュールの集まりです。
+**ブロックチェーン**は、**ステート**、または、例えば、新しいブロックを**ブロックチェーン**につなげる**同期**に接続されます。 + +**Minimal**はこれらの相互接続されたモジュールの基盤です。
+Polygon Edgeで実行するすべてのサービスの中心的なハブとして機能します。 + +## スタートアップマジック {#startup-magic} + +Minimalは、特に次のことに責任を負います: +* データディレクトリを設定する +* libp2p通信のためのキーストアを作成する +* ストレージを作成する +* コンセンサスを設定する +* GRPC、JSON RPC、および同期でブロックチェーンオブジェクトを設定する + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/ja-edge/architecture/modules/networking.md b/archive/edge/ja-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..3371c0efbf --- /dev/null +++ b/archive/edge/ja-edge/architecture/modules/networking.md @@ -0,0 +1,80 @@ +--- +id: networking +title: ネットワーク +description: Polygon Edgeのネットワークモジュールについて説明します。 +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## 概要 {#overview} + +ノードは、役立つ情報を取引するために、ネットワーク上の他のノードと通信する必要があります。
+このタスクを達成するために、Polygon Edgeは実際のテストを経た**libp2p**フレームワークを活用します。 + +**libp2p**を使用するという選択は、主に次の点に焦点を当てています: +* **スピード** - libp2pでは、(GETHおよび他のクライアントで使用されている)devp2pを超える大幅なパフォーマンス改善が行われています +* **拡張性** - システムの他の機能にとって素晴らしい基盤となります +* **モジュール性** - libp2pはPolygon Edgeと同様、本質的にモジュール式です。これにより、特にPolygon Edgeの一部をスワップ可能にする必要がある場合、より高い柔軟性を提供します。 + +## GRPC {#grpc} + +**libp2p**に加えて、Polygon Edgeは**GRPC**プロトコルを使用します。
+技術的に、Polygon Edgeは、いくつかのGRPCプロトコルを使用します。後ほど説明します。 + +GRPCレイヤーは、すべてのリクエスト/返信プロトコルを抽象化し、Polygon Edgeが機能するために必要なストリーミングプロトコルを簡素化します。 + +GRPCは、**プロトコルバッファ**を使用して*サービス*及び*メッセージ構成*を定義します。
+このサービスと構成は、*.proto*ファイルで定義され、それはコンパイルされ、言語に依存していません。 + +先ほどは、Polygon EdgeがいくつかのGRPCプロトコルを活用していることを述べました。
+これは、ノードオペレータの全体的なUXを高めるために実行され、GETHやParityなどのクライアントとラグが頻繁に発生します。 + +ノードオペレータは、探している情報を見つけるためにログを精査する代わりに、GRPCサービスを呼び出すことで、システムで何が起こっているのかをより良く把握します。 + +### ノードオペレータのためのGRPC {#grpc-for-node-operators} + +次のセクションは、[CLIコマンド](/docs/edge/get-started/cli-commands)セクションで簡潔に説明された内容であるため、馴染みがあるかもしれません。 + +**ノードオペレータ**が使用するためのGRPCサービスは、次のように定義されます: +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip + +CLIコマンドはこれらのサービスメソッドの実行を実際に呼び出します。 + +これらのメソッドは***minimal/system_service.go***で実行されます。 + +::: + +### 他のノードのためのGRPC {#grpc-for-other-nodes} + +Polygon Edgeは、ネットワーク上の他のノードで使用されるいくつかのサービスメソッドも実行します。
+言及したサービスは**[プロトコル](docs/edge/architecture/modules/consensus)**セクションで説明されています。 + +## 📜リソース {#resources} +* **[プロトコルバッファ](https://developers.google.com/protocol-buffers)** +* **[libp2p](https://libp2p.io/)** +* **[GRPC](https://grpc.io/)** diff --git a/archive/edge/ja-edge/architecture/modules/other-modules.md b/archive/edge/ja-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..93e8f853d5 --- /dev/null +++ b/archive/edge/ja-edge/architecture/modules/other-modules.md @@ -0,0 +1,36 @@ +--- +id: other-modules +title: 他のモジュール +description: Polygon Edgeのモジュールについて説明します。 +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## 暗号 {#crypto} + +**暗号**モジュールには、暗号のユーティリティ機能が含まれています。 + +## チェーン {#chain} + +**チェーン**モジュールには、チェーンパラメータ(アクティブフォーク、コンセンサスエンジンなど)が含まれています。 + +* **チェーン** - 事前定義されたチェーン設定(メインネット、goerli、ibft) + +## ヘルパー {#helper} + +**ヘルパー**モジュールにはヘルパーパッケージが含まれています。 + +* **dao** - Daoのユーティリティ +* **enode** - eノードエンコード/デコード機能 +* **hex** - 16進数のエンコード/デコード機能 +* **ipc** - IPC接続機能 +* **keccak** - Keccak機能 +* **rlputil** - Rlpのエンコード/デコードヘルパー機能 + +## コマンド {#command} + +**コマンド**モジュールには、CLIコマンドのインターフェースが含まれています。 \ No newline at end of file diff --git a/archive/edge/ja-edge/architecture/modules/sealer.md b/archive/edge/ja-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..a497ad0add --- /dev/null +++ b/archive/edge/ja-edge/architecture/modules/sealer.md @@ -0,0 +1,72 @@ +--- +id: sealer +title: シーラー +description: Polygon Edgeのシーラーモジュールの説明です。 +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## 概要 {#overview} + +**シーラー**はトランザクションを収集し、新しいブロックを作成するエンティティです。
+その後、そのブロックは**コンセンサス**モジュールに送信され、封印されます。 + +最終的なシーリングロジックは**コンセンサス**モジュール内に配置されます。 + +## 実行メソッド {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution 進行中の作業 + +**シーラー**と**コンセンサス**モジュールは近い将来シングルエンティティに統合されます。 + +新しいモジュールは、異なる種類のコンセンサスメカニズムのモジュラーロジックを組み込みますが、これは異なるシーリング実装を必要とします: +* **PoS**(ステーク・オブ・ステーク) +* **PoA**(プルーフ・オブ・オーソリティ) + +現在、**シーラー**と**コンセンサス**モジュールはPoW(プルーフ・オブ・ワーク)と連携しています。 +::: \ No newline at end of file diff --git a/archive/edge/ja-edge/architecture/modules/state.md b/archive/edge/ja-edge/architecture/modules/state.md new file mode 100644 index 0000000000..d06f6ff262 --- /dev/null +++ b/archive/edge/ja-edge/architecture/modules/state.md @@ -0,0 +1,242 @@ +--- +id: state +title: ステート +description: Polygon Edgeのステートモジュールについて説明します。 +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +**ステート**がどのように機能するかを理解するには、Ethereumの基本的な概念を理解する必要があります。
+ +**[Ethereumガイドのステート](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)**を読まれることを強く推奨します。 + +## 概要 {#overview} + +Ethereumの基本的な概念を理解した今、次の概要は簡単に理解することができるかと思います。 + +**ワールドステートトライ**は、存在するEthereumアカウントすべてを持つということを説明しました。
+これらのアカウントは、Merkleトライの残りの部分です。それぞれがエンコードされた**アカウントステート**情報を持っています。 + +これにより、Polygon Edgeは、特定のタイミングの特定のMerkleトライを取得することができます。
+たとえば、ブロック10でのステートのハッシュを取得することができます。 + +Merkleトライは、どの時点でも***スナップショット***と呼ばれています。 + +**ステートトライ**、または**ストレージトライ**について、***スナップショット***をもつことができます - これらは基本的に同じです。
唯一の違いは、残りが表すものです: + +* ストレージトライの場合、残りの部分は任意のステートを含み、そこにあるものを処理または知ることはできません。 +* ステートトライの場合、残りの部分はアカウントを表します + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + +**スナップショット**インターフェースは、次のように定義されています: + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +コミットできる情報は*オブジェクト構造体*によって定義されます: + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +
Merkleトライの実装は*state/immutable-trie*フォルダにあります。*state/immutable-trie/state.go*は**ステート**インターフェースを実装します。 + +*state/immutable-trie/trie.go*はメインのmerkleトライオブジェクトです。Merkleトライの最適化バージョンを表しできるだけ多くのメモリを再利用します。 + +## Executor {#executor} + +*state/executor.go*はPolygon Edgeがブロックが現在の状態をどのように変更するかを決定するのに必要な情報をすべてふくみあ含みます。*ProcessBlock*の実装はこちらにあります。 + +*適用*メソッドは実際の状態遷移を行います。ExecutorはEVMを呼び出します。 + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## ランタイム {#runtime} + +状態の遷移が実行されると、状態の遷移を実行するメインモジュールはEVMになります(state/runtime/evmに配置)。 + +**ディスパッチテーブル**は**オペコード**と命令間で一致します。 + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +EVMに電力を供給するコアロジックは*実行*ループです。
+ +これは、EVMのメインエントリポイントです。ループを行い、現在のオペコードをチェックし、命令を取り込み、実行可能かどうかをチェックし、ガスを消費し、それが失敗するか停止するまで命令を実行します。 + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/ja-edge/architecture/modules/storage.md b/archive/edge/ja-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..cdf4f74dd9 --- /dev/null +++ b/archive/edge/ja-edge/architecture/modules/storage.md @@ -0,0 +1,116 @@ +--- +id: storage +title: ストレージ +description: Polygon Edgeのストレージモジュールについて説明します。 +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## 概要 {#overview} + +Polygon Edgeは現在データストレージ用に**LevelDB**および**インメモリ**データストアを利用しています。 + +Polygon Edge全体を通して、モジュールが内在するデータストアとやり取りする必要がある場合、やり取りしているDBエンジンまたはサービスについて知る必要はありません。 + +DBレイヤーは**ストレ**ージと呼ばれるモジュールの間で抽象化され、これはモジュールがクエリするインターフェースをエクスポートします。 + +各DBレイヤーは、現在は**LevelDB**のみで、これらのメソッドを個別に実行し、その実行に確実に適合するようにします。 + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### プレフィックス {#prefixes} + +LevelDBストレージのクエリを確定的にするため、また鍵ストレージのクラッシュを回避するため、Polygon Edgeはデータ保存時にプレフィックスとサブプレフィックスを活用します。 + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## 今後の計画 {#future-plans} + +近い将来の計画に、以下のような最も人気のあるDBソリューションの一部を追加することも含まれます: +* PostgreSQL +* MySQL + + +## 📜リソース {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/ja-edge/architecture/modules/syncer.md b/archive/edge/ja-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..1d9b7d7e6f --- /dev/null +++ b/archive/edge/ja-edge/architecture/modules/syncer.md @@ -0,0 +1,66 @@ +--- +id: syncer +title: Syncer +description: Polygon EdgeのSyncerモジュールについて説明します。 +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## 概要 {#overview} + +このモジュールは同期プロトコルのためのロジックを含みます。これは、新しいノードを実行中のネットワークと同期、またはコンセンサス(ノンバリデータ)に参加しないノードのための新しいブロックの検証/挿入に使用されます。 + +Polygon Edgeはネットワーキングレイヤーとして**libp2p**を使用し、その上で**gRPC**を実行します。 + +Polygon Edgeには基本的に2つの同期タイプがあります: +* バルク同期 - 一時に大規模な範囲のブロックを同期 +* ウォッチ同期 - ブロックごとに同期 + +### バルク同期 {#bulk-sync} + +バルク同期の手順は比較的簡単で、他のピアから可能な(利用可能な)かぎり多くのブロックを同期し、できるだけ速く追い付くことを目的にするものです。 + +以下がバルク同期のプロセスの流れです: + +1. **ノードがバルク同期を必要としているか判断する** - このステップでは、ノードがピアマップをチェックし、ローカルのノードが有するブロックよりも多くの数のブロックを誰かが持っているか確認します。 +2. **最高のピアを探す(同期ピアマップを使用する)** - このステップでは、ノードは上記の例で述べた条件に基づいて同期する最高のピアを見つけます。 +3. **バルク同期ストリームを開く** - このステップでは、共通ブロック番号からブロックをバルク同期するために、ノードは最高のピアにgRPCストリームを開きます。 +4. **バルク送信を行う時最高のピアはストリームを閉じる** - このステップでは、ノードが同期している最高のピアが持っているすべての利用可能なブロックを送信するとすぐにストリームを閉じます。 +5. **バルク同期が完了した時、ノードがバリデータか確認する** - このステップでは、ストリームは最高のピアによって閉じられ、ノードはバルク同期後にバリデータであるか確認する必要があります。 + * もしバリデータならば、同期ステートから飛び出してコンセンサスへの参加をスタートします。 + * もしそうでなければ、引き続き **ウォッチ同期**します。 + +### ウォッチ同期 {#watch-sync} + +:::info + +ウォッチ同期の手順はノードがバリデータでなく、接近するブロックを聞くだけのネットワークの定期的なノンバリデータノードである場合のみに実行されます。 +::: + +ウォッチ同期の動作はかなり簡単で、ノードはすでにネットワークの残りの部分と同期されており、入ってくる新しいブロックだけを解析する必要があります。 + +以下がウォッチ同期のプロセスの流れです: + +1. **ピアのステータスが更新される時に新しいブロックを追加する** - このステップでは、ノードが新しいブロックイベントについて聞き、新しいブロックがあるときにgRPC機能呼び出しを実行し、ブロックを取得し、ローカルステートを更新します。 +2. **最新のブロックを同期した後にノードがバリデータであるかチェックする** + * もしそうである場合、同期ステートから飛び出します。 + * そうでない場合、引き続き新しいブロックイベントについて聞きます。 + +## パフォーマンスレポート {#perfomance-report} + +:::info + +パフォーマンスはローカルマシン上で**百万ブロック**を同期することにより測定されました。 +::: + +| 名前 | 結果 | +|----------------------|----------------| +| 100万ブロックの同期 | 〜25分 | +| 100万ブロックの転送 | 〜1分 | +| GRPC呼び出し数 | 2 | +| テストカバレッジ | 〜93% | \ No newline at end of file diff --git a/archive/edge/ja-edge/architecture/modules/txpool.md b/archive/edge/ja-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..97f1aa2df1 --- /dev/null +++ b/archive/edge/ja-edge/architecture/modules/txpool.md @@ -0,0 +1,222 @@ +--- +id: txpool +title: TxPool +description: Polygon EdgeのTxPoolモジュールについて説明します。 +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## 概要 {#overview} + +TxPoolモジュールは、システムのさまざまな部分からトランザクションが追加されるトランザクションプールの実装を表します。また、このモジュールでは、下記に説明するノードオペレータに役立つ機能もいくつか提供しています。 + +## オペレータコマンド {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +ノードオペレータは、**[CLIコマンド](/docs/edge/get-started/cli-commands#transaction-pool-commands)**セクションで説明されているように、これらのGRPCエンドポイントをクエリできます。 + +## トランザクションの処理 {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +***addImpl***メソッドは、**TxPool**モジュールの基本となるものです。システムにトランザクションが追加される中心的な場所であり、GRPCサービス、JSON RPCエンドポイントからクライアントが**ゴシップ**プロトコルを介してトランザクションを受信するたびに呼び出されます。 + +これは、トランザクションが追加されるコンテキスト(GRPC、JSON RPCなど)を示す引数**ctx**として取り込まれます。
もう1つのパラメータは、プールに追加されるトランザクションのリストです。 + +ここで注意すべき重要な点は、トランザクション内の**From**フィールドのチェックです。 +* **From**フィールドが**空**の場合、暗号化されていない/署名されていないトランザクションと見なされます。これらの種類のトランザクションは開発モードでのみ許可されます +* **From**フィールドが**空でない**場合は、署名付きトランザクションであるため、署名検証が行われます + +これらすべての検証の後、トランザクションは有効であると見なされます。 + +## データ構造 {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +混乱を引き起こす可能性のあるTxPoolオブジェクトのフィールドは、**キュー**リストと**ソート済み**リストです。 +* **キュー** - アカウントトランザクションのソート済みリストのヒープ実装(ナンス単位) +* **ソート済み** - 現在プロモートされているすべてのトランザクション(すべての実行可能トランザクション)のソート済みリスト。ガス価格でソート + +## ガス制限エラー管理 {#gas-limit-error-management} + +トランザクションを送信するたびに、TxPoolでトランザクションを処理する方法が3つあります。 + +1. 保留中のすべてのトランザクションがブロックに適合できます +2. 1つ以上の保留中のトランザクションがブロックに適合できません +3. 1つ以上の保留中のトランザクションがブロックに適合することはありません + +ここで、**_適合_**という言葉は、トランザクションがTxPoolに残っているガスよりも低いガス制限を持っていることを意味します。 + +最初のシナリオでは、エラーは発生しません。 + +### 第2シナリオ {#second-scenario} + +- TxPoolの残りのガスは、最後のブロックのガス制限に設定されています。たとえば、**5000**としましょう +- 最初のトランザクションが処理され、TxPoolの**3000**ガスが消費されます + - TxPoolの残りのガスは**2000**になりました +- 2回目のトランザクションは、最初のトランザクションと同じで、両方とも3000ユニットのガスを消費します +- TxPoolの残りのガスはトランザクションガスより**低い**ため、現在のブロックでは処理できません + - 次のブロックで処理できるように、保留中のトランザクションキューに戻されます +- 最初のブロックが書き込まれます、**ブロック#1**と呼びましょう +- TxPoolの残りのガスが**ブロック#1**のガス制限である親ブロックに設定されます +- TxPool保留トランザクションキューに戻されたトランザクションが処理され、ブロックに書き込まれます + - TxPoolの残りのガスは**2000**になりました +- 2つ目のブロックが書きこまれています +- ... + +![TxPoolエラーシナリオ#1](/img/edge/txpool-error-1.png) + +### 第3シナリオ {#third-scenario} +- TxPoolの残りのガスは、最後のブロックのガス制限に設定されています。たとえば、**5000**としましょう +- 最初のトランザクションが処理され、TxPoolの**3000**ガスが消費されます + - TxPoolの残りのガスは**2000**になりました +- ガスフィールドを**6000**に設定した2回目の取引が提出されます +- ブロックのガス制限がトランザクションガスより**低い**ため、このトランザクションは廃棄されます + - ブロックに適合することはできません +- 最初のブロックが書きこまれています +- ... + + +![TxPoolエラーシナリオ#2](/img/edge/txpool-error-2.png) + +> これは、次のエラーが発生するたびに発生します: +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## ブロックガス目標 {#block-gas-target} + +ノードがブロックのガス制限を実行中のチェーン上の特定の目標に対してそれ以下に保ちたい場合があります。 + +ノードオペレータは、新たに作成されたブロックにこの制限を適用しようとする特定のノードの目標ガス制限を設定できます。他のノードの大部分にも同様の(または同じ)目標ガス制限が設定されている場合、ブロックガス制限は常にブロックガス目標あたりにあり、新しいブロックが作成されると、ゆっくりと(最大`1/1024 * parent block gas limit`)進みます。 + +### 例となるシナリオ {#example-scenario} + +* ノード演算子は、シングルのノードのブロックガス制限を`5000`に設定します +* 他のノードも、`7000`として設定されたシングルのノードとは別に、`5000`として設定されます +* ガス目標を`5000`に設定したノードはプロポーザーになると、ガスの制限がすでに目標に達しているかどうかをチェックします。 +* ガス制限が目標値に達していない場合(高い/低い)、プロポーザーノードは、ブロックガス目標値を目標値の方向に最大(1/1024*親ガス制限)に設定します + 1. 例: `parentGasLimit = 4500`と`blockGasTarget = 5000`のプロポーザーは、新しいブロックのガス制限を`4504.39453125`(`4500/1024 + 4500`)として計算します + 2. 例: `parentGasLimit = 5500`と`blockGasTarget = 5000`のプロポーザーは、新しいブロックのガス制限を`5494.62890625`(`5500 - 5500/1024`)として計算します +* これにより、目標が`7000`に設定されているシングルのプロポーザーは制限をあまり進めることができず、`5000`に設定されているノードの大部分は常に制限を維持しようとするため、チェーン内のブロックガスの制限が目標に維持されます。 \ No newline at end of file diff --git a/archive/edge/ja-edge/architecture/modules/types.md b/archive/edge/ja-edge/architecture/modules/types.md new file mode 100644 index 0000000000..fea66b922e --- /dev/null +++ b/archive/edge/ja-edge/architecture/modules/types.md @@ -0,0 +1,40 @@ +--- +id: types +title: タイプ +description: Polygon Edgeのタイプモジュールの説明です。 +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## 概要 {#overview} + +**タイプ**モジュールは次のようなコアオブジェクトタイプを実装しています: + +* **アドレス** +* **ハッシュ** +* **ヘッダ** +* 多くのヘルパー関数 + +## RLPエンコード/デコード {#rlp-encoding-decoding} + +GETHなどのクライアントとは異なり、Polygon Edgeはエンコーディングにリフレクションを使用しません。
+パフォーマンス劣化やスケーリングの困難化などの新しい問題をもたらすため、リフレクションを使用しないことを選びました。 + +**タイプ**モジュールはFastRLPパッケージを使用してRLPマーシャリングとマーシャリングの解除用の使いやすいインターフェースを提供します。 + +マーシャリングは*MarshalRLPWith*と*MarshalRLPTo*メソッドを通じて行われます。類似したメソッドがマーシャリングの解除ために存在します。 + +これらのメソッドを手動で定義することにより、Polygon Edgeではリフレクションを使用する必要がありません。*rlp_marshal.go*で、マーシャリング用のメソッドを見つけられます: + +* **ボディ** +* **ブロック** +* **ヘッダ** +* **レシート** +* **ログ** +* **トランザクション** \ No newline at end of file diff --git a/archive/edge/ja-edge/architecture/overview.md b/archive/edge/ja-edge/architecture/overview.md new file mode 100644 index 0000000000..802577739e --- /dev/null +++ b/archive/edge/ja-edge/architecture/overview.md @@ -0,0 +1,59 @@ +--- +id: overview +title: アーキテクチャの概要 +sidebar_label: Overview +description: Polygon Edgeのアーキテクチャの紹介。 +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +まず*モジュラー*であるソフトウェアを作るというアイデアから始まりました。 + +これはPolygon Edgeのほぼすべての部分に存在するものです。下記の簡単な概要は構築されたアーキテクチャとそのレイヤーに関するものです。 + +## Polygon Edgeのレイヤー {#polygon-edge-layering} + +![Polygon Edgeアーキアーキテクチャ](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +すべてベースネットワークレイヤーから始まりますが、これは**libp2p**を活用します。この技術を用いることを決めました。その理由は、これがPolygon Edgeの設計哲学に適合するからです。Libp2pは以下のとおりです: + +- モジュール式 +- 拡張可能 +- 高速 + +最も重要なのは、それがより高度な機能のために優れた基盤を提供することですが、これは後ほどカバーします。 + + +## 同期とコンセンサス {#synchronization-consensus} +同期とコンセンサスのプロトコルの分離により、クライアントの実行方法次第で、モジュール化と**カスタム**同期、コンセンサス方式の導入が可能になります。 + +Polygon Edgeは既存のプラグ可能なコンセンサスアルゴリズムを提供するよう設計されています。 + +現在サポートしているコンセンサスアルゴリズムのリスト: + +* IBFT PoA +* IBFT PoS + +## ブロックチェーン {#blockchain} +ブロックチェーンレイヤーはPolygon Edgeシステムのすべてを調整する中央レイヤーです。これは付随する*モジュール*セクションで詳しく取り上げています。 + +## ステート {#state} +ステート内部レイヤーはステート移行ロジックを含みます。新しいブロックが含まれる時にステートがどのように変化するかに対応します。これは付随する*モジュール*セクションで詳しく取り上げています。 + +## JSON RPC {#json-rpc} +JSON RPCレイヤーはdApp開発者がブロックチェーンとやり取りするために使用するAPIレイヤーです。これは付随する*モジュール*セクションで詳しく取り上げています。 + +## TxPool {#txpool} +TxPoolレイヤーはトランザクションプールを表し、トランザクションが複数のエントリーポイントから追加できるためにシステム内の他のモジュールと密接にリンクしています。 + +## grpc {#grpc} +gRPC(googleリモートプロシージャコール)は、Googleが最初に作成した堅牢なオープンソースRPCフレームワークです。GRPCレイヤーはオペレータのやり取りに重要です。これを通じてノードオペレータはクライアントと簡単にやり取りできるため、楽しめるUXを提供します。 diff --git a/archive/edge/ja-edge/community/propose-new-feature.md b/archive/edge/ja-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..9dc9495a05 --- /dev/null +++ b/archive/edge/ja-edge/community/propose-new-feature.md @@ -0,0 +1,60 @@ +--- +id: propose-new-feature +title: 新しい機能を提案 +description: "新しい機能を提案するPRテンプレートと説明" +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## 概要 {#overview} + +修正を含めるか、コードに貢献していただける場合は、まずチームに連絡していただくことを強く推奨します。
+Polygon Edgeは、簡潔かつ要領を得た比較的基本の機能の提案テンプレートを使用します。 + +## PRテンプレート {#pr-template} + +### 説明 {#description} + +このPRで何が行われたかについての詳細な説明をしてください。 + +### 変更には、次を含みます {#changes-include} + +- [ ]バグ修正(問題を解決する非破壊的の変更) +- [ ]ホットフィックス(緊急の問題を解決し、迅速に注意する必要がある変更) +- [ ]新しい機能(機能性を追加する非破壊的変更) +- [ ]破壊的変更(後方互換性がない変更、および/または現在の機能を変更する) + +### 破壊的変更 {#breaking-changes} + +破壊的変更が行われた場合は、このセクションを埋めてください、そうでない場合は削除してください。 + +### チェックリスト {#checklist} + +- [ ]私はこのPRを自分自身に割り当てた +- [ ]少なくとも1人のレビュアーを追加した +- [ ]関連するラベルを追加した +- [ ]公式ドキュメントを更新した +- [ ]コードに十分なドキュメントを追加した + +### テスト {#testing} + +- [ ]公式テストスイートでこのコードをテストした +- [ ]このコードを手動でテストした + +## 手動テスト {#manual-tests} + +この機能について手動テストを実行した場合は、このセクションを埋め、そうでない場合は削除してください。 + +### ドキュメントの更新 {#documentation-update} + +該当する場合、このセクションでドキュメント更新PRをリンクし、そうでない場合は削除してください。 + +### 追加コメント {#additional-comments} + +該当する場合は、このセクションに追加コメントを投稿し、そうでない場合は削除してください。 \ No newline at end of file diff --git a/archive/edge/ja-edge/community/report-bug.md b/archive/edge/ja-edge/community/report-bug.md new file mode 100644 index 0000000000..3eb2988333 --- /dev/null +++ b/archive/edge/ja-edge/community/report-bug.md @@ -0,0 +1,55 @@ +--- +id: report-bug +title: 問題の報告 +description: Polygon Edgeの問題を報告するためのテンプレートと手順。 +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## 概要 {#overview} + +物は時に壊れます。
+問題が生じた場合、チームに知らせていただくのが常により良い選択です。
+Polygon EdgeのGitHubページでは、新しい問題を記録し、チームと協議を開始することができます。 + +## 問題テンプレート {#issue-template} + +## [問題の題名] + +### 説明 {#description} + +ここで問題をできるだけ詳細に説明する + +### ご自身の環境 {#your-environment} + +* OSとバージョン +* Polygon Edgeのバージョン +* 問題を起こすブランチ + +### 問題を再現するための手順 {#steps-to-reproduce} + +* 問題を再現する方法を教えてください
+* 分かる場合は、問題の所在
+* ある場合は、問題を引き起こしたコマンド + +### 期待した動き {#expected-behaviour} + +どうなるべきだったか説明してください + +### 実際の動き {#actual-behaviour} + +代わりに何が起こったか教えてください + +### ログ {#logs} + +もしあれば、問題を示すあらゆるログをここにペーストしてください。 + +### ソリューション案 {#proposed-solution} + +問題を解決する方法について考えがある場合、ここに書いてください、そうすれば協議を開始することができます。 \ No newline at end of file diff --git a/archive/edge/ja-edge/configuration/manage-private-keys.md b/archive/edge/ja-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..1fee97dcff --- /dev/null +++ b/archive/edge/ja-edge/configuration/manage-private-keys.md @@ -0,0 +1,71 @@ +--- +id: manage-private-keys +title: 秘密鍵の管理 +description: "秘密鍵の管理方法と鍵の種類。" +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## 概要 {#overview} + +Polygon Edgeには、直接管理する2種類の秘密鍵があります: + +* **コンセンサスメカニズムに使用される秘密鍵** +* **libp2pによるネットワークに使用される秘密鍵** +* **(オプション)バリデータの署名を集約するためのコンセンサスメカニズムに使用されるBLS秘密鍵** + +現在、Polygon Edgeは直接のアカウント管理をサポートしていません。 + +[バックアップと復元ガイド](/docs/edge/working-with-node/backup-restore)で概説されているディレクトリ構造に基づいて、Polygon Edgeはこれらの鍵ファイルを2つの異なるディレクトリ(**コンセンサス**と**キーストア**)に保存します。 + +## 鍵形式 {#key-format} + +秘密鍵はシンプルな**Base64形式**で保存されているため、人間が読みやすく携帯性があります。 + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info 鍵タイプ + +Polygon Edge内で生成および使用されるすべての秘密鍵ファイルは、曲線[secp256k1](https://en.bitcoin.it/wiki/Secp256k1)のECDSAに依存しています。 + +カーブは非標準であるため、標準化されたPEM形式で符号化および保存することはできません。この鍵タイプに準拠していない鍵のインポートはサポートされていません。 +::: +## コンセンサス秘密鍵 {#consensus-private-key} + +*コンセンサス秘密鍵*として言及される秘密鍵ファイルは、**バリデータ秘密鍵**とも呼ばれます。この秘密鍵は、ノードがネットワーク内でバリデータとして動作しており、新しいデータに署名する必要がある場合に使用されます。 + +秘密鍵ファイルは`consensus/validator.key`にあり、前述の[鍵形式](/docs/edge/configuration/manage-private-keys#key-format)に準拠しています。 + +:::warning + +バリデータ秘密鍵は、各バリデータノードに固有です。同じ鍵をすべてのバリデータ間で共有することはできません。これはチェーンのセキュリティを損なう可能性があるためです。 +::: + +## ネットワーク秘密鍵 {#networking-private-key} + +ネットワーク用に記述された秘密鍵ファイルは、対応するPeerIDを生成し、ノードがネットワークに参加するようにするためにlibp2pによって使用されます。 + +これは`keystore/libp2p.key`にあり、前述の[鍵形式](/docs/edge/configuration/manage-private-keys#key-format)に準拠しています。 + +## BLS秘密鍵 {#bls-secret-key} + +BLS秘密鍵ファイルは、コンセンサスレイヤーでコミットされたシールを集約するために使用されます。BLSによる集約コミットシールのサイズは、シリアル化されたコミットECDSA署名よりも小さくなります。 + +BLS機能はオプションであり、BLSを使用するかどうかを選択できます。詳細については、[BLS](/docs/edge/consensus/bls)を参照してください。 + +## インポート/エクスポート {#import-export} + +鍵ファイルはディスク上のシンプルなBase64に保存されているため、簡単にバックアップまたはインポートできます。 + +:::caution 鍵ファイルの変更 + +すでに設定されている/実行中のネットワーク上の鍵ファイルに対して何らかの変更を加えると、重大なネットワーク/コンセンサスの中断が発生する可能性があります。これは、コンセンサスおよびピア検出メカニズムによってこれらの鍵から派生したデータがノード固有のストレージに保存され、このデータによって接続が開始され、コンセンサスロジックが実行されるためです。 +::: \ No newline at end of file diff --git a/archive/edge/ja-edge/configuration/prometheus-metrics.md b/archive/edge/ja-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..78f0ac581e --- /dev/null +++ b/archive/edge/ja-edge/configuration/prometheus-metrics.md @@ -0,0 +1,34 @@ +--- +id: prometheus-metrics +title: Prometheusメトリクス +description: "Polygon EdgeのPrometheusメトリクスを有効化する方法" +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## 概要 {#overview} + +Polygon EdgeはPrometheusメトリクスを報告及び提供し、順番が来ると、Prometheusコレクターを使用して消費します。 + +Prometheusメトリクスはデフォルトでは無効化されています。設定ファイル内の`--prometheus`フラグまたは`Telemetry.prometheus`フィールドを使用してリスナーアドレスを指定することによって有効化することができます。メトリクスは指定されたアドレスの`/metrics`下で提供されます。 + +## 利用可能なメトリクス {#available-metrics} + +次のメトリクスは利用できます: + +| **名前** | **タイプ** | **説明** | +|-----------------------------------------------|---------------|-------------------------------------------------| +| txpool_pending_transactions | Gauge | TxPoolにおける保留中のトランザクション数 | +| consensus_validator | Gauge | バリデータ数 | +| consensus_rounds | Gauge | ラウンド数 | +| consensus_num_txs | Gauge | 最後のブロックにおけるトランザクション数 | +| consensus_block_interval | Gauge | このブロックと最後のブロック間の秒単位での時間 | +| network_peers | Gauge | 接続されたピア数 | +| network_outbound_connections_count | Gauge | アウトバウンド接続数 | +| network_inbound_connections_count | Gauge | インバウンド接続数 | +| network_pending_outbound_connections_count | Gauge | 保留中のアウトバウンド接続数 | +| network_pending_inbound_connections_count | Gauge | 保留中のインバウンド接続数 | \ No newline at end of file diff --git a/archive/edge/ja-edge/configuration/sample-config.md b/archive/edge/ja-edge/configuration/sample-config.md new file mode 100644 index 0000000000..1e4a2e72e2 --- /dev/null +++ b/archive/edge/ja-edge/configuration/sample-config.md @@ -0,0 +1,150 @@ +--- +id: sample-config +title: サーバ設定ファイル +description: "設定ファイルを使用してPolygon Edgeサーバを起動します。" +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# サーバ設定ファイル {#server-configuration-file} +さまざまな設定オプションでサーバを起動することは、フラグを使用する代わりに設定ファイルを使用して行うことができます。 +設定ファイルでサーバを起動するのに使用するコマンド:`polygon-edge server --config ` + +## デフォルト設定で設定ファイルをエクスポート {#export-config-file-with-default-configuration} +Polygon Edgeサーバのデフォルト設定での設定は、`yaml`または`json`ファイル形式で設定ファイルにエクスポートすることができます。このファイルは設定ファイルを使用してサーバを実行するためのテンプレートとして使用することができます。 + +### YAML {#yaml} +`yaml`形式で設定ファイルを生成する: +```bash +polygon-edge server export --type yaml +``` +または +```bash +polygon-edge server export +``` +`default-config.yaml`という名の設定ファイルは、このコマンドを実行したディレクトリと同じディレクトリに作成されます。 + +ファイルの例: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +`json`形式で設定ファイルを生成する: +```bash +polygon-edge server export --type json +``` +`default-config.json`という名の設定ファイルは、このコマンドを実行したディレクトリと同じディレクトリに作成されます。 + +ファイルの例: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +[CLIコマンド](/docs/edge/get-started/cli-commands)セクションをチェックして、これらのパラメータをどのように使用するか情報を取得してください。 + +### タイプスクリプトスキーマ {#typescript-schema} + +設定ファイルのサンプルフォーマットを以下に示します。TypeScriptに書かれており、プロパティタイプ(`string`, `number`, `boolean`)を表現し、そこから設定を得るできます。すべてのプロパティがオプションであることを表現するために、`type-fest`の`PartialDeep`タイプを使用するということを言及しておくべきでしょう。 + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/ja-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/ja-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..3889e076b2 --- /dev/null +++ b/archive/edge/ja-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,126 @@ +--- +id: set-up-aws-ssm +title: AWS SSM(システムマネージャ)の設定 +description: "Polygon EdgeにAWS SSM(システムマネージャ)を設定します。" +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## 概要 {#overview} + +現在、Polygon Edgeは2つの主なランタイムシークレットを守ることに関心を持っています: +* ノードがバリデータの場合、ノードによって使用される**バリデータ秘密鍵** +* 他のピアと参加し通信するため、libp2pによって使用される**ネットワーク秘密鍵** + +追加情報については、[秘密鍵の管理ガイド](/docs/edge/configuration/manage-private-keys)をお読みください + +Polygon Edgeのモジュールは**秘密を守る方法を知る必要はありません**。 最終的には、モジュールは秘密が遠くのサーバーに保存されているのかあるいはノードのディスクにローカルで保存されているかは問題にしません。 + +モジュールが秘密保持について知る必要があるのは、**秘密を使用することを知っている**ことと**どの秘密を取得 +または保存**するかを知っていることだけです。 これらの操作のより微細な実装についての詳細は`SecretsManager`に委任されますが、これは言うまでもなく抽象化です。 + +Polygon Edgeを起動するノードオペレータはどのシークレットマネージャを使用したいかを指定でき、正しいシークレットマネージャがインスタンス化されるとただちに、モジュールが前述のインターフェースを通じて秘密を処理します。これには秘密がディスクに保存されているか、またはサーバーにあるかには関わりません。 + +この記事では、Polygon Edgeを立ち上げ[AWSシステムマネージャパラメータストア](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html)で実行するために必要なステップを示します。 + +:::info 以前のガイド + +この記事を読まれる前に、次の記事を読まれることを**強くお勧めしまします**:[**ローカル設定**](/docs/edge/get-started/set-up-ibft-locally) +および[**クラウド設定**](/docs/edge/get-started/set-up-ibft-on-the-cloud)。 +::: + + +## 前提条件 {#prerequisites} +### IAMポリシー {#iam-policy} +ユーザーはAWSシステムマネージャパラメータストアの読み取り/書き込み操作を可能にするIAMポリシーを作成する必要があります。IAMポリシーを無事作成した後、ユーザーはPolygon Edgeサーバーを実行しているEC2インスタンスにこれを添付する必要があります。IAMポリシーは次のようになります: +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +AWS SSM IAMロールに関する詳細情報は[AWSドキュメント](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html)で確認できます。 + +先に進む前に必要な情報: +* **リージョン**(システムマネージャとノードが所在するリージョン) +* **パラメータパス**(秘密が配置される任意のパス、たとえば `/polygon-edge/nodes`) + +## ステップ1 -シークレットマネージャ設定の生成 {#step-1-generate-the-secrets-manager-configuration} + +Polygon EdgeがAWS SSMとシームレスに通信できるようにするために、AWS SSM上の秘密の保管に必要なすべての情報を含む、すでに生成された設定ファイルを解析する必要があります。 + +設定を生成するには次のコマンドを実行します: + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +存在するパラメータ: +* `PATH`は設定ファイルをエクスポートすべきパスです。デフォルトは`./secretsManagerConfig.json` +* `NODE_NAME`はAWS SSM設定が設定されている現在のノードの名前です。これは任意の値にすることができます。デフォルトは`polygon-edge-node` +* `REGION`はAWS SSMが存在するリージョンです。これはAWS SSMを利用するノードと同じリージョンでなくてはなりません。 +* `SSM_PARAM_PATH`は秘密が保存されるパスの名前です。たとえば、`--name node1`と`ssm-parameter-path=/polygon-edge/nodes`が特定されていれば、秘密は`/polygon-edge/nodes/node1/`として保存されます。 + +:::caution ノード名 + +ノード名を指定する場合は注意してください。 + +Polygon Edgeは、指定されたノード名を使用して、AWS SSMで生成および使用する秘密を追跡します。既存のノード名を指定すると、AWS SSMに秘密を書き込めないという結果をもたらす可能性があります。 + +秘密は、以下のベースパスに保存されます:`SSM_PARAM_PATH/NODE_NAME` + +::: + +## ステップ2 - 設定を使用した秘密鍵の初期化 {#step-2-initialize-secret-keys-using-the-configuration} + +すでに設定ファイルが存在するため、必要な秘密鍵をステップ1で設定した設定ファイルで`--config`を使用して初期化できます: + +```bash +polygon-edge secrets init --config +``` + +`PATH`パラメータはステップ1から以前に生成されたシークレットマネージャパラメータの場所になります。 + +:::info IAMポリシー + +このステップは、読み書き操作を可能にするIAMポリシーが正しく設定されていないおよび/またはこのコマンドを実行するEC2インスタンスに添付されていない場合、失敗します。 +::: + +## ステップ3 - ジェネシスファイルの生成 {#step-3-generate-the-genesis-file} + +ジェネシスファイルは[**ローカル設定**](/docs/edge/get-started/set-up-ibft-locally) +および[**クラウド設定**](/docs/edge/get-started/set-up-ibft-on-the-cloud)ガイドと同様の方法に、多少の変更を加えて生成する必要があります。 + +AWS SSMがローカルなファイルシステムの代わりに使用されているため、`--ibft-validator`フラグを通じてバリデータアドレスを追加する必要があります。 +```bash +polygon-edge genesis --ibft-validator ... +``` + +## ステップ4 - Polygon Edgeクライアントの起動 {#step-4-start-the-polygon-edge-client} + +鍵が設定され、ジェネシスファイルが生成されたため、このプロセスの最終ステップは`server`コマンドでPolygon Edgeを起動することです。 + +`server`コマンドは前述のガイドと同様の方法に若干の追加 - `--secrets-config`フラグを加えて使用されます: +```bash +polygon-edge server --secrets-config ... +``` + +`PATH`パラメータはステップ1から以前に生成されたシークレットマネージャパラメータの場所になります。 \ No newline at end of file diff --git a/archive/edge/ja-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/ja-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..9eb2691dc1 --- /dev/null +++ b/archive/edge/ja-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,109 @@ +--- +id: set-up-gcp-secrets-manager +title: GCPシークレットマネージャの設定 +description: "Polygon Edge用のGCPシークレットマネージャを設定します。" +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## 概要 {#overview} + +現在、Polygon Edgeは2つの主なランタイムシークレットを守ることに関心を持っています: +* ノードがバリデータの場合、ノードによって使用される**バリデータ秘密鍵** +* 他のピアと参加し通信するため、libp2pによって使用される**ネットワーク秘密鍵** + +追加情報については、[秘密鍵の管理ガイド](/docs/edge/configuration/manage-private-keys)をお読みください + +Polygon Edgeのモジュールは**秘密を守る方法を知る必要はありません**。 最終的には、モジュールは秘密が遠くのサーバーに保存されているのかあるいはノードのディスクにローカルで保存されているかは問題にしません。 + +モジュールが秘密保持について知る必要があるのは、**秘密を使用することを知っている**ことと**どの秘密を取得 +または保存**するかを知っていることだけです。 これらの操作のより微細な実装についての詳細は`SecretsManager`に委任されますが、これは言うまでもなく抽象化です。 + +Polygon Edgeを起動するノードオペレータはどのシークレットマネージャを使用したいかを指定でき、正しいシークレットマネージャがインスタンス化されるとただちに、モジュールが前述のインターフェースを通じて秘密を処理します。介して秘密を処理します。 + +この文書では、[GCPシークレットマネージャ](https://cloud.google.com/secret-manager)でPolygon Edgeを起動して実行するために必要な手順について詳しく説明します。 + +:::info 以前のガイド + +この記事を読まれる前に、次の記事を読まれることを**強くお勧めしまします**:[**ローカル設定**](/docs/edge/get-started/set-up-ibft-locally) +および[**クラウド設定**](/docs/edge/get-started/set-up-ibft-on-the-cloud)。 +::: + + +## 前提条件 {#prerequisites} +### GCP請求アカウント {#gcp-billing-account} +GCPシークレットマネージャを使用するには、ユーザはGCPポータルで[請求アカウント](https://console.cloud.google.com/)を有効にする必要があります。GCPプラットフォーム上の新しいGoogleアカウントには、無料トライアルの王様としてスタートするためのファンドがいくつか提供されています。詳細は[GCPドキュメント](https://cloud.google.com/free)をご覧ください + +### シークレットマネージャAPI {#secrets-manager-api} +ユーザは、GCPシークレットマネージャAPIを使用する前に有効にする必要があります。 +これは、[シークレットマネージャAPIポータル](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com)から実行できます。詳細情報:[シークレットマネージャ設定](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + +### GCP資格情報 {#gcp-credentials} +最後に、ユーザは認証に使用される新しい資格情報を生成する必要があります。これは、[ここ](https://cloud.google.com/secret-manager/docs/reference/libraries)に記載されている手順に従って行うことができます。 +生成されたjsonファイルには資格情報が含まれており、GCPシークレットマネージャを使用する必要がある各ノードに転送する必要があります。 + +続行する前に必要な情報: +* **プロジェクトID**(GCPプラットフォームで定義されているプロジェクトID) +* **資格情報ファイルの場所**(資格情報を含むjsonファイルへのパス) + +## ステップ1 - シークレットマネージャ設定の生成 {#step-1-generate-the-secrets-manager-configuration} + +Polygon EdgeがGCP SMとシームレスに通信できるようにするには、GCP SM上のシークレットストレージに必要なすべての情報を含む、すでに生成された設定ファイルを解析する必要があります。 + +設定を生成するには、次のコマンドを実行します: + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +存在するパラメータ: +* `PATH`は設定ファイルをエクスポートすべきパスです。デフォルトは`./secretsManagerConfig.json` +* `NODE_NAME`GCP SM設定が設定される現在のノードの名前です。任意の値を指定できます。デフォルトは`polygon-edge-node` +* `PROJECT_ID`は、アカウントの設定およびシークレットマネージャAPIのアクティベーション中にユーザがGCPコンソールで定義したプロジェクトのIDです。 +* `GCP_CREDS_FILE`は、シークレットマネージャへの読み取り/書き込みアクセスを許可する資格情報を含むjsonファイルへのパスです。 + +:::caution ノード名 + +ノード名を指定する場合は注意してください。 + +Polygon Edgeは、指定されたノード名を使用して、GCP SMで生成および使用される秘密を追跡します。既存のノード名を指定すると、GCP SMへの秘密の書き込みに失敗する場合があります。 + +秘密は、次の基本パスに保存されます:`projects/PROJECT_ID/NODE_NAME` + +::: + +## ステップ2 - 設定を使用した秘密鍵の初期化 {#step-2-initialize-secret-keys-using-the-configuration} + +すでに設定ファイルが存在するため、必要な秘密鍵をステップ1で設定した設定ファイルで`--config`を使用して初期化できます: + +```bash +polygon-edge secrets init --config +``` + +`PATH`パラメータは、ステップ1から以前に生成されたシークレットマネージャパラメータの場所です。 + +## ステップ3 - ジェネシスファイルの生成 {#step-3-generate-the-genesis-file} + +ジェネシスファイルは[**ローカル設定**](/docs/edge/get-started/set-up-ibft-locally) +[**クラウド設定**](/docs/edge/get-started/set-up-ibft-on-the-cloud)ガイドと同様の方法で生成する必要があり、若干の変更が必要です。 + +GCP SMがローカルファイルシステムの代わりに使用されているため、次の`--ibft-validator`フラグを使用してバリデータアドレスを追加する必要があります: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## ステップ4 - Polygon Edgeクライアントのスタート {#step-4-start-the-polygon-edge-client} + +鍵が設定され、ジェネシスファイルが生成されたため、このプロセスの最終ステップは`server`コマンドでPolygon Edgeを起動することです。 + +`server`コマンドは前述のガイドと同様の方法に若干の追加 - `--secrets-config`フラグを加えて使用されます: +```bash +polygon-edge server --secrets-config ... +``` + +`PATH`パラメータはステップ1から以前に生成されたシークレットマネージャパラメータの場所になります。 \ No newline at end of file diff --git a/archive/edge/ja-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/ja-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..5035a41e2f --- /dev/null +++ b/archive/edge/ja-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,108 @@ +--- +id: set-up-hashicorp-vault +title: Hashicorp Vaultの設定 +description: "Polygon Edge用のHashicorp Vaultを設定します。" +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## 概要 {#overview} + +現在、Polygon Edgeは2つの主なランタイムシークレットを守ることに関心を持っています: +* ノードがバリデータの場合、ノードによって使用される**バリデータ秘密鍵** +* 他のピアと参加し通信するためにlibp2pによって使用される**ネットワーキング秘密鍵** + +:::warning + +バリデータ秘密鍵は、各バリデータノードに固有です。同じ鍵をすべてのバリデータ間で共有することはできません。これはチェーンのセキュリティを損なう可能性があるためです。 +::: + +詳細情報については、[秘密鍵管理ガイド](/docs/edge/configuration/manage-private-keys)を参照してください。 + +Polygon Edgeのモジュールは**秘密を守る方法を知る必要はありません**。 最終的には、モジュールは秘密が遠くのサーバーに保存されているのかあるいはノードのディスクにローカルで保存されているかは問題にしません。 + +モジュールが秘密保持について知る必要があるのは、**秘密を使用することを知っている**ことと**どの秘密を取得 +または保存**するかを知っていることだけです。 これらの操作のより微細な実装についての詳細は`SecretsManager`に委任されますが、これは言うまでもなく抽象化です。 + +Polygon Edgeを起動するノードオペレータはどのシークレットマネージャを使用したいかを指定でき、正しいシークレットマネージャがインスタンス化されるとただちに、モジュールが前述のインターフェースを通じて秘密を処理します。介して秘密を処理します。 + +この文書では、[Hashicorp Vault](https://www.vaultproject.io/)サーバでPolygon Edgeを起動して実行するために必要な手順について詳しく説明します。 + +:::info 以前のガイド + +この記事を読まれる前に、次の記事を読まれることを**強くお勧めしまします**:[**ローカル設定**](/docs/edge/get-started/set-up-ibft-locally) +および[**クラウド設定**](/docs/edge/get-started/set-up-ibft-on-the-cloud)。 +::: + + +## 前提条件 {#prerequisites} + +この文書では、Hashicorp Vaultサーバの機能しているインスタンスが**すでに設定されていること**を前提としています。 + +また、Polygon Edgeに使用されているHashicorp Vaultサーバで**KVストレージを有効にする必要があります**。 + +続行する前に必要な情報: +* **サーバURL**(Hashicorp VaultサーバのAPI URL) +* **トークン**(KVストレージエンジンへのアクセスに使用されるアクセストークン) + +## ステップ1 - シークレットマネージャ設定の生成 {#step-1-generate-the-secrets-manager-configuration} + +Polygon EdgeがVaultサーバとシームレスに通信できるようにするには、Vault上のシークレットストレージに必要なすべての情報を含む、すでに生成された設定ファイルを解析する必要があります。 + +設定を生成するには、次のコマンドを実行します: + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +存在するパラメータ: +* `PATH`は設定ファイルをエクスポートすべきパスです。デフォルトは`./secretsManagerConfig.json` +* `TOKEN`は、[前提条件のセクション](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites)で前述したアクセストークンです +* `SERVER_URL`は、VaultサーバのAPIのURLで、[前提条件のセクション](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites)でも説明されています +* `NODE_NAME`は、Vault設定が設定されている現在のノードの名前です。任意の値を指定できます。デフォルトは`polygon-edge-node` + +:::caution ノード名 + +ノード名を指定する場合は注意してください。 + +Polygon Edgeは、指定されたノード名を使用して、Vaultインスタンスで生成および使用される秘密を追跡します。既存のノード名を指定すると、Vaultサーバでデータが上書きされることがあります。 + +秘密は、次の基本パスに保存されます:`secrets/node_name` +::: + +## ステップ2 - 設定を使用した秘密鍵の初期化 {#step-2-initialize-secret-keys-using-the-configuration} + +すでに設定ファイルが存在するため、必要な秘密鍵をステップ1で設定した設定ファイルで`--config`を使用して初期化できます: + +```bash +polygon-edge secrets init --config +``` + +`PATH`パラメータは、ステップ1から以前に生成されたシークレットマネージャパラメータの場所です。 + +## ステップ3 - ジェネシスファイルの生成 {#step-3-generate-the-genesis-file} + +ジェネシスファイルは[**ローカル設定**](/docs/edge/get-started/set-up-ibft-locally) +[**クラウド設定**](/docs/edge/get-started/set-up-ibft-on-the-cloud)ガイドと同様の方法で生成する必要があり、若干の変更が必要です。 + +Hashicorp Vaultがローカルファイルシステムの代わりに使用されているため、次の`--ibft-validator`フラグを使用してバリデータアドレスを追加する必要があります: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## ステップ4 - Polygon Edgeクライアントのスタート {#step-4-start-the-polygon-edge-client} + +鍵が設定され、ジェネシスファイルが生成されたため、このプロセスの最終ステップは`server`コマンドでPolygon Edgeを起動することです。 + +`server`コマンドは前述のガイドと同様の方法に若干の追加 - `--secrets-config`フラグを加えて使用されます: +```bash +polygon-edge server --secrets-config ... +``` + +`PATH`パラメータはステップ1から以前に生成されたシークレットマネージャパラメータの場所になります。 \ No newline at end of file diff --git a/archive/edge/ja-edge/consensus/bls.md b/archive/edge/ja-edge/consensus/bls.md new file mode 100644 index 0000000000..6b1af81242 --- /dev/null +++ b/archive/edge/ja-edge/consensus/bls.md @@ -0,0 +1,141 @@ +--- +id: bls +title: BLS +description: "BLSモードに関する説明とインストラクション。" +keywords: + - docs + - polygon + - edge + - bls +--- + +## 概要 {#overview} + +BLSは、Boneh–Lynn–Shacham(BLS)とも呼ばれ、ユーザーが署名者であることを確認できる暗号署名スキームです。複数の署名を集約できる署名スキームです。Polygon Edgeでは、IBFTコンセンサスモードでセキュリティを向上させるためにBLSがデフォルトで使用されています。BLSは署名をシングルバイトの配列に集約し、ブロックヘッダーサイズを削減できます。チェーンごとにBLSを使用するかどうかを選択できます。ECDSA鍵はBLSモードが有効であるかどうかにかかわらず使用されます。 + +## ビデオプレゼンテーション {#video-presentation} + +[![bls - ビデオ](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## BLSを使用して新しいチェーンを設定する方法 {#how-to-setup-a-new-chain-using-bls} + +設定手順の詳細については[ローカル設定](/docs/edge/get-started/set-up-ibft-locally)と[クラウド設定](/docs/edge/get-started/set-up-ibft-on-the-cloud)を参照してください。 + +## 既存のECDSA PoAチェーンからBLS PoAチェーンに移行する方法 {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +このセクションでは既存のPoAチェーンでBLSモードを使用する方法を説明します。次のステップはPoAチェーンでBLSを有効にするために必要です。 + +1. すべてのノードを停止する +2. バリデータ用のBLS鍵を生成する +3. genesis.jsonにフォーク設定を追加する +4. すべてのノードを再起動する + +### 1. すべてのノードの停止 {#1-stop-all-nodes} + +バリデータのすべてのプロセスをCtrl + c(コントロール + c)を押すことで終了します。最新のブロックの高さ(ブロックコミットログで最も高いシーケンス番号)を覚えておいてください。 + +### 2. BLS鍵の生成 {#2-generate-the-bls-key} + +`secrets init`と`--bls`でBLS鍵を生成します。既存のECDSAとネットワーク鍵を維持し、新しいBLS鍵を追加するには、`--ecdsa`と`--network`を無効にする必要があります。 + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. フォーク設定の追加 {#3-add-fork-setting} + +`ibft switch`コマンドがフォーク設定を`genesis.json`に追加し、それにより、既存のチェーン内でBLSを有効にすることができます。 + +PoAネットワークでは、バリデータはコマンドに与えられる必要があります。`genesis`コマンドの方法と同様に、`--ibft-validators-prefix-path`または`--ibft-validator`フラグを使用してバリデータを指定できます。 + +チェーンがBLSと`--from`フラグの使用を開始している高さを指定します。 + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. すべてのノードの再起動 {#4-restart-all-nodes} + +`server`コマンドですべてのノードを再起動します。以前のステップで指定された`from`のブロックが作成された後、チェーンはBLSを有効にし、次のようにログを表示します: + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +また、ログはブロックが作成された後、ブロックごとに作成にどの検証モードが使用されたかを表示します。 + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## 既存のECDSA PoSチェーンからBLS PoSチェーンに移行する方法 {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +このセクションでは既存のPoSチェーンでBLSモードを使用する方法を説明します。次のステップはPoSチェーンでBLSを有効化するために必要です。 + +1. すべてのノードを停止する +2. バリデータ用のBLS鍵を生成する +3. genesis.jsonにフォーク設定を追加する +4. ステーキングコントラクトを呼び出し、BLS公開鍵を登録する +5. すべてのノードを再起動する + +### 1. すべてのノードの停止 {#1-stop-all-nodes-1} + +バリデータのすべてのプロセスをCtrl + c(コントロール + c)を押すことで終了します。最新のブロックの高さ(ブロックコミットログで最も高いシーケンス番号)を覚えておいてください。 + +### 2. BLS鍵の生成 {#2-generate-the-bls-key-1} + +`secrets init`と`--bls`フラグでBLS鍵を生成します。既存のECDSAとネットワーク鍵を維持し、新しいBLS鍵を追加するには、`--ecdsa`と`--network`を無効にする必要があります。 + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. フォーク設定の追加 {#3-add-fork-setting-1} + +`ibft switch`コマンドがフォーク設定を`genesis.json`に追加し、それにより、既存のチェーン内からBLSを有効にすることができます。 + +チェーンがBLSモードの使用をスタートする高さを`from`フラグで、コントラクトが更新される高さを`development`フラグを使用して指定します。 + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. ステーキングコントラクトのBLS公開鍵の登録 {#4-register-bls-public-key-in-staking-contract} + +フォークが追加され、バリデータが再起動された後、各バリデータはステーキングコントラクトの`registerBLSPublicKey`を呼び出し、BLS公開鍵を登録する必要があります。これは`--deployment`で指定された高さの後、`--from`で指定された高さの前に行わなくてはなりません。 + +BLS公開鍵を登録するスクリプトは[Staking SmartContract repo](https://github.com/0xPolygon/staking-contracts)に定義されています。 + +`BLS_PUBLIC_KEY`を`.env`ファイルに登録するよう設定します。他のパラメータの詳細については[pos-stake-unstake](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts)を参照してください。 + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +次のコマンドで`.env`でコントラクトに与えられたBLS公開鍵を登録します。 + +```bash +npm run register-blskey +``` + +:::warning バリデータはBLS公開鍵を手動で登録する必要があります。 + +BLSモードでは、バリデータは独自のアドレスとBLS公開鍵を所有している必要があります。コンセンサスレイヤーはコンセンサスがコントラクトからバリデータ情報を取得する時にコントラクト内にBLS公開鍵を登録していないバリデータを無視します。 +::: + +### 5. すべてのノードの再起動 {#5-restart-all-nodes} + +`server`コマンドですべてのノードを再起動します。チェーンは以前のステップで指定された`from`でブロックが作成された後にBLSを有効にします。 diff --git a/archive/edge/ja-edge/consensus/migration-to-pos.md b/archive/edge/ja-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..f6315dacdd --- /dev/null +++ b/archive/edge/ja-edge/consensus/migration-to-pos.md @@ -0,0 +1,40 @@ +--- +id: migration-to-pos +title: PoAからPoSへの移行 +description: "PoAからPoS IBFTモードに移行する、またはその逆のための方法です。" +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## 概要 {#overview} + +このセクションでは、ブロックチェーンをリセットする必要なく、クラスター実行のためのPoAからPoS IBFTモードへの移行、およびその逆を説明します。 + +## PoSへ移行する方法 {#how-to-migrate-to-pos} + +すべてのノードを停止し、`ibft switch`コマンドでgenesis.jsonにフォーク設定を追加し、ノードを再起動する必要があります。 + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution ECDSAを使用している場合の切り替え +ECDSAを使用する場合、ECDSAを使用していることを言及して、`--ibft-validator-type`フラグをスイッチに追加する必要があります。含まれていない場合、Edgeは自動的にBLSに切り替えます。 + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::PoSに切り替えるには、2つのブロック高さを指定する必要があります`deployment`。そして、`from``deployment`.は`from`ステーキングコントラクトを展開するための高さであり、PoSの開始の高さです。ステーキングコントラクトはアドレス`0x0000000000000000000000000000000000001001`で`deployment`でデプロイされますが、これは事前にデプロイされたコントラクトの場合と同様です。 + +ステーキングコントラクトの詳細については、[プルーフ・オブ・ステーク](/docs/edge/consensus/pos-concepts)を確認してください。 + +:::warning バリデータは手動でステークする必要があります + +PoSの開始時にバリデータになるためには、各バリデータはコントラクトが`deployment`でデプロイされた後、`from`の前にステークすることが必要です。各バリデータによる自身のバリデータセットの更新は、PoSの開始時のステーキングコントラクトのセットによって設定されます。 + +ステーキングについての詳細については、「ステーキングの**[設定」を参照してプルーフ・オブ・ステークを使用してください。](/docs/edge/consensus/pos-stake-unstake)** +::: diff --git a/archive/edge/ja-edge/consensus/poa.md b/archive/edge/ja-edge/consensus/poa.md new file mode 100644 index 0000000000..4a26490291 --- /dev/null +++ b/archive/edge/ja-edge/consensus/poa.md @@ -0,0 +1,107 @@ +--- +id: poa +title: プルーフ・オブ・オーソリティ(PoA) +description: "プルーフ・オブ・オーソリティ(PoA)に関する説明とインストラクション。" +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## 概要 {#overview} + +IBFT PoAはPolygon Edgeのデフォルトのコンセンサスメカニズムです。PoAでは、バリデータはブロックを作成し、ブロックチェーンにシリーズで追加する責任を持ちます。 + +すべてのバリデータが動的バリデータセットを構成し、そこでは投票方式を用いることでバリデータをセットに追加または削除することができます。つまり、バリデータが投票を通じてバリデータセットに追加/削除されることは、バリデータノードの過半数(51%)が特定のバリデータをセットに追加/削除するよう投票することで可能になります。この方法では、悪意のあるバリデータを認識、ネットワークから除外する一方、新しい信頼できるバリデータがネットワークに追加することができます。 + +すべてのバリデータは順番に次のブロック(ラウンドロビン)を提案し、ブロックをブロックチェーンに検証/挿入する場合、圧倒的多数(2/3を超える)のバリデータがそのブロックを承認しなくてはなりません。 + +バリデータ以外に、ブロックの作成には参加しないが、ブロックの検証プロセスに参加するノンバリデータが存在します。 + +## バリデータをバリデータセットに追加する {#adding-a-validator-to-the-validator-set} + +このガイドでは、4つのバリデータノードを持つアクティブIBFTネットワークに新しいバリデータノードを追加する方法を説明します。ネットワークを設定するのに役立ちたい場合は、[ローカル](/edge/get-started/set-up-ibft-locally.md)設定 / [クラウド](/edge/get-started/set-up-ibft-on-the-cloud.md)設定セクションを参照してください。 + +### ステップ1:IBFTのデータフォルダの初期化と新しいノード用バリデータ鍵の生成 {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +新しいノードでIBFTを起動し実行するために、まずデータフォルダを初期化し、鍵を生成する必要があります: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +このコマンドはバリデータの鍵(アドレス)とノードIDを表示します。次のステップではバリデータの鍵(アドレス)が必要です。 + +### ステップ2:他のバリデータノードからの新しい候補の提案 {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +新しいノードがバリデータになるには、バリデータの少なくとも51%がそれを提案する必要があります。 + +既存のバリデータノードからgrpcアドレス:127.0.0.1:10000で新しいバリデータ(`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`)を提案する方法の例: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +IBFTコマンドの構造は[CLIコマンド](/docs/edge/get-started/cli-commands)セクションでカバーされています。 + +:::info BLS公開鍵 + +BLS公開鍵はネットワークがBLSで実行されている場合のみ必要です。BLSモードで実行されていないネットワークに`--bls`は必要ありません。 +::: + +### ステップ3:クライアントノードの実行 {#step-3-run-the-client-node} + +この例ではすべてのノードが同じマシン上にあるネットワークを実行しようとしているため、ポートコンフリクトを回避するよう注意する必要があります。 + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +すべてのブロックを取得した後、コンソール内で新しいノードが検証に参加していることに気付くでしょう。 + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info ノンバリデータをバリデータに昇格する + +当然ノンバリデータは投票プロセスによってバリデータになることができますが、投票プロセス後にバリデータセットに含まれることに成功するためには、ノードを`--seal`フラグとともに再起動する必要があります。 + +::: + +## バリデータをバリデータセットから削除する {#removing-a-validator-from-the-validator-set} + +この操作はかなり簡単です。バリデータノードをバリデータセットから削除するには、このコマンドが過半数のバリデータノードに実行される必要があります。 + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info BLS公開鍵 + +BLS公開鍵はネットワークがBLSで実行されている場合のみ必要です。BLSモードで実行されていないネットワークに`--bls`は必要ありません。 +::: + +コマンド実行後、バリデータの数が減少したことを確認しましょう(このログの例では4から3)。 + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/ja-edge/consensus/pos-concepts.md b/archive/edge/ja-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..6e32cf9e11 --- /dev/null +++ b/archive/edge/ja-edge/consensus/pos-concepts.md @@ -0,0 +1,104 @@ +--- +id: pos-concepts +title: プルーフ・オブ・ステーク(PoS) +description: "プルーフ・オブ・ステーク(PoS)に関する説明とインストラクション。" +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## 概要 {#overview} + +このセクションではプルーフ・オブ・ステーク(PoS)で現在存在しているいくつかの概念のより優れた概要を提供することを目的にしています。Polygon Edgeの実装 + +Polygon Edgeのプルーフ・オブ・ステーク(PoS)の実装は既存のPoA IBFT実装の代替となることを意図しており、ノードオペレータにチェーンを開始する際にこの2つから容易に選択する能力を提供します。 + +## PoS機能 {#pos-features} + +プルーフ・オブ・ステークの実装の背後にあるコアロジックは、**[ステーキングスマートコントラクト。](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)** + +このコントラクトはPoSメカニズムPolygon Edgeチェーンが初期化されるたびにプリデプロイされ、アドレス`0x0000000000000000000000000000000000001001`で +ブロック`0`から使用可能です。 + +### エポック {#epochs} + +エポックはPolygon EdgeにPoSが追加されるとともに導入された概念です。 + +エポックはあるバリデータセットがブロックを生成できる特別のタイムフレーム(ブロック)とみなされます。その長さは変更可能であり、つまりノードオペレータがジェネシス生成中にエポックの長さを設定できるということです。 + +各エポックの末尾に、_エポックブロック_が作成され、そのイベント後に新しいエポックが開始されます。エポックブロックの詳細については[エポックブロック](/docs/edge/consensus/pos-concepts#epoch-blocks)セクションを参照してください。 + +バリデータセットは各エポックの終わりに更新されます。ノードはエポックブロックの作成中にステーキングスマートコントラクトからバリデータセットをクエリし、取得したデータをローカルストレージに保存します。このクエリと保存のサイクルは各エポックの最後に繰り返されます。 + +基本的に、これによりステーキングスマートコントラクトがバリデータセットのアドレスを完全にコントロールし、ノードに唯一の責任 - 最新のバリデータセット情報を取り込むエポック中にコントラクトをクエリすることを確実にします。これは個別のノードからバリデータセットを管理する責任を軽減します。 + +### ステーキング {#staking} + +アドレスは`stake`メソッドを呼び出し、トランザクションにステーク額の値を指定することで、ステーキングスマートコントラクトにファンドをステークすることができます。 + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +ステーキングスマートコントラクトにファンドをステークすることにより、アドレスはバリデータセットを入力することができ、したがってブロック生成プロセスに参加できるようになります。 + +:::info ステーキング用のしきい値 + +現在、バリデータセットを入力する際の最小しきい値は`1 ETH`ステーキングに設定されています。 + +::: + +### アンステーキング {#unstaking} + +ファンドをステークしたアドレスでは、**ステークしたすべてのファンドのアンステークをすぐに**行うことができます。 + +アンステーキングはステーキングスマートコントラクトの`unstake`メソッドを呼び出すことで行います。 + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +ファンドのアンステーク後、アドレスはステーキングスマートコントラクトのバリデータセットから削除され、次のエポック中はバリデータとみなされません。 + +## エポックブロック {#epoch-blocks} + +**エポックブロック**はPolygon EdgeのIBFTのPoS実装に導入される概念です。 + +実質的に、エポックブロックは**トランザクションを含まない**特別なブロックであり、**エポックの最後**にのみ発生します。例えば、ブロックに**設定**した場合、`50`ブロックは`50`ブロック`100``150`とみなされます。 + +これらは通常のブロック生産中には発生しない追加ロジックを実行するために使用されます。 + +最も重要なことは、これらはノードがステーキングスマートコントラクトから**最新のバリデータセット情報を取得する**必要があることを示しているということです。 + +エポックブロックでバリデータセットを更新した後、バリデータセットは(変更または変更なしで)ステーキングスマートコントラクトから最新の情報を取り込むまで、その後の`epochSize - 1`ブロックのために使用されます。 + +エポックの長さ(ブロック)は、特別なフラグ`--epoch-size`を使用することで、ジェネシスファイルを生成する際に修正できます: + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +エポックのデフォルトサイズはPolygon Edgeの`100000`ブロックです。 + +## コントラクトのプリデプロイメント {#contract-pre-deployment} + +Polygon Edgeは、_プリデプロイ_ +を[ステーキングスマートコントラクト](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)に行い、 +それは、アドレス`0x0000000000000000000000000000000000001001`への**ジェネシス生成**中に行われます。 + +これはEVMを実行することなく、スマートコントラクトのブロックチェーンステートを変更することで、パスイン設定値をジェネシスコマンドに使用することで行われます。 diff --git a/archive/edge/ja-edge/consensus/pos-stake-unstake.md b/archive/edge/ja-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..d05a669495 --- /dev/null +++ b/archive/edge/ja-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,158 @@ +--- +id: pos-stake-unstake +title: プルーフ・オブ・ステーク(PoS)の設定と使用 +description: "ステーク、アンステーク、その他のステーキング関連の手順。" +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## 概要 {#overview} + +このガイドでは、Polygon Edgeでプルーフ・オブ・ステーク(PoS)ネットワークを設定する方法、ノードがバリデータになるためにファンドをステークする方法、ファンドをアンステークする方法の詳細を説明します。 + +読み取り、通過することをお**勧め**します。[ローカル設定](/docs/edge/get-started/set-up-ibft-locally) +および[クラウド設定](/docs/edge/get-started/set-up-ibft-on-the-cloud)のセクションを、このPoSガイドに進む前によく読んで理解してください。これらのセクションはPolygon Edgeでプルーフ・オブ・オーソリティ―(PoA)クラスターを起動するために必要なステップを示します。 + +現在、ステーキングスマートコントラクト上にファンドをステークできるバリデータの数に制限はありません。 + +## ステーキングスマートコントラクト {#staking-smart-contract} + +ステーキングスマートコントラクトのレポジトリは[ここ](https://github.com/0xPolygon/staking-contracts)にあります。 + +ここには必要なテストスクリプト、ABIファイル、そして最も重要なステーキングスマートコントラクト自体があります。 + +## Nノードクラスターの設定 {#setting-up-an-n-node-cluster} + +Polygon Edgeでネットワークを設定する方法は +[ローカル設定](/docs/edge/get-started/set-up-ibft-locally) +と[クラウド設定](/docs/edge/get-started/set-up-ibft-on-the-cloud)セクションでカバーされています。 + +PoSとPoAクラスタの設定における**唯一の違い**はジェネシス生成の部分です。 + +**PoSクラスタのためにジェネシスファイルを生成する時、追加フラグが必要です`--pos`**: + +```bash +polygon-edge genesis --pos ... +``` + +## エポックの長さの設定 {#setting-the-length-of-an-epoch} + +エポックは[エポックブロック](/docs/edge/consensus/pos-concepts#epoch-blocks)セクションで詳細にカバーしています。 + +クラスター(ブロック)のエポックのサイズを設定するには、ジェネシスファイルの生成時に、追加フラグを指定します`--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +この値はジェネシスファイルにエポックサイズは`50`ブロックであるべきと指定します。 + +エポック(ブロック)のサイズのデフォルト値は`100000`です。 + +:::info エポックの長さを引き下げる + +[エポックブロック](/docs/edge/consensus/pos-concepts#epoch-blocks)セクションで示したように、エポックブロックはノード用にバリデータセットを更新するために使用されます。 + +ブロック単位の(`100000`)エポックの長さのデフォルトは、バリデータセットの更新までに時間がかかる可能性があります。新しいブロックが追加されるのに~2秒かかることを考慮すると、バリデータセットが変更されるのに~55.5時間かかる可能性があります。 + +エポックの長さにより低い値を設定すると、バリデータセットが確実により頻繁に更新されます。 +::: + +## ステーキングスマートコントラクトスクリプトの使用 {#using-the-staking-smart-contract-scripts} + +### 前提条件 {#prerequisites} + +ステーキングスマートコントラクトのレポジトリはHardhatプロジェクトであり、これはNPMを必要とします。 + +これを正しく初期化するために、以下をメインディレクトリ内で実行します: + +```bash +npm install +```` + +### 提供されたヘルパースクリプトを設定する {#setting-up-the-provided-helper-scripts} + +デプロイされたステーキングスマートコントラクトとのやり取り用のスクリプトは[ステーキングスマートコントラクトのレポジトリ](https://github.com/0xPolygon/staking-contracts)にあります。 + +スマートコントラクトのレポジトリの場所に次のパラメータを持つ`.env`ファイルを作成します: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +パラメータは次のとおりです: + +* **JSONRPC_URL** - ノードを実行するJSON-RPCエンドポイント +* **PRIVATE_KEYS** - ステーカーアドレスの秘密鍵 +* **STAKING_CONTRACT_ADDRESS** - ステーキングスマートコントラクトのアドレス( +デフォルト`0x0000000000000000000000000000000000001001`) +* **BLS_PUBLIC_KEY** - ステーカーのBLS公開鍵。ネットワークがBLSで実行している場合にのみ必要 + +### ステーキングファンド {#staking-funds} + +:::info ステーキングアドレス + +ステーキングスマートコントラクトはアドレス`0x0000000000000000000000000000000000001001`にプリデプロイされます。 + +ステーキングメカニズムとのあらゆる種類のやり取りは指定されたアドレスにあるステーキングスマートコントラクトを通じて行われます。 + +ステーキングスマートコントラクトの詳細については、以下を参照してください +**[ステーキングスマートコントラクト](/docs/edge/consensus/pos-concepts#contract-pre-deployment)**セクション。 + +::: + +バリデータセットの一部になるためには、アドレスはしきい値を上回る額のファンドをステークする必要があります。 + +現在、バリデータセットの一部になるためのデフォルトのしきい値は`1 ETH`です。 + +ステーキングはステーキングスマートコントラクトの`stake`メソッドを呼び出し、`>= 1 ETH`値を指定することで開始できます。 + +`.env`ファイル([前セクション](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts)で触れられたもの)を設定し、チェーンをPoSモードで起動した後、ステーキングはスターキングスマートコントラクトのレポジトリ内で次のコマンドで実行することができます: + +```bash +npm run stake +``` + +`stake`Hardhatスクリプトは`1 ETH`のデフォルト額をステークしますが、これは`scripts/stake.ts`ファイルを修正することで変更できます。 + +ステークされているファンドが`>= 1 ETH`である場合、ステーキングスマートコントラクト上のバリデータセットは更新され、アドレスは次のエポックの開始時からバリデータセットの一部となります。 + +:::info BLS鍵の登録 + +ネットワークがBLSモードで実行されている場合、ノードがバリデータになるためには、ステーキング後にそのBLS公開鍵を登録する必要があります。 + +これは、次のコマンドで実行することができます: + +```bash +npm run register-blskey +``` +::: + +### ファンドのアンステーク {#unstaking-funds} + +ステークを持つアドレスは、**すべてのファンドを**同時にアンステークできます。 + +`.env`ファイル([前セクション](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts)で触れられたもの)を設定し、チェーンをPoSモードで起動した後、アンステーキングはステーキングスマートコントラクトのレポジトリの次のコマンドで実行することができます: + +```bash +npm run unstake +``` + +### ステーカーのリストの取得 {#fetching-the-list-of-stakers} + +ファンドをステークするすべてのアドレスはステーキングスマートコントラクトに保存されます。 + +`.env`ファイル([前セクション](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts)で触れられたもの)を設定し、チェーンをPoSモードで起動した後、バリデータのリストはステーキングスマートコントラクトのレポジトリ内で次のコマンドで取得できます。 + +```bash +npm run info +``` diff --git a/archive/edge/ja-edge/faq/Contracts.md b/archive/edge/ja-edge/faq/Contracts.md new file mode 100644 index 0000000000..65e04ff8b4 --- /dev/null +++ b/archive/edge/ja-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: スマートコントラクトのよくある質問 +description: "Polygon Edgeのスマートコントラクトに関するよくある質問" +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## Polygon Edgeはスマートコントラクトをサポートしていますか? {#does-polygon-edge-support-smart-contracts} + +はい。Polygon EdgeネットワークはEthereumと互換性のあるブロックチェーンであるため、Ethereumでデプロイ可能なスマートコントラクトはPolygon Edgeチェーンでもデプロイ可能です。 + +## デプロイ後にPoSのステーキングコントラクトロジックを更新することは可能ですか? {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +今のところ、PoSネットワークを起動した後は、ステーキングコントラクトロジックを変更することはできませんが、これはジェネシスファイルの一部であるためです。したがって、たとえばバリデータの最小数/最大数を変更することはできません。できることはステークまたはアンステーク、バリデータの追加または削除です。 + + + diff --git a/archive/edge/ja-edge/faq/Gas.md b/archive/edge/ja-edge/faq/Gas.md new file mode 100644 index 0000000000..d92471d8db --- /dev/null +++ b/archive/edge/ja-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: ガスに関するよくある質問 +description: "Polygon Edgeのガスに関するよくある質問" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## ガス価格の最小化をどのように行うのですか? {#how-to-enforce-a-minimum-gas-price} +サーバーコマンドで提供される`--price-limit`フラグを使用することができます。これにより設定した価格制限以上のガスを持つトランザクションのみをノードが受け付けるようなります。ネットワーク全体でこれを確実にするには、すべてのノードが同じ価格制限を持つことを確認する必要があります。 + + +## ガス手数料0で取引することはできますか? {#can-you-have-transactions-with-0-gas-fees} +はい、可能です。ノードが執行するデフォルトの価格制限は`0`、つまりノードはガス価格が`0`に設定されているトランザクションを受け入れることを意味します。 + +## ガス(ネイティブ)トークンの総供給を設定する方法は? {#how-to-set-the-gas-native-token-total-supply} + +前払いされた残高を`--premine flag`を使用してアカウント(アドレス)に設定することができます。これはジェネシスファイルからの設定であり、後で変更できないことに注意してください。 + +`--premine flag`を使用する方法の例: + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +これは前払い残高1000ETHを0x3956E90e632AEbBF34DEB49b71c28A83Bc029862に設定します(引数からの額はweiベースです)。 + +ガストークンの前払い額は総供給となります。ネイティブ通貨(ガストークン)の額を後でミントすることはできません。 + +## EdgeはERC-20をガストークンとしてサポートしていますか? {#does-edge-support-erc-20-as-a-gas-token} + +EdgeはERC-20をガストークンとしてサポートしていません。ガスとしてサポートしているのはEdgeのネイティブ通貨のみです。 + +## ガス制限を増やす方法は? {#how-to-increase-the-gas-limit} + +Polygon Edgeでガス制限を増やすための2つのオプションがあります: +1. チェーンをワイプし、ジェネシスファイルで最大uint64値に増加`block-gas-limit`します。 +2. すべてのノードでガス制限を増やすために、高い値を持つ`--block-gas-target`フラグを使用します。これにはノード再起動が必要です。詳細な説明は[こちらです。](/docs/edge/architecture/modules/txpool/#block-gas-target) \ No newline at end of file diff --git a/archive/edge/ja-edge/faq/Tokens.md b/archive/edge/ja-edge/faq/Tokens.md new file mode 100644 index 0000000000..424f6b7477 --- /dev/null +++ b/archive/edge/ja-edge/faq/Tokens.md @@ -0,0 +1,22 @@ +--- +id: tokens +title: トークンのよくある質問 +description: "Polygon Edgeトークンに関するよくある質問" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## Polygon EdgeはEIP-1559をサポートしていますか? {#does-polygon-edge-support-eip-1559} +現時点でPolygon EdgeはEIP-1559をサポートしていません。 + +## 通貨(トークン)シンボルをどのように設定しますか? {#how-to-set-the-currency-token-symbol} + +トークンシンボルは単にUIのものなので、ネットワークのどこででも設定またはハードコードすることはできません。しかし、たとえばMetamaskなど、ネットワークをウォレットに追加する時に変更できます。 + +## チェーンが停止した場合、トランザクションはどうなりますか。 {#what-happens-to-transactions-when-a-chain-halts} + +処理されていないトランザクションはすべて、TxPool(キューのエンキューまたはプロモーション)内にあります。チェーンが停止した場合(すべてのブロック制限が停止する)、これらのトランザクションはブロックにすることはありません。
チェーンが停止する場合に限ります。ノードが停止または再起動された場合、実行されていないトランザクションがまだTxPoolに存在している場合、黙って削除されます。
ノードが再起動される必要があるため、破損変更が導入された場合にもトランザクションが起こります。 diff --git a/archive/edge/ja-edge/faq/Validators.md b/archive/edge/ja-edge/faq/Validators.md new file mode 100644 index 0000000000..ff7fea2df1 --- /dev/null +++ b/archive/edge/ja-edge/faq/Validators.md @@ -0,0 +1,85 @@ +--- +id: validators +title: バリデータに関するよくある質問 +description: "Polygon Edgeバリデータに関するよくある質問" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## バリデータの追加/削除方法は? {#how-to-add-remove-a-validator} + +### PoA {#poa} +バリデータの追加/削除は、投票によって行われます。[ここに](/docs/edge/consensus/poa)詳細なガイドがあります。 + +### PoS {#pos} +[ここ](/docs/edge/consensus/pos-stake-unstake)に、ノードがバリデータになるようにファンドをステークする方法と、アンステークする(バリデータを削除する)方法についてのガイドがあります。 + +以下にご注意ください: +- ジェネシスフラグ`--max-validator-count`を使用して、バリデータセットに参加できるステーカーの最大数を設定することができます。 +- ジェネシスフラグ`--min-validator-count `を使用して、バリデータセットに参加するために必要な最小ステーカー数を設定できます(デフォルトでは`1`)。 +- 最大バリデータ数に達した場合、既存のバリデータをセットから削除するまで、別のバリデータを追加できません(新しいバリデータのステーク額が大きい場合でも関係ありません)。バリデータを削除する場合、残りのバリデータの数は`--min-validator-count`を下回ることはできません。 +- バリデータになるためのデフォルトのしきい値は、ネイティブネットワーク(ガス)通貨`1`単位です。 + + + +## バリデータにはどのくらいのディスク領域が推奨されますか? {#how-much-disk-space-is-recommended-for-a-validator} + +保守的に見積もったランウェイとして100Gから始めること、その後ディスクを確実に拡大できるようにしておくことをお勧めします。 + + +## バリデータの数に制限はありますか? {#is-there-a-limit-to-the-number-of-validators} + +技術的な制限について話している場合、Polygon Edgeはネットワーク内のノード数の上限を明示的に設定していません。ノードごとに接続キャップ(インバウンド/アウトバウンド接続数)を設定できます。 + +実際的な制限について話すと、100ノードクラスタでは、10ノードクラスタよりもパフォーマンスが低下します。クラスタ内のノード数を増やすことで、通信の複雑さが増し、一般的にはネットワークの負荷が増加します。すべては、実行しているネットワークの種類と、使用しているネットワークトポロジの種類によって異なります。 + +## PoAからPoSへの切り替え方法は? {#how-to-switch-from-poa-to-pos} + +PoAはデフォルトのコンセンサスメカニズムです。新しいクラスタをPoSに切り替えるには、ジェネシスファイルを生成するときに`--pos`フラグを追加する必要があります。クラスタを実行している場合は、スイッチの作成方法を[ここで](/docs/edge/consensus/migration-to-pos)確認できます。コンセンサスのメカニズムと設定に関して必要なすべての情報は、[コンセンサスセクション](/docs/edge/consensus/poa)で確認できます。 + +## 破壊的変更があった場合、ノードを更新するにはどうすればよいですか? {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +この手順の詳細なガイドは[ここ](/docs/edge/validator-hosting#update)にあります。 + +## PoS Edgeの最小ステーキング額は設定可能ですか? {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +デフォルトの最小ステーキング額は`1 ETH`で、設定はできません。 + +## JSON RPCコマンド`eth_getBlockByNumber`と`eth_getBlockByHash`がマイナーのアドレスを返さないのはなぜですか? {#not-return-the-miner-s-address} + +現在Polygon Edgeで使用されているコンセンサスはIBFT2.0であり、代わりにCliquePoA([etherum/EIPs#225](https://github.com/ethereum/EIPs/issues/225))で説明されている投票メカニズムに基づいています。 + +EIP-225(Clique PoA)を見てみると、これは、`miner`(別名`beneficiary`)が何に使用されているかを説明する関連部分です: + +
+次のように、ethashヘッダーフィールドを再利用します: +
    +
  • 受益者/マイナー:許可された署名者のリストの変更を提案するアドレス。
  • +
      +
    • 通常はゼロで満たされており、投票中にのみ修正されます。
    • +
    • それにもかかわらず、投票メカニズムに関する実装の複雑さを避けるために、任意の値が許可されます(非署名者の投票のような無意味な値であっても)。
    • +
    • チェックポイント(つまり、エポック遷移)ブロックにゼロを入力する必要があります。
    • +
    + +
+ +
+ +したがって、`miner`フィールドは、ブロックのプロポーザを表示するのではなく、特定のアドレスに対する投票を提案するために使用されます。 + +ブロックのプロポーザに関する情報は、ブロックヘッダー内のRLPエンコードされたイスタンブール追加データフィールドのシールフィールドから公開鍵を回復することによって見つけることができます。 + +## ジェネシスのどの部分と値を安全に変更できますか。 {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +既存のgenesis.jsonファイルの手動コピーを作成してから編集してください。また、genesis.jsonファイルを編集する前にチェーン全体を停止する必要があります。ジェネシスファイルが変更されると、新しいバージョンがバリデータとバルディエータノードに分散する必要があります。 + +::: + +**ジェネシスファイルのブートノードセクションのみを安全に変更することができ、**リストからブートノードを追加または削除することができます。 \ No newline at end of file diff --git a/archive/edge/ja-edge/get-started/cli-commands.md b/archive/edge/ja-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..7b4d67ecd1 --- /dev/null +++ b/archive/edge/ja-edge/get-started/cli-commands.md @@ -0,0 +1,2213 @@ +--- +id: cli-commands +title: CLIコマンド +description: "Polygon EdgeのCLIコマンドとコマンドフラグのリストです。" +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +このセクションでは、現在のPolygon Edgeのコマンド、コマンドフラグとこれらがどのように使用されるかを詳しく説明します。 + +:::tip JSON出力サポート + +`--json`フラグは一部のコマンドでサポートされます。 このフラグはコマンドに出力をJSON形式で表示するように指示します + +::: + +## スタートアップコマンド {#startup-commands} + +| **コマンド** | **説明** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| server | すべてのモジュールをまとめてブートストラップすることによりブロックチェーンクライアントを開始するデフォルトコマンドです。 | +| genesis | *genesis.json*ファイルを生成します、これはクライアントを起動する前に定義済みのチェーンステートを設定するために使用されます。ジェネシスファイルの構造は下記に説明しています | +| ジェネシスプレデプロイ | 新鮮なネットワークのためのスマートコントラクトを事前に展開します。 | + +### サーバフラグ {#server-flags} + + +| **すべてのサーバーフラグ** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [prometheus](/docs/edge/get-started/cli-commands#prometheus) | [block-gas-target](/docs/edge/get-started/cli-commands#block-gas-target) | +| [max-peers](/docs/edge/get-started/cli-commands#max-peers) | [max-inbound-peers](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [max-outbound-peers](/docs/edge/get-started/cli-commands#max-outbound-peers) | [max-enqueued](/docs/edge/get-started/cli-commands#max-enqueued) | +| [log-level](/docs/edge/get-started/cli-commands#log-level) | [log-to](/docs/edge/get-started/cli-commands#log-to) | +| [chain](/docs/edge/get-started/cli-commands#chain) | [join](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [価格制限](/docs/edge/get-started/cli-commands#price-limit) | [maxスロット](/docs/edge/get-started/cli-commands#max-slots) | +| [設定](/docs/edge/get-started/cli-commands#config) | [secrets-config](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-interval](/docs/edge/get-started/cli-commands#dev-interval) | +| [no-discover](/docs/edge/get-started/cli-commands#no-discover) | [restore](/docs/edge/get-started/cli-commands#restore) | +| [block-time](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +Polygon Edgeのクライアントデータの保存に使用されるデータディレクトリを指定するのに使用されます。デフォルト: `./test-chain`。 + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +JSON-RPCサービスのアドレスとポートを設定する`address:port`。 +ポートだけが`:10001`と定義されている場合、すべてのインターフェース`0.0.0.0:10001`に結合されます。 +省略された場合はサービスはデフォルト`address:port`に結合されます。 +デフォルトアドレス:`0.0.0.0:8545`。 + +--- + +####

json-rpc-block-range-limit + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +fromBlock/toBlockの値(例:eth_getLogs)を含むjson-rpcリクエストの実行時に考慮すべき最大ブロック範囲を設定します。デフォルト:`1000`。 + +--- + +####

json-rpc-batch-request-limit + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +json-rpcバッチリクエストを処理する際に考慮する最大の長さを設定します。デフォルト: `20`。 + +--- + +####

grpc + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +gRPCサービスのアドレスとポートを設定する`address:port`。 +デフォルトアドレス:`127.0.0.1:9632`。 + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +libp2pサービスのアドレスとポートを設定する`address:port`。 デフォルトアドレス:`127.0.0.1:1478`。 + +--- + +####

prometheus + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +prometheusサーバ`address:port`のアドレスとポートを設定します。 +ポートだけが`:5001`と定義されている場合、サービスはすべてのインターフェース`0.0.0.0:5001`に結合されます。 +省略された場合サービスは開始されません。 + +--- + +####

block-gas-target + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +チェーン用の目標ブロックガス制限を設定します。デフォルト(執行されていない): `0`。 + +ブロックガスの目標に関する詳しい説明は[Txセクション](/docs/edge/architecture/modules/txpool#block-gas-target)で確認できます。 + +--- + +####

max-peers + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +クライアントの最大ピアカウントを設定します。デフォルト: `40`。 + +ピア制限は`max-peers`または`max-inbound/outbound-peers`フラグを使用して指定する必要があります。 + +--- + +####

max-inbound-peers + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +クライアンドの最大インバウンドピアカウントを設定します。`max-peers`が設定されている場合、max-inbound-peer制限は以下の式を使用して計算されます。 + +`max-inbound-peer = InboundRatio * max-peers`、そこでは`InboundRatio`が`0.8`となります。 + +--- + +####

max-outbound-peers + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +クライアントの最大アウトバウンドピアカウントを設定します。`max-peers`が設定されている場合、max-outbound-peerカウントは以下の式を使用して計算されます。 + +`max-outbound-peer = OutboundRatio * max-peers`、そこでは`OutboundRatio`が`0.2`となります。 + +--- + +####

max-enqueued + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +アカウントごとのエンキューされたトランザクションの最大数を設定します。デフォルト:`128`。 + +--- + +####

log-level + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +コンソール出力のログレベルを設定します。デフォルト: `INFO`。 + +--- + +####

log-to + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +サーバコマンドからのすべてのログ出力を保持するログファイル名を定義します。デフォルトでは、すべてのサーバログがコンソール(stdout)に出力されますが、フラグが設定されている場合、サーバコマンドを実行している時はコンソールには出力されません。 + +--- + +####

chain + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +チェーン開始に使用されるジェネシスファイルを設定します。デフォルト: `./genesis.json`。 + +--- + +####

join + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +結合すべきピアのアドレスを指定します。 + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +ピアによって見ることができるため、ポートなしの外部IPアドレスを設定します。 + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +ホストDNSアドレスを設定します。これは外部DNSを宣伝するために使用できます。`dns`、`dns4`、`dns6`をサポートします。 + +--- + +####

価格制限 + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +プールへの受け入れを強制するために、最小ガス価格の制限を設定します。デフォルト:`1`。 + +--- + +####

maxスロット + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +プール内の最大スロット数を設定します。デフォルト: `4096`。 + +--- + +####

設定 + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +CLI設定へのパスを指定します。`.json`をサポートします。 + +--- + +####

secrets-config + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +シークレットマネージャ設定ファイルへのパスを設定します。Hashicorp Vault、AWS SSM、GCPシークレットマネージャ用に使用されます。省略された場合、ローカルFSシークレットマネジャーが使用されます。 + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +クライアントを開発モードに設定します。デフォルト:`false`。devモードでは、ピアディスカバリーがデフォルトで無効になっています。 + +--- + +####

dev-interval + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +クライアントの開発通知間隔を秒単位で設定します。デフォルト:`0`。 + +--- + +####

no-discover + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +クライアントが他のピアを発見することを防ぎます。デフォルト:`false`。 + +--- + +####

restore + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +指定されたアーカイブファイルからブロックを復元します。 + +--- + +####

block-time + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +ブロック時間を秒単位で設定します。デフォルト:`2` + +--- + +####

access-control-allow-origins + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +JSON-RPCリクエストからのレスポンスを共有できるように許可ドメインを設定します。 +複数のドメインを承認するために、複数のフラグ`--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"`を追加します。 +省略された場合、Access-Control-Allow-Originsヘッダーは`*`に設定され、すべてのドメインが許可されます。 + +--- + +### ジェネシスフラグ {#genesis-flags} +| **すべてのジェネシスフラグ** | +|---------------------------------------|---------------------------------------------| +| [dir](/docs/edge/get-started/cli-commands#dir) | [名前](/docs/edge/get-started/cli-commands#name) | +| [pos](/docs/edge/get-started/cli-commands#pos) | [epoch-size](/docs/edge/get-started/cli-commands#epoch-size) | +| [premine](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [ibft-validator-type](/docs/edge/get-started/cli-commands#ibft-validator-type) | [ibft-validators-prefix-path](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [ibft-validator](/docs/edge/get-started/cli-commands#ibft-validator) | [block-gas-limit](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [consensus](/docs/edge/get-started/cli-commands#consensus) | [bootnode](/docs/edge/get-started/cli-commands#bootnode) | +| [max-validator-count](/docs/edge/get-started/cli-commands#max-validator-count) | [min-validator-count](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

dir + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +Polygon Edgeのジェネシスデータ用にディレクトリを設定します。デフォルト:`./genesis.json`。 + +--- + +####

名前 + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +チェーン名を設定します。デフォルト:`polygon-edge`。 + +--- + +####

pos + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +クライアントはプルーフ・オブ・ステークIBFTを使用する必要があることを示すフラグを設定します。フラグが提供されていないまたは`false`の場合のデフォルトはプルーフ・オブ・オーソリティです。 + +--- + +####

epoch-size + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +チェーンのエポックサイズを設定します。デフォルト`100000`。 + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +前払いされた口座と残高を`address:amount`のフォーマットで設定します。 +額は10進数または16進数に設定できます。デフォルトの事前登録残高:(`0xD3C21BCECCEDA1000000`100万ネイティブ通貨トークン)。 + +--- + +####

chainid + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +チェーンのIDを設定します。デフォルト:`100`。 + +--- + +####

ibft-validator-type + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +ブロックヘッダの検証モードを指定します。可能な値:`[ecdsa, bls]`。デフォルト:`bls`。 + +--- + +####

ibft-validators-prefix-path + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +バリデータフォルダディレクトリのプレフィックスパスです。フラグ`ibft-validator`が省略された場合に必要になります。 + +--- + +####

ibft-validator + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +渡されたアドレスをIBFTバリデータとして設定します。フラグ`ibft-validators-prefix-path`が省略された場合に必要になります。 +1. ネットワークがECDSAで実行されている場合、フォーマットは`--ibft-validator [ADDRESS]`です。 +2. ネットワークがBLSで実行されている場合、フォーマットは`--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]`です。 + +--- + +####

block-gas-limit + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +ブロック内の全操作で使用されるガスの最大数を指します。デフォルト:`5242880`。 + +--- + +####

consensus + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +コンセンサスプロトコルを設定します。デフォルト:`pow`。 + +--- + +####

bootnode + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +p2pディスカバリーブートストラップ用のMultiaddr URLです。このフラグは複数回使用することができます。 +IPアドレスの代わりに、ブートノードのDNSアドレスを提供することも可能です。 + +--- + +####

max-validator-count + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +PoSコンセンサスで設定されたバリデータセットに参加できる最大ステーカー数です。 +この数字は、MAX_SAFE_INTEGER(2^53 - 2)値を超えることはできません。 + +--- + +####

min-validator-count + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +PoSコンセンサスで設定されたバリデータセットに参加する必要がある最低限のステーカー数です。この数はmax-validator-countの値を超えることはできません。デフォルトは1です。 + +--- + +### genesisの予備展開フラグ {#genesis-predeploy-flags} + +

artifacts-path

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +`abi`コントラクトアーティファクトJSONへのパスを設定`bytecode`します。`deployedBytecode` + +--- + +

chain

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +更新する`genesis.json`ファイルへのパスを設定します。デフォルト`./genesis.json`。 + +--- + +

コンストラクターargs

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +Smart Contractコンストラクターの引数を設定します。これらの引数をどのように見えるかについて詳しいガイドは、[事前展開の記事](/docs/edge/additional-features/predeployment)を参照してください。 + +--- + +

事前デプロイアドレス

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +事前デプロイするアドレスを設定します。デフォルト`0x0000000000000000000000000000000000001100`。 + +--- + + +## オペレータコマンド {#operator-commands} + +### ピアコマンド {#peer-commands} + +| **コマンド** | **説明** | +|------------------------|-------------------------------------------------------------------------------------| +| peers add | 新しいピアをそのlibp2pアドレスを使用して追加します。 | +| peers list | クライアントがlibp2pを通じて接続されているすべてのピアのリストを表示します。 | +| peers status | libp2pアドレスを使用して、ピアリストから特定のピアのステータスを返します。 | + +

ピア追加フラグ

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +multiaddr形式のピアのlibp2pアドレスです。 + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +gRPC APIのアドレス。デフォルト:`127.0.0.1:9632`。 + +

ピアリストフラグ

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +gRPC APIのアドレス。デフォルト:`127.0.0.1:9632`。 + +

ピアステータスフラグ

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +p2pネットワーク内の特定のピアのlibp2pノードID。 + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +gRPC APIのアドレス。デフォルト:`127.0.0.1:9632`。 + +### IBFTコマンド {#ibft-commands} + +| **コマンド** | **説明** | +|------------------------|-------------------------------------------------------------------------------------| +| ibft snapshot | IBFTスナップショットを返します | +| ibft candidates | 提案された候補者の現在のセット、およびまだ含まれてない候補者をクエリします。 | +| ibft propose | バリデータセットについて追加/削除する新しい候補者を提案します。 | +| ibft status | IBFTクライアントの全体的なステータスを返します | +| ibft switch | IBFTタイプを切り替えるためにgenesis.jsonファイルにフォーク設定を追加 | +| ibft quorum | ブロック番号を指定し、その後コンセンサスに到達するために最適なクォーラムサイズメソッドを使用します。 | + + +

ibftスナップショットフラグ

+ +

number

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +スナップショットのブロックの高さ(数)。 + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +gRPC APIのアドレス。デフォルト:`127.0.0.1:9632`。 + +

ibft候補フラグ

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +gRPC APIのアドレス。デフォルト:`127.0.0.1:9632`。 + +

ibft提案フラグ

+ +

vote

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +バリデータセットへの変更を提案します。可能な値:`[auth, drop]`。 + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +投票するアカウントのアドレス。 + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +投票するアカウントのBLS公開鍵は、BLSモードでのみ必要です。 + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +gRPC APIのアドレス。デフォルト:`127.0.0.1:9632`。 + +

ibftステータスフラグ

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +gRPC APIのアドレス。デフォルト:`127.0.0.1:9632`。 + +

ibftスイッチフラグ

+ +

chain

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +更新するジェネシスファイルを指定します。デフォルト:`./genesis.json`。 + +--- + +

タイプ

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +切り替えるIBFTタイプを指定します。可能な値:`[PoA, PoS]`。 + +--- + +

deployment

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +コントラクトデプロイメントの高さを指定します。PoSでのみ利用できます。 + +--- + +

from

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +ブロックヘッダの検証モードを指定します。可能な値:`[ecdsa, bls]`。デフォルト:`bls`。 + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +新しいバリデータのディレクトリのパスをプレフィックスします。フラグ`ibft-validator`が省略された場合に必要になります。IBFTモードがPoA(`--pos`フラグは省略)である時にのみ使用できます。 + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +渡されたアドレスをフォークの後に使用するIBFTバリデータとして設定します。フラグ`ibft-validators-prefix-path`が省略された場合に必要になります。PoAモードでのみ使用できます。 +1. ネットワークがECDSAで実行されている場合、フォーマットは`--ibft-validator [ADDRESS]`です。 +2. ネットワークがBLSで実行されている場合、フォーマットは`--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]`です。 + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +PoSコンセンサスで設定されたバリデータセットに参加できる最大ステーカー数です。 +この数字は、MAX_SAFE_INTEGER(2^53 - 2)値を超えることはできません。 + +--- + +

min-validator-count

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +PoSコンセンサスで設定されたバリデータセットに参加する必要がある最低限のステーカー数です。この数はmax-validator-countの値を超えることはできません。デフォルトは1です。 + +フォークの最初の高さを指定します。 + +--- + +

ibftクォーラムフラグ

+ +

from

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +クォーラム計算をQuorumOptimalに切り替える高さは、数式`(2/3 * N)`を使用しますが、`N`はバリデータノードの数です。これは下位互換性のため、つまり一定のブロックの高さまでについてクォーラムレガシー計算を使用したチェーンだけのためであることに注意してください。 + +--- + +

chain

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +更新するジェネシスファイルを指定します。デフォルト:`./genesis.json`。 + +### トランザクションプールコマンド {#transaction-pool-commands} + +| **コマンド** | **説明** | +|------------------------|--------------------------------------------------------------------------------------| +| txpool status | プール内のトランザクション数を返します。 | +| txpool subscribe | トランザクションプール内のイベントをサブスクライブします | + +

txpoolステイタスフラグ

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +gRPC APIのアドレス。デフォルト:`127.0.0.1:9632`。 + +

txpoolサブスクライブフラグ

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +gRPC APIのアドレス。デフォルト:`127.0.0.1:9632`。 + +--- + +

promoted

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +TxPool内のプロモーションされたTxイベントをサブスクライブします。 + +--- + +

dropped

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +TxPoolでトロップしたTxイベントをサブスクライブします。 + +--- + +

demoted

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +TxPool内の降格されたtxイベントをサブスクライブします。 + +--- + +

added

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +TxPoolに追加されたTxイベントをサブスクライブします。 + +--- + +

enqueued

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +アカウントキューにエンキューされたtxイベントをサブスクライブします。 + +--- + +### ブロックチェーンコマンド {#blockchain-commands} + +| **コマンド** | **説明** | +|------------------------|-------------------------------------------------------------------------------------| +| status | クライアントのステータスを返します。回答の詳細は以下にあります | +| monitor | ブロックチェーンイベントストリームをサブスクライブします。回答の詳細は以下にあります | +| version | クライアントの現在のバージョンを返します。 | + +

ステータスフラグ

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +gRPC APIのアドレス。デフォルト:`127.0.0.1:9632`。 + +

モニターフラグ

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +gRPC APIのアドレス。デフォルト: `127.0.0.1:9632`。 + +--- +

バージョンコマンド

+ + + + + + version + + + + +リリースバージョン、gitブランチ、コミットハッシュ、ビルド時間を表示します。 + +## シークレットコマンド {#secrets-commands} + +| **コマンド** | **説明** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| secrets init | 対応するシークレットマネージャへの秘密鍵を初期化します。 | +| secrets generate | Polygon Edgeで解析することができるシークレットマネージャ設定ファイルを生成します。 | +| 秘密の出力 | BLS公開鍵アドレス、バリデータ公開鍵アドレス、および参照のためにノードIDを印刷します。 | + +### シークレット初期化フラグ {#secrets-init-flags} + +

設定

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +シークレットマネージャ設定ファイルへのパスを設定します。Hashicorp Vault用に使用されます。省略された場合、ローカルFSシークレットマネジャーが使用されます。 + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +ローカルFSを使用する場合はPolygon Edgeデータ用のディレクトリを設定します。 + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +ECDSA鍵を生成するかどうかを示すフラグを設定します。デフォルト:`true`。 + +--- + +

network

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +Libp2pネットワーク鍵を生成するかどうかを示すフラグを設定します。デフォルト:`true`。 + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +BLS鍵を生成するかどうかを示すフラグを設定します。デフォルト:`true`。 + +### シークレット生成フラグ {#secrets-generate-flags} + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +シークレットマネージャ設定ファイル用のディレクトリを設定します。デフォルト: `./secretsManagerConfig.json` + +--- + +

タイプ

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +シークレットマネージャのタイプを指定します[`hashicorp-vault`]。 デフォルト:`hashicorp-vault` + +--- + +

token

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +サービスのアクセストークンを指定します。 + +--- + +

server-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +サービスのサーバURLを指定します。 + +--- + +

名前

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +オンサービス記録保存用のノード名を指定します。デフォルト:`polygon-edge-node` + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Hashicorp Vaultのシークレットマネージャに使用されるネームスペースを指定します。デフォルト:`admin` + +### secretsがフラグを出力する {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +BLS公開鍵のみを出力するかどうかを示すフラグを設定します。デフォルト:`true` + +--- + +

設定

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +シークレットマネージャ設定ファイルへのパスを設定します。省略された場合、ローカルFSシークレットマネジャーが使用されます。 + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +ローカルFSを使用する場合はPolygon Edgeデータ用のディレクトリを設定します。 + +--- + +

node-id

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +ネットワークノードIDのみを出力するかどうかを示すフラグを設定します。デフォルト:`true` + +--- + +

バリデータ

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +バリデータアドレスだけを出力するかどうかを示すフラグを設定します。デフォルト:`true` + +--- + +## レスポンス {#responses} + +### ステータスレスポンス {#status-response} + +レスポンスオブジェクトはプロトコルバッファを使用して定義されます。 +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### モニターレスポンス {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## ユーティリティ {#utilities} + +### ホワイトリストコマンド {#whitelist-commands} + +| **コマンド** | **説明** | +|------------------------|-------------------------------------------------------------------------------------| +| whitelist show | ホワイトリスト情報を表示します | +| whitelist deployment | スマートコントラクトのデプロイメントホワイトリストを更新します。 | + +

ホワイトリスト表示

+ + + + + whitelist show + + + + +ホワイトリスト情報が表示されます。 + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +更新するジェネシスファイルを指定します。デフォルト:`./genesis.json`。 + +--- + +

ホワイトリストデプロイメント

+ +

chain

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +更新するジェネシスファイルを指定します。デフォルト:`./genesis.json`。 + +--- + +

add

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +コントラクトデプロイメントホワイトリストに新しいアドレスを追加します。コントラクトデプロイメントホワイトリスト内のアドレスだけがコントラクトをデプロイできます。空の場合、すべてのアドレスがコントラクトデプロイメントを実行できます。 + +--- + +

remove

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +コントラクトデプロイメントホワイトリストからアドレスを削除します。コントラクトデプロイメントホワイトリスト内のアドレスだけがコントラクトをデプロイできます。空の場合、すべてのアドレスがコントラクトデプロイメントを実行できます。 + +--- + +### バックアップフラグ {#backup-flags} + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +gRPC APIのアドレス。デフォルト:`127.0.0.1:9632`。 + +--- + +

out

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +保存するアーカイブファイルのパス。 + +--- + +

from

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +アーカイブ内のブロックの最初の高さ。デフォルト:0。 + +--- + +

to

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +アーカイブ内のブロックの最後の高さ。 + +--- + +## ジェネシステンプレート {#genesis-template} +ジェネシスファイルはブロックチェーンの当初のステートを設定するために使用する必要があります(例、一部のアカウントが開始用の残高を持っている必要がある場合)。 + +次の *./genesis.json* ファイルが生成されます: +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### データディレクトリ {#data-directory} + +*data-dir*フラグを実行する時、**test-chain**フォルダが生成されます。 +フォルダ構造は次のサブフォルダから構成されます: +* **blockchain** - ブロックチェーンオブジェクトのLevelDBを保存する +* **trie** - MerkleトライのLevelDBを保存する +* **keystore** - クライアントの秘密鍵を保存するこれは、libp2p秘密鍵とシーリング/バリデータ秘密鍵が含まれます。 +* **consensus** - クライアントが作業中に必要となりうるすべてのコンセンサス情報を保存します。 + +## リソース {#resources} +* **[プロトコルバッファ](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/ja-edge/get-started/installation.md b/archive/edge/ja-edge/get-started/installation.md new file mode 100644 index 0000000000..ca11eecf53 --- /dev/null +++ b/archive/edge/ja-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: インストール +description: "Polygon Edgeをインストールする方法" +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +より適したインストールの方法を参照してください。 + +事前構築されたリリースを使用し、提供されたチェックサムを確認することを推奨します。 + +## 事前構築されたリリース {#pre-built-releases} + +リリースのリストについては、[GitHubリリース](https://github.com/0xPolygon/polygon-edge/releases)ページを参照してください。 + +Polygon Edgeには、DarwinとLinuxのクロスコンパイルされたAMD64/ARM64バイナリが付属しています。 + +--- + +## Dockerイメージ {#docker-image} + +公式Dockerイメージは、[hub.docker.comレジストリ](https://hub.docker.com/r/0xpolygon/polygon-edge)にあります。 + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## ソースからの構築 {#building-from-source} + +`go install`を使用する前に、Go`>=1.18`をインストールし、適切に設定されているか確認してください。 + +安定したブランチは最新リリースであります。 + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## `go install`を使用する + +`go install`を使用する前に、Go`>=1.17`をインストールし、適切に設定されているか確認してください。 + +`go install github.com/0xPolygon/polygon-edge@release/` + +バイナリは`GOBIN`環境変数で利用可能になり、最新のリリースからの変更が含まれます。[GitHub](https://github.com/0xPolygon/polygon-edge/releases)リリースで最新のものを確認することができます。 diff --git a/archive/edge/ja-edge/get-started/set-up-ibft-locally.md b/archive/edge/ja-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..9379d7207f --- /dev/null +++ b/archive/edge/ja-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,400 @@ +--- +id: set-up-ibft-locally +title: ローカル設定 +description: "ステップバイステップのローカル設定ガイドです。" +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution このガイドはテスト用の目的のみにお使いください。 + +下記のガイドはテストと開発の目的のためにローカルマシンにPolygon Edgeネットワークを設定する方法について説明します。 + +手順は実際に使用するシナリオのためにPolygon Edgeネットワークをクラウドプロバイダー:クラウド**[設定](/docs/edge/get-started/set-up-ibft-on-the-cloud)** + +::: + + +## 要件 {#requirements} + +Polygon Edgeをインストールするには、[インストール](/docs/edge/get-started/installation)を参照してください。 + +## 概要 {#overview} + +![ローカル設定](/img/edge/ibft-setup/local.svg) + +このガイドの目標は[IBFTコンセンサスプロトコル](https://github.com/ethereum/EIPs/issues/650)で作動する`polygon-edge`ブロックチェーンネットワークを確立することです。ブロックチェーンネットワークは4ノードからなり、その4ノードはすべてバリデータノードであるため、ブロックの提案と他のプロポーザから提供されたブロックの検証の両方を行う資格があります。4ノードはすべて同じマシン上で実行されますが、これはこのガイドで、最短で完全に機能するIBFRクラスターを提供しようとしているためです。 + +これを行うための、4つの簡単なステップを示します: + +1. データディレクトリの初期化は、4ノードにそれぞれのバリデータ鍵を生成と空のブロックチェーンデータディレクトリの初期化の両方を行います。バリデータ鍵が重要なのは、これらの鍵を使用して初期のバリデータセットでジェネシスブロックをブートストラップする必要があるためです。 +2. ブードノード用に接続文字列を準備することは最初に起動したときにどのノードに接続するかについて実行するすべてのノードにとって非常に重要な情報となります。 +3. `genesis.json`ファイルを生成するには入力として**ステップ1**で生成された、ジェネシスブロックにネットワークの最初のバリデータを設定するために使用するバリデータ鍵と**ステップ2**からのブートノード接続文字列の両方が必要です。 +4. すべてのノードを実行することがこのガイドの最終目標であり、最後のステップになります。ノードにどのデータディレクトリを使用し、当初のネットワークステートをブートストラップする`genesis.json`をどこで見つけるかを指示します。 + +4つのノードはすべてローカルホストで実行されるため、設定プロセス中には各ノードのデータディレクトリがすべて同じ親ディレクトリに存在することが想定されます。 + +:::info バリデータの数 + +クラスタ内のノード数に最小値はありません。つまり、バリデータノードが1つだけのクラスタも可能です。 +_シングル_のノードクラスタでは、**クラッシュ耐性**や**BFT保証**がないことに注意してください。 + +BFT保証を達成するために推奨される最小ノード数は4です。これは、4ノードクラスタでは1ノードの不備は許容され、残りの3ノードは正常に機能します。 + +::: + +## ステップ1:IBFTのデータフォルダを初期化し、バリデータ鍵を生成する {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +IBFTを起動し実行するには、各ノードについてデータフォルダを1つずつ初期化する必要があります。 + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +これらの各コマンドはバリデータ鍵、BLS公開鍵、[ノードID](https://docs.libp2p.io/concepts/peer-id/)をプリントします。次のステップで、最初のノードのノードIDが必要です。 + +### 秘密の出力 {#outputting-secrets} +必要に応じて、秘密の出力を再度取得することができます。 + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## ステップ2:ブートノードのmultiaddr接続文字列を準備します {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +ノードが正常に接続を確立するには、ネットワーク上の残りすべてのノードに関する情報を得るために接続する`bootnode`サーバを知っておく必要があります。`bootnode`はしばしばp2pジャーゴンの`rendezvous`サーバとしても知られています。 + +`bootnode`はPolygon Edgeノードの特殊なインスタンスではありません。すべてのPolygon Edgeノードは`bootnode`として機能することができますが、しかしすべてのPolygon Edgeノードはネットワーク内のすべての残りのノードと接続するための情報を提供するために連絡される指定されたブートノードのセットを持つ必要があります。 + +ブートノードを指定するための接続文字列を作成するには、[multiaddr形式](https://docs.libp2p.io/concepts/addressing/)に準拠する必要があります: +``` +/ip4//tcp//p2p/ +``` + +このガイドでは、最初のノードと2番目のノードを、他のすべてのノードのブートノードとして扱います。このシナリオでは、`node 1`または`node 2`に接続するノードは、相互にコントラクトされたブートノードを介して相互に接続する方法に関する情報を取得します。 + +:::info ノードをスタートするには、少なくとも1つのブートノードを指定する必要があります + +ネットワーク内の他のノードが相互に検出できるように、少なくとも**1つ**のブートノードが必要です。より多くのブートノードを使用することをお勧めします。これは、停止時にネットワークに復元力を提供するためです。 +このガイドでは2つのノードをリストしますが、これはその場で変更できるもので、`genesis.json`ファイルの有効性には影響ありません。 +::: + +ローカルホスト上で実行しているため、``は`127.0.0.1`であると仮定しても安全です。 + +``には、`10001`を使用します。これは、このポートを後で聞くために`node 1`のlibp2pサーバを設定するからです。 + +最後に、以前に実行したコマンド`polygon-edge secrets init --data-dir test-chain-1`コマンドの出力から取得できる``が必要です(これはの`node1`ための鍵とデータディレクトリを生成するために使用されました)。 + +アセンブリ後、ブートノードとして使用する`node 1`に対するmultiaddr接続文字列はこのように見えます(最後にある``だけは異なるはずです)。 +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +同様に、次に示すように第2ブートノード用にmultiaddrを構築します +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info IPSの代わりのDNSホスト名 + +Polygon Edgeは、ノードの構成にDNSホスト名を使用することをサポートします。これは、さまざまな理由でノードのIPアドレスが変更される可能性があるため、クラウドベースの展開に非常に役立つ機能です。 + +DNSホスト名を使用する場合の接続文字列のmultiaddr形式は次のとおりです: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## ステップ3:4ノードをバリデータとしてジェネシスファイルを生成する {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +このコマンドが行う内容: + +* `--ibft-validators-prefix-path`はPolygon Edgeで使用できるIBFTを指定したプレフィックスフォルダパスを設定します。このディレクトリはバリデータの秘密鍵を保持する`consensus/`フォルダを収納するために使用されます。バリデータの公開鍵はジェネシスファイル(ブートストラップノードの最初のリスト)を構築するために必要です。このフラグはローカルホストにネットワークを設定する際にのみ理にかなうもので、実際のシナリオではすべてのノードのデータディレクトリが公開鍵を容易に読み取ることができる同じファイルシステムに置かれることは期待できません。 +* `--bootnode`はノードが互いを見つけることを可能にするブートノードのアドレスを設定します。**ステップ2**で説明したように、`node 1`のmultiaddr文字列を使用します。 + +このコマンドの結果は新しいブロックチェーンのジェネシスブロックを含む`genesis.json`ファイルであり、定義済みのバリデータセットと接続を確立するために最初に連絡するノードの設定が含まれています。 + +:::info ECDSAに切り替える + +BLSはブロックヘッダーのデフォルトのバリデーションモードです。ECDSAモードでチェーンを実行したい場合は、引数を指定して`—ibft-validator-type`フラグを使用することができます`ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info アカウント残高の前払い + +おそらく、いくつかのアドレスが「前払い」残高を持つブロックチェーンネットワークを設定したいと思われるでしょう。 + +これを実現するには、ブロックチェーン上の特定の残高で初期化する`--premine`フラグを、アドレスごとに必要な数だけ渡します。 + +たとえば、ジェネシスブロックで`0x3956E90e632AEbBF34DEB49b71c28A83Bc029862`アドレスに1000ETHを前払いする場合は、次の引数を提供する必要があります: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**前払い額はETHではなくWEIであることに注意してください。** + +::: + +:::info ブロックのガス制限を設定します + +各ブロックのデフォルトのガス制限は`5242880`です。この値はジェネシスファイルに書き込まれますが、増減が必要になる場合があります。 + +これを行うには、次に示すように、フラグ`--block-gas-limit`の後に目的の値を入力します: + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info システムファイル記述子の制限を設定します + +一部のオペレーティングシステムでは、デフォルトのファイル記述子の制限(開くファイルの最大数)が非常に小さくなっています。 +ノードのスループットを高くしたい場合は、OSレベルでこの制限を増やすことを検討することもあるでしょう。 + +Ubuntu distroの手順は次のとおりです(Ubuntu/Debian distroを使用していない場合は、お使いのOSの公式ドキュメントをチェックしてください): +- 現在のOS制限(開くファイル)をチェックします +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- 開いているファイルの制限を増やします + - ローカルで - 現在のセッションだけに影響します: + ```shell + ulimit -u 65535 + ``` + - グローバルでまたはユーザ単位(/etc/security/limits.confファイルの末尾に制限を追加): + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +任意で、追加パラメータを変更し、ファイルを保存してシステムを再起動します。 +再起動後、ファイル記述子の制限を再度チェックします。 +それは、limits.confファイルで定義した値に設定されている必要があります。 +::: + + +## ステップ4:すべてのクライアントを実行する {#step-4-run-all-the-clients} + +4ノードからなるPolygon Edgeネットワーク全体を同一マシンで実行しようとしているため、ポートコンフリクトを回避するよう注意する必要があります。このため、これはノードの各サーバのリスニングポートを決定するために次の論法を使用します: + +- `10000`はgRPCサーバの`node 1`向け、`20000`はGRPCサーバの`node 2`向けなど。 +- `10001`はlibp2pサーバの`node 1`向け、`20001`はlibp2pサーバの`node 2`向けなど。 +- `10002`はJSON-RPCサーバの`node 1`向け、`20002`はJSON-RPCサーバの`node 2`向けなど。 + +**第1**クライアントを実行するために(ポート`10001`に注意します。これが**ステップ2**でlibp2p multiaddrの一部としてノード1のノードIDと一緒に使用されたためです): + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +**第2**クライアントを実行するために: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +**第3**クライアントを実行するには: + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +**第4**クライアントを実行するために: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +これまでに行われたことを簡単に説明します: + +* クライアントデータ用のディレクトリは、**./test-chain-\***として指定されています。 +* ノードごとにそれぞれポート**10000**、**20000**、**30000**、**40000**でGRPCサーバが起動されています。 +* ノードごとにそれぞれポート**10001**、**20001**、**30001**、**40001**でlibp2pサーバが起動されています。 +* ノードごとにそれぞれポート**10002**、**20002**、**30002**、**40002**でJSON-RPCサーバが起動されています。 +* *シール*フラグは起動されているノードがブロックシーリングに参加するつもりであることを意味します。 +* *チェーン*フラグはチェーン設定に使用するジェネシスファイルを指定します。 + +ジェネシスファイルの構造は[CLIコマンド](/docs/edge/get-started/cli-commands)セクションでカバーされています。 + +以前のコマンドを実行した後、ブロックのシール、ノード不備からの回復が可能な、4ノードのPolygon Edgeネットワークを設定しました。 + +:::info 設定ファイルを使用してクライアントを起動します + +すべての設定パラメータをCLI引数として指定する代わりに、次のコマンドを実行することで設定ファイルを使用してクライアントを起動することもできます: + +````bash +polygon-edge server --config +```` +例: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +現在、設定ファイルをサポートしており、設定ファイルを`json`ベースに`yaml`しています。サンプル設定ファイルは**[こちら](/docs/edge/configuration/sample-config)**でご覧いただけます。 + +::: + +:::info ノンバリデータノードを実行するステップ + +ノンバリデータは常にバリデータノードから受信した最新のブロックを同期します。次のコマンドを実行すると、ノンバリデータノードをスタートできます。 + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +たとえば、次のコマンドを実行して、**第5**ノンバリデータクライアントを追加できます: + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info 価格制限を指定します + +Polygon Edgeノードは、着信トランザクションに対して設定された**価格制限**で開始できます。 + +価格制限の単位は`wei`です。 + +価格制限の設定は、現在のノードで処理されたトランザクションは設定された価格制限**よりも高い**ガス価格を必要とすることを意味し、そうでなければブロックに含まれることはありません。 + +ノードの大半が一定の価格制限を尊重することで、ネットワーク内のトランザクションは一定の価格しきい値を下回ることはできないというルールを強制します。 + +価格制限のデフォルト値は`0`です。つまり、デフォルトではまったく適用されません。 + +`--price-limit`フラグを使用する例: +````bash +polygon-edge server --price-limit 100000 ... +```` + +価格制限は**非ローカルトランザクションにのみ適用される**ことに注意する必要があります。つまり、ノードにローカルで追加されるトランザクションには、価格制限が適用されません。 + +::: + +:::info WebSocket URL + +デフォルトでは、Polygon Edgeを実行すると、チェーンの場所に基づいてWebSocket URLが生成されます。 +URLスキーム`wss://`はHTTPSリンクに、そして`ws://`はHTTPに使用されます。 + +ローカルホストWebSocketのURL: +````bash +ws://localhost:10002/ws +```` +ポート番号は、ノードに選択されたJSON-RPCポートによって異なることに注意してください。 + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## ステップ5: Polygon Edgeネットワークとのやり取り {#step-5-interact-with-the-polygon-edge-network} + +少なくとも1つの実行クライアントを設定したので、上記で前払いしたアカウントを使用し4ノードのいずれかにJSON-RPC URLを指定することで、先に進み、ブロックチェーンとやり取りできるようになります。 +- ノード1:`http://localhost:10002` +- ノード2:`http://localhost:20002` +- ノード3:`http://localhost:30002` +- ノード4:`http://localhost:40002` + +このガイドに従って新しく構築されたクラスタにオペレータコマンドを発行します:[オペレータ情報をクエリする方法](/docs/edge/working-with-node/query-operator-info)(構築したクラスタのGRPCポートはノードごとにそれぞれが`10000`/`20000`/`30000`/`40000`となっています) diff --git a/archive/edge/ja-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/ja-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..e7cd592984 --- /dev/null +++ b/archive/edge/ja-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,426 @@ +--- +id: set-up-ibft-on-the-cloud +title: クラウド設定 +description: "ステップバイステップのクラウド設定ガイド。" +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info このガイドは、メインネットまたはテストネットの設定を対象としています + +次のガイドでは、テストネットまたはメインネットのプロダクション設定のために、クラウドプロバイダにPolygon Edgeネットワークを設定する方法を説明します。 + +実稼働環境のようなセットアップを行う前に、`polygon-edge`を迅速にテストするためにPolygonEdgeネットワークをローカルでセットアップする場合は、**[ローカル設定](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## 要件 {#requirements} + +Polygon Edgeをインストールするには、[インストール方法](/docs/edge/get-started/installation)を参照してください。 + +### VM接続の設定 {#setting-up-the-vm-connectivity} + +選択したクラウドプロバイダに応じて、ファイアウォール、セキュリティグループ、またはアクセス制御リストを使用してVM間の接続とルールを設定することができます。 + +他のVMに公開する必要がある`polygon-edge`の唯一の部分はlibp2pサーバであるため、デフォルトのlibp2pポート`1478`上でVM間の通信をすべて許可するだけで十分です。 + +## 概要 {#overview} + +![クラウド設定](/img/edge/ibft-setup/cloud.svg) + +このガイドでは[IBFTコンセンサスプロトコル](https://github.com/ethereum/EIPs/issues/650)で作動する`polygon-edge`ブロックチェーンネットワークを確立することを目的にしています。ブロックチェーンネットワークは4つのノードで構成され、その4つはすべてバリデータノードであり、したがってブロックの提案と他の提案者から来たブロックの検証の両方が可能です。 +このガイドの目的は、バリデータ鍵をプライベートにしてトラストレスネットワークの設定を確実にすると同時に、完全に機能するPolygon Edgeネットワークを提供することですので、4つのノードはそれぞれ独自のVMで実行されます。 + +これを実現するために、次の4つの簡単な手順を案内します: + +0. 上記の**要件**のリストを参照してください。 +1. 各バリデータの秘密鍵を生成し、データディレクトリを初期化します +2. 共有`genesis.json`に配置するブートノードの接続文字列を準備します +3. ローカルマシンに`genesis.json`を作成し、各ノードに送信/転送します +4. すべてのノードをスタートします + +:::info バリデータの数 + +クラスタ内のノード数に最小値はありません。つまり、バリデータノードが1つだけのクラスタも可能です。 +_シングル_のノードクラスタでは、**クラッシュ耐性**や**BFT保証**がないことに注意してください。 + +BFT保証を達成するために推奨される最小ノード数は4です。これは、4ノードクラスタでは1ノードの障害が許容され、残りの3ノードは正常に機能するためです。 + +::: + +## ステップ1:データフォルダの初期化とバリデータ鍵の生成 {#step-1-initialize-data-folders-and-generate-validator-keys} + +Polygon Edgeを起動して実行するには、各ノードでデータフォルダを初期化する必要があります。: + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +これらの各コマンドは、バリデータ鍵、bls公開鍵、および[ノードID](https://docs.libp2p.io/concepts/peer-id/)を出力します。次のステップで、最初のノードのノードIDが必要です。 + +### 秘密の出力 {#outputting-secrets} +必要に応じて、秘密の出力を再度取得することができます。 + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning データディレクトリを自分自身で保管してください! + +上記で生成されたデータディレクトリは、ブロックチェーン状態を保持するディレクトリを初期化するだけでなく、バリデータの秘密鍵も生成します。**この鍵は秘密にしておく必要があります。この鍵が盗まれると、誰かがネットワーク内であなたになりすまし、バリデータになることができるからです!** + +::: + +## ステップ2:ブートノードのmultiaddr接続文字列を準備します {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +ノードが正常に接続を確立するには、ネットワーク上の残りすべてのノードに関する情報を取得するために接続する`bootnode`サーバを認識している必要があります。`bootnode`は、p2p用語では`rendezvous`サーバとも呼ばれます。 + +`bootnode`は、Polygon Edgeノードの特殊なインスタンスではありません。すべてのPolygon Edgeノードは`bootnode`として機能することができ、すべてのPolygon Edgeノードには、ネットワーク内の残りすべてのノードとの接続方法に関する情報を提供するためにコントラクトされるブートノードのセットが指定されている必要があります。 + +ブートノードを指定するための接続文字列を作成するには、[multiaddr形式](https://docs.libp2p.io/concepts/addressing/)に準拠する必要があります: +``` +/ip4//tcp//p2p/ +``` + +このガイドでは、最初のノードと2番目のノードを、他のすべてのノードのブートノードとして扱います。このシナリオでは、`node 1`または`node 2`に接続するノードは、相互にコントラクトされたブートノードを介して相互に接続する方法に関する情報を取得します。 + +:::info ノードをスタートするには、少なくとも1つのブートノードを指定する必要があります + +ネットワーク内の他のノードが相互に検出できるように、少なくとも**1つ**のブートノードが必要です。より多くのブートノードを使用することをお勧めします。これは、停止時にネットワークに復元力を提供するためです。 +このガイドでは、2つのノードを示しますが、`genesis.json`ファイルの有効性に影響を与えることなく、すぐに変更できます。 +::: + +multiaddr接続文字列の最初の部分は``であるため、ここでは他のノードから到達可能なIPアドレスを入力する必要があります。これは、設定によっては`127.0.0.1`ではなくプライベートIPアドレスまたはパブリックIPアドレスである可能性があります。 + +``にはデフォルトのlibp2pポートであるため、`1478`を使用します。 + +最後に、以前に実行したコマンド`polygon-edge secrets init --data-dir data-dir`(`node 1`用の鍵とデータディレクトリの生成に使用されたコマンド)の出力から取得できるが``必要です + +アセンブリ後、ブートノードとして使用する`node 1`へのmultiaddr接続文字列は次のようになります(末尾にある``だけが異なるはずです): +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +同様に、次に示すように、2番目のブートノード用にmultiaddrを構築します +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info IPSではなくDNSホスト名 + +Polygon Edgeは、ノードの構成にDNSホスト名を使用することをサポートします。これは、さまざまな理由でノードのIPアドレスが変更される可能性があるため、クラウドベースの展開に非常に役立つ機能です。 + +DNSホスト名を使用する場合の接続文字列のmultiaddr形式は次のとおりです: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## ステップ3:4つのノードをバリデータとして使用してジェネシスファイルを生成します {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +このステップはローカルマシン上で実行できますが、4つのバリデータそれぞれに対してバリデータ公開鍵が必要になります。 + +バリデータは、`secrets init`コマンドの出力に次に示すように`Public key (address)`を安全に共有できるため、公開鍵で識別される初期バリデータセット内のこれらのバリデータでgenesis.jsonを安全に生成できます: + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +4つのバリデータの公開鍵をすべて受信した場合は、次のコマンドを実行して`genesis.json`を生成できます + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +このコマンドが行うこと: + +* `--ibft-validator`は、ジェネシスブロックに設定された初期バリデータセットに含まれる必要があるバリデータの公開鍵を設定します。多くの初期バリデータが存在する場合があります。 +* `--bootnode`は、ノードが相互に検索できるようにするブートノードのアドレスを設定します。 +**ステップ2**で説明したように、`node 1`のmultiaddr文字列を使用しますが、上記のようにブートノードを必要なだけ追加できます。 + +:::info ECDSAに切り替える + +BLSはブロックヘッダーのデフォルトのバリデーションモードです。ECDSAモードでチェーンを実行したい場合は、引数を指定して`—ibft-validator-type`フラグを使用することができます`ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info アカウント残高の前払い + +おそらく、いくつかのアドレスが「前払い」残高を持つブロックチェーンネットワークを設定したいと思われるでしょう。 + +これを実現するには、ブロックチェーン上の特定の残高で初期化する`--premine`フラグを、アドレスごとに必要な数だけ渡します。 + +たとえば、ジェネシスブロックで`0x3956E90e632AEbBF34DEB49b71c28A83Bc029862`アドレスに1000ETHを前払いする場合は、次の引数を提供する必要があります: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**前払い額はETHではなくWEIであることに注意してください。** + +::: + +:::info ブロックのガス制限を設定します + +各ブロックのデフォルトのガス制限は`5242880`です。この値はジェネシスファイルに書き込まれますが、増減が必要になる場合があります。 + +これを行うには、次に示すように、フラグ`--block-gas-limit`の後に目的の値を入力します: + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info システムファイル記述子の制限を設定します + +一部のオペレーティングシステムでは、デフォルトのファイル記述子の制限(開くファイルの最大数)が非常に小さくなっています。 +ノードのスループットを高くしたい場合は、OSレベルでこの制限を増やすことを検討することもあるでしょう。 + +Ubuntu distroの手順は次のとおりです(Ubuntu/Debian distroを使用していない場合は、お使いのOSの公式ドキュメントをチェックしてください): +- 現在のOS制限(開くファイル)をチェックします +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- 開いているファイルの制限を増やします + - ローカルで - 現在のセッションだけに影響します: + ```shell + ulimit -u 65535 + ``` + - グローバルでまたはユーザ単位(/etc/security/limits.confファイルの末尾に制限を追加): + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +任意で、追加パラメータを変更し、ファイルを保存してシステムを再起動します。 +再起動後、ファイル記述子の制限を再度チェックします。 +この値は、limits.confファイルで定義した値に設定する必要があります。 + +::: + +以下を指定した後: +1. バリデータセットとしてジェネシスブロックに含まれるバリデータの公開鍵 +2. ブートノードmultiaddr接続文字列 +3. ジェネシスブロックに含めるように前払されたアカウントと残高 + +`genesis.json`を生成するには、ネットワーク内のすべてのVMにコピーする必要があります。設定によっては、コピー/ペーストするか、ノードオペレータに送信するか、単にSCP/FTPで上書きします。 + +ジェネシスファイルの構造については、[CLIコマンド](/docs/edge/get-started/cli-commands)セクションを参照してください。 + +## ステップ4:すべてのクライアントを実行します {#step-4-run-all-the-clients} + +:::note クラウドプロバイダ上のネットワーキング + +ほとんどのクラウドプロバイダは、IPアドレス(特にパブリックアドレス)をVMのダイレクトネットワークインターフェースとして公開せず、見えないNATプロキシを設定します。 + + +この場合、ノードが相互に接続できるようにするには、`0.0.0.0`IPアドレスをリッスンしてすべてのインターフェイスでバインドする必要がありますが、他のノードがインスタンスへの接続に使用できるIPアドレスまたはDNSアドレスを指定する必要があります。これは、外部IPアドレスまたはDNSアドレスをそれぞれ指定できる`--nat`または`--dns`引数を使用することによって実現されます。 + +#### 例 {#example} + +リッスンする関連IPアドレスは`192.0.2.1`ですが、どのネットワークインターフェイスにも直接バインドされません。 + +ノードの接続を許可するには、次のパラメータを渡します: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +または、DNSアドレス`dns/example.io`を指定する場合は、次のパラメータを渡します: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +これにより、ノードはすべてのインターフェイスでリッスンしますが、クライアントが指定された`--nat`または`--dns`アドレスを使用してそのノードに接続していることも認識します。 + +::: + +**第1**クライアントを実行するには: + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +**第2**クライアントを実行するには: + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +**第3**クライアントを実行するには: + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +**第4**クライアントを実行するには: + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +前のコマンドを実行した後、ブロックをシールしてノード障害から回復することができる4ノードのPolygon Edgeネットワークを設定しました。 + +:::info 設定ファイルを使用してクライアントを起動します + +すべての設定パラメータをCLI引数として指定する代わりに、次のコマンドを実行して、設定ファイルを使用してクライアントを起動することもできます: + +````bash +polygon-edge server --config +```` +例: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +現在、`json`ベースの設定ファイルのみをサポートしています。サンプル設定ファイルは**[こちらを](/docs/edge/configuration/sample-config)**ご覧ください。 + +::: + +:::info ノンバリデータノードを実行するステップ + +ノンバリデータは常にバリデータノードから受信した最新のブロックを同期します。次のコマンドを実行すると、ノンバリデータノードをスタートできます。 + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +たとえば、次のコマンドを実行して、**第5**ノンバリデータクライアントを追加できます: + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info 価格制限を指定します + +Polygon Edgeノードは、着信トランザクションに対して設定された**価格制限**で開始できます。 + +価格制限の単位は`wei`です。 + +価格制限を設定するということは、現在のノードによって処理されるすべてのトランザクションが、設定された価格制限**よりも高い**ガス価格を持つ必要があることを意味します。そうでない場合、それはブロックに含まれません。 + +大多数のノードが特定の価格制限を尊重すると、ネットワーク内のトランザクションは特定の一定の価格しきい値を下回ることはできないというルールを強制します。 + +価格制限のデフォルト値は`0`です。つまり、デフォルトではまったく適用されません。 + +`--price-limit`フラグを使用する例: +````bash +polygon-edge server --price-limit 100000 ... +```` + +価格制限は**非ローカルトランザクションにのみ適用される**ことに注意する必要があります。つまり、ノードにローカルで追加されるトランザクションには、価格制限が適用されません。 + +::: + +:::info WebSocket URL + +デフォルトでは、Polygon Edgeを実行すると、チェーンの場所に基づいてWebSocket URLが生成されます。 +URLスキーム`wss://`はHTTPSリンクに、そして`ws://`はHTTPに使用されます。 + +ローカルホストWebSocketのURL: +````bash +ws://localhost:10002/ws +```` +ポート番号は、ノードに選択されたJSON-RPCポートによって異なることに注意してください。 + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/ja-edge/get-started/terraform-aws-deployment.md b/archive/edge/ja-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..f7d0c356bb --- /dev/null +++ b/archive/edge/ja-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,162 @@ +--- +id: terraform-aws-deployment +title: Terraform AWSデプロイメント +description: "Terraformを使用してAWSクラウドプロバイダにPolygon Edgeネットワークをデプロイする" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info 実稼働環境デプロイメントガイド +これは、公式の実稼働対応の完全自動化AWS導入ガイドです。 + +***[クラウド](set-up-ibft-on-the-cloud)***または***[ローカル](set-up-ibft-locally)***への手動での展開は、テスト用やクラウドプロバイダがAWSではない場合に推奨されます。 +::: + +:::info +このデプロイメントはPoAだけです。 +PoSメカニズムが必要な場合は、この***[ガイド](/docs/edge/consensus/migration-to-pos)***に従ってPoAからPoSに切り替えます。 +::: + +このガイドでは、バリデータノードが複数の可用性領域にまたがっているため、実稼働可能なAWSクラウドプロバイダにPolygon Edgeブロックチェーンネットワークを展開するプロセスについて詳しく説明します。 + +## 前提条件 {#prerequisites} + +### システムツール {#system-tools} +* [terraform](https://www.terraform.io/) +* [aws cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [awsアクセス鍵IDと秘密アクセス鍵](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Terraform変数 {#terraform-variables} +デプロイを実行する前に、2つの変数を提供する必要があります: + +* `alb_ssl_certificate` - ALBがhttpsプロトコルに使用するAWS証明書マネージャの証明書のARN。 +証明書は、展開を開始する前に生成する必要があり、「**発行済み**」の状態である必要があります +* `premine` - 前払い用のネイティブ通貨を受け取るアカウント。値は公式[CLI](/docs/edge/get-started/cli-commands#genesis-flags)フラグ仕様に従う必要があります + +## デプロイメント情報 {#deployment-information} +### デプロイされるリソース {#deployed-resources} +デプロイするリソースの高レベルの概要: + +* 専用VPC +* 4つのバリデータノード(ブートノードでもある) +* ノードの発信インターネットトラフィックを許可する4つのNATゲートウェイ +* 最初の(ジェネシス)ブロックを生成し、チェーンを開始するために使用されるラムダ関数 +* 専用のセキュリティグループとIAMの役割 +* genesis.jsonファイルの保存に使用されるS3バケット +* JSON-RPCエンドポイントを公開するために使用されるアプリケーションロードバランサ + +### フォールトトレランス {#fault-tolerance} + +このデプロイメントには、可用性ゾーンが4つある領域だけが必要です。各ノードはシングルのAZに配置されます。 + +各ノードをシングルのAZに配置することにより、ブロックチェーンクラスタ全体がシングルのノード(AZ)の障害に対してフォールトトレランスを実現します。Polygon Edgeは、シングルのノードが4つのバリデータノードクラスタで障害になることを可能にするIBFTコンセンサスを実装するためです。 + +### コマンドラインアクセス {#command-line-access} + +バリデータノードは公共のインターネットに公開されておらず(JSON-PRCはALBを介してのみアクセス可能)、付属するパブリックIPアドレスもありません。 +ノードコマンドラインアクセスは[AWSシステムマネージャ(セッションマネージャ)](https://aws.amazon.com/systems-manager/features/)を介してのみ可能です。 + +### ベースAMIアップグレード {#base-ami-upgrade} + +このデプロイメントでは、`ubuntu-focal-20.04-amd64-server`AWS AMIを使用します。AWSAMIが更新されると、EC2の*再デプロイメント*がトリガー**されません**。 + +何らかの理由でベースAMIを更新する必要がある場合は、`terraform apply`以前に各インスタンスに対して`terraform taint`コマンドを実行することによって、ベースAMIを更新できます。 + `terraform taint module.instances[].aws_instance.polygon_edge_instance`コマンドを実行すると、インスタンスが汚染される可能性が +あります。 + +例: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info + +実稼働環境では、ブロックチェーンネットワークを機能させるために、`terraform taint`は、1つずつ実行する必要があります。 +::: + +## デプロイメント手順 {#deployment-procedure} + +### プリデプロイメントステップ {#pre-deployment-steps} +* [polygon-technology-edge](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) terraform registry readmeに目を通します +* `polygon-technology-edge`モジュールのreadmeページにある*プロビジョニング手順*を使用して、モジュールを`main.tf`ファイルに追加します +* `terraform init`コマンドを実行して、必要なすべてのTerraform依存関係をインストールします +* [AWS証明書マネージャ](https://aws.amazon.com/certificate-manager/)で新しい証明書を提供します +* 指定された証明書が「**発行済み**」の状態であることを確認し、証明書の**ARN**をメモします +* CLIでモジュールの出力を取得するには、出力ステートメントを設定します + +#### `main.tf`例 {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### `terraform.tfvars`例 {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### デプロイメントステップ {#deployment-steps} +* `terraform.tfvars`ファイルを作成します +* (上記で説明したように)必要なTerraform変数をこのファイルに設定します。 +:::info + +このデプロイメントを完全にカスタマイズできるその他の必須ではない変数があります。`terraform.tfvars`ファイルに独自の値を追加することで、デフォルト値を上書きできます。 + +使用可能なすべての変数の仕様は、モジュールのTerraform***[レジストリ](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)***にあります。 +::: +* `aws s3 ls`を実行してAWS CLI認証が正しく設定されていることを確認します - エラーは発生していないはずです +* インフラ`terraform apply`を展開します + +### ポストデプロイメントステップ {#post-deployment-steps} +* 展開が完了したら、CLIに出力される`json_rpc_dns_name`変数値に注意してください +* 指定された`json_rpc_dns_name`値にドメイン名を指定するパブリックdns cnameレコードを作成します。例: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* cnameレコードが伝播したら、JSON-PRCエンドポイントを呼び出して、チェーンが正常に動作しているかチェックします。 +上記の例から: + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## 破棄手順 {#destroy-procedure} +:::warning +次の手順では、これらのTerraformスクリプトを使用して展開されたインフラ全体を完全に削除します。 +適切な[ブロックチェーンのデータバックアップ](docs/edge/working-with-node/backup-restore)があること、そして/またはテスト環境で作業していることを確認します。 + +::: + +インフラ全体を削除する必要がある場合は、次のコマンド`terraform destroy`を実行します。 +さらに、デプロイメントが行われた領域のAWS[パラメータストア](https://aws.amazon.com/systems-manager/features/)に保存されている秘密を手動で削除する必要があります。 diff --git a/archive/edge/ja-edge/overview.md b/archive/edge/ja-edge/overview.md new file mode 100644 index 0000000000..9fdad9bdc6 --- /dev/null +++ b/archive/edge/ja-edge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Polygon Edge +sidebar_label: What is Edge +description: "Polygon Edgeの紹介" +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +Polygon Edgeは、Ethereumと互換性のあるブロックチェーンネットワーク、サイドチェーン、一般的な拡張ソリューションを構築するためのモジュラー及び拡張可能なフレームワークです。 + +その主な使用目的はEthereumスマートコントラクトやトランザクションとの完全な互換性を提供しながら新しいブロックチェーンネットワークをブートストラップすることです。これはIBFT(イスタンブールビザンチンフォールトトレラント)コンセンサスメカニズムを使用し、[PoA(プルーフ・オブ・オーソリティ)](/docs/edge/consensus/poa)と[PoS(プルーフ・オブ・ステーク)](/docs/edge/consensus/pos-stake-unstake)の2つでサポートされています。 + +Polygon Edgeは、[中央集権型ブリッジソリューション](/docs/edge/additional-features/chainbridge/overview)を利用することで、[ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20)と[ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721)の両方のトークンの転送を可能にし、複数のブロックチェーンネットワークとの通信もサポートします。 + +[JSON-RPC](/docs/edge/working-with-node/query-json-rpc)エンドポイントを通じてPolygon Edgeとやりとりするのに業界標準のウォレットが使用でき、ノードオペレータは[GRPC](/docs/edge/working-with-node/query-operator-info)プロトコルを通じてノード上でさまざまなアクションを実行することができます。 + +Polygonの詳細については、[公式ウェブサイト](https://polygon.technology)をご覧ください。 + +**[GitHubリポジトリ](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +これは進行中のものであり、将来アーキテクチャに関する変更が起こる可能性があります。コードはまだ監査されていません +それでも、実稼働での使用を希望される場合はPolygonチームにご連絡ください。 + +::: + + + +ローカルで`polygon-edge`ネットワークを実行して開始するには、次をご確認ください:[インストール](/docs/edge/get-started/installation)と[ローカル設定](/docs/edge/get-started/set-up-ibft-locally)。 diff --git a/archive/edge/ja-edge/performance-reports/overview.md b/archive/edge/ja-edge/performance-reports/overview.md new file mode 100644 index 0000000000..0964c5b8c2 --- /dev/null +++ b/archive/edge/ja-edge/performance-reports/overview.md @@ -0,0 +1,30 @@ +--- +id: overview +title: 概要 +description: "Polygon Edgeテストについて" +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +これらのテストを実行するために使用`loadbot`した当社は、減価償却を行っています。 +::: + +| タイプ | 値 | テストへのリンク | +| ---- | ----- | ------------ | +| 定期的な転送 | 1428 tps | [2022年7月4日](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| ERC-20の転送 | 1111 tps | [2022年7月4日](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| NFTのミント | 714 tps | [2022年7月4日](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +私たちの目標は、高パフォーマンス、豊富な機能性、ブロックチェーンクライアントソフトウェアを簡単に設定し、維持することです。すべてのテストはPolygon Edge Loadbotを使用して行いました。 +このセクションにあるすべてのパフォーマンスレポートは適切に日付が記され、環境は明確に記載されテスト手法も明確に説明されています。 + +これらのパフォーマンステストの目標は、Polygon Edgeブロックチェーンネットワークの現実世界でのパフォーマンスを示すことです。同じ環境で、我々のLoadbotを使用して、誰でも、ここに掲載された同じ結果を得ることができるはずです。 + +すべてのパフォーマンステストは、EC2インスタンスノードからなるチェーン上のAWSプラットフォームで実施されました。 \ No newline at end of file diff --git a/archive/edge/ja-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/ja-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..1926b3723f --- /dev/null +++ b/archive/edge/ja-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,130 @@ +--- +id: test-2022-01-21 +title: 2022年1月21日 +description: "1月21日のパフォーマンステスト" +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## 2022年1月21日 {#january-21st-2022} + +### まとめ {#summary} + +:::caution +これらのテストを実行するために使用`loadbot`した当社は、減価償却を行っています。 +::: + +このテストはパフォーマンスを大幅に向上したTxPoolリファクタの後に行われました([v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0)でリリース)。 + +目標は30人の積極的に参加しているバリデータからなる大型ネットワークを設定し、全トランザクションがシングルノードのJSON-RPCに送信される中、コンセンサスとTxPoolトランザクションゴシッピングについて適切にストレステストすることにありました。 + +狙いは可能な限り最大のTPSを達成するよう努めることではありませんでした。というのもネットワーク規模はパフォーマンスにマイナスの影響を与えるためです。またブロックガス制限とブロック時間は多くのシステムリソースを消費しないために妥当な値に設定することで、コモディティのハードウェアでの実行を可能にします。 + +### 結果 {#results} + +| メトリック | 値 | +| ------ | ----- | +| 毎秒のトランザクション | 344 | +| トランザクションの失敗 | 0 | +| トランザクションの成功 | 10000 | +| 総実行時間 | 30秒 | + +### 環境 {#environment} + +
+ ホスト設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
クラウドプロバイダAWS
インスタンスサイズt2.xlarge
ネットワークプライベートサブネット
オペレーティングシステムLinux Ubuntu 20.04 LTS - Focal Fossa
ファイル記述子の制限65535
最大ユーザープロセス数65535
+
+
+
+
+ +
+ ブロックチェーン設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edgeバージョン開発ブランチ上の8377162281d1a2e4342ae27cd4e5367c4364aee2にコミット
バリデータノード30
ノンバリデータノード0
コンセンサスIBFT PoA
ブロック時間2000ミリ秒
ブロックガス制限5242880
+
+
+
+
+ +
+ Loadbotの設定 +
+
+ + + + + + + + + + + + + +
総トランザクション10000
毎秒送信されるトランザクション400
トランザクションの種類EOAからEOAへの転送
+
+
+
+
diff --git a/archive/edge/ja-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/ja-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..988e26861b --- /dev/null +++ b/archive/edge/ja-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,389 @@ +--- +id: test-2022-03-02 +title: 2022年3月2日 +description: "3月2日のパフォーマンステスト" +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### まとめ {#summary} + +:::caution +これらのテストを実行するために使用`loadbot`した当社は、減価償却を行っています。 +::: + +このテストは高負荷時のSC ERC20トークン転送とSC ERC721トークンのミント機能およびトランザクションのスピードを測定するために行われました。 + +目標は高負荷時にすべてが予想通りに機能するかチェックすることでした。これはLoadbot出力でガスメトリクスを導入した理由でもあり、ブロックが適切にトランザクションで満たされていたかを表示するものです。 + +すべてのトランザクションはGRPC APIを介してシングルノードに送信され、受領確認はJSON-RPC APIを介して受信されました。すべてのトランザクションが終了した後、ガス情報はeth_getBlockByNumber JSON-RPCメソッドを使用して各ブロックから読み取られました。 + +目的は可能な限り最大のTPSを達成することに努めることではありませんでした。ブロックガス制限とブロック時間をシステムリソースをあまり消費しない妥当な値に設定することで、コモディティのハードウェアでの実行を可能にすることです。 + +### 結果 ERC20 {#results-erc20} + +| メトリック | 値 | +| ------ | ----- | +| トランザクションタイプ | ERC20 | +| 毎秒のトランザクション | 65 | +| 失敗したトランザクション | 0 | +| 成功したトランザクション | 5000 | +| ERC20トランザクション実行時間 | 76.681690秒 | +| SCデプロイ時間 | 4.048250秒 | + +### 結果 ERC721 {#results-erc721} + +| メトリック | 値 | +| ------ | ----- | +| トランザクションタイプ | ERC721 | +| 毎秒のトランザクション | 20 | +| 失敗したトランザクション | 0 | +| 成功したトランザクション | 2000 | +| ERC721トランザクション実行時間 | 97.239920秒 | +| SCデプロイ時間 | 3.048970秒 | + +### 環境 ERC20 {#environment-erc20} + +
+ ホスト設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
クラウドプロバイダAWS
インスタンスサイズt2.micro
ネットワークプライベートサブネット
オペレーティングシステムLinux Ubuntu 20.04 LTS - Focal Fossa
ファイル記述子の制限65535
最大ユーザープロセス数65535
+
+
+
+
+ +
+ ブロックチェーン設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edgeバージョン開発ブランチ上に8a033aa1afb191abdac04636d318f83f32511f3cをコミットします
バリデータノード6
ノンバリデータノード0
コンセンサスIBFT PoA
ブロック時間2秒
ブロックガス制限5242880
平均ブロック使用率95%
+
+
+
+
+ +
+ Loadbot設定 +
+
+ + + + + + + + + + + + + +
総トランザクション5000
毎秒送信されるトランザクション数200
トランザクションタイプERC20からERC20への転送
+
+
+
+
+ +
+ Loadbotログ + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### 環境 ERC721 {#environment-erc721} + +
+ ホスト設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
クラウドプロバイダAWS
インスタンスサイズt2.micro
ネットワークプライベートサブネット
オペレーティングシステムLinux Ubuntu 20.04 LTS - Focal Fossa
ファイル記述子の制限65535
最大ユーザープロセス数65535
+
+
+
+
+ +
+ ブロックチェーン設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edgeバージョン開発ブランチ上に8a033aa1afb191abdac04636d318f83f32511f3cをコミットします
バリデータノード6
ノンバリデータノード0
コンセンサスIBFT PoA
ブロック時間2秒
ブロックガス制限5242880
平均ブロック使用率94%
+
+
+
+
+ +
+ Loadbot設定 +
+
+ + + + + + + + + + + + + +
総トランザクション2000
毎秒送信されるトランザクション数200
トランザクションタイプERC721トークンミント
+
+
+
+
+ +
+ Loadbotログ + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/ja-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/ja-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..1696b276c7 --- /dev/null +++ b/archive/edge/ja-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,954 @@ +--- +id: test-2022-03-23 +title: 2022年3月23日 +description: "3月23日のパフォーマンステスト" +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### まとめ {#summary} + +:::caution +これらのテストを実行するために使用`loadbot`した当社は、減価償却を行っています。 +::: + +このテストは高負荷時のSC ERC20トークン転送、SC ERC721トークンミント、EOAからEOAへのトランザクションの機能性と、高性能のハードウェアリソースを持つノードでのトランザクションの速度を測定するために行われました。 + +目標は高負荷時にすべてが予想通りに機能するかチェックすることでした。これはLoadbot出力でガスメトリクスを導入した理由でもあり、これはブロックが適切にトランザクションで満たされていたかを表示します。 + +すべてのトランザクションはGRPC APIを介してシングルノードに送信され、受信確認はJSON-RPC APIを介して受信されました。すべてのトランザクションが終了した後、ガス情報はeth_getBlockByNumber JSON-RPCメソッドを使用して各ブロックから読み取られました。 + +狙いは利用可能なハードウェアリソースにおいて最大限のTPSに到達することにありました。これを達成するために、ブロックガス制限とブロック時間パラメータを変更することで、可能な限り最高のtps結果を得、システムの整合性と安定性を保持します。 + +:::info ブロックガス制限 + +ブロックガス制限は、トランザクションの実行に大量のガスを使用している場合には比較的高い数値に増やすことも可能です。下記に述べた例では、ERC721トークンミントはブロックガス制限を(20 000 000の代わりに)80 000 000に設定したところずっと早く実行されましたが、ブロックガス制限を8000万でERC20トークンを転送するとサーバーがクラッシュしました。 +::: + +:::info 実稼働環境 + +実稼働環境を設定する時、チェーンで高パフォーマンスを達成しようとする場合は注意を払う必要があります。ブロックガス制限パラメータが高い値に設定されている場合、ブロック時間が1秒に設定され、シングルノードに高いトランザクション負荷がかかり、そのノードが大量の(すべてが使用可能でない場合)RAMを消費し、サーバクラッシュを引き起こす可能性があります。 +Loadbotを使用してすべてを徹底的にテストし、システムリソースの利用状況を監視し、設定パラメータを適切に設定します。 +::: + +:::info Out of Memory(メモリ不足)エラー + +一部のlinuxディストリビューションはシステムの安定性を維持するために非常に高いRAM使用量(OOMエラー)を持つプロセスを自動的に中止します。このOOMエラーのログ出力は次のようになります。 +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### EOAからEOAへの転送の結果 {#results-of-eoa-to-eoa-transfers} +| メトリック | 値 | +| ------ | ----- | +| トランザクションタイプ | EOAからEOAへ | +| 毎秒トランザクション | 689 | +| 失敗したトランザクション | 0 | +| 成功したトランザクション | 20000 | +| 使用された合計ブロック数 | 25 | +| 総実行時間 | 29.921110秒 | + +### ERC20トークン転送の結果 {#results-of-erc20-token-transfers} + +| メトリック | 値 | +| ------ | ----- | +| トランザクションタイプ | ERC20 | +| 毎秒トランザクション | 500 | +| 失敗したトランザクション | 0 | +| 成功したトランザクション | 20000 | +| 使用された合計ブロック数 | 33 | +| ERC20トランザクション実行時間 | 40.402900秒 | +| SCデプロイ時間 | 2.004140秒 | + +### ERC721トークンミントの結果 {#results-of-erc721-token-minting} + +| メトリック | 値 | +| ------ | ----- | +| トランザクションタイプ | ERC721 | +| 毎秒トランザクション | 157 | +| 失敗したトランザクション | 0 | +| 成功したトランザクション | 20000 | +| 使用された合計ブロック数 | 124 | +| ERC721トランザクション実行時間 | 127.537340秒 | +| SCデプロイ時間 | 2.004420秒 | + + +### 非常に高いブロックガス制限(8000万)でのERC721トークンミントの結果 {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| メトリック | 値 | +| ------ | ----- | +| トランザクションタイプ | ERC721 | +| 毎秒トランザクション | 487 | +| 失敗したトランザクション | 0 | +| 成功したトランザクション | 20000 | +| 使用された合計ブロック数 | 34 | +| ERC721トランザクション実行時間 | 41.098410秒 | +| SCデプロイ時間 | 2.004300秒 | + + +### EOAからEOAへの環境 {#environment-eoa-to-eoa} +
+ ホスト設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
クラウドプロバイダAWS
インスタンスサイズc5.2xlarge
ネットワークプライベートサブネット
オペレーティングシステムAmazon Linux 2 AMI(HVM) - カーネル5.10
ファイル記述制限65535
最大ユーザープロセス数65535
+
+
+
+
+ +
+ ブロックチェーン設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edgeバージョン開発ブランチに06e11eac8da98c79c938fc53dda2da3318cfbe04をコミットする
バリデータノード4
ノンバリデータノード0
コンセンサスIBFT PoA
ブロック時間1秒
ブロックガス制限20000000
最大スロット1000000
平均ブロック使用率84.00%
+
+
+
+
+ +
+ Loadbotの設定 +
+
+ + + + + + + + + + + + + +
総トランザクション20000
毎秒送信されるトランザクション689
トランザクションタイプEOAからEOAへの転送
+
+
+
+
+ +
+ Loadbotログ + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### 環境 ERC20 {#environment-erc20} +
+ ホスト設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
クラウドプロバイダAWS
インスタンスサイズc5.2xlarge
ネットワークプライベートサブネット
オペレーティングシステムAmazon Linux 2 AMI(HVM) - カーネル5.10
ファイル記述制限65535
最大ユーザープロセス数65535
+
+
+
+
+ +
+ ブロックチェーン設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edgeバージョン開発ブランチに06e11eac8da98c79c938fc53dda2da3318cfbe04をコミットする
バリデータノード4
ノンバリデータノード0
コンセンサスIBFT PoA
ブロック時間1秒
ブロックガス制限20000000
最大スロット1000000
平均ブロック使用率88.38%
+
+
+
+
+ +
+ Loadbotの設定 +
+
+ + + + + + + + + + + + + +
総トランザクション20000
毎秒送信されるトランザクション500
トランザクションタイプERC20からERC20への転送
+
+
+
+
+ +
+ Loadbotログ + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### 環境 ERC721 {#environment-erc721} +
+ ホスト設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
クラウドプロバイダAWS
インスタンスサイズc5.2xlarge
ネットワークプライベートサブネット
オペレーティングシステムAmazon Linux 2 AMI(HVM) - カーネル5.10
ファイル記述制限65535
最大ユーザープロセス数65535
+
+
+
+
+ +
+ ブロックチェーン設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edgeバージョン開発ブランチに06e11eac8da98c79c938fc53dda2da3318cfbe04をコミットする
バリデータノード4
ノンバリデータノード0
コンセンサスIBFT PoA
ブロック時間1秒
ブロックガス制限20000000
最大スロット1000000
平均ブロック使用率92.90%
+
+
+
+
+ +
+ Loadbotの設定 +
+
+ + + + + + + + + + + + + +
総トランザクション20000
毎秒送信されるトランザクション157
トランザクションタイプERC721トークンミント
+
+
+
+
+ +
+ Loadbotログ + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### 環境 ERC20 - 非常に高いブロックガス制限 {#environment-erc20-very-high-block-gas-limit} +
+ ホスト設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
クラウドプロバイダAWS
インスタンスサイズc5.2xlarge
ネットワークプライベートサブネット
オペレーティングシステムAmazon Linux 2 AMI(HVM) - カーネル5.10
ファイル記述制限65535
最大ユーザープロセス数65535
+
+
+
+
+ +
+ ブロックチェーン設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edgeバージョン開発ブランチに06e11eac8da98c79c938fc53dda2da3318cfbe04をコミットする
バリデータノード4
ノンバリデータノード0
コンセンサスIBFT PoA
ブロック時間1秒
ブロックガス制限80000000
最大スロット1000000
平均ブロック使用率---
+
+
+
+
+ +
+ Loadbotの設定 +
+
+ + + + + + + + + + + + + +
総トランザクション20000
毎秒送信されるトランザクション---
トランザクションタイプERC20からERC20への転送
+
+
+
+
+ +
+ OOMエラーログ + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### 環境 ERC721 -非常に高いブロックガス制限 {#environment-erc721-very-high-block-gas-limit} +
+ ホスト設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
クラウドプロバイダAWS
インスタンスサイズc5.2xlarge
ネットワークプライベートサブネット
オペレーティングシステムAmazon Linux 2 AMI(HVM) - カーネル5.10
ファイル記述制限65535
最大ユーザープロセス数65535
+
+
+
+
+ +
+ ブロックチェーン設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edgeバージョン開発ブランチに06e11eac8da98c79c938fc53dda2da3318cfbe04をコミットする
バリデータノード4
ノンバリデータノード0
コンセンサスIBFT PoA
ブロック時間1秒
ブロックガス制限80000000
最大スロット1000000
平均ブロック使用率84.68%
+
+
+
+
+ +
+ Loadbotの設定 +
+
+ + + + + + + + + + + + + +
総トランザクション20000
毎秒送信されるトランザクション487
トランザクションタイプERC721トークンミント
+
+
+
+
+ +
+ Loadbotログ + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/ja-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/ja-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..2462dc869d --- /dev/null +++ b/archive/edge/ja-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,566 @@ +--- +id: test-2022-07-04 +title: 2022年7月4日 +description: "7月4日のパフォーマンステスト。" +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### まとめ {#summary} + +:::caution +これらのテストを実行するために使用`loadbot`した当社は、減価償却を行っています。 +::: + +このテストは高負荷時のSC ERC20トークン転送、SC ERC721トークンミント、EOAからEOAへのトランザクションの機能性と、高性能のハードウェアリソースを持つノードでのトランザクションの速度を測定するために行われました。 + +目標は高負荷時にすべてが予想通りに機能するかチェックすることでした。これはLoadbot出力でガスメトリクスを導入した理由でもあり、これはブロックが適切にトランザクションで満たされていたかを表示します。 + +すべてのトランザクションはGRPC APIを介してシングルノードに送信され、受信確認はJSON-RPC APIを介して受信されました。すべてのトランザクションが終了した後、ガス情報はeth_getBlockByNumber JSON-RPCメソッドを使用して各ブロックから読み取られました。 + +狙いは利用可能なハードウェアリソースにおいて最大限のTPSに到達することにありました。これを達成するために、ブロックガス制限とブロック時間パラメータを変更することで、可能な限り最高のtps結果を得、システムの整合性と安定性を保持します。 + + +:::info 実稼働環境 + +実稼働環境を設定する時、チェーンで高パフォーマンスを達成しようとする場合は注意を払う必要があります。ブロックガス制限パラメータが高い値に設定されている場合、ブロック時間が1秒に設定され、シングルノードに高いトランザクション負荷がかかり、そのノードが大量の(すべてが使用可能でない場合)RAMを消費し、サーバクラッシュを引き起こす可能性があります。 +loadbotを使用して、すべてを徹底的にテストし、システムリソース使用率を監視し、それに応じて設定パラメータを設定します。 + +::: + + + +### EOAからEOAへの転送の結果 {#results-of-eoa-to-eoa-transfers} +| メトリック | 値 | +| ------ | ----- | +| トランザクションタイプ | EOAからEOAへ | +| 毎秒トランザクション | 1428 | +| 失敗したトランザクション | 0 | +| 成功したトランザクション | 30000 | +| 使用された合計ブロック数 | 15 | +| 総実行時間 | 21.374620秒 | + +### ERC20トークン転送の結果 {#results-of-erc20-token-transfers} + +| メトリック | 値 | +| ------ | ----- | +| トランザクションタイプ | ERC20 | +| 毎秒トランザクション | 1111 | +| 失敗したトランザクション | 0 | +| 成功したトランザクション | 50000 | +| 使用された合計ブロック数 | 38 | +| ERC20トランザクション実行時間 | 45.906450秒 | +| SCデプロイ時間 | 2.006580秒 | + +### ERC721トークンミントの結果 {#results-of-erc721-token-minting} + +| メトリック | 値 | +| ------ | ----- | +| トランザクションタイプ | ERC721 | +| 毎秒トランザクション | 714 | +| 失敗したトランザクション | 0 | +| 成功したトランザクション | 30000 | +| 使用された合計ブロック数 | 39 | +| ERC721トランザクション実行時間 | 42.864140秒 | +| SCデプロイ時間 | 2.005500秒 | + + + + +### EOAからEOAへの環境 {#environment-eoa-to-eoa} +
+ ホスト設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
クラウドプロバイダAWS EC2
インスタンスサイズc6a.48xlarge
ネットワークプライベートサブネット
オペレーティングシステムLinux Ubuntu 20.04 LTS - Focal Fossa
ファイル記述子の制限65535
最大ユーザープロセス数65535
+
+
+
+
+ +
+ ブロックチェーン設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edgeバージョンリリース v0.4.1
バリデータノード4
ノンバリデータノード0
コンセンサスIBFT PoA
ブロック時間1秒
ブロックガス制限70778880
最大スロット276480
平均ブロック使用率59.34%
+
+
+
+
+ +
+ Loadbot設定 +
+
+ + + + + + + + + + + + + +
総トランザクション30000
毎秒送信されるトランザクション数1428
トランザクションタイプEOAからEOAへの転送
+
+
+
+
+ +
+ Loadbotログ + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### 環境 ERC20 {#environment-erc20} +
+ ホスト設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
クラウドプロバイダAWS EC2
インスタンスサイズc6a.48xlarge
ネットワークプライベートサブネット
オペレーティングシステムLinux Ubuntu 20.04 LTS - Focal Fossa
ファイル記述子の制限65535
最大ユーザープロセス数65535
+
+
+
+
+ +
+ ブロックチェーン設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edgeバージョンリリース v0.4.1
バリデータノード4
ノンバリデータノード0
コンセンサスIBFT PoA
ブロック時間1秒
ブロックガス制限47185920
最大スロット184320
平均ブロック使用率81.29%
+
+
+
+
+ +
+ Loadbot設定 +
+
+ + + + + + + + + + + + + +
総トランザクション50000
毎秒送信されるトランザクション数1111
トランザクションタイプERC20からERC20への転送
+
+
+
+
+ +
+ Loadbotログ + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### 環境 ERC721 {#environment-erc721} +
+ ホスト設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
クラウドプロバイダAWS EC2
インスタンスサイズc6a.48xlarge
ネットワークプライベートサブネット
オペレーティングシステムLinux Ubuntu 20.04 LTS - Focal Fossa
ファイル記述子の制限65535
最大ユーザープロセス数65535
+
+
+
+
+ +
+ ブロックチェーン設定 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edgeバージョンリリース v0.4.1
バリデータノード4
ノンバリデータノード0
コンセンサスIBFT PoA
ブロック時間1秒
ブロックガス制限94371840
最大スロット1000000
平均ブロック使用率93.88%
+
+
+
+
+ +
+ Loadbot設定 +
+
+ + + + + + + + + + + + + +
総トランザクション30000
毎秒送信されるトランザクション数714
トランザクションタイプERC721トークンミント
+
+
+
+
+ +
+ Loadbotログ + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/ja-edge/troubleshooting.md b/archive/edge/ja-edge/troubleshooting.md new file mode 100644 index 0000000000..193b9edb59 --- /dev/null +++ b/archive/edge/ja-edge/troubleshooting.md @@ -0,0 +1,68 @@ +--- +id: troubleshooting +title: トラブルシューティング +description: "Polygon Edgeのトラブルシューティングセクション" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# トラブルシューティング {#troubleshooting} + +## `method=eth_call err="invalid signature"`エラー {#error} + +Polygon Edgeでウォレットを使用してトランザクションを行う時は、ウォレットのローカルネットワーク設定で以下を確実に行ってください: + +1. `chainID`が正しいものである。Edgeのデフォルト`chainID`は`100`ですが、ジェネシスフラグ`--chain-id`を利用してカスタマイズすることができます。 + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. 「RPC URL」で、接続するノードのJSON RPCポートを使用するフィールドを確認してください。 + + +## WebSocketのURLを取得する方法 {#how-to-get-a-websocket-url} + +デフォルトでは、Polygon Edgeを実行するとチェーン位置に基づいてWebSocketエンドポイントが公開されます。URLスキーム`wss://`がHTTPSリンク用に、`ws://`がHTTP用に使用されます。 + +ローカルホストWebSocketのURL: +````bash +ws://:/ws +```` +ポート番号は、ノードに選択されたJSON-RPCポートによって異なることに注意してください。 + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## コントラクトをデプロイしようとしている時の`insufficient funds`エラー {#error-when-trying-to-deploy-a-contract} + +このエラーが発生した場合、望むアドレスに十分なファンドがあること、および使用されているアドレスが正しいことを確認してください。
+前払い残高を設定するには、ジェネシスフラグ`genesis [--premine ADDRESS:VALUE]`を利用し、ジェネシスファイルを生成します。このフラグを使用する例: +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +これは1000000000000000000000WEIを0x3956E90e632AEbBF34DEB49b71c28A83Bc029862に前払いします。 + + +## Chainbridgeを使用中ERC20トークンがリリースされない {#erc20-tokens-not-released-while-using-chainbridge} + +Polygon PoSとローカルのEdgeネットワークとの間でERC20トークンを転送しようとして、ERC20トークンを預け入れ、提案もリレイヤーで実行しますが、トークンはEdgeネットワークにリリースされない場合、Polygon EdgeチェーンのERC20ハンドラにリリースするのに十分なトークンがあることを確認してください。
+送信先チェーンのハンドラコントラクトではロックリリースモードのためにリリースするのに十分なトークンが必要です。ローカルEdgeネットワークのERC20ハンドラに全くERC20トークンがない場合、新しいトークンをミントし、それをERC20ハンドラに転送してください。 + +## Chainbridgeを使用する時の`Incorrect fee supplied`エラー {#error-when-using-chainbridge} + +このエラーはMumbai Polygon PoSチェーンとローカルPolygon Edge設定の間でERC20トークンを転送しようとする時に発生する可能性があります。このエラーが表示されるのは、`--fee`フラグを使用してデプロイする際の手数料を設定するものの、デポジットトランザクションでは同じ値を設定していない時です。下記のコマンドを使用して手数料を変更できます: +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +このフラグについての詳細は[こちら](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md)をご覧ください。 + + + + + diff --git a/archive/edge/ja-edge/validator-hosting.md b/archive/edge/ja-edge/validator-hosting.md new file mode 100644 index 0000000000..1691e5d891 --- /dev/null +++ b/archive/edge/ja-edge/validator-hosting.md @@ -0,0 +1,251 @@ +--- +id: validator-hosting +title: バリデータホスティング +description: "Polygon Edgeのホスティング要件" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +次に、Polygon Edgeネットワークでバリデータノードを適切にホストするための推奨事項を示します。以下の項目に注意して、バリデータの設定が安全、安定、およびパフォーマンスに適切に構成されていることを確認してください。 + +## ナレッジベース {#knowledge-base} + +バリデータノードを実行する前に、このドキュメントをよくお読みください。 +役立つその他のドキュメントは次のとおりです: + +- [インストール](get-started/installation) +- [クラウド設定](get-started/set-up-ibft-on-the-cloud) +- [CLIコマンド](get-started/cli-commands) +- [サーバ設定ファイル](configuration/sample-config) +- [秘密鍵](configuration/manage-private-keys) +- [Prometheusメトリクス](configuration/prometheus-metrics) +- [シークレットマネージャ](/docs/category/secret-managers) +- [バックアップ/復元](working-with-node/backup-restore) + +## 最小システム要件 {#minimum-system-requirements} + +| タイプ | 値 | 影響を受ける対象 | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 2コア |
  • JSON-RPCクエリの数
  • ブロックチェーン状態のサイズ
  • ブロックガス制限
  • ブロック時間
| +| RAM | 2GB |
  • JSON-RPCクエリの数
  • ブロックチェーン状態のサイズ
  • ブロックガス制限
| +| ディスク |
  • 10GBのルートパーティション
  • ディスク拡張用のLVMを使用した30GBルートパーティション
|
  • ブロックチェーン状態のサイズ
| + + +## サービス設定 {#service-configuration} + +`polygon-edge`バイナリは、ネットワーク接続が確立されると自動的にシステムサービスとして実行され、スタート/停止/再起動機能を備えている必要があります。`systemd.`のようなサービスマネージャを使用することをお勧めします + +`systemd`システム設定ファイルの例: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### バイナリ {#binary} + +実稼働環境では、`polygon-edge`バイナリは手動でコンパイルするのではなく、構築済みのGitHubリリースバイナリからのみ展開する必要があります。 +:::info + +`develop`GitHubブランチを手動でコンパイルすると、環境に破壊的な変更が加わる可能性があります。 +そのため、Polygon Edgeバイナリはリリースからのみデプロイすることをお勧めします。これには、破壊的な変更の克服方法に関する情報が含まれてるためです。 + +::: + +インストールメソッドの詳細については、[インストール](/docs/edge/get-started/installation)を参照してください。 + +### データストレージ {#data-storage} + +ブロックチェーン全体の状態を含む`data/`フォルダは、自動的にディスクバックアップ、ボリューム拡張ができ、かつ障害発生時にディスク/ボリュームを別のインスタンスにオプションとしてマウントできるように、専用のディスク/ボリュームにマウントする必要があります。 + + +### ログファイル {#log-files} + +ログファイルは(`logrotate`のようなツールを使用して)毎日ローテーションする必要があります。 +:::warning + +ログローテーションなしで設定すると、ログファイルが使用可能なディスク領域をすべて使い果たし、バリデータのアップタイムが中断される可能性があります。 + +::: + +`logrotate`設定例: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +ログストレージの推奨事項については、以下の[ログ](#logging)セクションを参照してください。 + +### その他の依存関係 {#additional-dependencies} + +`polygon-edge`は静的にコンパイルされ、追加のホストOS依存性は必要ありません。 + +## メンテナンス {#maintenance} + +次に、Polygon Edgeネットワークの実行中のバリデータノードを維持するためのベストプラクティスを示します。 + +### バックアップ {#backup} + +Polygon Edgeノードに推奨されるバックアップ手順は2種類あります。 + +可能な場合は、Polygon Edgeバックアップを常に使用できるオプションとして両方を使用することをお勧めします。 + +* ***ボリュームバックアップ*** : +Polygon Edgeノードの`data/`ボリュームまたは可能な場合は、全体のVMの毎日増分バックアップです。 + + +* ***Polygon Edgeバックアップ*** : +Polygon Edgeの定期的なバックアップを行い、`.dat`ファイルをオフサイトまたは安全なクラウドオブジェクトストレージに移動するCRONジョブを毎日実行することをお勧めします。 + +Polygon Edgeバックアップは、理想としては上記のボリュームバックアップと重複すべきではありません。 + +Polygon Edgeのバックアップの実行方法については、[バックアップ/復元ノードのインスタンス](working-with-node/backup-restore)を参照してください。 + +### ログ {#logging} + +Polygon Edgeノードから出力されるログは次のとおりです: +- インデックス化と検索機能を備えた外部データストアに送信されます +- ログ保持期間は30日です + +Polygon Edgeバリデータを初めて設定する場合は、問題を迅速にデバッグできる`--log-level=DEBUG`オプションを使用してノードをスタートすることをお勧めします。 + +:::info + +`--log-level=DEBUG`により、ノードのログ出力は可能な限り詳細になります。 +デバッグログは、ログローテーションソリューションを設定する際に考慮する必要があるログファイルのサイズを大幅に大きくします。 +::: +### OSセキュリティパッチ {#os-security-patches} + +管理者は、バリデータインスタンスOSが常に最新のパッチで更新されていることを毎月少なくとも1回は確認する必要があります。 + +## メトリクス {#metrics} + +### システムメトリクス {#system-metrics} + +管理者は、何らかのシステムメトリクスモニタ(Telegraf + InfluceDB + GrafanaまたはサードパーティのSaaSなど)を設定する必要があります。 + +監視する必要があり、アラーム通知を設定する必要があるメトリクス: + +| メトリクス名 | アラームしきい値 | +|-----------------------|-------------------------------| +| CPU使用率(%) | 90%を超える(5分以上) | +| RAM使用率(%) | 90%を超える(5分以上) | +| ルートディスク使用率(%) | 90%を超える | +| データディスク使用率 | 90%を超える | + +### バリデータメトリクス {#validator-metrics} + +管理者は、ブロックチェーンのパフォーマンスを監視するために、Polygon EdgeのPrometheus APIからメトリクスのコレクションを設定する必要があります。 + +公開されているメトリクスとPrometheusメトリクス収集を設定する方法を理解するには、[Prometheusメトリクス](configuration/prometheus-metrics)を参照してください。 + + +次のメトリクスに特に注意する必要があります: +- ***ブロック生産時間*** - ブロックの生産時間が通常よりも長い場合は、ネットワークに潜在的な問題がある可能性があります +- ***コンセンサスラウンド数*** - ラウンドが複数ある場合は、ネットワーク内のバリデータセットに問題がある可能性があります +- ***ピアの数*** - ピアの数が減少すると、ネットワークに接続の問題があります + +## セキュリティ {#security} + +次に、Polygon Edgeネットワークの実行中のバリデータノードを保護するためのベストプラクティスを示します。 + +### APIサービス {#api-services} + +- ***JSON-RPC*** - +(ロードバランサを介して、または直接)公開する必要がある唯一のAPIサービスです。 +このAPIは、すべてのインターフェイスまたは特定のIPアドレス(例:`--json-rpc 0.0.0.0:8545`または`--json-prc 192.168.1.1:8545`)で実行する必要があります。 +:::info + +これはAPIに公開されているため、セキュリティとレート制限を提供するために、ロードバランサ/リバースプロキシを前面に配置することをお勧めします。 + +::: + + +- ***LibP2P*** - +これは、ノードがピア通信に使用するネットワークAPIです。すべてのインターフェイスまたは特定のIPアドレス(`--libp2p 0.0.0.0:1478`または`--libp2p 192.168.1.1:1478`)で実行する必要があります。このAPIは公開すべきではありませんが、他のすべてのノードから到達可能である必要があります。 +:::info + +ローカルホスト(`--libp2p 127.0.0.1:1478`)で実行した場合、他のノードは接続できません。 + +::: + + +- ***GRPC*** +このAPIは、オペレータコマンドを実行し、他のコマンドに注意する場合にだけ使用されます。したがって、ローカルホスト(`--grpc-address 127.0.0.1:9632`)だけで実行する必要があります。 + +### Polygon Edgeシークレット {#polygon-edge-secrets} + +Polygon Edgeのシークレット(`ibft`と`libp2p`鍵)は、ローカルファイルシステムに保存するべきではありません。 +代わりに、サポートされている[シークレットマネージャ](configuration/secret-managers/set-up-aws-ssm)を使用する必要があります。 +ローカルファイルシステムへのシークレットの保存は、実稼働環境以外の環境でのみ使用する必要があります。 + +## 更新 {#update} + +次に、バリデータノードに必要なアップデート手順を示します。手順はステップバイステップで説明しています。 + +### 更新手順 {#update-procedure} + +- 公式GitHub[リリース](https://github.com/0xPolygon/polygon-edge/releases)から最新のPolygon Edgeバイナリをダウンロードします +- Polygon Edgeサービスを停止します(例:`sudo systemctl stop polygon-edge.service`) +- 既存のバイナリをダウンロードした`polygon-edge`バイナリと置き換えます(例:`sudo mv polygon-edge /usr/local/bin/`) +- `polygon-edge version`を実行して正しい`polygon-edge`バージョンがインストールされているかどうかを確認します。リリースバージョンに対応している必要があります。 +- `polygon-edge`サービスを開始する前に、下位互換性の手順を実行する必要がある場合は、リリースドキュメントを確認します。 +- `polygon-edge`サービスをスタートします(例:`sudo systemctl start polygon-edge.service`) +- 最後に、`polygon-edge`ログ出力を確認し、`[ERROR]`ログなしですべてが実行されていることを確認します + +:::warning + +ブレークリリースがある場合は、現在実行中のバイナリが新しいリリースと互換性がないため、このアップデート手順をすべてのノードで実行する必要があります。 + +つまり、`polygon-edge`バイナリが交換され、サービスが再起動されるまで、チェーンを短時間停止する必要があるため、それに応じて計画を立てます。 + +**[Ansible](https://www.ansible.com/)**や一部のカスタムスクリプトなどのツールを使用して、アップデートを効率的に実行し、チェーンダウンタイムを最小限に抑えることができます。 +::: + +## スタートアップ手順 {#startup-procedure} + +次に、望ましいPolygon Edgeバリデータの起動手順のフローを示します + +- [ナレッジベース](#knowledge-base)のセクションに記載されているドキュメントを読みます +- バリデータノードに最新のOSパッチを適用します +- 公式GitHub[リリース](https://github.com/0xPolygon/polygon-edge/releases)から最新の`polygon-edge`バイナリをダウンロードし、ローカルインスタンス`PATH`に置きます +- `polygon-edge secrets generate`CLIコマンドを使用して、サポートされている[シークレットマネージャ](/docs/category/secret-managers)のひとつを初期化します +- `polygon-edge secrets init`[CLIコマンド](/docs/edge/get-started/cli-commands#secrets-init-flags)を使用してシークレットを生成し、保存します +- `NodeID`と`Public key (address)`の値に注意します +- `polygon-edge genesis`[CLIコマンド](/docs/edge/get-started/cli-commands#genesis-flags)を使用して、[クラウド設定](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators)の説明に従って`genesis.json`ファイルを生成します +- `polygon-edge server export`[CLIコマンド](/docs/edge/configuration/sample-config)を使用してデフォルトの設定ファイルを生成します +- ローカルバリデータノード環境(ファイルパスなど)に対応するように`default-config.yaml`ファイルを編集します +- `polygon-edge`バイナリが`default-config.yaml`ファイルからサーバを実行するPolygon Edgeサービス(`systemd`または類似のもの)を作成します +- サービスを開始して、Polygon Edgeサーバーをスタートします(例:`systemctl start polygon-edge`) +- `polygon-edge`ログ出力を確認し、ブロックが生成されていること、および`[ERROR]`ログがないことを確認します +- [`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid)のようなJSON-RPCメソッドを呼び出して、チェーンの機能を確認します diff --git a/archive/edge/ja-edge/working-with-node/backup-restore.md b/archive/edge/ja-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..673c0b3dd8 --- /dev/null +++ b/archive/edge/ja-edge/working-with-node/backup-restore.md @@ -0,0 +1,87 @@ +--- +id: backup-restore +title: ノードインスタンスのバックアップ/復元 +description: "Polygon Edgeノードインスタンスをバックアップおよび復元する方法。" +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## 概要 {#overview} + +このガイドでは、Polygon Edgeノードインスタンスをバックアップおよび復元する方法について詳しく説明します。 +基本フォルダとその内容、およびバックアップと復元を正常に実行するために重要なファイルについて説明します。 + +## 基本フォルダ {#base-folders} + +Polygon Edgeは、ストレージエンジンとしてLevelDBを活用しています。 +Polygon Edgeノードを起動すると、指定した作業ディレクトリに次のサブフォルダが作成されます: +* **blockchain** - ブロックチェーンデータを保存します +* **trie** - Merkleトライ(ワールドステートデータ)を保存します +* **keystore** - クライアントの秘密鍵を保存します。これには、libp2p秘密鍵とシーリング/バリデータ秘密鍵が含まれます +* **consensus** - 作業中にクライアントに必要なすべてのコンセンサス情報を保存します。現在のところ、ノードの*バリデータ秘密鍵*が保存されます + +Polygon Edgeインスタンスをスムーズに実行するには、これらのフォルダを維持することが重要です。 + +## 実行中のノードからバックアップを作成し、新しいノードに復元を行います {#create-backup-from-a-running-node-and-restore-for-new-node} + +このセクションでは、実行中のノードでブロックチェーンのアーカイブデータを作成し、別のインスタンスに復元する手順について説明します。 + +### バックアップ {#backup} + +`backup`コマンドは、gRPCによって実行ノードからブロックを取得し、アーカイブファイルを生成します。コマンドに`--from`と`--to`が指定されていない場合、このコマンドはブロックをジェネシスから最新に取り込みます。 + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### 復元 {#restore} + +サーバは、`--restore`フラグで始まるときに、スタート時にアーカイブからブロックをインポートします。新しいノードの鍵があることを確認してください。鍵のインポートまたは生成の詳細については、[シークレットマネージャセクション](/docs/edge/configuration/secret-managers/set-up-aws-ssm)を参照してください。 + +```bash +$ polygon-edge server --restore archive.dat +``` + +## データ全体のバックアップ/復元 {#back-up-restore-whole-data} + +このセクションでは、状態データと鍵を含むデータのバックアップと新しいインスタンスへの復元について説明します。 + +### ステップ1:実行中のクライアントを停止します {#step-1-stop-the-running-client} + +Polygon Edgeはデータストレージに**LevelDB**を使用するため、**LevelDB**はデータベースファイルへの同時アクセスを許可しないため、バックアップ中はノードを停止する必要があります。 + +さらに、Polygon Edgeはクローズ時にデータのフラッシュも行います。 + +最初のステップでは、(サービスマネージャ、またはプロセスにSIGINT信号を送信する他のメカニズムを使用して)実行中のクライアントを停止します。そうすると正常にシャットダウンしながら2つのイベントをトリガーできます: +* 実行中のデータをディスクにフラッシュ +* LevelDBによるDBファイルロックの解除 + +### ステップ2:ディレクトリのバックアップ {#step-2-backup-the-directory} + +クライアントが実行されていないので、データディレクトリを別のメディアにバックアップできます。`.key`拡張子を持つファイルには、現在のノードのなりすましに使用できる秘密鍵データが含まれており、これらのデータを第三者または未知の者と共有してはいけないということを心に留めておいてください。 + +:::info + +生成された`genesis`ファイルを手動でバックアップして復元してください。そうすると復元されたノードが完全に動作します。 +::: + +## 復元 {#restore-1} + +### ステップ1:実行中のクライアントを停止します {#step-1-stop-the-running-client-1} + +Polygon Edgeのいずれかのインスタンスが実行されている場合は、ステップ2を正常に実行するために停止する必要があります。 + +### ステップ2:バックアップしたデータディレクトリを目的のフォルダにコピーします {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +クライアントが実行されていない場合は、バックアップ済みのデータディレクトリを目的のフォルダにコピーできます。 +さらに、以前にコピーした`genesis`ファイルを復元します。 + +### ステップ3:正しいデータディレクトリを指定しながら、Polygon Edgeクライアントを実行します {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +Polygon Edgeで復元されたデータディレクトリを使用するには、起動時にユーザーがデータディレクトリへのパスを指定する必要があります。`data-dir`フラグに関する情報については、[CLIコマンド](/docs/edge/get-started/cli-commands)のセクションを参照してください。 diff --git a/archive/edge/ja-edge/working-with-node/query-json-rpc.md b/archive/edge/ja-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..05bf7638ba --- /dev/null +++ b/archive/edge/ja-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,89 @@ +--- +id: query-json-rpc +title: JSON RPCエンドポイントのクエリ +description: "前払いアカウントでデータをクエリし、チェーンを起動します。" +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## 概要 {#overview} + +Polygon EdgeのJSON RPCレイヤーは開発者にHTTPリクエストを通じてブロックチェーンと簡単にやり取りする機能を提供します。 + +この例は情報のクエリに**curl**などのツールを使用することや前払いアカウントでチェーンを起動し、トランザクションを送信することをカバーします。 + +## ステップ1:前払いアカウントでジェネシスファイルを作成 {#step-1-create-a-genesis-file-with-a-premined-account} + +ジェネシスファイルを作成するには、次のコマンドを実行します: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +**premine**フラグは**ジェネシス**ファイルの当初残高に含まれるアドレスを設定します
+この場合、アドレス`0x1010101010101010101010101010101010101010`は当初の**デフォルト残高**は +`0xD3C21BCECCEDA1000000`となります(100万個のネイティブ通貨トークン)。 + +残高を指定したかった場合は、`:`を使用して残高とアドレスをこのように分けられます: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +残高は`hex`または`uint256`値のいずれかになります。 + +:::warning 秘密鍵を持つのは前払いアカウントのみです! + +アカウントに前払いし、これらにアクセスするための秘密鍵を持たない場合、前払い残高は使用できなくなります + +::: + +## ステップ2:Polygon Edgeの開発モードでの起動 {#step-2-start-the-polygon-edge-in-dev-mode} + +[CLIコマンド](/docs/edge/get-started/cli-commands)セクションで説明している、Polygon Edgeを開発モードで起動するには、次を実行します: +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## ステップ3:アカウント残高のクエリ {#step-3-query-the-account-balance} + +クライアントが**ステップ1**で作成したジェネシスファイルを使用して開発モードで起動、実行したら、**curl**などのツールを使用してアカウント残高をクエリすることができます: +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +コマンドは次の出力を返すはずです: +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## ステップ4:転送トランザクションの送信 {#step-4-send-a-transfer-transaction} + +前払い用に設定したアカウントに正しい残高があることを確認したら、Etherを転送できます: + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/ja-edge/working-with-node/query-operator-info.md b/archive/edge/ja-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..81c5dc58ed --- /dev/null +++ b/archive/edge/ja-edge/working-with-node/query-operator-info.md @@ -0,0 +1,85 @@ +--- +id: query-operator-info +title: オペレータ情報をクエリする +description: "オペレータ情報をクエリする方法" +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## 前提条件 {#prerequisites} + +このガイドでは、すでに[ローカル設定](/docs/edge/get-started/set-up-ibft-locally)または[クラウドにIBFTクラスタを設定する方法のガイド](/docs/edge/get-started/set-up-ibft-on-the-cloud)を読まれたことを前提にしています。 + +どのような種類のオペレータ情報でもクエリするために機能しているノードが必要です。 + +Polygon Edgeで、ノードオペレータは制御され、それらが動作しているノードが何を実施しているかについて知らされます。
+いつでも、gRPC上に構築されたノード情報レイヤーを使用し、重要な情報を得ることができます。ログの精査は不要です。 + +:::note + +ノードが`127.0.0.1:8545`で実行されていない場合は、このドキュメントにリストされているコマンドにフラグ`--grpc-address `を追加してください。 + +::: + +## ピア情報 {#peer-information} + +### ピアリスト {#peers-list} + +接続されたピアの完全なリスト(実行中のノード自体を含む)を取得するには、次のコマンドを実行します: +````bash +polygon-edge peers list +```` + +これにより、実行中のクライアントの現在のピアであるlibp2pアドレスのリストが返されます。 + +### ピアステータス {#peer-status} + +特定のピアのステータスについては、次を実行してください: +````bash +polygon-edge peers status --peer-id
+```` +*アドレス*パラメータはピアのlibp2pアドレスです。 + +## IBFT情報 {#ibft-info} + +多くの場合において、オペレータは、IBFTコンセンサスで操作中のノードの状態について知りたいと思うかもしれません。 + +幸いなことに、Polygon Edgeはこの情報を見つける簡単な方法を提供しています。 + +### スナップショット {#snapshots} + +次のコマンドを実行すると、最新のスナップショットが返されます。 +````bash +polygon-edge ibft snapshot +```` +特定の高さ(ブロック番号)でスナップショットをクエリするには、オペレータは次を実行します: +````bash +polygon-edge ibft snapshot --num +```` + +### 候補者 {#candidates} + +候補者の最新情報を得るには、オペレータは次を実行できます: +````bash +polygon-edge ibft candidates +```` +このコマンドは提案された候補者の現在のセット、およびまだ含まれてない候補者をクエリします。 + +### ステータス {#status} + +次のコマンドは実行中のIBFTクライアントの現在のバリデータ鍵を返します: +````bash +polygon-edge ibft status +```` + +## トランザクションプール {#transaction-pool} + +トランザクションプールで現在のトランザクション数を見つけるには、オペレータは次を実行します: +````bash +polygon-edge txpool status +```` diff --git a/archive/edge/ko-edge/additional-features/blockscout.md b/archive/edge/ko-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..bcdade38c9 --- /dev/null +++ b/archive/edge/ko-edge/additional-features/blockscout.md @@ -0,0 +1,417 @@ +--- +id: blockscout +title: Blockscout +description: Polygon 엣지와 함께 작동하도록 Blockscout 인스턴스를 설정하는 방법. +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## 개요 {#overview} +이 가이드는 Blockscout 인스턴스를 Polygon 에지와 함께 작동하도록 컴파일하고 배포하는 방법에 대해 자세히 설명합니다. +Blockscout에는 자체 [문서](https://docs.blockscout.com/for-developers/manual-deployment)가 있지만 이 가이드는 Blockscout 인스턴스를 설정하는 방법의 간단하지만 자세한 단계별 지침에 중점을 둡니다. + +## 환경 {#environment} +* 운영체제: sudo 권한이 있는 Ubuntu Server 20.04 LTS [다운로드 링크](https://releases.ubuntu.com/20.04/) +* 서버 하드웨어: CPU 8개/16GB RAM/50GB HDD(LVM) +* 데이터베이스 서버: CPU 2개/4GB RAM/100GB SSD/PostgreSQL 13.4 전용 서버 + +### DB 서버 {#db-server} +이 가이드를 따르려면 데이터베이스 서버가 준비되어 있고, 데이터베이스와 DB 사용자가 구성되어 있어야 합니다. +PostgreSQL 서버를 배포하고 구성하는 방법은 이 가이드에서 자세히 다루지 않습니다. +[DigitalOcean 가이드](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart)처럼 이를 위한 가이드는 많습니다. + +:::info 고지 사항 + +이상적인 프로덕션 설정이 아닌 단일 인스턴스에서 Blockscout을 시작하고 실행하는 데 도움을 주는 가이드입니다. +프로덕션에서는 역방향 프록시, 부하 분산 장치, 확장성 옵션 등을 아키텍처에 도입하고 싶을 것입니다. + +::: + +# Blockscout 배포 절차 {#blockscout-deployment-procedure} + +## 파트 1 - 종속 항목 설치 {#part-1-install-dependencies} +시작하기 전에 Blockscout가 의존하는 모든 바이너리를 설치해야 합니다. + +### 업데이트 및 업그레이드 시스템 {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### Erlang 저장소 추가 {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### NodeJS 저장소 추가 {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### Rust 설치 {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### 필요한 Erlang 버전 설치 {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### 필요한 Elixir 버전 설치 {#install-required-version-of-elixir} +Elixir 버전은 `1.13`이어야 합니다. 공식 저장소에서 이 버전을 설치하려고 하면 +`erlang`이 `Erlang/OTP 25`로 업데이트되며, 이는 올바른 버전이 아닙니다. +따라서 GitHub 릴리스 페이지에서 미리 컴파일된 특정 `elixir` 버전을 설치해야 합니다. + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +이제 `exlixir` 시스템 바이너리를 적절히 설정해야 합니다. +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +`elixir -v`를 실행하여 `elixir` 및 `erlang`이 제대로 설치되었는지 확인합니다. +다음 결과가 출력됩니다. +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning +`Erlang/OTP`는 버전 `24`여야 하고, `Elixir`는 버전 `1.13.*`이어야 합니다. +그렇지 않으면 Blockscout를 컴파일하거나 실행하는 데 문제가 발생할 수 있습니다. + +::: +:::info + +공식 ***[Blockscout 요구 사항 페이지](https://docs.blockscout.com/for-developers/information-and-settings/requirements)***를 확인하세요. + +::: + +### NodeJS 설치 {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### Cargo 설치 {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### 다른 종속 항목 설치 {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### 필요에 따라 Postgresql 클라이언트를 설치해 DB 연결 확인 {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## 파트 2 - 환경 변수 설정 {#part-2-set-environment-variables} +Blockscout 컴파일을 시작하기 전에 환경 변수를 설정해야 합니다. +이 가이드에서는 작동을 위한 최소한의 기본값만 설정합니다. +설정할 수 있는 변수의 전체 목록은 [여기](https://docs.blockscout.com/for-developers/information-and-settings/env-variables)에서 확인하세요. + +### 데이터베이스 연결을 환경 변수로 설정 {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +이제 제공된 매개변수로 DB 연결을 테스트합니다. +PG 환경 변수를 제공했으니 다음을 실행하기만 하면 데이터베이스에 연결할 수 있습니다. +```bash +psql +``` + +데이터베이스가 올바르게 구성되었다면 다음 psql 프롬프트가 표시됩니다. +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +그렇지 않으면 다음과 같은 오류가 표시될 수 있습니다. +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +이 경우 [이 문서](https://ubuntu.com/server/docs/databases-postgresql)가 도움이 될 수 있습니다. + +:::info DB 연결 + +다음 파트로 넘어가기 전에 모든 DB 연결 문제를 해결했는지 확인하세요. +Blockscout 사용자에게 슈퍼유저 권한을 부여해야 합니다. + +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## 파트 3 - Blockscout 복제 및 컴파일 {#part-3-clone-and-compile-blockscout} +이제 마지막으로 Blockscout 설치를 시작합니다. + +### Blockscout 저장소 복제 {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### 프로덕션 빌드를 보호하는 비밀 키 기반 생성 {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +맨 마지막 줄에는 임의의 문자로 이루어진 긴 문자열이 표시됩니다. +이는 다음 단계로 넘어가기 전에 `SECRET_KEY_BASE` 환경 변수로 설정해야 합니다. +예시: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### 프로덕션 모드 설정 {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### 컴파일 {#compile} +복제 디렉터리에 CD 명령어를 입력하여 컴파일 시작 + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info + +이전에 배포했다면 이전 빌드 ***mix phx.digest.clean***에서 정적 자산을 삭제합니다. + +::: + +### 데이터베이스 마이그레이션 {#migrate-databases} +:::info + +이 부분은 DB 연결을 제대로 설정 또는 제공하지 않았거나 +DATABASE_URL 환경 변수에 잘못된 매개변수를 정의하면 실패합니다. +데이터베이스 사용자에게는 슈퍼유저 권한이 있어야 합니다. + +::: +```bash +mix do ecto.create, ecto.migrate +``` + +데이터베이스를 먼저 삭제해야 한다면, 다음을 실행하세요. +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### npm 종속 항목 설치 및 프론트엔드 자산 컴파일 {#install-npm-dependencies-and-compile-frontend-assets} +디렉터리를 프론트엔드 자산이 있는 폴더로 변경해야 합니다. + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info 참고 + +해당 자산을 컴파일하는 데 몇 분 정도 소요될 수 있으며, 출력 결과는 표시되지 않습니다. +프로세스가 멈춘 것처럼 보일 수 있지만, 조금 기다려주세요. +컴파일 프로세스가 완료되면 다음과 같이 출력됩니다.`webpack 5.69.1 compiled with 3 warnings in 104942 ms` + +::: + +### 정적 자산 빌드 {#build-static-assets} +이 단계를 진행하려면 Blockscout 복제 폴더의 루트로 돌아가야 합니다. +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### 자체 서명 인증서 생성 {#generate-self-signed-certificates} +:::info + +`https`를 사용하지 않으면 이 단계는 건너뛰어도 됩니다. + +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## 파트 4 - Blockscout 서비스 생성 및 실행 {#part-4-create-and-run-blockscout-service} +이 부분에서는 Blockscout이 백그라운드에서 실행되고 시스템 재부팅 후에도 유지되도록 시스템 서비스를 설정해야 합니다. + +### 서비스 파일 생성 {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### 서비스 파일 편집 {#edit-service-file} +원하는 Linux 텍스트 편집기를 사용해 이 파일을 편집하고 서비스를 구성합니다. +```bash +sudo vi /etc/systemd/system/explorer.service +``` +explorer.service 파일의 내용은 다음과 같습니다. +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### 시스템 부팅 시 서비스가 시작되도록 사용 설정 {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### Blockscout 복제 폴더를 시스템 전체 위치로 이동 {#move-your-blockscout-clone-folder-to-system-wide-location} +Blockscout 서비스가 Blockscout 저장소에서 복제하고 모든 자산을 컴파일한 폴더에 액세스할 수 있어야 합니다. +```bash +sudo mv ~/blockscout /usr/local +``` + +### Blockscout 서비스에서 사용할 환경 변수 파일 생성 {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info + +파트 3에서 생성한 `SECRET_KEY_BASE`를 사용합니다. + +::: +파일을 저장하고 종료합니다. + +### Blockscout 서비스 시작 {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## 파트 5 - Blockscout 인스턴스 기능 테스트 {#part-5-test-out-the-functionality-of-your-blockscout-instance} +이제 Blockscout 서비스가 실행되고 있는지 확인하는 일만 남았습니다. +다음으로 서비스 상태를 확인하세요. +```bash +sudo systemctl status explorer.service +``` + +서비스 출력 결과를 확인하려면 다음을 실행하세요. +```bash +sudo journalctl -u explorer.service -f +``` + +새로운 수신 대기 포트가 있는지 다음에서 확인할 수 있습니다. +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +수신 대기 포트 목록을 가져와야 하며 목록에는 다음 항목이 있어야 합니다. +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +Blockscout 웹 서비스는 env 파일에 정의된 포트와 프로토콜을 실행합니다. 이 예에서는 `4000`(http) 로 실행됩니다. +문제가 없으면 `http://:4000`을 통해 Blockscout 웹 포털에 액세스할 수 있습니다. + +## 고려 사항 {#considerations} +최고의 성능을 위해 Blockscout 쿼리에만 사용할 전용/로컬 `polygon-edge` 전체 아카이브 +비 유효성 검사 노드를 사용하는 것이 좋습니다. +Blockscout는 백엔드에서 모든 쿼리를 실행하므로 이 노드의 `json-rpc` API를 공개적으로 노출할 필요가 없습니다. + + +## 마무리 글 {#final-thoughts} +Blockscout 단일 인스턴스를 성공적으로 배포했습니다. 그러나 프로덕션의 경우 이 인스턴스를 Nginx 같은 역방향 프록시 뒤에 배치하는 것을 고려해야 합니다. +사용 사례에 따라 데이터베이스와 인스턴스 확장성에 대해서도 생각해 봐야 합니다. + +다양한 사용자 지정 옵션이 있으니 공식 [Blockscout 문서](https://docs.blockscout.com/)를 반드시 확인해야 합니다. \ No newline at end of file diff --git a/archive/edge/ko-edge/additional-features/chainbridge/definitions.md b/archive/edge/ko-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..ff6808f5b6 --- /dev/null +++ b/archive/edge/ko-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,220 @@ +--- +id: definitions +title: 일반적 정의 +description: ChainBridge에서 사용되는 용어의 일반적 정의 +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## 릴레이어 {#relayer} +Chainbridge는 릴레이어형 브리지입니다. 릴레이어의 역할은 요청 실행(예: 소각/잠금 해제할 토큰 수)에 투표하는 것입니다. +릴레이어는 모든 체인의 이벤트를 모니터링하고, 체인에서 `Deposit` 이벤트를 수신하는 경우 대상 체인 브리지 계약의 제안에 투표합니다. 필요한 수의 투표가 제출되면 릴레이어는 브리지 계약에서 메서드를 호출하여 제안을 실행합니다. 브리지는 핸들러 계약에 실행을 위임합니다. + + +## 계약 유형 {#types-of-contracts} +ChainBridge에서는 각 체인에 브리지, 핸들러, 대상이라는 세 가지 유형의 계약이 있습니다. + +| **유형** | **설명** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| 브리지 계약 | 요청, 투표, 실행을 관리하는 브리지 계약은 각 체인에 배포되어야 합니다. 사용자는 브리지에서 `deposit`을 호출하여 이전을 시작하고 브리지는 대상 계약에 해당하는 핸들러 계약에 프로세스를 위임합니다. 핸들러 계약이 대상 계약을 성공적으로 호출하면 브리지 계약은 `Deposit` 이벤트를 내보내 릴레이어에게 알립니다. | +| 핸들러 계약 | 이 계약은 대상 계약과 상호작용하여 입금 및 제안을 실행합니다. 사용자의 요청을 검증하고 대상 계약을 호출하며 대상 계약의 일부 설정을 지원합니다. 인터페이스가 다른 각각의 대상 계약을 호출하는 특정 핸들러 계약이 존재하며, 핸들러 계약의 간접 호출은 모든 종류의 자산이나 데이터을 이전할 수 있는 브리지를 만듭니다. 현재 ChainBridge에서 구현하는 핸들러 계약에는 ERC20 핸들러, ERC721 핸들러, 일반 핸들러의 세 가지 유형이 있습니다. | +| 대상 계약 | 교환되는 자산 또는 체인 간에 전송되는 메시지를 관리하는 계약입니다. 이 계약과의 상호작용은 브리지의 양쪽에서 이루어집니다. | + +
+ +![ChainBridge 아키텍처](/img/edge/chainbridge/architecture.svg) +*ChainBridge 아키텍처* + +
+ +
+ +![ERC20 토큰 이전 워크플로](/img/edge/chainbridge/erc20-workflow.svg) +*ERC20 토큰 이전 워크플로의 예* + +
+ +## 계정 유형 {#types-of-accounts} + +시작하기 전에, 계정에 트랜잭션을 생성하기에 충분한 기본 토큰이 있는지 확인하세요. Polygon 엣지에서는 제네시스 블록을 생성할 때 사전 채굴된 잔액을 계정에 할당할 수 있습니다. + +| **유형** | **설명** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| 관리자 | 이 계정에 기본적으로 관리자 역할이 부여됩니다. | +| 사용자 | 자산을 전송/수신하는 발신자/수신자 계정입니다. 토큰 이전을 승인하고 이전을 시작하기 위해 브리지 계약에서 입금을 호출할 때 발신자 계정은 가스 요금을 지불합니다. | + +:::info 관리자 역할 + +특정 작업은 관리자 역할 계정에서만 수행할 수 있습니다. 기본적으로 브리지 계약의 배포자는 관리자 역할을 갖습니다. 다른 계정에 관리자 역할을 부여하거나 삭제하는 방법은 아래에서 확인할 수 있습니다. + +### 관리자 역할 추가 {#add-admin-role} + +관리자 추가 + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### 관리자 역할 취소 {#revoke-admin-role} + +관리자 삭제 + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## `admin` 계정이 허용하는 작업은 다음과 같습니다. {#account-are-as-below} + +### 리소스 설정 {#set-resource} + +핸들러 계약 주소로 리소스 ID를 등록합니다. + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### 계약을 소각/발행 가능하도록 만들기 {#make-contract-burnable-mintable} + +핸들러에서 토큰 계약을 발행/소각 가능하도록 설정합니다. + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### 제안 취소 {#cancel-proposal} + +실행할 제안을 취소합니다. + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### 일시 정지/일시 정지 해제 {#pause-unpause} + +입금, 제안 생성, 투표, 입금 실행을 일시적으로 정지합니다. + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### 요금 변경 {#change-fee} + +브리지 계약에 지불되는 요금을 변경합니다. + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### 릴레이어 추가/삭제 {#add-remove-a-relayer} + +계정을 새 릴레이어로 추가하거나 릴레이어에서 계정을 삭제합니다. + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### 릴레이어 임계값 변경 {#change-relayer-threshold} + +제안 실행에 필요한 투표 수를 변경합니다. + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## 체인 ID {#chain-id} + +ChainBridge `chainId`는 블록체인 네트워크를 구별하기 위해 브릿지에서 사용하는 임의의 값으로, uint8의 범위 안에 있어야 합니다. 혼등하지 않도록 언급하자면, 이는 네트워크의 체인 ID와 동일하지 않습니다. 고유한 값이어야 하지만 네트워크의 ID와 같을 필요는 없습니다. + +이 사례에서는 Mumbai 테스트넷의 체인 ID가 `80001`이지만 uint8로 표현할 수 없으므로 `chainId`에 `99`를 설정했습니다. + +## 리소스 ID {#resource-id} + +리소스 ID는 네트워크 간에 전송되는 특정 자산(리소스)과 연결된, 크로스체인 환경 내의 고유한 32바이트 값입니다. + +리소스 ID는 임의의 값이지만 보통은 규칙으로 마지막 바이트에 소스 체인(이 자산의 출처인 네트워크)의 체인 ID가 포함됩니다. + +## Polygon PoS용 JSON-RPC URL {#json-rpc-url-for-polygon-pos} + +이 가이드에서는 Polygon이 제공하는 공개 JSON-RPC URL(https://rpc-mumbai.matic.today)을 사용합니다(트래픽 제한 또는 속도 제한이 있을 수 있음). 이는 Polygon Mumbai 테스트넷과 연결하는 데에만 사용됩니다. 계약을 배포하는 경우 JSON-RPC에 많은 쿼리/요청을 보내기 때문에 Infura와 같은 외부 서비스에서 JSON-RPC URL을 얻는 것을 권장합니다. + +## 토큰 이전 처리 방법 {#ways-of-processing-the-transfer-of-tokens} +체인 간에 ERC20 토큰을 이전할 때는 다음 두 가지 모드에서 처리할 수 있습니다. + +### 잠금/해제 모드 {#lock-release-mode} +소스 체인: 전송하려는 토큰은 핸들러 계약에서 잠금 처리됩니다.
+대상 체인: 소스 체인에서 전송한 금액 만큼의 토큰이 잠금 해제되고, 핸들러 계약에서 대상 체인의 수신자 계정으로 이전됩니다. + +### 소각/발행 모드 {#burn-mint-mode} +소스 체인: 전송하려는 토큰은 소각됩니다.
대상 체인: 소스 체인에서 전송 및 소각된 금액 만큼의 토큰이 대상 체인에서 발행되어 수신자 계정으로 이전됩니다. + +체인마다 서로 다른 모드를 사용할 수 있습니다. 즉, 이전을 위해 서브체인에서 토큰을 발행하면서 메인 체인에서는 토큰을 잠금 처리할 수 있습니다. 예를 들어, 총 공급 일정이나 발행 일정이 통제되는 경우 토큰을 잠금/해제하는 것이 합리적일 수 있습니다. 서브체인의 계약이 메인 체인의 공급을 따라야 하는 경우 토큰이 발행/소각됩니다. + +기본 모드는 잠금/해제 모드입니다. 토큰을 발행/소각 가능하도록 하려면 `adminSetBurnable` 메서드를 호출해야 합니다. 실행 즉시 토큰을 발행하려면 ERC20 핸들러 계약에 `minter` 역할을 부여해야 합니다. + + diff --git a/archive/edge/ko-edge/additional-features/chainbridge/overview.md b/archive/edge/ko-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..aa6fda9fe1 --- /dev/null +++ b/archive/edge/ko-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: 개요 +description: ChainBridge 개요 +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## ChainBridge란? {#what-is-chainbridge} + +ChainSafe가 빌드한 ChainBridge는 EVM 및 Substrate 호환 체인을 지원하는 모듈식 다방향 블록체인 브리지입니다. 사용자는 2개의 서로 다른 체인 사이에서 모든 종류의 자산 또는 메시지를 전송할 수 있습니다. + +ChainBridge에 관한 자세한 정보를 확인하려면 개발자가 제공하는 [공식 문서](https://chainbridge.chainsafe.io/)를 참고하시기 바랍니다. + +이 가이드는 ChainBridge를 Polygon 엣지에 통합하는 것을 돕기 위한 것으로, 실행 중인 Polygon PoS(Mumbai 테스트넷)와 로컬 Polygon 엣지 네트워크 간의 브리지 설정 방법을 안내합니다. + +## 요구사항 {#requirements} + +이 가이드에서는 Polygon 엣지 노드, ChainBridge 릴레이어(자세한 내용은 [여기](/docs/edge/additional-features/chainbridge/definitions) 참조), 로컬로 계약을 배포하고 리소스를 등록하며 브리지 설정을 변경하는 CLI 도구인 cb-sol-cli 도구([여기](https://chainbridge.chainsafe.io/cli-options/#cli-options) 참조)를 실행합니다. 설정을 시작하기 전에 다음 환경을 갖춰야 합니다. + +* Go: 1.17 이상 +* Node.js: 16.13.0 이상 +* Git + + +또한, 다음 저장소를 일부 애플리케이션을 실행할 버전으로 복제해야 합니다. + +* [Polygon 엣지](https://github.com/0xPolygon/polygon-edge): `develop` 분기에서 +* [ChainBridge](https://github.com/ChainSafe/ChainBridge): v1.1.5 +* [ChainBridge 배포 도구](https://github.com/ChainSafe/chainbridge-deploy): `main` 분기의 `f2aa093` + + +다음 섹션으로 넘어가기 전에 Polygon 엣지 네트워크를 설정해야 합니다. 자세한 내용은 [로컬 설정](/docs/edge/get-started/set-up-ibft-locally) 또는 [클라우드 설정](/docs/edge/get-started/set-up-ibft-on-the-cloud)을 확인하시기 바랍니다. \ No newline at end of file diff --git a/archive/edge/ko-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/ko-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..86cffed731 --- /dev/null +++ b/archive/edge/ko-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,142 @@ +--- +id: setup-erc20-transfer +title: ERC20 토큰 이전 +description: ChainBridge에서 ERC-20 이전 설정 방법 +keywords: + - docs + - polygon + - edge + - Bridge +--- + +지금까지 Polygon PoS와 Polygon 엣지 체인 간에 자산/데이터를 교환하기 위한 브리지를 설정했습니다. 이 섹션에서는 ERC20 브리지를 설정하고 서로 다른 블록체인 간에 토큰을 전송하는 방법을 설명합니다. + +## 1단계: 리소스 ID 등록 {#step-1-register-resource-id} + +첫째, 크로스체인 환경의 리소스와 연결된 리소스 ID를 등록합니다. 리소스 ID는 이러한 블록체인 간에 이전하는 리소스에 고유한 32바이트 값이어야 합니다. 리소스 ID는 임의의 값이지만 규칙을 통해 마지막 바이트에 홈 체인의 체인 ID를 포함할 수 있습니다(홈 체인은 리소스를 가져온 원래 네트워크를 가리킵니다). + +리소스 ID를 등록하려면 `cb-sol-cli bridge register-resource` 명령어를 사용하면 됩니다. `admin` 계정의 비공개 키를 제공해야 합니다. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (선택 사항) 계약을 발행/소각 가능하도록 만들기 {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## 2단계: ERC20 토큰 이전 {#step-2-transfer-erc20-token} + +Polygon PoS 체인에서 Polygon 엣지 체인으로 ERC20 토큰을 전송합니다. + +먼저 토큰을 발행하여 가져올 수 있습니다. `minter` 역할이 있는 계정은 새 토큰을 발행할 수 있습니다. ERC20 계약을 배포한 계정은 기본적으로 `minter` 역할이 있습니다. 다른 계정을 `minter` 역할의 구성원으로 지정하려면 `cb-sol-cli erc20 add-minter` 명령어를 실행해야 합니다. + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +현재 잔액을 확인하려면 `cb-sol-cli erc20 balance` 명령어를 사용하면 됩니다. + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +그런 다음, ERC20 핸들러로 계정의 ERC20 토큰 이전을 승인해야 합니다. + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +토큰을 Polygon 엣지 체인으로 이전하려면 `deposit`을 호출합니다. + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +입금 트랜잭션이 성공하면 릴레이어가 이벤트를 가져와 해당 제안에 투표합니다. 필요한 투표 수가 제출되면 Polygon 엣지 체인의 수신자 계정으로 토큰을 전송하기 위한 트랜잭션을 실행합니다. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +실행 트랜잭션이 성공하면 Polygon 엣지 체인 내에서 토큰을 받게 됩니다. + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/ko-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/ko-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..2d75502480 --- /dev/null +++ b/archive/edge/ko-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,134 @@ +--- +id: setup-erc721-transfer +title: ERC721 NFT 이전 +description: ChainBridge에서 ERC721 이전 설정 방법 +keywords: + - docs + - polygon + - edge + - Bridge +--- + +이 섹션에서는 ERC721 브리지를 설정하고 블록체인 네트워크 간에 NFT를 전송하는 방법을 설명합니다. + +## 1단계: 리소스 ID 등록 {#step-1-register-resource-id} + +먼저 두 체인의 브리지 계약에서 ERC721 토큰의 리소스 ID를 등록해야 합니다. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (선택 사항): 계약을 발행/소각 가능하도록 만들기 {#optional-make-contracts-mintable-burnable} + +토큰을 발행/소각 가능하도록 하기 위해 다음 명령어를 호출해야 합니다. + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## 2단계: NFT 이전 {#step-2-transfer-nft} + +먼저, 필요한 경우 NFT를 발행합니다. + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +NFT 소유자를 확인하기 위해 `cb-sol-cli erc721 owner`를 사용할 수 있습니다. + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +그런 다음, ERC721 핸들러에 의한 NFT 이전을 승인합니다. + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +마지막으로, 이전을 시작합니다. + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +릴레이어는 이벤트를 가져와 해당 제안에 투표합니다. 필요한 투표 수가 제출되면 Polygon 엣지 체인의 수신자 계정으로 NFT를 전송하기 위한 트랜잭션을 실행합니다. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +실행이 완료된 후 Polygon 엣지 네트워크에서 NFT의 소유자를 확인할 수 있습니다. + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/ko-edge/additional-features/chainbridge/setup.md b/archive/edge/ko-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..1027bf0b88 --- /dev/null +++ b/archive/edge/ko-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,198 @@ +--- +id: setup +title: 설정 +description: chainBridge 설정 방법 +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## 계약 배포 {#contracts-deployment} + +이 섹션에서는 `cb-sol-cli`를 사용하여 필요한 계약을 Polygon PoS 및 Polygon 엣지 체인에 배포합니다. + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +먼저 `cb-sol-cli deploy` 명령어로 Polygon PoS 체인에 계약을 배포합니다. 명령어에 `--all` 플래그를 사용하면 브리지, ERC20 핸들러, ERC721 핸들러, 일반 핸들러, ERC20 및 ERC721 계약을 포함한 모든 계약을 배포할 수 있습니다. 또한, 기본 릴레이어 계정 주소 및 임계값을 설정합니다. + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +체인 ID와 JSON-RPC URL에 관한 정보는 [여기](/docs/edge/additional-features/chainbridge/definitions)를 참조하세요. + +:::caution + +`cb-sol-cli`에서 기본 가스 가격은 `20000000`(`0.02 Gwei`)입니다. 트랜잭션에 적절한 가스 가격을 설정하려면 `--gasPrice` 인수를 사용하여 값을 설정하세요. + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +브리지 계약은 배포에 약 0x3f97b8(4167608) 가스를 사용합니다. 생성 중인 블록이 계약 생성 트랜잭션을 포함할 수 있는 충분한 블록 가스 한도를 가지고 있는지 확인하세요. Polygon 엣지에서 블록 가스 한도를 변경하는 방법에 대해 자세히 알아보려면 +[로컬 설정](/docs/edge/get-started/set-up-ibft-locally)을 확인하세요. + +::: + +계약이 배포되면 다음 결과가 표시됩니다. + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +이제 Polygon 엣지 체인에 계약을 배포할 수 있습니다. + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +다음 단계에 필요하므로, 배포된 스마트 계약 주소가 표시된 터미널 출력을 저장하세요. + +## 릴레이어 설정 {#relayer-setup} + +이 섹션에서는 2개 체인 사이에서 데이터를 교환하는 릴레이어를 시작합니다. + +우선, ChainBridge 저장소를 복제하고 빌드해야 합니다. + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +그다음, `config.json`을 생성하고 각 체인에 JSON-RPC URL, 릴레이어 주소 및 계약 주소를 설정해야 합니다. + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +릴레이어를 시작하려면, 릴레이어 계정 주소에 해당하는 비공개 키를 가져와야 합니다. 비공개 키를 가져올 때 비밀번호를 입력해야 합니다. 가져오기에 성공하면, `keys/
.key` 아래에 키가 저장됩니다. + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +이제 릴레이어를 시작할 수 있습니다. 처음 키 저장 시 선택했던 것과 동일한 비밀번호를 입력해야 합니다. + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +릴레이어가 시작되면 각 체인의 새로운 블록을 확인하기 시작할 것입니다. diff --git a/archive/edge/ko-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/ko-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..4f813fb61f --- /dev/null +++ b/archive/edge/ko-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,255 @@ +--- +id: use-case-erc20-bridge +title: 사용 사례 - ERC20 브리지 +description: ERC20 계약 브리지의 예 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +이 섹션의 목표는 실제 사용 사례를 위해 ERC20 브리지의 설정 흐름을 안내하는 것입니다. + +이 가이드에서는 Mumbai Polygon PoS 테스트넷 및 Polygon 엣지 로컬 체인을 사용합니다. Mumbai용 JSON-RPC 엔드포인트가 있는지 그리고 로컬 환경에서 Polygon 엣지를 설정했는지 확인하세요. 자세한 내용은 [로컬 설정](/docs/edge/get-started/set-up-ibft-locally) 또는 [클라우드 설정](/docs/edge/get-started/set-up-ibft-on-the-cloud)을 참조하세요. + +## 시나리오 {#scenario} + +이 시나리오의 목표는 프라이빗 체인(Polygon 엣지)에서 일반 사례의 사용자가 저비용으로 이전할 수 있도록 이미 퍼블릭 체인(Polygon PoS)에 배포한 ERC20 토큰에 대해 브리지를 설정하는 것입니다. 이 경우, 총 토큰 공급량은 퍼블릭 체인에서 정의되었으며, 프라이빗 체인에는 퍼블릭 체인에서 프라이빗 체인으로 이전된 토큰 금액만 있어야 합니다. 이러한 이유 때문에 퍼블릭 체인에서는 잠금/해제 모드를 사용하고 프라이빗 체인에서는 소각/발행 모드를 사용해야 합니다. + +퍼블릭 체인에서 프라이빗 체인으로 토큰을 보내면, 퍼블릭 체인의 ERC20 핸들러 계약에서는 해당 토큰이 잠기고 프라이빗 체인에서는 동일한 금액의 토큰이 발행됩니다. 반면, 프라이빗 체인에서 퍼블릭 체인으로 이전이 발생하면, 프라이빗 체인의 토큰은 소각되고 퍼블릭 체인의 ERC20 핸들러 계약에서는 동일한 금액의 토큰이 잠금 해제됩니다. + +## 계약 {#contracts} + +ChainBridge가 개발한 계약 대신 간단한 ERC20 계약을 사용하여 설명합니다. 소각/발행 모드의 경우, ERC20 계약에는 `mint` 및 `burnFrom` 메서드 그리고 ERC20을 위한 다음과 같은 메서드가 있어야 합니다. + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +모든 코드와 스크립트는 Github 저장소 [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example)에서 찾을 수 있습니다. + +## 1단계: 브리지 및 ERC20 핸들러 계약 배포 {#step1-deploy-bridge-and-erc20-handler-contracts} + +첫 번째로, 두 체인에서 `cb-sol-cli`를 사용하여 브리지 및 ERC20 핸들러 계약을 배포합니다. + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +다음과 같은 브리지 및 ERC20 핸들러 계약 주소를 얻게 됩니다. + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## 2단계: ERC20 계약 배포 {#step2-deploy-your-erc20-contract} + +ERC20 계약을 배포합니다. 이 예에서는 hardhat 프로젝트 [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example)를 사용해 설명합니다. + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +`.env` 파일을 생성하고 다음 값을 설정하세요. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +다음으로 두 체인에 ERC20 계약을 배포합니다. + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +배포에 성공하면 다음과 같은 계약 주소를 얻게 됩니다. + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## 3단계: 브리지에 리소스 ID 등록 {#step3-register-resource-id-in-bridge} + +크로스체인 환경의 리소스와 연관된 리소스 ID를 등록합니다. 두 체인에 동일한 리소스 ID를 설정해야 합니다. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## 4단계: 엣지의 ERC20 브리지에 발행/소각 모드 설정 {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +Polygon 엣지에서는 브리지가 소각/발행 모드로 작동할 것으로 예상됩니다. `cb-sol-cli`를 사용하여 소각/발행 모드를 설정합니다. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +또한, ERC20 핸들러 계약에 발행자 및 소각자 역할을 부여해야 합니다. + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## 5단계: 토큰 발행 {#step5-mint-token} + +Mumbai 체인에서 새로운 ERC20 토큰을 발행할 것입니다. + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +트랜잭션이 성공하면 계정은 발행된 토큰을 보유하게 됩니다. + +## 6단계: ERC20 이전 시작 {#step6-start-erc20-transfer} + +이 단계를 시작하기 전에 릴레이어를 시작했는지 확인하세요. 자세한 내용은 [설정](/docs/edge/additional-features/chainbridge/setup)을 확인하세요. + +Mumbai에서 엣지로의 토큰 이전 중에 Mumbai의 ERC20 핸들러 계약은 계정으로부터 토큰을 인출합니다. 이전 전에 승인을 호출합니다. + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +마지막으로, `cb-sol-cli`를 사용하여 Mumbai에서 엣지로의 토큰 이전을 시작합니다. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +입금 트랜잭션에 성공하면 릴레이어가 이벤트를 가져와 제안에 투표합니다. 릴레이어는 필요한 투표 수가 제출되면 Polygon 엣지 체인의 수신자 계정으로 토큰을 보내기 위한 트랜잭션을 실행합니다. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +실행 트랜잭션에 성공하면 Polygon 엣지 체인에서 토큰을 받게 됩니다. diff --git a/archive/edge/ko-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/ko-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..5e9130cdbe --- /dev/null +++ b/archive/edge/ko-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,308 @@ +--- +id: use-case-erc721-bridge +title: 사용 사례 - ERC721 브리지 +description: ERC721 계약 브리지의 예 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +이 섹션의 목표는 실제 사용 사례를 위해 ERC20 브리지의 설정 흐름에 대해 안내하는 것입니다. + +이 가이드에서는 Mumbai Polygon PoS 테스트넷 및 Polygon 엣지 로컬 체인을 사용합니다. Mumbai용 JSON-RPC 엔드포인트가 있는지 그리고 로컬 환경에서 Polygon 엣지를 설정했는지 확인하세요. 자세한 내용은 [로컬 설정](/docs/edge/get-started/set-up-ibft-locally) 또는 [클라우드 설정](/docs/edge/get-started/set-up-ibft-on-the-cloud)을 참조하세요. + +## 시나리오 {#scenario} + +이 시나리오는 일반적인 경우에 사용자가 프라이빗 체인(Polygon 엣지)에서 저비용으로 전송할 수 있도록 이미 퍼블릭 체인(Polygon PoS)에 배포된 ERC721 NFT용 브리지를 설정하는 시나리오입니다. 이 경우 원래의 메타데이터는 퍼블릭 체인에 정의되어 있고 퍼블릭 체인에서 이전된 NFT만 프라이빗 체인에 존재할 수 있습니다. 이러한 이유로 퍼블릭 체인에서는 잠금/해제 모드를 사용하고 프라이빗 체인에서는 소각/발행 모드를 사용해야 합니다. + +퍼블릭 체인에서 프라이빗 체인으로 NFT를 전송하면, 퍼블릭 체인의 ERC721 핸들러 계약에서는 해당 토큰이 잠금 처리되고 프라이빗 체인에서는 동일한 금액의 토큰이 발행됩니다. 반면, 프라이빗 체인에서 퍼블릭 체인으로 이전이 발생하면, 프라이빗 체인의 NFT는 소각되고 퍼블릭 체인의 ERC20 핸들러 계약에서 동일한 금액의 NFT가 잠금 해제됩니다. + +## 계약 {#contracts} + +ChainBridge가 개발한 계약 대신 간단한 ERC721 계약을 사용하여 설명합니다. 소각/발행 모드의 경우, ERC721 계약에는 다음과 같이 ERC721에 정의된 메서드와 별도로 `mint` 및 `burn` 메서드가 있어야 합니다. + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +모든 코드와 스크립트는 Github 저장소([Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example))에서 찾을 수 있습니다. + +## 1단계: 브리지 및 ERC721 핸들러 계약 배포 {#step1-deploy-bridge-and-erc721-handler-contracts} + +먼저, 두 체인에서 `cb-sol-cli`를 사용하여 브리지 및 ERC20 핸들러 계약을 배포합니다. + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +다음과 같은 브리지 및 ERC721 핸들러 계약 주소를 얻게 됩니다. + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## 2단계: ERC721 계약 배포 {#step2-deploy-your-erc721-contract} + +ERC721 계약을 배포합니다. 이 예에서는 hardhat 프로젝트([Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example))를 사용해 설명합니다. + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +`.env` 파일을 생성하고 다음 값을 설정하세요. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +그런 다음, 두 체인에 ERC721 계약을 배포합니다. + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +배포에 성공하면 다음과 같은 계약 주소를 얻게 됩니다. + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## 3단계: 브리지에 리소스 ID 등록 {#step3-register-resource-id-in-bridge} + +크로스체인 환경의 리소스와 연결된 리소스 ID를 등록합니다. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## 4단계: 엣지의 ERC721 브리지에 발행/소각 모드 설정 {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +브리지는 엣지에서 소각/발행 모드로 작동합니다. 소각/발행 모드를 설정합니다. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +그리고 ERC721 핸들러 계약에 발행자 및 소각자 역할을 부여해야 합니다. + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## 5단계: NFT 발행 {#step5-mint-nft} + +Mumbai 체인 내에서 새로운 ERC721 NFT를 발행합니다. + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +트랜잭션이 성공하면 해당 계정은 발행된 NFT를 보유하게 됩니다. + +## 6단계: ERC721 이전 시작 {#step6-start-erc721-transfer} + +이 단계를 시작하기 전에 릴레이어를 시작했는지 확인하시기 바랍니다. 자세한 내용은 [설정](/docs/edge/additional-features/chainbridge/setup)을 확인하세요. + +Mumbai에서 엣지로 NFT를 이전하는 동안, Mumbai의 ERC721 핸들러 계약은 계정에서 NFT를 출금합니다. 이전 전에 승인을 호출합니다. + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +마지막으로, Mumbai에서 엣지로 NFT 이전을 시작합니다. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +입금 트랜잭션에 성공하면 릴레이어가 이벤트를 가져와 해당 제안에 투표합니다. +릴레이어는 필요한 수의 투표가 제출되면 Polygon 엣지 체인의 수신자 계정으로 NFT를 이전하는 트랜잭션을 실행합니다. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +실행 트랜잭션에 성공하면 Polygon 엣지 체인 내에서 NFT를 받게 됩니다. diff --git a/archive/edge/ko-edge/additional-features/permission-contract-deployment.md b/archive/edge/ko-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..3887e11397 --- /dev/null +++ b/archive/edge/ko-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,86 @@ +--- +id: permission-contract-deployment +title: 스마트 계약 배포 권한 +description: 스마트 계약 배포 권한을 추가하는 방법. +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## 개요 {#overview} + +이 가이드에서는 스마트 계약을 배포할 수 있는 주소를 허용 목록에 추가하는 방법에 관해 자세히 설명합니다. +네트워크 운영자는 사용자가 네트워크의 목적과 무관한 스마트 계약을 배포하지 못하도록 해야 할 수 있습니다. 네트워크 운영자는 다음 작업을 할 수 있습니다. + +1. 스마트 계약 배포를 위한 허용 목록에 주소 추가 +2. 스마트 계약 배포를 위한 허용 목록에서 주소 삭제 + +## 비디오 프레젠테이션 {#video-presentation} + +[![허가 계약 배포 - 비디오](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## 사용 방법 {#how-to-use-it} + + +[CLI 명령어](/docs/edge/get-started/cli-commands#whitelist-commands) 페이지에서 배포 허용 목록과 관련된 모든 CLI 명령어를 확인할 수 있습니다. + +* `whitelist show`: 허용 목록 정보를 표시합니다 +* `whitelist deployment --add`: 계약 배포 허용 목록에 새 주소를 추가합니다 +* `whitelist deployment --remove`: 계약 배포 허용 목록에서 새 주소를 삭제합니다 + +#### 배포 허용 목록의 모든 주소 표시 {#show-all-addresses-in-the-deployment-whitelist} + +배포 허용 목록에서 주소를 찾는 방법은 두 가지가 있습니다. +1. 허용 목록이 저장되어 있는 `genesis.json`을 확인합니다 +2. `whitelist show`를 실행하면 Polygon 엣지가 지원하는 모든 허용 목록의 정보가 출력됩니다 + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### 배포 허용 목록에 주소 추가 {#add-an-address-to-the-deployment-whitelist} + +배포 허용 목록에 새 주소를 추가하려면 `whitelist deployment --add [ADDRESS]` CLI 명령어를 실행합니다. 허용 목록의 주소 수에는 제한이 없습니다. 계약 배포 허용 목록에 있는 주소만 계약을 배포할 수 있습니다. 허용 목록이 비어 있다면 모든 주소가 계약을 배포할 수 있습니다. + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### 배포 허용 목록에서 주소 삭제 {#remove-an-address-from-the-deployment-whitelist} + +배포 허용 목록에서 주소를 삭제하려면 `whitelist deployment --remove [ADDRESS]` CLI 명령어를 실행합니다. 계약 배포 허용 목록에 있는 주소만 계약을 배포할 수 있습니다. 허용 목록이 비어 있다면 모든 주소가 계약을 배포할 수 있습니다. + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/ko-edge/architecture/modules/blockchain.md b/archive/edge/ko-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..fba8b41b61 --- /dev/null +++ b/archive/edge/ko-edge/architecture/modules/blockchain.md @@ -0,0 +1,160 @@ +--- +id: blockchain +title: 블록체인 +description: Polygon 엣지의 블록체인 및 상태 모듈에 대해 설명합니다. +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## 개요 {#overview} + +Polygon 엣지의 주요 모듈은 **블록체인** 및 **상태** 모듈입니다.
+ +**블록체인**은 블록 재구성 문제를 다루는 동력원입니다. 즉, 블록체인에 새로운 블록이 포함될 때 발생하는 모든 논리를 다룹니다. + +**상태**는 *상태 전환* 객체를 나타냅니다. 새로운 블록이 포함될 때 상태 변화를 다룹니다.
특히 **상태**는 다음을 처리합니다. +* 트랜잭션 실행 +* EVM 실행 +* Merkle 트리 변경 +* 자세한 내용은 **상태** 섹션에 설명되어 있습니다. 🙂 + +핵심은 이 두 부분이 밀접하게 연결되어 있고 클라이언트가 작동할 수 있도록 긴밀히 협력한다는 것입니다.
예를 들어, **블록체인** 레이어에서 새로운 블록을 수신하면(재구성 발생하지 않음) 상태 전환을 수행하도록 **상태**를 호출합니다. + +또한, **블록체인**은 합의와 관련된 일부 부분도 다루어야 합니다(예: *이 ethHash가 정확한가?*, *이 PoW가 정확한가?*).
요약하면, **블록체인은 모든 블록이 포함된 논리의 핵심입니다**. + +## *WriteBlocks* + +**블록체인** 레이어와 관련된 가장 중요한 부분 중 하나는 *WriteBlocks* 메서드입니다. + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +*WriteBlocks* 메서드는 블록체인에 블록을 작성하는 진입점입니다. 매개변수로서 이 메서드는 다양한 블록을 수용합니다.
+우선, 블록을 검증합니다. 그런 다음 체인에 작성합니다. + +실제 *상태 전환*은 *WriteBlocks* 내 *processBlock* 메서드를 호출함으로써 수행됩니다. + +블록체인에 블록을 작성하기 위한 진입점이므로 다른 모듈(예: **봉인**)도 이 메서드를 활용합니다. + +## 블록체인 구독 {#blockchain-subscriptions} + +블록체인 관련 변경 사항을 모니터링할 수 있는 방법이 필요하며,
+이를 위해 **구독**을 사용할 수 있습니다. + +구독을 사용하면 블록체인 이벤트 스트림을 모니터링하고 유의미한 데이터를 즉시 수신할 수 있습니다. + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +**블록체인 이벤트**에는 실제 체인에 발생한 변경 사항과 관련된 정보가 포함되어 있습니다. 여기에는 재구성과 새로운 블록이 포함됩니다. + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip 복습 + +[CLI 명령어](/docs/edge/get-started/cli-commands)에서 ***monitor*** 명령어를 설명한 적이 있습니다. + +블록체인 이벤트는 Polygon 엣지에서 발생하는 원래 이벤트로, 전송 용이성을 위해 나중에 프로토콜 버퍼 메시지 형식으로 매핑됩니다. + +::: \ No newline at end of file diff --git a/archive/edge/ko-edge/architecture/modules/consensus.md b/archive/edge/ko-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..919eb287a9 --- /dev/null +++ b/archive/edge/ko-edge/architecture/modules/consensus.md @@ -0,0 +1,509 @@ +--- +id: consensus +title: 합의 +description: Polygon 엣지의 합의 모듈에 대해 설명합니다. +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## 개요 {#overview} + +**합의** 모듈은 합의 메커니즘을 위한 인터페이스를 제공합니다. + +현재는 다음과 같은 합의 엔진이 제공됩니다. +* **IBFT PoA** +* **IBFT PoS** + +Polygon 엣지는 모듈성 및 플러그형 상태를 유지하고자 합니다.
+사용성 및 사용 용이성을 저해하지 않고 새로운 합의 메커니즘이 최우선적으로 구축될 수 있도록 +핵심 합의 논리를 추상화한 이유가 여기에 있습니다. + +## 합의 인터페이스 {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + +***합의*** 인터페이스는 앞서 설명한 추상화의 핵심입니다.
+* **VerifyHeader** 메서드는 도우미 함수로, 합의 레이어는 이 함수를 **블록체인** 레이어에 노출합니다. +이 메서드는 헤더를 검증합니다. +* **Start** 메서드는 단순히 합의 프로세스 그리고 이와 관련된 모든 것을 시작합니다. 여기에는 동기화, +봉인, 수행해야 하는 모든 것이 포함됩니다. +* **Close** 메서드는 합의 연결을 닫습니다. + +## 합의 구성 {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +데이터를 저장할 합의 프로토콜의 사용자 정의 위치 또는 합의 메커니즘에 사용하려는 사용자 정의 키-값 맵을 제출해야 할 때가 있습니다. 이 작업은 새로운 합의 인스턴스가 생성될 때 읽는 ***Config*** 구조체를 +통해 수행할 수 있습니다. + +## IBFT {#ibft} + +### ExtraData {#extradata} + +블록체인 헤더 객체는 여러 필드 중에서도 특히 **ExtraData**라는 필드를 갖고 있습니다. + +IBFT는 이 추가 필드를 사용하여 블록과 관련된 연산 정보를 저장하고, 다음과 같은 질문에 답합니다. +* "누가 이 블록에 서명했습니까?" +* "이 블록의 검사기는 무엇입니까?" + +IBFT를 위한 이러한 추가 필드는 다음과 같이 정의됩니다. +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### 데이터 서명 {#signing-data} + +노드가 IBFT의 정보에 서명할 수 있도록 *signHash* 메서드를 활용합니다. +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +또 다른 주목할 만한 메서드는 *VerifyCommittedFields*로, 정당한 검사기의 커밋된 봉인인지 확인합니다. +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### 스냅샷 {#snapshots} + +스냅샷은 이름에서 알 수 있듯이 *스냅샷* 또는 특정 블록 높이(번호)의 시스템 *상태*를 제공합니다. + +스냅샷에는 검사기인 노드 세트와 투표 정보가 포함되어 있습니다(검사기는 다른 검사기를 위해 투표할 수 있음). +검사기는 제출된 **채굴자** 헤더에 투표 정보를 포함시키고 **난스** 값을 변경합니다. +* 노드가 검사기를 삭제하려는 경우 난스 값은 **모두 1**입니다. +* 노드가 검사기를 추가하려는 경우 난스 값은 **모두 0**입니다. + +스냅샷은 ***processHeaders*** 메서드를 사용하여 계산됩니다. + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +이 메서드는 일반적으로 1개의 헤더로 호출하지만, 여러 헤더로 호출해도 흐름은 동일합니다.
+제출된 각 헤더에 대해 IBFT는 헤더의 제안자가 검사기인지 확인해야 합니다. 이 작업은 최신 스냅샷을 구한 다음 +노드가 검사기 세트에 속해 있는지를 확인함으로써 쉽게 완료할 수 있습니다. + +다음으로, 난스를 확인합니다. 투표가 포함 및 집계됩니다. 투표가 충분하면 노드를 검사기 세트에 추가하거나 삭제합니다. +그다음으로는 새로운 스냅샵이 저장됩니다. + +#### 스냅샷 스토어 {#snapshot-store} + +스냅샷 서비스는 **snapshotStore**라는 항목을 관리하고 업데이트합니다. 이 항목은 사용 가능한 모든 스냅샷의 목록을 저장합니다. +이를 사용하여 서비스는 어떤 스냅샷이 어떤 블록 높이와 관련이 있는지 신속하게 알아낼 수 있습니다. +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### IBFT 시작 {#ibft-startup} + +IBFT를 시작하기 위해 Polygon 엣지는 먼저 IBFT 전송을 설정해야 합니다. +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +이 작업은 결국 새로운 프로토 버프 메시지와 함께 IBFT 프로토로 새로운 주제를 생성합니다.
+이 메시지는 검사기가 사용합니다. 그런 다음 Polygon 엣지는 해당 주제를 구독하고 그에 따라 메시지를 처리합니다. + +#### MessageReq {#messagereq} + +검사기가 교환한 메시지: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +**MessageReq**의 **View** 필드는 체인 내 현재 노드 위치를 나타내며, +*round* 및 *sequence* 속성이 있습니다. +* **round**는 높이 관련 제안자 라운드를 나타냅니다. +* **sequence**는 블록체인의 높이를 나타냅니다. + +IBFT 구현에 제출되는 *msgQueue*의 목적은 메시지 요청을 저장하는 것입니다. 이 메서드는 +*View*를 통해 메시지에 명령합니다(처음에는 sequence, 그다음에는 round를 통해). 또한, IBFT 구현에는 시스템 내 다양한 상태에 대한 서로 다른 대기열이 있습니다. + +### IBFT 상태 {#ibft-states} + +**Start** 메서드를 사용하여 합의 메커니즘이 시작되면 상태 머신을 시뮬레이션하는 무한 루프가 발생합니다. +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### SyncState {#syncstate} + +처음에 모든 노드는 **Sync** 상태에서 시작합니다. + +블록체인으로부터 새로운 데이터를 가져와야 하기 때문입니다. 클라이언트는 이것이 검사기인지 파악하고 현재 스냅샷을 찾아야 합니다. 이 상태는 대기 중인 블록을 해결합니다. + +동기화가 끝나고 클라이언트가 이를 검사기라고 판단하면 **AcceptState** 상태로 전환되어야 합니다. +클라이언트가 검사기가 **아니면** 동기화가 계속되고 **SyncState** 상태를 유지합니다. + +#### AcceptState {#acceptstate} + +**Accept** 상태는 항상 스냅샷과 검사기 세트를 확인합니다. 현재 노드가 검사기 세트에 있지 않으면 +**Sync** 상태로 돌아갑니다. + +노드가 **검사기인 경우**에는 제안자를 계산합니다. 현재 노드가 제안자로 밝혀지면 블록을 구축하고 preprepare 메시지를 보낸 다음 prepare 메시지를 전송합니다. + +* Preprepare 메시지 - 제안에 대해 알리기 위해 제안자가 검사기에게 보내는 메시지 +* Prepare 메시지 - 검사기가 제안에 동의하는 메시지 모든 노드가 모든 prepare 메시지를 받습니다. +* Commit 메시지 - 제안 관련 커밋 정보를 담고 있는 메시지 + +현재 노드가 검사기가 **아니면** *getNextMessage* 메서드를 사용하여 이전에 표시된 대기열의 메시지를 읽습니다.
+그리고 preprepare 메시지를 기다립니다. 모든 것이 정확하다고 확인되면 노드는 **Validate** 상태로 이동합니다. + +#### ValidateState {#validatestate} + +**Validate** 상태는 다소 간단합니다. 이 상태에서는 모든 노드가 메시지를 읽고 로컬 스냅샷 상태에 해당 메시지를 추가합니다. diff --git a/archive/edge/ko-edge/architecture/modules/json-rpc.md b/archive/edge/ko-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..960e49fcdb --- /dev/null +++ b/archive/edge/ko-edge/architecture/modules/json-rpc.md @@ -0,0 +1,180 @@ +--- +id: json-rpc +title: JSON RPC +description: Polygon 엣지의 JSON RPC 모듈에 관한 설명. +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## 개요 {#overview} + +**JSON RPC** 모듈은 dApp 개발자가 블록체인과 상호작용하는 데 사용하는 **JSON RPC API 레이어**를 +구현합니다. + +여기에는 표준 **[json-rpc 엔드포인트](https://eth.wiki/json-rpc/API)**와 웹소켓 엔드포인트에 대한 지원이 +포함됩니다. + +## 블록체인 인터페이스 {#blockchain-interface} + +Polygon 엣지는 엔드포인트를 전달하기 위해, ***블록체인 인터페이스***를 사용하여 JSON RPC 모듈이 사용해야 하는 모든 메서드를 정의합니다. + +블록체인 인터페이스는 **[Minimal](/docs/edge/architecture/modules/minimal)** 서버에서 구현됩니다. JSON RPC 레이어로 전달되는 +기본 구현입니다. + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## ETH 엔드포인트 {#eth-endpoints} + +모든 표준 JSON RPC 엔드포인트는 다음에서 구현됩니다. + +````bash +jsonrpc/eth_endpoint.go +```` + +## 필터 관리자 {#filter-manager} + +**필터 관리자**는 JSON RPC 서버와 함께 실행되는 서비스입니다. + +블록체인에서 블록 필터링을 지원합니다.
+구체적으로 **로그**와 **블록** 수준 필터가 모두 포함되어 있습니다. + +필터 관리자는 구독 이벤트에 크게 의존하며, +이는 [블록체인](blockchain#blockchain-subscriptions) 섹션에 설명되어 있습니다. + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +필터 관리자 이벤트는 *실행* 메서드에서 디스패치됩니다. + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## 📜 리소스 {#resources} +* **[이더리움 JSON-RPC](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/ko-edge/architecture/modules/minimal.md b/archive/edge/ko-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..c6ec193bec --- /dev/null +++ b/archive/edge/ko-edge/architecture/modules/minimal.md @@ -0,0 +1,119 @@ +--- +id: minimal +title: 최소한의 모듈 +description: Polygon 엣지의 최소한의 모듈에 대한 설명. +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## 개요 {#overview} + +앞서 언급했듯이, Polygon 엣지는 일련의 다양한 모듈로 구성되어 있으며 이 모듈은 서로 연결되어 있습니다.
+**블록체인**은 **상태**나 **동기화**(새 블록을 **블록체인**으로 연결) 등과 연결되어 있습니다. + +**최소한의 모듈**은 이렇게 상호 연결된 모듈의 초석이라 할 수 있으며,
+Polygon 엣지에서 실행되는 모든 서비스의 중심 허브 역할을 합니다. + +## 스타트업 매직 {#startup-magic} + +무엇보다도 최소한의 모듈은 다음을 책임집니다. +* 데이터 디렉터리 설정 +* libp2p 통신을 위한 키스토어 생성 +* 스토리지 생성 +* 합의 설정 +* GRPC, JSON RPC, 동기화를 통한 블록체인 객체 설정 + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/ko-edge/architecture/modules/networking.md b/archive/edge/ko-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..f57d11b65d --- /dev/null +++ b/archive/edge/ko-edge/architecture/modules/networking.md @@ -0,0 +1,80 @@ +--- +id: networking +title: 네트워킹 +description: Polygon 엣지의 네트워킹 모듈 설명. +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## 개요 {#overview} + +노드는 유용한 정보를 교환하기 위해 네트워크의 다른 노드와 통신해야 합니다.
+이 작업을 위해 Polygon 엣지는 테스트를 거친 **libp2p** 프레임워크를 활용합니다. + +**libp2p**를 선택한 것은 주로 다음 사항에 중점을 두었기 때문입니다. +* **속도** - libp2p는 devp2p(GETH 및 다른 클라이언트에서 사용됨)에 비해 상당한 성능 개선이 이루어졌습니다. +* **확장 가능성** - 시스템의 다른 기능을 위한 훌륭한 기반 역할을 합니다. +* **모듈성** - libp2p는 Polygon 엣지처럼 기본적으로 모듈성을 가지며, 특히 Polygon 엣지에 스왑 가능성이 필요한 부분이 있을 경우 더 큰 유연성을 제공합니다. + +## GRPC {#grpc} + +Polygon 엣지는 **libp2p** 외에도 **GRPC** 프로토콜을 사용합니다.
+기술적으로 Polygon 엣지는 여러 GRPC 프로토콜을 사용합니다. 이에 관해서는 나중에 다루겠습니다. + +GRPC 레이어를 통해 모든 요청/응답 프로토콜을 추상화하고 Polygon 엣지가 작동하는 데 필요한 스트리밍 프로토콜을 단순화할 수 있습니다. + +GRPC는 **프로토콜 버퍼**를 활용해 *서비스*와 *메시지 구조*를 정의합니다.
+서비스 및 구조는 언어에 구애받지 않는 컴파일된 *.proto* 파일에 정의됩니다. + +앞서 Polygon 엣지가 몇몇 GRPC 프로토콜을 활용한다는 사실을 언급했습니다.
+GETH 및 Parity와 같은 클라이언트에서 종종 지연되는 문제가 있어, 노드 연산자의 전체 UX를 향상시키기 위한 목적이었습니다. + +노드 연산자는 원하는 정보를 찾기 위해 로그를 가려내는 대신 GRPC 서비스를 호출하여 시스템에서 발생하는 상황을 더 잘 파악할 수 있습니다. + +### 노드 연산자를 위한 GRPC {#grpc-for-node-operators} + +다음 섹션은 [CLI 명령어](/docs/edge/get-started/cli-commands) 섹션에서 간략하게 다루었기 때문에 좀 더 익숙할 것입니다. + +**노드 연산자**에서 사용할 GRPC 서비스도 유사한 방식으로 정의됩니다. +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip + +실제로 CLI 명령어는 이러한 서비스 메서드 구현을 호출합니다. + +메서드는 ***minimal/system_service.go***에서 구현됩니다. + +::: + +### 다른 노드를 위한 GRPC {#grpc-for-other-nodes} + +Polygon 엣지 역시 네트워크의 다른 노드가 사용하는 몇몇 서비스 메서드를 구현합니다.
+이러한 서비스는 **[프로토콜](docs/edge/architecture/modules/consensus)** 섹션에서 설명합니다. + +## 📜 리소스 {#resources} +* **[프로토콜 버퍼](https://developers.google.com/protocol-buffers)** +* **[libp2p](https://libp2p.io/)** +* **[gRPC](https://grpc.io/)** diff --git a/archive/edge/ko-edge/architecture/modules/other-modules.md b/archive/edge/ko-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..e56d363a96 --- /dev/null +++ b/archive/edge/ko-edge/architecture/modules/other-modules.md @@ -0,0 +1,36 @@ +--- +id: other-modules +title: 기타 모듈 +description: Polygon 엣지의 일부 모듈에 대한 설명. +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## 암호화폐 {#crypto} + +**암호화폐** 모듈은 암호화폐 유틸리티 함수를 포함합니다. + +## 체인 {#chain} + +**체인** 모듈은 체인 매개변수(활성 포크, 합의 엔진 등)를 포함합니다. + +* **체인** - 사전 정의된 체인 구성(메인넷, goerli, ibft) + +## 도우미 {#helper} + +**도우미** 모듈은 도우미 패키지를 포함합니다. + +* **dao** - Dao 유틸 +* **enode** - Enode 인코딩/디코딩 함수 +* **hex** - Hex 인코딩/디코딩 함수 +* **ipc** - IPC 연결 함수 +* **keccak** - Keccak 함수 +* **rlputil** - Rlp 인코딩/디코딩 도우미 함수 + +## 명령어 {#command} + +**명령어** 모듈은 CLI 명령어를 위한 인터페이스를 포함합니다. \ No newline at end of file diff --git a/archive/edge/ko-edge/architecture/modules/sealer.md b/archive/edge/ko-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..862fe56544 --- /dev/null +++ b/archive/edge/ko-edge/architecture/modules/sealer.md @@ -0,0 +1,73 @@ +--- +id: sealer +title: 봉인 +description: Polygon 엣지의 봉인 모듈에 대한 설명. +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## 개요 {#overview} + +**봉인**은 트랜잭션을 수집하고 새로운 블럭을 생성하는 항목입니다.
+그런 다음 해당 블록을 **합의** 모듈로 보내 봉인합니다. + +최종 봉인 논리는 **합의** 모듈에서 확인할 수 있습니다. + +## 실행 메서드 {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution 진행 중인 작업 + +**봉인** 및 **합의** 모듈은 조만간 단일 항목으로 결합될 것입니다. + +새로운 모듈에서는 서로 다른 봉인 구현을 요구하는 다양한 종류의 합의 메커니즘의 모듈 논리가 통합될 것입니다. +* **PoS**(지분증명) +* **PoA**(권위증명) + +현재 **봉인** 및 **합의** 모듈은 PoW(작업증명)를 통해 작동합니다. + +::: \ No newline at end of file diff --git a/archive/edge/ko-edge/architecture/modules/state.md b/archive/edge/ko-edge/architecture/modules/state.md new file mode 100644 index 0000000000..9faeb3cc31 --- /dev/null +++ b/archive/edge/ko-edge/architecture/modules/state.md @@ -0,0 +1,246 @@ +--- +id: state +title: 상태 +description: Polygon 엣지의 상태 모듈에 대한 설명. +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +**상태** 작동 방식을 제대로 이해하려면 일부 기본적인 이더리움 개념을 이해해야 합니다.
+ +**[이더리움 가이드의 '상태'](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)**를 확인하시기 바랍니다. + +## 개요 {#overview} + +기본적인 이더리움 개념을 숙지했다면 아래 개요를 쉽게 이해하실 수 있습니다. + +존재하는 모든 이더리움 계정은 **월드 상태 트리**에 있다고 설명했습니다.
+이 계정들은 Merkle 트리의 리프입니다. 각 리프는 인코딩된 **계정 상태** 정보를 포함합니다. + +이를 통해 Polygon 엣지는 특정 시점의 특정 Merkle 트리를 가져올 수 있습니다.
+예를 들어, 블록 10에서 상태 해시를 가져올 수 있습니다. + +이 시점의 Merkle 트리를 ***스냅샷***이라고 부릅니다. + +**상태 트리** 또는 **스토리지 트리**의 ***스냅샷***이 있을 수 있으며, 이들은 기본적으로 동일합니다.
+유일한 차이점은 리프가 의미하는 것입니다. + +* 스토리지 트리의 경우, 리프에 임의의 상태가 포함되어 있으나 이를 처리하거나 그 안에 무엇이 있는지 알 수 없습니다. +* 상태 트리의 경우, 리프는 계정을 나타냅니다. + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + +**스냅샷** 인터페이스는 다음과 같이 정의됩니다. + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +커밋할 수 있는 정보는 *객체 구조체*에 의해 정의됩니다. + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +Merkle 트리의 구현은 *state/immutable-trie* 폴더에서 확인할 수 있습니다.
+*state/immutable-trie/state.go*는 **상태** 인터페이스를 구현합니다. + +*state/immutable-trie/trie.go*는 주요 Merkle 트리 객체로서, 가능한 한 많은 메모리를 재사용하는 +Merkle 트리의 최적화된 버전을 나타냅니다. + +## 실행자 {#executor} + +*state/executor.go*에는 Polygon 엣지가 블록의 현재 상태를 변경하는 방법을 정하는 데 필요한 모든 정보가 포함되어 있습니다. *ProcessBlock*의 구현은 여기에서 확인할 수 있습니다. + +*적용* 메서드는 실제 상태 전환을 수행합니다. 실행자는 EVM을 호출합니다. + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## 런타임 {#runtime} + +상태 전환이 실행될 때, 상태 전환을 실행하는 메인 모듈은 EBM입니다(state/runtime/evm에 위치). + +**디스패치 테이블**은 **명령 코드**와 명령 간의 매칭을 수행합니다. + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +EBM을 구동하는 핵심 논리는 *실행* 루프로,
+ +EVM의 주요 진입점입니다. 루프 작업을 수행하고 현재의 명령 코드를 확인하며 명령을 가져와 +실행 가능 여부를 점검하며, 가스를 소비하고 실패하거나 정지할 때까지 명령을 실행합니다. + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/ko-edge/architecture/modules/storage.md b/archive/edge/ko-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..a14afeebae --- /dev/null +++ b/archive/edge/ko-edge/architecture/modules/storage.md @@ -0,0 +1,118 @@ +--- +id: storage +title: 스토리지 +description: Polygon 엣지의 스토리지 모듈에 관한 설명. +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## 개요 {#overview} + +현재 Polygon 엣지는 데이터 저장에 **LevelDB**와 **인메모리** 데이터 스토어를 활용합니다. + +Polygon 엣지 전반에서 모듈이 기본 데이터 스토어와 상호 작용할 때 +모듈은 어떤 DB 엔진 및 서비스와 통신 중인지 알 필요가 없습니다. + +DB 레이어는 모듈이 쿼리하는 인터페이스를 내보내는 **스토리지**라는 모듈 사이에서 추상화됩니다. + +각 DB 레이어(현재는 **LevelDB**만 있음)는 이러한 메서드를 개별적으로 구현하며 메서드가 구현에 적합한지 확인합니다. + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### 프리픽스 {#prefixes} + +LevelDB 스토리지 쿼리를 확정하고 키 스토리지 충돌을 피하기 위해 Polygon 엣지는 +데이터를 저장할 때 프리픽스 및 서브-프리픽스를 활용합니다. + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## 향후 계획 {#future-plans} + +조만간 가장 많이 사용되는 DB 솔루션을 추가할 계획입니다(아래 참조). +* PostgreSQL +* MySQL + + +## 📜 리소스 {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/ko-edge/architecture/modules/syncer.md b/archive/edge/ko-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..e760cc1f60 --- /dev/null +++ b/archive/edge/ko-edge/architecture/modules/syncer.md @@ -0,0 +1,68 @@ +--- +id: syncer +title: 동기화 +description: Polygon 엣지의 동기화 모듈에 관한 설명. +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## 개요 {#overview} + +이 모듈에는 동기화 프로토콜에 대한 논리가 포함되어 있습니다. 새 노드를 실행 중인 네트워크와 동기화하거나 합의에 참여하지 않는 노드(비 검사기)를 위한 새 블록을 검증/삽입하는 데 사용됩니다. + +Polygon 엣지는 **libp2p**를 네트워크 레이어로 사용하고 **gRPC**를 실행합니다. + +Polygon 엣지에는 기본적으로 2가지의 동기화 유형이 있습니다. +* 대량 동기화(Bulk Sync) - 한 번에 넓은 범위의 블록을 동기화 +* 감시 동기화(Watch Sync) - 블록 단위로 동기화 + +### 대량 동기화 {#bulk-sync} + +대량 동기화의 목표는 다른 피어의 사용 가능한 블록을 최대한 빨리, 최대한 많이 동기화하는 것입니다. 이를 달성하기 위한 대량 동기화 단계는 상당히 단순합니다. + +다음은 대량 동기화 프로세스의 흐름입니다. + +1. ㅗ** 노드에 대량 동기화가 필요한지 결정 ** - 이 단계에서 노드는 피어 맵을 확인하여 해당 노드가 로컬에 가진 것보다 더 큰 블록 번호를 가진 노드가 있는지 판단합니다. +2. ** 최적의 피어 찾기(동기화 피어 맵 사용) ** - 이 단계에서 노드는 위 예에서 설명한 기준에 따라 동기화할 최적의 피어를 찾습니다. +3. ** 대량 동기화 스트림 열기 ** - 이 단계에서 노드는 공통 블록 번호의 블록과 대량 동기화를 진행하기 위해 gRPC 스트림을 최적의 피어로 엽니다. +4. ** 대량 전송이 완료되면 최적의 피어가 스트림을 닫음 ** - 이 단계에서 노드와 동기화 중인 최적의 피어는 사용 가능한 블록을 모두 전송하자마자 스트림을 닫습니다. +5. ** 대량 동기화가 완료되면 노드가 검사기인지 확인 ** - 이 단계에서 최적의 피어가 스트림을 닫고 대량 동기화가 완료되면, 노드가 검사기인지 확인해야 합니다. + * 노드가 검사기면 동기화 상태에서 벗어나 합의에 참여하기 시작합니다. + * 검사기가 아니면 **감시 동기화**를 진행합니다. + +### 감시 동기화 {#watch-sync} + +:::info + +감시 동기화 단계는 노드가 검사기가 아닌, 블록을 수신 대기하는 네트워크의 일반적인 비 검사기 노드인 경우에만 실행됩니다. + +::: + +감시 동기화의 동작은 상당히 단순합니다. 노드는 이미 나머지 네트워크와 동기화되어 있으며, 새로 들어오는 블록만 파싱하면 됩니다. + +다음은 감시 동기화 프로세스의 흐름입니다. + +1. ** 피어의 상태가 업데이트될 때 새 블록 추가 ** - 이 단계에서 노드는 새 블록 이벤트를 수신 대기합니다. 새 블록이 발생하면 gRPC 함수 호출을 실행하여 블록을 가져오고 로컬 상태를 업데이트합니다. +2. ** 최신 블록을 동기화한 후 노드가 검사기인지 확인 ** + * 그렇다면, 동기화 상태 종료 + * 그렇지 않다면, 새 블록 이벤트에 대한 수신 대기 상태 지속 + +## 성능 보고 {#perfomance-report} + +:::info + +로컬 머신에서 **백만 개의 블록**을 동기화하여 성능을 측정했습니다. + +::: + +| 이름 | 결과 | +|----------------------|----------------| +| 1백만 개의 블록 동기화 | ~ 25분 | +| 1백만 개의 블록 전송 | ~ 1분 | +| GRPC 호출 수 | 2 | +| 테스트 범위 | ~ 93% | \ No newline at end of file diff --git a/archive/edge/ko-edge/architecture/modules/txpool.md b/archive/edge/ko-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..d0d4e25bb5 --- /dev/null +++ b/archive/edge/ko-edge/architecture/modules/txpool.md @@ -0,0 +1,224 @@ +--- +id: txpool +title: TxPool +description: Polygon 엣지의 TxPool 모듈에 대한 설명. +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## 개요 {#overview} + +TxPool 모듈은 트랜잭션이 시스템의 다른 부분에서 추가되는 경우 트랜잭션 풀 구현을 나타냅니다. 또한 이 모듈은 노드 연산자에 몇 가지 유용한 기능을 제공합니다. 이에 대해서는 아래에서 다룹니다. + +## 연산자 명령어 {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +노드 연산자는 **[CLI 명령어](/docs/edge/get-started/cli-commands#transaction-pool-commands)** 섹션에서 설명하는 대로 이러한 GRPC 엔드포인트를 쿼리할 수 있습니다. + +## 트랜잭션 처리 {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +***addImpl*** 메서드는 **TxPool** 모듈에서 가장 중요한 부분입니다. +시스템에서 트랜잭션이 추가되는 중심 위치이며, 클라이언트가 **Gossip** 프로토콜을 통해 트랜잭션을 수신할 때마다 GRPC 서비스, JSON RPC 엔드포인트에서 호출됩니다. + +**ctx** 인수를 사용하며, 이는 트랜잭션이 추가되는 컨텍스트(GRPC, JSON RPC...)를 나타냅니다.
다른 매개변수는 풀에 추가될 트랜잭션의 목록입니다. + +여기에서 중요한 점은 트랜잭션 내의 **From** 필드에 대한 확인입니다. +* **From** 필드가 **비어 있다면**, 암호화/서명되지 않은 트랜잭션으로 간주됩니다. 이러한 종류의 트랜잭션은 개발 모드에서만 허용됩니다. +* **From** 필드가 **비어 있지 않다면**, 서명된 트랜잭션이라는 의미이며, 서명 검증이 이루어집니다. + +모든 검증이 완료되면 트랜잭션은 유효한 것으로 간주됩니다. + +## 데이터 구조 {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +혼동을 일으킬 수 있는 TxPool 객체 필드는 **queue** 및 **sorted** 목록입니다. +* **queue** - 계정 트랜잭션이 정렬된 목록의 힙 구현(난스 기준) +* **sorted** - 현재 승격된 모든 트랜잭션(모든 실행 가능한 트랜잭션)이 정렬된 목록. 가스 가격 기준 정렬 + +## 가스 한도 오류 관리 {#gas-limit-error-management} + +트랜잭션을 제출할 때마다 TxPool에서 세 가지 방식으로 이를 처리합니다. + +1. 대기 중인 모든 트랜잭션이 하나의 블록 안에 들어갈 수 있습니다 +2. 대기 중인 하나 이상의 트랜잭션이 하나의 블록 안에 들어갈 수 없습니다 +3. 대기 중인 하나 이상의 트랜잭션이 하나의 블록 안에 절대로 들어갈 수 없을 것입니다 + +여기에서 '**_들어가다_**'란 트랜잭션의 가스 한도가 TxPool에 남아 있는 가스보다 낮다는 것을 의미합니다. + +첫 번째 시나리오는 오류를 발생시키지 않습니다. + +### 두 번째 시나리오 {#second-scenario} + +- TxPool에 남아 있는 가스는 마지막 블록의 가스 한도가 됩니다(예: **5000**) +- 첫 번째 트랜잭션이 처리되면서 TxPool의 **3000** 가스를 소비합니다 + - TxPool에 남아 있는 가스는 이제 **2000**입니다 +- 첫 번째 트랜잭션과 동일한 두 번째 트랜잭션이 제출됩니다(둘 모두 3000 단위의 가스를 소비합니다) +- TxPool에 남아 있는 가스는 해당 트랜잭션 가스보다 **낮기** 때문에 현재 블록에서 처리될 수 없습니다 + - 다음 블록에서 처리될 수 있도록 대기 트랜잭션 대기열로 들어갑니다 +- 첫 번째 블록이 작성되었스며, 이를 **블록 #1**이라고 부르겠습니다 +- TxPool에 남아 있는 가스는 상위 블록으로 설정됩니다 - **블록 #1**의 가스 한도 +- TxPool 대기 트랜잭션 대기열로 들어간 트랜잭션이 이제 처리되어 블록에 작성됩니다 + - 이제 TxPool에 남아 있는 가스는 **2000**입니다 +- 두 번째 블록이 작성되었습니다 +- ... + +![TxPool 오류 시나리오 #1](/img/edge/txpool-error-1.png) + +### 세 번째 시나리오 {#third-scenario} +- TxPool에 남아 있는 가스는 마지막 블록의 가스 한도가 됩니다(예: **5000**) +- 첫 번째 트랜잭션이 처리되면서 TxPool의 **3000** 가스를 소비합니다 + - TxPool에 남아 있는 가스는 이제 **2000**입니다 +- 가스 필드가 **6000**으로 설정된 두 번째 트랜잭션이 제출되었습니다 +- 해당 블록의 가스 한도가 트랜잭션 가스보다 **낮기** 때문에 이 트랜잭션은 삭제됩니다 + - 이 트랜잭션은 절대로 하나의 블록에 들어갈 수 없습니다 +- 첫 번째 블록이 작성되었습니다 +- ... + + +![TxPool 오류 시나리오 #2](/img/edge/txpool-error-2.png) + +> 이 시나리오는 다음 오류가 발생할 때 발생합니다. +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## 블록 가스 목표 {#block-gas-target} + +노드가 블록 가스 한도를 실행 중인 체인상에서 일정 목표 이하로 유지하려는 상황이 존재합니다. + +노드 연산자는 특정 노드에 목표 가스 한도를 설정할 수 있으며, 해당 노드는 새로 생성되는 블록에 이 한도를 적용하려고 할 것입니다. +나머지 노드의 대부분에도 비슷한(또는 동일한) 목표 가스 한도가 설정되어 있는 경우, 블록 가스 한도는 항상 블록 가스 목표 주변에 머물면서 새 블록이 생성됨에 따라 천천히 목표를 향해 진행합니다(최대값: `1/1024 * parent block gas limit`). + +### 예시 시나리오 {#example-scenario} + +* 노드 연산자가 단일 노드의 블록 가스 한도를 `5000`으로 설정합니다 +* `7000`으로 구성된 단일 노드와 별도로, 다른 노드들도 `5000`으로 구성됩니다 +* 가스 목표가 `5000`으로 설정된 노드가 제안자가 되는 경우, 이 노드는 가스 한도가 이미 목표 수준인지 확인합니다 +* 가스 한도가 목표 수준이 아닌 경우(즉, 더 높거나 낮은 경우), 제안자 노드는 블록 가스 목표를 같은 방향으로 최대(1/1024 * 상위 가스 한도)로 설정합니다 + 1. 예: `parentGasLimit = 4500` 및 `blockGasTarget = 5000`, 제안자는 새 블록의 가스 한도를 `4504.39453125`(`4500/1024 + 4500`)로 계산합니다 + 2. 예: `parentGasLimit = 5500` 및 `blockGasTarget = 5000`, 제안자는 새 블록의 가스 한도를 `5494.62890625`(`5500 - 5500/1024`)로 계산합니다 +* 이를 통해 체인의 블록 가스 한도는 목표 수준을 유지합니다. 목표가 `7000`으로 설정된 단일 제안자는 한도를 크게 초과할 수 없고, 목표가 `5000`으로 설정된 대다수의 노드는 항상 그 수준을 유지하려 하기 때문입니다 \ No newline at end of file diff --git a/archive/edge/ko-edge/architecture/modules/types.md b/archive/edge/ko-edge/architecture/modules/types.md new file mode 100644 index 0000000000..6b67e3209d --- /dev/null +++ b/archive/edge/ko-edge/architecture/modules/types.md @@ -0,0 +1,43 @@ +--- +id: types +title: 유형 +description: Polygon 엣지의 유형 모듈에 대한 설명. +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## 개요 {#overview} + +**유형** 모듈은 다음과 같은 핵심 객체 유형을 구현합니다. + +* **주소** +* **해시** +* **헤더** +* 여러 도우미 함수 + +## RLP 인코딩 / 디코딩 {#rlp-encoding-decoding} + +GETH와 같은 클라이언트와 달리 Polygon 엣지는 인코딩에 리플렉션을 사용하지 않습니다.
+리플렉션 사용을 선호하지 않은 이유는 성능 악화, 확장의 어려움과 같은 +새로운 문제가 발생하기 때문입니다. + +**유형** 모듈은 FastRLP 패키지를 사용하여 RLP 마셜링 및 마셜링 취소를 할 수 있는 편리한 인터페이스를 제공합니다. + +마셜링은 *MarshalRLPWith* 및 *MarshalRLPTo* 메서드를 통해 수행됩니다. 마셜링 취소를 위한 유사한 메서드도 +있습니다. + +Polygon 엣지는 이러한 메서드를 수동으로 정의하므로 리플렉션이 필요하지 않습니다. *rlp_marshal.go*에서 +마셜링을 위한 메서드를 확인할 수 있습니다. + +* **Bodies** +* **Blocks** +* **Headers** +* **Receipts** +* **Logs** +* **Transactions** \ No newline at end of file diff --git a/archive/edge/ko-edge/architecture/overview.md b/archive/edge/ko-edge/architecture/overview.md new file mode 100644 index 0000000000..e4e93ce8bf --- /dev/null +++ b/archive/edge/ko-edge/architecture/overview.md @@ -0,0 +1,60 @@ +--- +id: overview +title: 아키텍처 개요 +sidebar_label: Overview +description: Polygon 엣지의 아키텍처 소개 +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +Polygon은 *모듈식* 소프트웨어를 구축하려는 아이디어와 함께 시작했습니다. + +이 아이디어는 Polygon 엣지의 거의 모든 부분에 반영되어 있습니다. Polygon 엣지에 구축된 아키텍처 및 레이어링에 대한 간략한 개요를 아래에서 확인할 수 있습니다. + +## Polygon 엣지 레이어링 {#polygon-edge-layering} + +![Polygon 엣지 아키텍처](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +**libp2p**를 활용하는 기본 네트워킹 레이어에서 모든 것이 시작됩니다. 이 기술을 선택한 이유는 +Polygon 엣지의 설계 철학에 부합하기 때문입니다. Libp2p는 + +- 모듈식입니다. +- 확장 가능합니다. +- 빠릅니다. + +무엇보다도 나중에 다룰 추가 고급 기능을 위한 탁월한 기반을 제공합니다. + + +## 동기화 및 합의 {#synchronization-consensus} +클라이언트가 실행되는 방식에 따라 동기화 및 합의 프로토콜을 분리하면 모듈성과 **사용자 정의** 동기화 및 합의 메커니즘 구현을 지원할 수 있습니다. + +Polygon 엣지는 곧바로 활용 가능한 플러그형 합의 알고리즘을 제공하도록 설계되었습니다. + +현재 지원되는 합의 알고리즘 목록: + +* IBFT PoA +* IBFT PoS + +## 블록체인 {#blockchain} +블록체인 레이어는 Polygon 엣지 시스템 내 모든 것을 조정하는 중심 레이어입니다. 해당 *모듈* 섹션에서 자세히 설명합니다. + +## 상태 {#state} +상태 내부 레이어에는 상태 전환 논리가 포함되어 있습니다. 새로운 블록이 포함될 때 상태 변화를 다룹니다. 해당 *모듈* 섹션에서 자세히 설명합니다. + +## JSON RPC {#json-rpc} +JSON RPC 레이어는 dApp 개발자가 블록체인과 상호작용하는 데 사용하는 API 레이어입니다. 해당 *모듈* 섹션에서 자세히 설명합니다. + +## TxPool {#txpool} +TxPool 레이어는 트랜잭션 풀을 나타냅니다. 여러 진입점에서 트랜잭션을 추가할 수 있기 때문에 시스템 내 다른 모듈과 밀접하게 연결되어 있습니다. + +## grpc {#grpc} +gRPC나 Google 원격 절차 Call은 Google이 처음에 확장 가능하고 빠른 API를 구축하기 위해 만든 강력한 오픈 소스 RPC 프레임워크입니다. GRPC 레이어는 연산자 상호작용에 매우 중요합니다. 이를 통해 노드 연산자는 클라이언트와 쉽게 상호작용하고 만족스러운 사용자 경험을 제공할 수 있습니다. diff --git a/archive/edge/ko-edge/community/propose-new-feature.md b/archive/edge/ko-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..1b07bee655 --- /dev/null +++ b/archive/edge/ko-edge/community/propose-new-feature.md @@ -0,0 +1,60 @@ +--- +id: propose-new-feature +title: 새 기능 제안 +description: "새 기능 제안을 위한 PR 템플릿 및 설명서." +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## 개요 {#overview} + +수정 사항을 포함시키거나 코드에 기여하고 싶다면 먼저 해당 팀에 연락하시기 바랍니다.
+Polygon 엣지는 간단하고 명료한 기능 제안 템플릿을 사용합니다. + +## PR 템플릿 {#pr-template} + +### 설명 {#description} + +이 PR에서 이루어진 작업에 관해 자세한 설명을 제공하세요. + +### 다음 변경 사항을 포함할 수 있습니다. {#changes-include} + +- [ ] 버그 수정(호환성을 손상하지 않으면서 문제를 해결하는 변경) +- [ ] 긴급 수정(긴급한 문제를 해결하고 즉각적인 주의를 필요로 하는 변경) +- [ ] 새 기능(호환성을 손상하지 않으면서 기능을 추가하는 변경) +- [ ] 호환성을 손상하는 변경(이전 버전과 호환되지 않으면서 현재의 기능을 변경하는 변경) + +### 호환성을 손상하는 변경 {#breaking-changes} + +호환성을 손상하는 변경이 이루어졌다면 이 섹션을 작성하고, 그렇지 않은 경우에는 이 섹션을 삭제하시기 바랍니다. + +### 체크리스트 {#checklist} + +- [ ] 이 PR을 제게 할당했습니다 +- [ ] 리뷰어를 최소 1명 추가했습니다 +- [ ] 관련 라벨을 추가했습니다 +- [ ] 공식 문서를 업데이트했습니다 +- [ ]코드 안에 충분한 문서를 추가했습니다 + +### 테스트 {#testing} + +- [ ] 공식 테스트 제품군을 사용해 이 코드를 테스트했습니다 +- [ ] 이 코드를 수동으로 테스트했습니다 + +## 수동 테스트 {#manual-tests} + +이 기능에 대해 수동 테스트가 이루어졌다면 섹션을 작성하고, 그렇지 않은 경우에는 이 섹션을 삭제하시기 바랍니다. + +### 문서 업데이트 {#documentation-update} + +문서 업데이트 PR이 있는 경우에는 이 섹션에 링크를 추가하고, 그렇지 않은 경우에는 이 섹션을 삭제하시기 바랍니다. + +### 추가 의견 {#additional-comments} + +추가 의견이 있으면 이 섹션을 작성하고, 그렇지 않은 경우에는 이 섹션을 삭제하시기 바랍니다. \ No newline at end of file diff --git a/archive/edge/ko-edge/community/report-bug.md b/archive/edge/ko-edge/community/report-bug.md new file mode 100644 index 0000000000..032c43e9d9 --- /dev/null +++ b/archive/edge/ko-edge/community/report-bug.md @@ -0,0 +1,55 @@ +--- +id: report-bug +title: 문제 보고 +description: Polygon 엣지 문제의 보고를 위한 템플릿 및 지침. +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## 개요 {#overview} + +때때로 문제가 발생합니다.
+어떠한 문제를 발견하든 팀에 알리는 것이 좋습니다.
+Polygon 엣지 GitHub 페이지에서 새로운 문제를 보고하고 팀과 이에 대한 논의를 시작할 수 있습니다. + +## 문제 템플릿 {#issue-template} + +## [문제의 주제] + +### 설명 {#description} + +여기에 문제를 최대한 자세하게 설명하세요. + +### 사용자 환경 {#your-environment} + +* OS 및 버전 +* Polygon 엣지 버전 +* 문제를 일으키는 분기 + +### 재현 단계 {#steps-to-reproduce} + +* 문제의 재현 방법을 알려주세요.
+* 알고 있는 경우, 문제가 발생한 위치
+* 해당하는 경우, 문제를 유발한 명령어 + +### 예상 동작 {#expected-behaviour} + +어떤 동작이 발생해야 하는지 알려주세요. + +### 실제 동작 {#actual-behaviour} + +실제로 일어나고 있는 상황을 알려주세요. + +### 로그 {#logs} + +문제를 보여주는 로그가 있으면 여기에 붙여 넣으세요. + +### 해결 방법 제안 {#proposed-solution} + +문제 해결 방법에 대한 아이디어가 있는 경우 논의를 시작할 수 있도록 알려주세요. \ No newline at end of file diff --git a/archive/edge/ko-edge/configuration/manage-private-keys.md b/archive/edge/ko-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..5eab59aedf --- /dev/null +++ b/archive/edge/ko-edge/configuration/manage-private-keys.md @@ -0,0 +1,76 @@ +--- +id: manage-private-keys +title: 비공개 키 관리 +description: "비공개 키 관리 방법 및 비공개 키의 유형." +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## 개요 {#overview} + +Polygon 엣지에서 직접 관리하는 두 가지 유형의 비공개 키가 있습니다. + +* **합의 메커니즘에 사용되는 비공개 키** +* **libp2p가 네트워킹에 사용하는 비공개 키** +* **(선택 사항) 합의 메커니즘에서 검사기의 서명을 취합하는 데 사용하는 BLS 비공개 키** + +현재 Polygon 엣지는 직접적인 계정 관리를 지원하지 않습니다. + +[백업 및 복원 가이드](/docs/edge/working-with-node/backup-restore)에서 설명하는 디렉터리 구조를 기반으로, Polygon 엣지는 위에 언급된 키 파일을 **consensus**, **keystore**라는 서로 다른 두 개의 디렉터리에 저장합니다. + +## 키 형식 {#key-format} + +비공개 키는 단순한 **Base64 형식**으로 저장되므로 사람이 읽기 쉽고 이동이 가능합니다. + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info 키 유형 + +Polygon 엣지 내부에서 생성되고 사용되는 모든 비공개 키 파일은 [secp256k1](https://en.bitcoin.it/wiki/Secp256k1) 곡선을 갖는 ECDSA에 의존합니다. + +이 곡선은 표준이 아니므로 표준화된 PEM 형식으로 인코딩하여 저장할 수 없습니다. +이 키 유형을 따르지 않는 키를 가져오는 것은 지원되지 않습니다. + +::: +## 합의 비공개 키 {#consensus-private-key} + +*합의 비공개 키*라는 비공개 키 파일은 **검사기 비공개 키**라고도 합니다. +이 비공개 키는 노드가 네트워크에서 검사기 역할을 하고 새 데이터에 서명해야 하는 경우 사용됩니다. + +이 비공개 키 파일은 `consensus/validator.key`에 있으며 언급된 [키 형식](/docs/edge/configuration/manage-private-keys#key-format)을 따릅니다. + +:::warning + +검사기 비공개 키는 각각의 검사기 노드에 고유한 것입니다. 체인 보안 침해 가능성 때문에 이 키는 모든 검사기가 공유할 수 없습니다. + +::: + +## 네트워킹 비공개 키 {#networking-private-key} + +위에 언급된 네트워킹용 비공개 키 파일은 libp2p에서 피어 ID를 생성하고 노드가 네트워크에 참여할 수 있게 하는 데 사용됩니다. + +`keystore/libp2p.key`에 있으며, 언급된 [키 형식](/docs/edge/configuration/manage-private-keys#key-format)을 따릅니다. + +## BLS 보안 비밀 키 {#bls-secret-key} + +BLS 보안 비밀 키 파일은 합의 레이어에서 커밋된 봉인을 집계하는 데 사용됩니다. BLS가 집계하는 커밋된 봉인의 크기는 직렬화된 커밋 ECDSA 서명보다 작습니다. + +BLS 기능은 선택 사항이며 BLS 사용 여부를 선택할 수 있습니다. 자세한 내용은 [BLS](/docs/edge/consensus/bls)를 참조하시기 바랍니다. + +## 가져오기 / 내보내기 {#import-export} + +키 파일은 단순한 Base64로 디스크에 저장되므로 쉽게 백업하거나 가져올 수 있습니다. + +:::caution 키 파일 변경 + +합의 및 피어 탐색 메커니즘은 이러한 키에서 도출된 데이터를 노드별 스토리지에 저장하고 이 데이터에 의존하여 연결을 시작하고 합의 논리를 수행하기 때문에, 이미 설정 또는 실행 중인 네트워크상의 키 파일에 대한 모든 종류의 변경은 심각한 네트워크/합의 중단으로 이어질 수 있습니다. + +::: \ No newline at end of file diff --git a/archive/edge/ko-edge/configuration/prometheus-metrics.md b/archive/edge/ko-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..0b32ddc222 --- /dev/null +++ b/archive/edge/ko-edge/configuration/prometheus-metrics.md @@ -0,0 +1,35 @@ +--- +id: prometheus-metrics +title: Prometheus 측정항목 +description: "Polygon 엣지에서 Prometheus 측정항목을 활성화하는 방법." +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## 개요 {#overview} + +Polygon 엣지는 Prometheus 측정항목을 보고 및 제공할 수 있으며, 그 후 이 측정항목을 Prometheus 수집기릁 통해 사용할 수 있습니다. + +기본적으로 Prometheus 측정항목은 비활성화되어 있으며, 구성 파일에서 `--prometheus` 플래그 또는 `Telemetry.prometheus` 필드를 사용하여 리스너 주소를 지정함으로써 활성화할 수 있습니다. +측정항목은 지정된 주소의 `/metrics` 아래에서 제공됩니다. + +## 사용 가능한 측정항목 {#available-metrics} + +다음 측정항목을 사용할 수 있습니다. + +| **이름** | **유형** | **설명** | +|-----------------------------------------------|---------------|-------------------------------------------------| +| txpool_pending_transactions | 측정 | 트랜잭션 풀에서 대기 중인 트랜잭션 수 | +| consensus_validators | 측정 | 검사기 수 | +| consensus_rounds | 측정 | 라운드 수 | +| consensus_num_txs | 측정 | 최근 블록의 트랜잭션 수 | +| consensus_block_interval | 측정 | 이 블록과 마지막 블록 사이의 시간(초) | +| network_peers | 측정 | 연결된 피어 수 | +| network_outbound_connections_count | 측정 | 아웃바운드 연결 수 | +| network_inbound_connections_count | 측정 | 인바운드 연결 수 | +| network_pending_outbound_connections_count | 측정 | 대기 중인 아웃바운드 연결 수 | +| network_pending_inbound_connections_count | 측정 | 대기 중인 인바운드 연결 수 | \ No newline at end of file diff --git a/archive/edge/ko-edge/configuration/sample-config.md b/archive/edge/ko-edge/configuration/sample-config.md new file mode 100644 index 0000000000..61e6ebc941 --- /dev/null +++ b/archive/edge/ko-edge/configuration/sample-config.md @@ -0,0 +1,151 @@ +--- +id: sample-config +title: 서버 구성 파일 +description: "구성 파일을 사용하여 Polygon 엣지 서버 시작하기." +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# 서버 구성 파일 {#server-configuration-file} +단순히 플래그 대신 구성 파일을 사용하여 다양한 구성 옵션으로 서버를 시작할 수 있습니다. +구성 파일로 서버를 시작하기 위해 사용하는 명령어는 `polygon-edge server --config `입니다. + +## 기본 구성의 구성 파일 내보내기 {#export-config-file-with-default-configuration} +Polygon 엣지 서버에 대한 기본 설정이 있는 구성은 `yaml` 또는 `json` 파일 형식의 구성 파일로 내보낼 수 있습니다. +이 파일을 구성 파일을 사용하여 서버를 실행하기 위한 템플릿으로 사용할 수 있습니다. + +### YAML {#yaml} +`yaml` 형식으로 구성 파일을 생성하려면 다음을 실행하세요. +```bash +polygon-edge server export --type yaml +``` +또는 다음을 실행하세요. +```bash +polygon-edge server export +``` +이 명령어를 실행한 디렉터리에 `default-config.yaml`이라는 이름의 구성 파일이 생성됩니다. + +파일 예시: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +`json` 형식으로 구성 파일을 생성하려면 다음을 실행하세요. +```bash +polygon-edge server export --type json +``` +이 명령어를 실행한 디렉터리에 `default-config.json`이라는 이름의 구성 파일이 생성됩니다. + +파일 예시: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +이러한 매개변수를 사용하는 방법에 관해 알아보려면 [CLI 명령어](/docs/edge/get-started/cli-commands) 섹션을 확인하세요. + +### Typescript 스키마 {#typescript-schema} + +다음은 구성 파일 형식의 예시입니다. 속성 유형(`number`, `boolean`, `string`)을 표현하기 위해 TypeScript로 작성되었으며, 이를 통해 구성을 도출할 수 있습니다. `type-fest`의 `PartialDeep` 유형은 모든 속성이 선택 사항임을 나타내는 데 사용됩니다. + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/ko-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/ko-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..ebb430e4c7 --- /dev/null +++ b/archive/edge/ko-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,139 @@ +--- +id: set-up-aws-ssm +title: AWS SSM(시스템 관리자) 설정 +description: "Polygon 엣지용 AWS SSM(시스템 관리자)을 설정합니다." +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## 개요 {#overview} + +현재 Polygon 엣지는 두 가지의 주요 런타임 보안 비밀을 유지하기 위해 노력하고 있습니다. +* 노드가 검사기인 경우 노드에서 사용하는 **검사기 비공개 키** +* 다른 피어와의 통신 및 참여를 위해 libp2p에서 사용하는 **네트워킹 비공개 키** + +자세한 정보는 [비공개 키 관리 가이드](/docs/edge/configuration/manage-private-keys)를 참조하세요. + +Polygon 엣지의 모듈은 **보안 비밀을 유지하는 방법을 알 필요가 없습니다**. 궁극적으로, 모듈은 +보안 비밀이 멀리 떨어진 서버에 저장되어 있는지 아니면 노드의 디스크에 로컬로 저장되어 있는지 고려할 필요가 없어야 합니다. + +모듈이 보안 비밀 유지와 관련하여 알아야 할 것은 **보안 비밀 사용 방법** 그리고 **어떤 비밀을 가져오거나 +저장해야 하는지**가 전부입니다. 이러한 작업의 고급 구현 세부 정보는 `SecretsManager`에 위임되며, 이는 물론 추상적 개념입니다. + +Polygon 엣지를 시작하는 노드 연산자는 이제 사용할 비밀 관리자를 지정할 수 있습니다. +올바른 보안 비밀 관리자가 인스턴스화되는 즉시, 모듈은 언급된 인터페이스를 통해 보안 비밀을 처리합니다. +보안 비밀이 디스크에 저장되었는지, 서버에 저장되었는지는 고려하지 않습니다. + +이 문서에서는 +[AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html)와 함께 Polygon 엣지를 시작하고 실행하는 데 필요한 단계를 자세히 설명합니다. + +:::info 이전 가이드 + +이 문서를 읽기 전 **권장 사항**은 [**로컬 설정**](/docs/edge/get-started/set-up-ibft-locally) +및 [**클라우드 설정**](/docs/edge/get-started/set-up-ibft-on-the-cloud)에 관한 문서를 읽는 것입니다. + +::: + + +## 기본 요건 {#prerequisites} +### IAM 정책 {#iam-policy} +사용자는 AWS Systems Manager Parameter Store의 읽기/쓰기 작업을 허용하는 IAM 정책을 생성해야 합니다. +IAM 정책을 성공적으로 생성한 후에는 Polygon 엣지 서버를 실행하는 EC2 인스턴스에 연결해야 합니다. +IAM 정책은 다음과 같이 표시됩니다. +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +AWS SSM IAM 역할에 대한 자세한 정보는 [AWS 문서](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html)에서 찾을 수 있습니다. + +계속하기 전에 필요한 정보: +* **지역**(시스템 관리자 및 노드의 소재지) +* **매개변수 경로**(보안 비밀이 배치될 임의 경로, 예: `/polygon-edge/nodes`) + +## 1단계 - 보안 비밀 관리자 구성 생성 {#step-1-generate-the-secrets-manager-configuration} + +Polygon 엣지가 AWS SSM과 원활하게 통신할 수 있으려면 이미 생성된 +구성 파일을 파싱해야 합니다. 이 파일에는 AWS SSM의 보안 비밀 스토리지에 필요한 모든 정보가 포함되어 있습니다. + +구성을 생성하려면 다음 명령어를 실행합니다. + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +매개변수 의미: +* `PATH`는 구성 파일을 내보내야 하는 경로입니다. 기본 `./secretsManagerConfig.json` +* `NODE_NAME`은 AWS SSM 구성이 설정될 현재 노드의 이름입니다. 임의의 값일 수 있습니다. 기본 `polygon-edge-node` +* `REGION`은 AWS SSM이 있는 지역입니다. AWS SSM을 활용하는 노드와 동일한 지역이어야 합니다. +* `SSM_PARAM_PATH`는 보안 비밀이 저장될 경로의 이름입니다. 예를 들어, `--name node1`과 `ssm-parameter-path=/polygon-edge/nodes`가 +지정되면 보안 비밀은 `/polygon-edge/nodes/node1/`으로 저장됩니다. + +:::caution 노드 이름 + +노드 이름을 지정할 때 주의하세요. + +Polygon 엣지는 지정된 노드 이름을 사용하여 AWS SSM에서 생성하고 사용하는 보안 비밀을 추적합니다. +기존 노드 이름을 지정하면 AWS SSM에 보안 비밀을 작성하지 못하는 결과가 발생할 수 있습니다. + +보안 비밀은 다음 기본 경로에 저장됩니다. `SSM_PARAM_PATH/NODE_NAME` + +::: + +## 2단계 - 구성을 사용하여 보안 비밀 키 초기화 {#step-2-initialize-secret-keys-using-the-configuration} + +이제 구성 파일이 있으므로 +1단계에서 `--config`를 사용하여 설정한 구성 파일로 필요한 보안 비밀 키를 초기화할 수 있습니다. + +```bash +polygon-edge secrets init --config +``` + +`PATH` 매개변수는 1단계에서 생성한 보안 비밀 관리자 매개변수의 위치입니다. + +:::info IAM 정책 + +읽기/쓰기 작업을 허용하는 IAM 정책이 올바르게 구성되지 않았거나 이 명령어를 실행하는 EC2 인스턴스에 연결되지 않으면 이 단계는 실패합니다. + +::: + +## 3단계 - 제네시스 파일 생성 {#step-3-generate-the-genesis-file} + +제네시스 파일은 사소한 변경 사항을 제외하고는 [**로컬 설정**](/docs/edge/get-started/set-up-ibft-locally) +및 [**클라우드 설정**](/docs/edge/get-started/set-up-ibft-on-the-cloud) 가이드와 유사한 방식으로 생성되어야 합니다. + +로컬 파일 시스템 대신 AWS SSM을 사용 중이므로 `--ibft-validator`플래그를 통해 검사기 주소를 추가해야 합니다. +```bash +polygon-edge genesis --ibft-validator ... +``` + +## 4단계 - Polygon 엣지 클라이언트 시작 {#step-4-start-the-polygon-edge-client} + +이제 키가 설정되고 제네시스 파일이 생성되었으므로 이 프로세스의 마지막 단계는 +`server` 명령어로 Polygon 엣지를 시작하는 것입니다. + +`server` 명령어는 사소한 추가(`--secrets-config` 플래그)를 제외하고는 앞서 설명한 가이드와 동일한 방식으로 사용됩니다. +```bash +polygon-edge server --secrets-config ... +``` + +`PATH` 매개변수는 1단계에서 생성한 보안 비밀 관리자 매개변수의 위치입니다. \ No newline at end of file diff --git a/archive/edge/ko-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/ko-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..a5cd485216 --- /dev/null +++ b/archive/edge/ko-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,118 @@ +--- +id: set-up-gcp-secrets-manager +title: GCP Secrets Manager 설정 +description: "Polygon 엣지를 위한 GCP Secrets Manager 설정." +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## 개요 {#overview} + +현재 Polygon 엣지는 두 가지의 주요 런타임 보안 비밀을 유지하기 위해 노력하고 있습니다. +* 노드가 검사기인 경우 노드에서 사용하는 **검사기 비공개 키** +* 다른 피어와의 통신 및 참여를 위해 libp2p에서 사용하는 **네트워킹 비공개 키** + +자세한 정보는 [비공개 키 관리 가이드](/docs/edge/configuration/manage-private-keys)를 참조하세요. + +Polygon 엣지의 모듈은 **보안 비밀을 유지하는 방법을 알 필요가 없습니다**. 궁극적으로, 모듈은 +보안 비밀이 멀리 떨어진 서버에 저장되어 있는지 아니면 노드의 디스크에 로컬로 저장되어 있는지 고려할 필요가 없어야 합니다. + +모듈이 보안 비밀 유지와 관련하여 알아야 할 것은 **보안 비밀 사용 방법** 그리고 **어떤 비밀을 가져오거나 +저장해야 하는지**가 전부입니다. 이러한 작업의 고급 구현 세부 정보는 `SecretsManager`에 위임되며, 이는 물론 추상적 개념입니다. + +Polygon 엣지를 시작하는 노드 연산자는 이제 사용할 비밀 관리자를 지정할 수 있습니다. +올바른 보안 비밀 관리자가 인스턴스화되는 즉시, 모듈은 언급된 인터페이스를 통해 보안 비밀을 처리합니다. +보안 비밀이 디스크에 저장되었는지, 서버에 저장되었는지는 고려하지 않습니다. + +이 문서에서는 [GCP Secrets Manager](https://cloud.google.com/secret-manager)와 함께 Polygon 엣지를 시작하고 실행하는 데 필요한 단계를 자세히 설명합니다. + +:::info 이전 가이드 + +이 문서를 읽기 전 **권장 사항**은 [**로컬 설정**](/docs/edge/get-started/set-up-ibft-locally) +및 [**클라우드 설정**](/docs/edge/get-started/set-up-ibft-on-the-cloud)에 관한 문서를 읽는 것입니다. + +::: + + +## 기본 요건 {#prerequisites} +### GCP 청구 계정 {#gcp-billing-account} +GCP Secrets Manager를 활용하려면 사용자가 GCP 포털에서 [청구 계정](https://console.cloud.google.com/)을 활성화해야 합니다. GCP 플랫폼의 새 Google 계정에는 무료 체험판으로 시작할 수 있는 자금이 제공됩니다. 상세 정보: [GCP 문서](https://cloud.google.com/free) + +### Secrets Manager API {#secrets-manager-api} +사용자는 Secrets Manager를 사용 전에 [Secrets Manager API 포털](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com)을 통해 GCP Secrets Manager API를 활성화해야 합니다. +상세 정보: [Secrets Manger 구성](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + +### GCP 자격 증명 {#gcp-credentials} +마지막으로, 사용자는 인증에 사용될 새로운 자격 증명을 생성해야 합니다. +[여기](https://cloud.google.com/secret-manager/docs/reference/libraries)에 게시된 설명을 따르면 됩니다. +자격 증명이 포함된 생성된 json 파일은 GCP Secrets Manager를 활용해야 하는 각 노드로 전송되어야 합니다. + +계속하려면 다음 정보가 필요합니다. +* **프로젝트 ID**(GCP 플랫폼에 정의된 프로젝트 ID) +* **자격 증명 파일 위치**(자격 증명이 포함된 json 파일의 경로) + +## 1단계 - 보안 비밀 관리자 구성 생성 {#step-1-generate-the-secrets-manager-configuration} + +Polygon 엣지가 GCP SM과 원활하게 통신할 수 있으려면 이미 생성된 +구성 파일을 파싱해야 합니다. 이 파일에는 GCP SM의 보안 비밀 스토리지에 필요한 모든 정보가 포함되어 있습니다. + +구성을 생성하려면 다음 명령어를 실행합니다. + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +매개변수 의미: +* `PATH`는 구성 파일을 내보내야 하는 경로입니다. 기본은 `./secretsManagerConfig.json`입니다. +* `NODE_NAME`은 GCP SM 구성이 설정되는 현재 노드의 이름입니다. 임의의 값일 수 있습니다. 기본은 `polygon-edge-node`입니다. +* `PROJECT_ID`는 계정 설정 및 Secrets Manager API 활성화 과정에서 사용자가 GCP 콘솔에서 정의한 프로젝트의 ID입니다. +* `GCP_CREDS_FILE`은 Secrets Manager에 대한 읽기/쓰기 액세스를 허용하는 자격 증명이 포함된 json 파일의 경로입니다. + +:::caution 노드 이름 + +노드 이름을 지정할 때 주의하세요. + +Polygon 엣지는 지정된 노드 이름을 사용하여 GCP SM에서 생성하고 사용하는 보안 비밀을 추적합니다. +이미 존재하는 노드 이름을 지정하면 GCP SM에 보안 비밀을 쓰지 못하게 될 수 있습니다. + +보안 비밀은 다음 기본 경로에 저장됩니다. `projects/PROJECT_ID/NODE_NAME` + +::: + +## 2단계 - 구성을 사용하여 보안 비밀 키 초기화 {#step-2-initialize-secret-keys-using-the-configuration} + +이제 구성 파일이 있으므로 +1단계에서 `--config`를 사용하여 설정한 구성 파일로 필요한 보안 비밀 키를 초기화할 수 있습니다. + +```bash +polygon-edge secrets init --config +``` + +`PATH` 매개변수는 1단계에서 생성한 보안 비밀 관리자 매개변수의 위치입니다. + +## 3단계 - 제네시스 파일 생성 {#step-3-generate-the-genesis-file} + +제네시스 파일은 사소한 변경 사항을 제외하고는 [**로컬 설정**](/docs/edge/get-started/set-up-ibft-locally) +및 [**클라우드 설정**](/docs/edge/get-started/set-up-ibft-on-the-cloud) 가이드와 유사한 방식으로 생성되어야 합니다. + +로컬 파일 시스템 대신 GCP SM이 사용되고 있으므로 `--ibft-validator` 플래그를 통해 검사기 주소를 추가해야 합니다. +```bash +polygon-edge genesis --ibft-validator ... +``` + +## 4단계 - Polygon 엣지 클라이언트 시작 {#step-4-start-the-polygon-edge-client} + +이제 키가 설정되고 제네시스 파일이 생성되었으므로 이 프로세스의 마지막 단계는 +`server` 명령어로 Polygon 엣지를 시작하는 것입니다. + +`server` 명령어는 사소한 추가(`--secrets-config` 플래그)를 제외하고는 앞서 설명한 가이드와 동일한 방식으로 사용됩니다. +```bash +polygon-edge server --secrets-config ... +``` + +`PATH` 매개변수는 1단계에서 생성한 보안 비밀 관리자 매개변수의 위치입니다. \ No newline at end of file diff --git a/archive/edge/ko-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/ko-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..745e1c04d4 --- /dev/null +++ b/archive/edge/ko-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,118 @@ +--- +id: set-up-hashicorp-vault +title: Hashicorp Vault 설정 +description: "Polygon 엣지를 위한 Hashicorp Vault 설정." +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## 개요 {#overview} + +현재 Polygon 엣지는 두 가지의 주요 런타임 보안 비밀을 유지하기 위해 노력하고 있습니다. +* 노드가 검사기인 경우 노드에서 사용하는 **검사기 비공개 키** +* 다른 피어와의 통신 및 참여를 위해 libp2p에서 사용하는 **네트워킹 비공개 키** + +:::warning + +검사기 비공개 키는 각 검사기 노드에 고유한 것입니다. 체인 보안 침해 가능성 때문에 이 키는 모든 검사기 간에 공유할 수 없습니다. + +::: + +자세한 정보는 [비공개 키 관리 가이드](/docs/edge/configuration/manage-private-keys)를 참조하세요. + +Polygon 엣지의 모듈은 **보안 비밀을 유지하는 방법을 알 필요가 없습니다**. 궁극적으로, 모듈은 +보안 비밀이 멀리 떨어진 서버에 저장되어 있는지 아니면 노드의 디스크에 로컬로 저장되어 있는지 고려할 필요가 없어야 합니다. + +모듈이 보안 비밀 유지와 관련하여 알아야 할 것은 **보안 비밀 사용 방법** 그리고 **어떤 비밀을 가져오거나 +저장해야 하는지**가 전부입니다. 이러한 작업의 고급 구현 세부 정보는 `SecretsManager`에 위임되며, 이는 물론 추상적 개념입니다. + +Polygon 엣지를 시작하는 노드 연산자는 이제 사용할 비밀 관리자를 지정할 수 있습니다. +올바른 보안 비밀 관리자가 인스턴스화되는 즉시, 모듈은 언급된 인터페이스를 통해 보안 비밀을 처리합니다. +보안 비밀이 디스크에 저장되었는지, 서버에 저장되었는지는 고려하지 않습니다. + +이 문서에서는 [Hashicorp Vault](https://www.vaultproject.io/) 서버와 함께 Polygon 엣지를 시작하고 실행하는 데 필요한 단계를 자세히 설명합니다. + +:::info 이전 가이드 + +이 문서를 읽기 전 **권장 사항**은 [**로컬 설정**](/docs/edge/get-started/set-up-ibft-locally) +및 [**클라우드 설정**](/docs/edge/get-started/set-up-ibft-on-the-cloud)에 관한 문서를 읽는 것입니다. + +::: + + +## 기본 요건 {#prerequisites} + +이 문서에서는 작동하는 Hashicorp Vault 서버 인스턴스가 **이미 설정되어 있다고** 가정합니다. + +또한, Polygon 엣지에 사용되는 Hashicorp Vault 서버는 **활성화된 KV 스토리지**가 있어야 합니다. + +계속하려면 다음 정보가 필요합니다. +* **서버 URL**(Hashicorp Vault 서버의 API URL) +* **토큰**(KV 스토리지 엔진 액세스에 사용할 액세스 토큰) + +## 1단계 - 보안 비밀 관리자 구성 생성 {#step-1-generate-the-secrets-manager-configuration} + +Polygon 엣지가 Vault 서버와 원활하게 통신할 수 있으려면 이미 생성된 +구성 파일을 파싱해야 합니다. 이 파일에는 Vault의 보안 비밀 스토리지에 필요한 모든 정보가 포함되어 있습니다. + +구성을 생성하려면 다음 명령어를 실행합니다. + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +매개변수 의미: +* `PATH`는 구성 파일을 내보내야 하는 경로입니다. 기본값은 `./secretsManagerConfig.json`입니다. +* `TOKEN`은 [기본 요건 섹션](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites)에서 설명한 액세스 토큰입니다. +* `SERVER_URL`은 Vault 서버의 API URL이며 [기본 요건 섹션](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites)에도 설명되어 있습니다. +* `NODE_NAME`은 Vault 구성이 설정되고 있는 현재 노드의 이름입니다. 임의의 값일 수 있습니다. 기본값은 `polygon-edge-node`입니다. + +:::caution 노드 이름 + +노드 이름을 지정할 때 주의하세요. + +Polygon 엣지는 지정된 노드 이름을 사용하여 Vault 인스턴스에서 생성하고 사용하는 보안 비밀을 추적합니다. +이미 존재하는 노드 이름을 지정하면 Vault 서버에서 데이터를 덮어쓸 수 있습니다. + +보안 비밀은 다음 기본 경로에 저장됩니다. `secrets/node_name` + +::: + +## 2단계 - 구성을 사용하여 보안 비밀 키 초기화 {#step-2-initialize-secret-keys-using-the-configuration} + +이제 구성 파일이 있으므로 +1단계에서 `--config`를 사용하여 설정한 구성 파일로 필요한 보안 비밀 키를 초기화할 수 있습니다. + +```bash +polygon-edge secrets init --config +``` + +`PATH` 매개변수는 1단계에서 생성한 보안 비밀 관리자 매개변수의 위치입니다. + +## 3단계 - 제네시스 파일 생성 {#step-3-generate-the-genesis-file} + +제네시스 파일은 사소한 변경 사항을 제외하고는 [**로컬 설정**](/docs/edge/get-started/set-up-ibft-locally) +및 [**클라우드 설정**](/docs/edge/get-started/set-up-ibft-on-the-cloud) 가이드와 유사한 방식으로 생성되어야 합니다. + +로컬 파일 시스템 대신 Hashicorp Vault가 사용되고 있으므로 `--ibft-validator` 플래그를 통해 검사기 주소를 추가해야 합니다. +```bash +polygon-edge genesis --ibft-validator ... +``` + +## 4단계 - Polygon 엣지 클라이언트 시작 {#step-4-start-the-polygon-edge-client} + +이제 키가 설정되고 제네시스 파일이 생성되었으므로 이 프로세스의 마지막 단계는 +`server` 명령어로 Polygon 엣지를 시작하는 것입니다. + +`server` 명령어는 사소한 추가(`--secrets-config` 플래그)를 제외하고는 앞서 설명한 가이드와 동일한 방식으로 사용됩니다. +```bash +polygon-edge server --secrets-config ... +``` + +`PATH` 매개변수는 1단계에서 생성한 보안 비밀 관리자 매개변수의 위치입니다. \ No newline at end of file diff --git a/archive/edge/ko-edge/consensus/bls.md b/archive/edge/ko-edge/consensus/bls.md new file mode 100644 index 0000000000..5449872f29 --- /dev/null +++ b/archive/edge/ko-edge/consensus/bls.md @@ -0,0 +1,144 @@ +--- +id: bls +title: BLS +description: "BLS 모드에 관한 설명 및 지침." +keywords: + - docs + - polygon + - edge + - bls +--- + +## 개요 {#overview} + +BBLS라고도 하는 BS는 사용자가 서명자가 진짜임을 확인할 수 있는 암호화 서명 방식입니다. 여러 서명을 집계할 수 있는 시그니처 계획입니다. Polygon 엣지에서는 IBFT 합의 모드의 보안을 강화하기 위해 기본적으로 BLS를 사용합니다. BLS는 서명을 단일 바이트 배열로 집계하고 블록 헤더 크기를 줄일 수 있습니다. 각 체인은 BLS 사용 여부를 선택할 수 있습니다. ECDSA 키는 BLS 모드의 활성화 여부와 관계없이 사용됩니다. + +## 비디오 프레젠테이션 {#video-presentation} + +[![bls - 비디오](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## BLS를 사용하여 새로운 체인을 설정하는 방법 {#how-to-setup-a-new-chain-using-bls} + +자세한 설정 지침은 [로컬 셋업](/docs/edge/get-started/set-up-ibft-locally) / [클라우드 설정](/docs/edge/get-started/set-up-ibft-on-the-cloud) 섹션을 참조하세요. + +## 기존 ECDSA PoA 체인에서 BLS PoA 체인으로 마이그레이션하는 방법 {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +이 섹션은 기존 PoA 체인에서 BLS 모드를 사용하는 방법에 대해 설명합니다. +PoA 체인에서 BLS를 활성화하려면 다음 단계를 수행해야 합니다. + +1. 모든 노드를 종료합니다. +2. 검사기용 BLS 키를 생성합니다. +3. genesis.json에 포크 설정을 추가합니다. +4. 모드 노드를 다시 시작합니다. + +### 1. 모든 노드 종료 {#1-stop-all-nodes} + +Ctrl + c(Control + c)를 눌러 검사기의 모든 프로세스를 종료합니다. 마지막 블록 높이(블록 커밋 로그에서 가장 높은 시퀀스 번호)를 기억하시기 바랍니다. + +### 2. BLS 키 생성 {#2-generate-the-bls-key} + +`secrets init`가 있는 `--bls`는 BLS 키를 생성합니다. 기존 ECDSA 및 네트워크 키를 보존하면서 새로운 BLS 키를 추가하려면 `--ecdsa` 및 `--network`를 비활성화해야 합니다. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. 포크 설정 추가 {#3-add-fork-setting} + +`ibft switch` 명령어는 기존 체인에서 BLS를 활성화하는 포크 설정을 `genesis.json`에 추가합니다. + +PoA 네트워크의 경우 명령어에 검사기를 제공해야 합니다. `genesis` 명령어의 방식과 마찬가지로 `--ibft-validators-prefix-path`또는 `--ibft-validator` 플래그를 사용하여 검사기를 지정할 수 있습니다. + +`--from` 플래그와 함께 BLS를 사용하여 체인 시작 높이를 지정하세요. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. 모든 노드 재시작 {#4-restart-all-nodes} + +`server` 명령어로 모든 노드를 재시작하세요. 이전 단계에서 지정된 `from`의 블록이 생성되면 체인은 BLS를 활성화하고 아래와 같이 로그를 표시합니다. + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +또한, 로그는 블록이 생성된 후 각 블록을 생성하는 데 사용된 검증 모드를 보여줍니다. + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## 기존 ECDSA PoS 체인에서 BLS PoS 체인으로 마이그레이션하는 방법 {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +이 섹션은 기존 PoS 체인에서 BLS 모드를 사용하는 방법에 대해 설명합니다. +PoS 체인에서 BLS를 활성화하려면 다음 단계를 수행해야 합니다. + +1. 모든 노드를 종료합니다. +2. 검사기용 BLS 키를 생성합니다. +3. genesis.json에 포크 설정을 추가합니다. +4. 스테이킹 계약을 호출하여 BLS 공개 키를 등록합니다. +5. 모드 노드를 다시 시작합니다. + +### 1. 모든 노드 종료 {#1-stop-all-nodes-1} + +Ctrl + c(Control + c)를 눌러 검사기의 모든 프로세스를 종료합니다. 마지막 블록 높이(블록 커밋 로그에서 가장 높은 시퀀스 번호)를 기억하시기 바랍니다. + +### 2. BLS 키 생성 {#2-generate-the-bls-key-1} + +`--bls` 플래그가 있는 `secrets init`는 BLS 키를 생성합니다. 기존 ECDSA 및 네트워크 키를 보존하면서 새로운 BLS 키를 추가하려면 `--ecdsa` 및 `--network`를 비활성화해야 합니다. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. 포크 설정 추가 {#3-add-fork-setting-1} + +`ibft switch` 명령어는 체인의 중반부터 BLS를 활성화하는 포크 설정을 `genesis.json`에 추가합니다. + +`from` 플래그와 함께 BLS 모드를 사용하여 체인 시작 높이를 지정하고 `development` 플래그를 사용하여 계약이 업데이트되는 높이를 지정하세요. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. 스테이킹 계약에 BLS 공개 키 등록 {#4-register-bls-public-key-in-staking-contract} + +포크가 추가되고 검사기가 다시 시작되면, 각 검사기는 스테이킹 계약에서 `registerBLSPublicKey`를 호출하여 BLS 공개 키를 등록해야 합니다. 이 작업은 `--deployment`에 지정된 높이 뒤 그리고 `--from`에 지정된 높이 전에 수행되어야 합니다. + +BLS 공개 키를 등록하는 스크립트는 [스테이킹 스마트 계약 저장소](https://github.com/0xPolygon/staking-contracts)에 정의되어 있습니다. + +`.env` 파일에 등록할 `BLS_PUBLIC_KEY`를 설정합니다. 기타 매개변수에 대한 자세한 정보는 [pos-stake-unstake](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts)를 참조하세요. + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +다음 명령어는 `.env`에 제공된 BLS 공개 키를 계약에 등록합니다. + +```bash +npm run register-blskey +``` + +:::warning 검사기는 BLS 공개 키를 수동으로 등록해야 합니다. + +BLS 모드에서 검사기는 자체 주소와 BLS 공개 키가 있어야 합니다. 합의 레이어는 합의가 계약에서 검사기 정보를 가져올 때 계약에 BLS 공개 키를 등록하지 않는 검사기를 무시합니다. + +::: + +### 5. 모든 노드 재시작 {#5-restart-all-nodes} + +`server` 명령어로 모든 노드를 재시작하세요. 이전 단계에서 지정된 `from`의 블록이 생성되면 체인은 BLS를 활성화합니다. diff --git a/archive/edge/ko-edge/consensus/migration-to-pos.md b/archive/edge/ko-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..2877149850 --- /dev/null +++ b/archive/edge/ko-edge/consensus/migration-to-pos.md @@ -0,0 +1,40 @@ +--- +id: migration-to-pos +title: PoA에서 PoS로 마이그레이션 +description: "PoA에서 PoS IBFT 모드로 또는 그 반대로 마이그레이션하는 방법" +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## 개요 {#overview} + +이 섹션에서는 실행 중인 클러스터에서 블록체인을 초기화하지 않고도 PoA에서 PoS IBFT 모드로 또는 그 반대로 마이그레이션하는 방법을 설명합니다. + +## PoS로 마이그레이션하는 방법 {#how-to-migrate-to-pos} + +모든 노드를 종료하고 `ibft switch` 명령어를 통해 genesis.json에 포크 구성을 추가하고 노드를 다시 시작해야 합니다. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution ECDSA를 사용하여 전환 +ECDSA를 사용할 때 ECDSA를 사용한다는 것을 언급하면서 `--ibft-validator-type`플래그를 스위치에 추가해야 합니다. 포함되지 않은 경우 Ege는 자동으로 BLS로 전환할 수 있습니다. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::PoS로 전환하려면 2개의 블록 `deployment`높이를 지정해야 합니다. 스테이킹 계약을 배포할 수 있는 `from``deployment`높이이며 PoS의 시작의 `from`높이입니다. 스테이킹 계약은 사전 배포되는 계약과 마찬가지로 `deployment`에서 주소 `0x0000000000000000000000000000000000001001`에 배포됩니다. + +스테이킹 계약에 관한 자세한 내용은 [지분증명](/docs/edge/consensus/pos-concepts)을 참조하세요. + +:::warning 검사기는 수동으로 스테이킹해야 합니다 + +PoS 시작 시 검사기가 되려면 각 검사기는 계약이 `deployment`에 배포된 후 그리고 `from` 전에 스테이킹해야 합니다. 각 검사기는 PoS 시작 시 스테이킹 계약의 세트로 자체 검사기 세트를 업데이트합니다. + +스테이킹에 대해 더 자세히 알아보기 위해서는 **[설정 을 방문하고 스테이크의 증거를 사용하십시오](/docs/edge/consensus/pos-stake-unstake)**. +::: diff --git a/archive/edge/ko-edge/consensus/poa.md b/archive/edge/ko-edge/consensus/poa.md new file mode 100644 index 0000000000..f053f9ee6b --- /dev/null +++ b/archive/edge/ko-edge/consensus/poa.md @@ -0,0 +1,110 @@ +--- +id: poa +title: 권위증명(PoA) +description: "권위증명에 관한 설명 및 지침입니다." +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## 개요 {#overview} + +IBFT PoA는 Polygon 엣지의 기본 합의 메커니즘입니다. PoA에서 검사기는 블록을 생성하고 이 블록을 시리즈로 블록체인에 추가하는 역할을 담당합니다. + +모든 검사기는 동적 검사기 세트를 구성하며, 투표 메커니즘을 사용하여 이 세트에 추가되거나 삭제될 수 있습니다. 즉, 검사기 노드의 과반수(51%)가 특정 검사기를 세트에 추가/삭제하기로 투표하면 검사기는 검사기 세트의 일원이 되거나 해당 자격을 상실할 수 있습니다. 이러한 방식으로 악의적인 검사기를 감지하여 네트워크에서 삭제하고, 신뢰할 수 있는 새 검사기를 네트워크에 추가할 수 있습니다. + +모든 검사기는 차례대로 다음 블록을 제안하며(라운드-로빈), 블록을 검증해 블록체인에 삽입하려면 검사기의 초다수(2/3 초과)가 해당 블록을 승인해야 합니다. + +검사기 외에도, 블록 생성에는 참여하지 않지만 블록 검증 프로세스에는 참여하는 비 검사기가 있습니다. + +## 검사기 세트에 검사기 추가하기 {#adding-a-validator-to-the-validator-set} + +이 가이드는 4개의 검사기 노드가 있는 활성 IBFT 네트워크에 새 검사기 노드를 추가하는 방법을 설명합니다. +네트워크를 설정하는 데 도움이 필요하면 [로컬 설치](/edge/get-started/set-up-ibft-locally.md) / [클라우드 설정](/edge/get-started/set-up-ibft-on-the-cloud.md) 섹션을 참조하십시오. + +### 1단계: IBFT용 데이터 폴더를 초기화하고 새 노드의 검사기 키 생성하기 {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +새 노드에서 IBFT를 시작하고 실행하려면 먼저 데이터 폴더를 초기화하고 키를 생성해야 합니다. + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +이 명령어는 검사기 키(주소) 및 노드 ID를 출력합니다. 다음 단계에 이 검사기 키(주소)가 필요합니다. + +### 2단계: 다른 검사기 노드에서 새 후보 제안하기 {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +새 노드가 검사기가 되려면 최소 51%의 검사기가 해당 노드를 제안해야 합니다. + +grpc 주소(127.0.0.1:10000)의 기존 검사기 노드에서 새 검사기(`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`)를 제안하는 방법의 예: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +IBFT 명령어의 구조는 [CLI 명령어](/docs/edge/get-started/cli-commands) 섹션에서 설명합니다. + +:::info BLS 공개 키 + +BLS 공개 키는 네트워크가 BLS를 사용하여 실행되는 경우에만 필요합니다. BLS 모드에서 실행되지 않는 네트워크의 경우 `--bls`가 필요하지 않습니다. + +::: + +### 3단계: 클라이언트 노드 실행하기 {#step-3-run-the-client-node} + +이 예에서는 모든 노드가 동일한 머신에 있는 네트워크의 실행을 시도하고 있기 때문에 주의를 기울여 포트 충돌을 방지해야 합니다. + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +모든 블록을 가져온 후 콘솔 내부에서 새 노드가 검증에 참여하고 있음을 알 수 있습니다. + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info 비 검사기를 검사기로 승격하기 + +당연히 비 검사기는 투표 프로세스를 통해 검사기가 될 수 있습니다. 그러나 투표 프로세스 후 검사기 세트에 성공적으로 포함되려면 `--seal` 플래그를 사용해 노드가 다시 시작되도록 해야 합니다. + +::: + +## 검사기 세트에서 검사기 삭제하기 {#removing-a-validator-from-the-validator-set} + +이 작업은 상당히 간단합니다. 검사기 세트에서 검사기 노드를 삭제하려면 과반수의 검사기 노드에 다음 명령어를 실행해야 합니다. + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info BLS 공개 키 + +BLS 공개 키는 네트워크가 BLS를 사용하여 실행되는 경우에만 필요합니다. BLS 모드에서 실행되지 않는 네트워크의 경우 `--bls`가 필요하지 않습니다. + +::: + +명령어를 실행한 후 검사기의 수가 줄었는지 확인하세요(로그 예에서는 4에서 3으로 감소). + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/ko-edge/consensus/pos-concepts.md b/archive/edge/ko-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..b65094638b --- /dev/null +++ b/archive/edge/ko-edge/consensus/pos-concepts.md @@ -0,0 +1,121 @@ +--- +id: pos-concepts +title: 지분증명 +description: "지분증명에 관한 설명 및 지침입니다." +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## 개요 {#overview} + +이 섹션은 현재 Polygon 엣지의 지분증명(PoS) 구현에 반영된 몇 가지 개념에 대해 +보다 명확한 개요를 제공하기 위해 작성되었습니다. + +Polygon 엣지 지분증명(PoS) 구현은 기존의 PoA IBFT 구현에 대한 대안으로서, +노드 연산자는 체인을 시작할 때 이 두 가지 중에서 쉽게 선택할 수 있습니다. + +## PoS 기능 {#pos-features} + +지분증명 구현을 뒷받침하는 핵심 논리는 +**[스테이킹 스마트 계약서](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)**. + +이 계약은 Polygon 엣지 체인의 PoS 메커니즘이 초기화될 때마다 사전 배포되며 주소 +`0x0000000000000000000000000000000000001001`(블록 `0`)에서 사용 가능합니다. + +### 에포크 {#epochs} + +에포크는 Polygon 엣지에 PoS가 추가되면서 적용되는 개념입니다. + +에포크는 특정 검사기 세트가 블록을 생성할 수 있는 특별한 시간 프레임(블록 단위)으로 간주됩니다. +에포크 길이는 수정할 수 있습니다. 즉, 노드 연산자가 제네시스 생성 시 에포크 길이를 구성할 수 있습니다. + +각 에포크 종료 시 _에포크 블록_이 생성되고, 이 이벤트 후에 새로운 에포크가 시작됩니다. 에포크 블록에 대한 보다 자세한 내용은 +[에포크 블록](/docs/edge/consensus/pos-concepts#epoch-blocks) 섹션을 참조하세요. + +검사기 세트는 각 에포크 종료 시 업데이트됩니다. 노드는 에포크 블록이 생성되는 동안 스테이킹 스마트 계약의 검사기 세트를 쿼리하고, +획득한 데이터를 로컬 스토리지에 저장합니다. 이러한 쿼리 및 저장 주기는 +각 에포크 종료 시 반복됩니다. + +결론적으로 이를 통해 스테이킹 스마트 계약은 검사기 세트의 주소를 완전히 제어할 수 있고 +노드에게 단 하나의 역할만 남깁니다. 즉, 노드는 에포크 중에 최신 검사기 세트 정보를 가져오기 위해 계약을 한 번 +쿼리하면 됩니다. 따라서 개별 노드가 검사기 세트를 처리해야 하는 책임이 줄어들게 됩니다. + +### 스테이킹 {#staking} + +주소는 `stake` 메서드를 호출하고 트랜잭션에서 스테이킹 금액 값을 지정하여 스테이킹 스마트 계약의 자금을 +스테이킹할 수 있습니다. + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +주소는 스테이킹 스마트 계약의 자금을 스테이킹함으로써, 검사기 세트에 들어가 +블록 생성 프로세스에 참여할 수 있습니다. + +:::info 스테이킹 임계값 + +현재 검사기 세트에 들어가기 위해 필요한 최소 임계값은 `1 ETH`를 스테이킹하는 것입니다. + +::: + +### 스테이킹 해제 {#unstaking} + +자금을 스테이킹한 주소는 **스테이킹한 자금의 스테이킹 해제를 모두 한 번에** 수행해야 합니다. + +스테이킹 해제는 스테이킹 스마트 계약에서 `unstake` 메서드를 호출하면 됩니다. + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +자금을 스테이킹 해제하면 주소가 스테이킹 스마트 계약의 검사기 세트에서 삭제되고 +다음 에포크에서 검사기로 간주되지 않습니다. + +## 에포크 블록 {#epoch-blocks} + +**에포크 블록**은 Polygon 엣지에서 IBFT의 PoS 구현 시 적용되는 개념입니다. + +기본적으로 에포크 블록은 **트랜잭션을 포함하지 않는** 특수한 블록이며 **에포크 종료 시**에만 발생합니다. +예를 들어, **에폭시 크기가** 블록으로 설정되어 `50`있다면, 에폭시 블록은 `50`블록 `100``150`등으로 간주됩니다. + +에포크 블록은 일반적인 블록 생성에서 발생해서는 안 되는 추가 논리를 수행하는 데 사용됩니다. + +가장 중요한 점은 에포크 블록을 통해 노드가 스테이킹 스마트 계약에서 **최신 검사기 세트** 정보를 가져와야 +함을 알게 된다는 것입니다. + +에포크 블록에서 검사기 세트가 업데이트되면 이 검사기 세트는(변경되었는지 여부와 상관없이) +스테이킹 스마트 계약에서 최신 정보를 가져와 다시 업데이트될 때까지 그 다음의 `epochSize - 1` 블록에 사용됩니다. +스테이킹 스마트 계약에 있습니다. + +에포크 길이(블록 단위)는 제네시스 파일을 생성할 때 특별 플래그 `--epoch-size`를 사용하여 수정할 수 있습니다. + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +Polygon 엣지에서 에포크의 기본 크기는 `100000`블록입니다. + +## 계약 사전 배포 {#contract-pre-deployment} + +Polygon 엣지가 _사전 배포_하는 +[스테이킹 스마트 계약](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)은 +**제네시스 생성** 중에 주소 `0x0000000000000000000000000000000000001001`로 사전 배포됩니다. + +이러한 사전 배포는 EVM을 실행하지 않으며, 전달된 구성 값을 제네시스 명령어에 사용하여 스마트 계약의 블록체인 상태를 +직접 수정하는 방식으로 진행됩니다. diff --git a/archive/edge/ko-edge/consensus/pos-stake-unstake.md b/archive/edge/ko-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..dc99dac745 --- /dev/null +++ b/archive/edge/ko-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,176 @@ +--- +id: pos-stake-unstake +title: 지분증명(PoS) 설정 및 사용 +description: "스테이킹, 스테이킹 해제 및 기타 스테이킹 관련 지침입니다." +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## 개요 {#overview} + +이 가이드에서는 Polygon 엣지로 지분증명 네트워크를 설정하는 방법, 노드를 검사기로 만들기 위해 자금을 스테이킹하는 방법, 자금 스테이킹을 해제하는 방법을 자세히 안내합니다. + +읽거나 지나갈 수 있는 **것이 매우** 좋습니다. [로컬 설정](/docs/edge/get-started/set-up-ibft-locally) +/ [클라우드 설정](/docs/edge/get-started/set-up-ibft-on-the-cloud) 섹션을 +확인하세요. 이 섹션에는 Polygon 엣지로 권위증명(PoA) 클러스터를 시작하는 데 필요한 단계를 +설명합니다. + +현재 스테이킹 스마트 계약에서 자금을 스테이킹할 수 있는 검사기 수에 제한은 없습니다. + +## 스테이킹 스마트 계약 {#staking-smart-contract} + +스테이킹 스마트 계약의 저장소는 [여기](https://github.com/0xPolygon/staking-contracts)에 있습니다. + +이 저장소에는 필요한 테스트 스크립트와 ABI 파일은 물론 가장 중요한 스테이킹 스마트 계약 자체가 들어 있습니다. + +## N 노드 클러스터 설정 {#setting-up-an-n-node-cluster} + +Polygon 엣지로 네트워크를 설정하는 방법은 +[로컬 설정](/docs/edge/get-started/set-up-ibft-locally) +/ [클라우드 설정](/docs/edge/get-started/set-up-ibft-on-the-cloud) 섹션에서 다룹니다. + +PoS 및 PoA 클러스터 설정 간 **유일한 차이점**은 제네시스 생성 부분에 있습니다. + +**PoS 클러스터에 대한 제네시스 파일을 생성할 때는 다음과 같이 `--pos`**라는 추가 플래그가 필요합니다. + +```bash +polygon-edge genesis --pos ... +``` + +## 에포크 길이 설정 {#setting-the-length-of-an-epoch} + +에포크에 대한 자세한 내용은 [에포크 블록](/docs/edge/consensus/pos-concepts#epoch-blocks) 섹션에 나와 있습니다. + +클러스터의 에포크 크기를 블록 단위로 설정하려는 경우, 제네시스 파일을 생성할 때 +다음과 같이 `--epoch-size`라는 추가 플래그를 지정합니다. + +```bash +polygon-edge genesis --epoch-size 50 +``` + +제네시스 파일에서 이 값은 에포크 크기를 `50`블록으로 지정하고 있습니다. + +블록 단위의 에포크 크기 기본값은 `100000`입니다. + +:::info 에포크 길이 줄이기 + +[에포크 블록](/docs/edge/consensus/pos-concepts#epoch-blocks) 섹션에 나와 있듯이 +에포크 블록은 노드에 대한 검사기 세트를 업데이트하는 데 사용됩니다. + +블록 단위의 기본 에포크 길이(`100000`)는 검사기 세트의 업데이트를 기다리기에 긴 시간일 수 있습니다. 새로운 블록 추가에 +최대 2초가 걸린다고 생각하면 최대 55.5시간이 지나야 검사기 세트가 바뀔 수 있습니다. + +에포크 길이 값을 더 낮게 설정하면 검사기 세트가 더욱 자주 업데이트되도록 할 수 있습니다. + +::: + +## 스테이킹 스마트 계약 스크립트 사용 {#using-the-staking-smart-contract-scripts} + +### 기본 요건 {#prerequisites} + +스테이킹 스마트 계약 저장소는 NPM이 필요한 Hardhat 프로젝트입니다. + +정확하게 초기화하려면 메인 디렉터리에서 다음을 실행하세요. + +```bash +npm install +```` + +### 제공된 도우미 스크립트 설정 {#setting-up-the-provided-helper-scripts} + +배포된 스테이킹 스마트 계약과 상호작용하기 위한 스크립트는 +[스테이킹 스마트 계약 저장소](https://github.com/0xPolygon/staking-contracts)에 있습니다. + +스마트 계약 저장소 위치에서 다음과 같은 매개변수로 `.env` 파일을 생성하세요. + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +여기서 매개변수는 다음을 의미합니다. + +* **JSONRPC_URL** - 실행 노드를 위한 JSON-RPC 엔드포인트입니다. +* **PRIVATE_KEYS** - 스테이커 주소의 비공개 키입니다. +* **STAKING_CONTRACT_ADDRESS** - 스테이킹 스마트 계약의 주소입니다( +기본값 `0x0000000000000000000000000000000000001001`). +* **BLS_PUBLIC_KEY** - 스테이커의 BLS 공개 키입니다. 네트워크가 BLS로 실행되는 경우에만 필요합니다. + +### 자금 스테이킹 {#staking-funds} + +:::info 스테이킹 주소 + +스테이킹 스마트 계약은 주소 +`0x0000000000000000000000000000000000001001`에 사전 배포됩니다. + +스테이킹 메커니즘과의 모든 상호작용은 지정된 주소의 스테이킹 스마트 계약을 통해서 이루어집니다. + +스테이킹 스마트 계약에 대한 보다 자세한 내용은 +**[스테이킹 스마트 계약](/docs/edge/consensus/pos-concepts#contract-pre-deployment)** 섹션을 확인하세요. + +::: + +검사기 세트의 일부가 되기 위해서는 주소가 임계값을 초과하는 특정 금액의 자금을 스테이킹해야 합니다. + +현재 검사기 세트의 일부가 되기 위한 기본 임계값은 `1 ETH`입니다. + +스테이킹 스마트 계약의 `stake` 메서드를 호출하고 `>= 1 ETH` 값을 지정하여 스테이킹을 초기화할 수 있습니다. + +`.env` 파일 +([이전 섹션](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts)에서 설명)이 설정되고 +PoS 모드에서 체인이 시작된 후에는 스테이킹 스마트 계약 저장소의 다음 명령어로 스테이킹을 수행할 수 있습니다. + +```bash +npm run stake +``` + +`stake` Hardhat 스크립트는 기본 금액 `1 ETH`를 스테이킹하며, 이 금액은 `scripts/stake.ts` +파일을 수정하여 변경할 수 있습니다. + +스테이킹되는 자금이 `>= 1 ETH`인 경우, 스테이킹 스마트 계약의 검사기 세트가 업데이트되고 +다음 에포크부터 주소가 검사기 세트의 일부가 됩니다. + +:::info BLS 키 등록 + +네트워크가 BLS 모드에서 실행되는 경우, 노드가 검사기가 되려면 스테이킹 후 해당 BLS 공개 키를 등록해야 합니다. + +이 작업은 다음 명령어로 수행할 수 있습니다. + +```bash +npm run register-blskey +``` +::: + +### 자금 스테이킹 해제 {#unstaking-funds} + +지분이 있는 주소는 **자금 스테이킹을 해제할 때 모두** 한 번에 해제해야 합니다. + +`.env` 파일 +([이전 섹션](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts)에서 설명)이 +설정되고 PoS 모드에서 체인이 시작된 후 스테이킹 스마트 계약 저장소의 다음 명령어로 +스테이킹 해제를 수행할 수 있습니다. + +```bash +npm run unstake +``` + +### 스테이커 목록 가져오기 {#fetching-the-list-of-stakers} + +자금을 스테이킹하는 모든 주소는 스테이킹 스마트 계약에 저장됩니다. + +`.env` 파일 +([이전 섹션](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts)에서 설명)이 +설정되고 PoS 모드에서 체인이 시작된 후 스테이킹 스마트 계약 저장소의 다음 명령어로 +검사기 목록을 가져올 수 있습니다. + +```bash +npm run info +``` diff --git a/archive/edge/ko-edge/faq/Contracts.md b/archive/edge/ko-edge/faq/Contracts.md new file mode 100644 index 0000000000..c99b7dc251 --- /dev/null +++ b/archive/edge/ko-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: 스마트 계약 FAQ +description: "Polygon 엣지 스마트 계약에 대한 FAQ" +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## Polygon 엣지는 스마트 계약을 지원하나요? {#does-polygon-edge-support-smart-contracts} + +예. Polygon 엣지 네트워크는 이더리움과 호환 가능한 블록체인이므로 이더리움에 배포 가능한 스마트 계약은 Polygon 엣지 체인에도 배포할 수 있습니다. + +## 배포 후에 PoS의 스테이킹 계약 논리를 업데이트할 수 있나요? {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +PoS 네트워크를 시작한 후에는 스테이킹 계약 논리가 제네시스 파일의 일부가 되므로 현재로서는 변경할 수 없습니다. 예를 들면 검사기의 최소/최대 수를 변경할 수 없습니다. 가능한 작업은 스테이킹, 스테이킹 해제, 검사기를 추가하거나 삭제하는 정도입니다. + + + diff --git a/archive/edge/ko-edge/faq/Gas.md b/archive/edge/ko-edge/faq/Gas.md new file mode 100644 index 0000000000..a51a74992d --- /dev/null +++ b/archive/edge/ko-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: 가스 FAQ +description: "Polygon 엣지의 가스에 대한 FAQ" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## 최소 가스 가격을 적용하려면 어떻게 하나요? {#how-to-enforce-a-minimum-gas-price} +서버 명령어에 제공된 `--price-limit` 플래그를 사용하면 됩니다. 그러면 노드에서 사용자가 설정한 가격 한도 이상의 가스를 보유한 트랜잭션만 수락합니다. 이를 전체 네트워크에 적용하려면 모든 노드의 가격 한도가 동일해야 합니다. + + +## 가스 요금이 0인 트랜잭션이 있을 수 있나요? {#can-you-have-transactions-with-0-gas-fees} +예, 가능합니다. 노드가 적용하는 기본 가격 한도는 `0`입니다. 즉, 노드는 가스 가격이 `0`으로 설정된 트랜잭션을 수락하게 됩니다. + +## 가스(기본) 토큰 총 공급량은 어떻게 설정하나요? {#how-to-set-the-gas-native-token-total-supply} + +`--premine flag`를 사용하여 사전 채굴된 잔액을 계정(주소)에 설정할 수 있습니다. 이 설정은 제네시스 파일의 구성 항목이며 나중에 변경할 수 없습니다. + +`--premine flag`를 사용하는 방법의 예가 아래에 나와 있습니다. + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +이는 사전 채굴된 잔액 1000ETH를 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862에 설정합니다(인수의 금액은 wei 단위). + +사전 채굴된 가스 토큰 금액이 총 공급량이 됩니다. 나중에 다른 기본 화폐(가스 토큰) 금액은 발행할 수 없습니다. + +## 엣지에서 ERC-20을 가스 토큰으로 사용할 수 있나요? {#does-edge-support-erc-20-as-a-gas-token} + +엣지는 ERC-20 토큰을 가스 토큰으로 지원하지 않습니다. 가스에는 네이티브 엣지 통화만 지원됩니다. + +## 가스 제한을 어떻게 늘려야 할까요? {#how-to-increase-the-gas-limit} + +Polygon Edge에서 가스 제한을 증가시키기 위해 두 가지 옵션이 있습니다. +1. 제네시스 파일의 최대 uint64 값으로 체인을 제거하고 `block-gas-limit`증가 +2. 모든 노드의 가스 제한을 높이기 위해 높은 값으로 `--block-gas-target`플래그를 사용하십시오. 이 경우 노드 재부팅이 필요합니다. [자세한](/docs/edge/architecture/modules/txpool/#block-gas-target) 설명은 여기에서 자세히 설명합니다. \ No newline at end of file diff --git a/archive/edge/ko-edge/faq/Tokens.md b/archive/edge/ko-edge/faq/Tokens.md new file mode 100644 index 0000000000..eade419b44 --- /dev/null +++ b/archive/edge/ko-edge/faq/Tokens.md @@ -0,0 +1,23 @@ +--- +id: tokens +title: 토큰 FAQ +description: "Polygon 엣지 토큰에 대한 FAQ" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## Polygon 엣지는 EIP-1559를 지원하나요? {#does-polygon-edge-support-eip-1559} +현재 Polygon 엣지는 EIP-1559를 지원하지 않습니다. + +## 화폐(토큰) 기호는 어떻게 설정하나요? {#how-to-set-the-currency-token-symbol} + +토큰 기호는 UI에 해당하므로 네트워크 어디에서도 구성하거나 하드코딩할 수 없습니다. +그러나 예를 들어 메타마스크와 같은 지갑에 네트워크를 추가할 때는 토큰 기호를 변경할 수 있습니다. + +## 체인에서 중단되면 트랜잭션을 어떻게 될까요? {#what-happens-to-transactions-when-a-chain-halts} + +처리되지 않은 모든 거래는 TxPool(enbeygor 홍보 대기열에 포함)에 있습니다. 체인 할트(모든 블록 제작 정류장)를 사용하면 이러한 거래는 결코 블록에 들어가지 않을 것입니다.
이것은 체인 할트가 끝나면 경우에만 아닙니다. 노드가 중지되거나 다시 시작되면, 실행되지 않은 모든 거래가 여전히 TxPool에 있는 경우 조용히 제거됩니다.
노드가 다시 시작할 필요가 있으므로 어획 변경이 도입될 때 동일한 일이 발생할 것입니다. diff --git a/archive/edge/ko-edge/faq/Validators.md b/archive/edge/ko-edge/faq/Validators.md new file mode 100644 index 0000000000..0fc237399e --- /dev/null +++ b/archive/edge/ko-edge/faq/Validators.md @@ -0,0 +1,85 @@ +--- +id: validators +title: 검사기 FAQ +description: "Polygon 엣지 검사기 FAQ" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## 검사기를 추가/삭제하려면 어떻게 하나요? {#how-to-add-remove-a-validator} + +### PoA {#poa} +검사기는 투표를 통해 추가되거나 삭제됩니다. 이에 관한 전체 가이드는 [여기](/docs/edge/consensus/poa)에서 찾을 수 있습니다. + +### PoS {#pos} +노드가 검사기가 될 수 있도록 하는 자금 스테이킹 방법과 스테이킹 해제(검사기 삭제)하는 방법에 관한 가이드는 [여기](/docs/edge/consensus/pos-stake-unstake)에서 찾을 수 있습니다. + +다음 사항을 참고하세요. +- 제네시스 플래그 `--max-validator-count`를 사용하여 검사기 세트에 포함될 수 있는 최대 스테이커 수를 설정할 수 있습니다. +- 제네시스 플래그 `--min-validator-count `를 사용하여 검사기 세트에 포함해야 하는 최소 스테이커 수를 설정할 수 있습니다(기본 값은 `1`). +- 최대 검사기 수에 도달하면, 해당 세트에서 기존 검사기를 삭제해야 다른 검사기를 추가할 수 있습니다. 새 검사기의 스테이킹 금액이 더 높은 경우에도 마찬가지입니다. 검사기를 삭제하는 경우, 남은 검사기의 수는 `--min-validator-count` 이상이어야 합니다. +- 검사기가 되기 위한 기본 임계값인 `1`단위의 기본 네트워크(가스) 화폐가 있습니다. + + + +## 검사기에 어느 정도의 디스크 공간이 필요한가요? {#how-much-disk-space-is-recommended-for-a-validator} + +보수적으로 추정하여 최소 100G로 시작하고 나중에 디스크 확장이 가능하도록 하는 것이 좋습니다. + + +## 검사기 수에 한도가 있나요? {#is-there-a-limit-to-the-number-of-validators} + +기술적 제한과 관련하여, 네트워크에서 가질 수 있는 노드 수에 대해 Polygon 엣지가 명시한 한도는 없습니다. 노드별로 연결 한도(인바운드/아웃바운드 연결 수)를 정할 수 있습니다. + +현실적인 한계를 말하자면, 100노드 클러스터는 10노드 클러스터보다 성능이 떨어질 것입니다. 클러스터의 노드 수를 늘리면 일반적으로 통신 복잡성과 네트워킹 오버헤드가 커집니다. 그러나 이는 실행 중인 네트워크의 종류 및 네트워크 토폴로지의 종류에 따라 다릅니다. + +## PoA에서 PoS로 어떻게 전환하나요? {#how-to-switch-from-poa-to-pos} + +PoA는 기본 합의 메커니즘입니다. 새 클러스터의 경우, PoS로 전환하려면 제네시스 파일을 생성할 때 `--pos` 플래그를 추가해야 합니다. 실행 클러스터가 있는 경우, 전환하는 방법은 [여기](/docs/edge/consensus/migration-to-pos)에서 확인할 수 있습니다. 합의 메커니즘 및 설정에 관해 필요한 모든 정보는 [합의 섹션](/docs/edge/consensus/poa)에서 찾을 수 있습니다. + +## 호환성을 손상하는 변경이 있는 경우, 노드를 어떻게 업데이트하나요? {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +이 절차에 관한 자세한 가이드는 [여기](/docs/edge/validator-hosting#update)에서 찾을 수 있습니다. + +## PoS 엣지에 설정할 수 있는 최소 스테이킹 금액이 있나요? {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +최소 스테이킹 금액은 기본적으로 `1 ETH`이며, 별도로 구성할 수 없습니다. + +## JSON RPC 명령어 `eth_getBlockByNumber`및 `eth_getBlockByHash`가 채굴자의 주소를 반환하지 않는 이유는 무엇인가요? {#not-return-the-miner-s-address} + +현재 Polygon 엣지에서 사용되는 합의는 IBFT 2.0이며, 이는 다시 Clique PoA: [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225)에서 설명하는 투표 메커니즘을 기반으로 합니다. + +EIP-225(Clique PoA)를 보면, `miner`(일명 `beneficiary`)의 용도를 설명하는 부분입니다. + +
+Polygon은 다음과 같이 ethash 헤더 필드의 용도를 변경합니다. +
    +
  • 수익자 / 채굴자: 승인된 서명자 목록의 수정을 제안할 주소.
  • +
      +
    • 일반적으로 0이 입력되어 있으며 투표하는 동안에만 수정할 수 있습니다.
    • +
    • 그렇지만 투표 메커니즘 관련 구현의 복잡성이 커지지 않도록 임의의 값도 허용됩니다(비서명자 삭제 투표와 같은 무의미한 값도 가능).
    • +
    • 체크포인트(즉, 에포크 전환) 블록에는 0이 입력되어야 합니다.
    • +
    + +
+ +
+ +따라서 `miner` 필드는 블록의 제안자 표시가 아니라 일정 주소에 대한 투표 제안에 사용됩니다. + +블록 제안자에 관한 정보는 블록 헤더의 RLP 인코딩 Istanbul 추가 데이터 필드 중 봉인 필드에서 공개 키를 복구하여 찾을 수 있습니다. + +## 제네시스의 일부 및 값을 안전하게 수정할 수 있습니까? {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +편집 하려고 하기 전에 기존 genesis.json 파일의 수동 사본을 만드시는지 확인하십시오. 또한 genesis.json 파일을 편집하는 데 앞서 전체 체인을 중단해야 합니다. 또한 genesis.json 파일을 편집하기 전에 전체 체인을 사용해야 합니다. 제네시스 파일이 수정되면, 새로운 버전은 모든 비 검증자 및 valdiator 노드를 통해 배포해야 합니다. + +::: + +목록에서 부트 노드를 추가하거나 제거할 수 있는 **제네시스 파일의 부트 노드 섹션만으로도 안전하게 수정할** 수 있습니다. \ No newline at end of file diff --git a/archive/edge/ko-edge/get-started/cli-commands.md b/archive/edge/ko-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..57bb691287 --- /dev/null +++ b/archive/edge/ko-edge/get-started/cli-commands.md @@ -0,0 +1,2219 @@ +--- +id: cli-commands +title: CLI 명령어 +description: "Polygon 엣지 명령어 및 명령어 플래그 목록." +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +이 섹션에서는 Polygon 엣지의 현재 명령어와 명령 플래그, 그 사용 방식에 대해 설명합니다. + +:::tip JSON 출력 지원 + +일부 명령어에서 `--json` 플래그가 지원됩니다. 이 플래그는 명령어가 결과를 JSON 형식으로 출력하도록 지시합니다. + +::: + +## 시작 명령어 {#startup-commands} + +| **명령어** | **설명** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| server | 모든 모듈을 함께 부트스트랩하여 블록체인 클라이언트를 시작하는 기본 명령어입니다. | +| genesis | 클라이언트 시작 전에 사전 정의된 체인 상태를 설정하는 데 사용되는 *genesis.json* 파일을 생성합니다. 제네시스 파일 구조는 아래 설명으로 이루어집니다. | +| 제네시스 사전 배포 | 새로운 네트워크에 대한 스마트 계약을 미리 배포하기 | + +### 서버 플래그 {#server-flags} + + +| **모든 서버 플래그** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [프로메테우스](/docs/edge/get-started/cli-commands#prometheus) | [블록-gas-타겟](/docs/edge/get-started/cli-commands#block-gas-target) | +| [최대 쌍](/docs/edge/get-started/cli-commands#max-peers) | [최대-인바운드-쌍](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [최대-아웃바운드-쌍](/docs/edge/get-started/cli-commands#max-outbound-peers) | [최대-대기행렬](/docs/edge/get-started/cli-commands#max-enqueued) | +| [로그 레벨](/docs/edge/get-started/cli-commands#log-level) | [로그 투](/docs/edge/get-started/cli-commands#log-to) | +| [체인](/docs/edge/get-started/cli-commands#chain) | [가입](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [가격 한도](/docs/edge/get-started/cli-commands#price-limit) | [최대 슬롯](/docs/edge/get-started/cli-commands#max-slots) | +| [구성](/docs/edge/get-started/cli-commands#config) | [기밀-구성](/docs/edge/get-started/cli-commands#secrets-config) | +| [개발자](/docs/edge/get-started/cli-commands#dev) | [개발자 구간](/docs/edge/get-started/cli-commands#dev-interval) | +| [찾지 못함](/docs/edge/get-started/cli-commands#no-discover) | [복원](/docs/edge/get-started/cli-commands#restore) | +| [블록-시간](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +Polygon 엣지 클라이언트 데이터를 저장할 때 사용되는 데이터 디렉터리를 지정하는 데 사용됩니다. 기본값은 `./test-chain`입니다. + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +SON-RPC 서비스의 주소와 포트를 설정합니다(`address:port` ). +포트만 정의되면(`:10001`), 모든 인터페이스에 바인딩됩니다(`0.0.0.0:10001` ). +생략하는 경우, 서비스는 기본값에 바인딩됩니다(`address:port` ). +기본 주소는 `0.0.0.0:8545`입니다. + +--- + +####

json-rpc-block-range-limit + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +fromBlock 및 toBlock 값(예: eth_getLogs)을 포함하는 json-rpc 요청 실행 시 고려할 최대 블록 범위를 설정합니다. 기본값은 `1000`입니다. + +--- + +####

json-rpc-batch-request-limit + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +json-rpc 일괄 요청을 처리할 때 최대 길이를 설정합니다. 기본값은 `20`입니다. + +--- + +####

grpc + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +gRPC 서비스의 주소와 포트를 설정합니다(`address:port`). 기본 주소는 `127.0.0.1:9632`입니다. + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +libp2p 서비스의 주소와 포트를 설정합니다(`address:port`). 기본 주소는 `127.0.0.1:1478`입니다. + +--- + +####

prometheus + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +Prometheus 서버의 주소와 포트를 설정합니다(`address:port` ). +포트만 정의하면(`:5001`), 서비스는 모든 인터페이스에 바인딩됩니다(`0.0.0.0:5001` ). +생략하는 경우, 서비스가 시작되지 않습니다. + +--- + +####

block-gas-target + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +체인의 목표 블록 가스 한도를 설정합니다. 기본값은 `0`입니다(즉, 적용되지 않음). + +블록 가스 목표에 대한 자세한 설명은 [TxPool의 섹션](/docs/edge/architecture/modules/txpool#block-gas-target)에서 확인할 수 있습니다. + +--- + +####

max-peers + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +클라이언트의 최대 피어 수를 설정합니다. 기본값은 `40`입니다. + +피어 한도는 `max-peers` 또는 `max-inbound/outbound-peers` 플래그를 사용하여 지정해야 합니다. + +--- + +####

max-inbound-peers + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +클라이언트의 최대 인바운드 피어 수를 설정합니다. `max-peers`가 설정되면, 다음 공식에 따라 최대 인바운드 피어 한도가 계산됩니다. + +`max-inbound-peer = InboundRatio * max-peers`, `InboundRatio`는 `0.8` + +--- + +####

max-outbound-peers + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +클라이언트의 최대 아웃바운드 피어 수를 설정합니다. `max-peers`가 설정되면, 다음 공식에 따라 최대 아웃바운드 피어 수가 계산됩니다. + +`max-outbound-peer = OutboundRatio * max-peers`, `OutboundRatio`는 `0.2` + +--- + +####

max-enqueued + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +계정별로 대기열에 추가된 트랜잭션 최대 수를 설정합니다. 기본값은 `128`입니다. + +--- + +####

log-level + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +콘솔 출력의 로그 수준을 설정합니다. 기본값은 `INFO`입니다. + +--- + +####

log-to + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +서버 명령어의 모든 로그 출력을 포함하는 로그 파일 이름을 정의합니다. +기본적으로 모든 서버 로그는 콘솔(stdout)로 출력됩니다. +그러나 플래그가 설정된 경우, 서버 명령어를 실행하면 콘솔에 출력되지 않습니다. + +--- + +####

chain + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +체인을 시작하는 데 사용할 제네시스 파일을 지정합니다. 기본값은 `./genesis.json`입니다. + +--- + +####

join + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +조인해야 할 피어의 주소를 지정합니다. + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +포트 없이 외부 IP 주소를 설정합니다. 포트가 피어에 표시될 수 있기 때문입니다. + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +호스트 DNS 주소를 설정합니다. 외부 DNS를 광고하는 데 사용될 수 있습니다. `dns``dns4``dns6`지원 + +--- + +####

가격 한도 + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +풀 참여 승인에 적용할 최소 가스 가격 한도를 설정합니다. `1`디폴트: + +--- + +####

최대 슬롯 + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +풀의 최대 슬롯 수를 설정합니다. 기본값은 `4096`입니다. + +--- + +####

config + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +CLI 구성 경로를 지정합니다. `.json`을 지원합니다. + +--- + +####

secrets-config + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +보안 비밀 관리자 구성 파일 경로를 설정합니다. Hashicorp Vault, AWS SSM, GCP Secrets Manager에 사용됩니다. 생략하는 경우, 로컬 FS 보안 비밀 관리자가 사용됩니다. + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +클라이언트를 개발 모드로 설정합니다. `false`기본값: dev 모드에서 동료 발견은 기본적으로 비활성화됩니다. + +--- + +####

dev-interval + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +몇 초 안에 클라이언트의 개발 알림 간격을 설정합니다. 기본값은 `0`입니다. + +--- + +####

no-discover + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +클라이언트가 다른 피어를 탐색하지 못하도록 합니다. 기본값은 `false`입니다. + +--- + +####

restore + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +특정 보관 파일에서 블록을 복원합니다. + +--- + +####

block-time + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +몇 초 안에 블록 생성 시간을 설정합니다. 기본값은 `2`입니다. + +--- + +####

access-control-allow-origins + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +JSON-RPC 요청의 응답을 공유할 수 있도록 승인된 도메인을 설정합니다. +여러 개의 플래그 `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"`을 추가하여 여러 도메인을 승인할 수 있습니다. +생략하는 경우, Access-Control-Allow-Origins 헤더는 `*`로 설정되고 모든 도메인이 승인됩니다. + +--- + +### 제네시스 플래그 {#genesis-flags} +| **모든 genisic 플래그** | +|---------------------------------------|---------------------------------------------| +| [디렉토리](/docs/edge/get-started/cli-commands#dir) | [이름](/docs/edge/get-started/cli-commands#name) | +| [지분증명](/docs/edge/get-started/cli-commands#pos) | [에포크 ](/docs/edge/get-started/cli-commands#epoch-size)크기 | +| [premine](/docs/edge/get-started/cli-commands#premine) | [체인화된](/docs/edge/get-started/cli-commands#chainid) | +| [증명서 유효 검사기 유형](/docs/edge/get-started/cli-commands#ibft-validator-type) | [증명서 유효 검증 실행 경로](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [증명서 검증](/docs/edge/get-started/cli-commands#ibft-validator) | [블록 가스 제한](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [consensus](/docs/edge/get-started/cli-commands#consensus) | [부트 ](/docs/edge/get-started/cli-commands#bootnode)노드 | +| [최대 유효 검증 개수](/docs/edge/get-started/cli-commands#max-validator-count) | [최소 검증 개](/docs/edge/get-started/cli-commands#min-validator-count)수 | + + +####

dir + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +Polygon 엣지 제네시스 데이터를 위한 디렉터리를 설정합니다. 기본값은 `./genesis.json`입니다. + +--- + +####

이름 + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +체인 이름을 설정합니다. 기본값은 `polygon-edge`입니다. + +--- + +####

pos + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +클라이언트가 지분증명 IBFT를 사용해야 한다는 플래그를 설정합니다. +플래그가 제공되지 않거나 `false`인 경우, 권위증명이 기본값으로 설정됩니다. + +--- + +####

epoch-size + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +체인의 에포크 크기를 설정합니다. 기본값은 `100000`입니다. + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +사전 채굴 계정과 잔액을 `address:amount` 형식으로 설정합니다. +값은 소수이거나 6진수입니다. 기본 사전 불확실한 균형에 : `0xD3C21BCECCEDA1000000`(100만 개의 네이티브 통화 토큰). + +--- + +####

chainid + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +체인 ID를 설정합니다. 기본값은 `100`입니다. + +--- + +####

ibft-validator-type + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +블록 헤더의 검증 모드를 지정합니다. 가능한 값은 `[ecdsa, bls]`입니다. 기본값은 `bls`입니다. + +--- + +####

ibft-validators-prefix-path + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +검사기 폴더 디렉터리의 프리픽스 경로입니다. `ibft-validator` 플래그를 생략하는 경우 이 플래그가 있어야 합니다. + +--- + +####

ibft-validator + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +전달된 주소를 IBFT 검사기로 설정합니다. `ibft-validators-prefix-path` 플래그를 생략하는 경우 이 플래그가 있어야 합니다. +1. 네트워크가 ECDSA와 함께 실행되는 경우 `--ibft-validator [ADDRESS]` 형식입니다. +2. 네트워크가 BLS와 함께 실행중인 경우 `--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]` 형식입니다. + +--- + +####

block-gas-limit + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +블록의 모든 작업에 사용할 최대 가스 금액을 가리킵니다. 기본값은 `5242880`입니다. + +--- + +####

consensus + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +합의 프로토콜을 설정합니다. 기본값은 `pow`입니다. + +--- + +####

bootnode + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +P2P 탐색 부트스트랩을 위한 Multiaddr URL입니다. 이 플래그는 여러 번 사용할 수 있습니다. +IP 주소 대신, 부트노드의 DNS 주소를 제공할 수 있습니다. + +--- + +####

max-validator-count + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +PoS 합의에서 검사기 세트에 포함할 수 있는 최대 스테이커 수입니다. +MAX_SAFE_INTEGER(2^53 - 2) 값을 초과할 수 없습니다. + +--- + +####

min-validator-count + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +PoS 합의에 설정된 검사기 세트에 포함해야 할 최소 스테이커 수입니다. +최대 검사기 수의 값을 초과할 수 없습니다. +디폴트 1. + +--- + +### 제네시스 사전 배포 플래그 {#genesis-predeploy-flags} + +

아티팩트 패스

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +`abi``bytecode`계약을 포함하는 계약 아티팩트 JSON에 경로를 설정합니다.`deployedBytecode` + +--- + +

chain

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +업데이트 될 `genesis.json`파일에 경로를 설정합니다. `./genesis.json`디폴트 + +--- + +

Procercuster-Arg

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +누구든지 경우 스마트 계약 구축자 인수를 설정합니다. 이러한 인수가 어떻게 생겼는지에 대한 자세한 가이드를 보려면 [사전 배포 기사를](/docs/edge/additional-features/predeployment) 참조하십시오. + +--- + +

사전 배포 주소

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +주소를 미리 배포하도록 설정합니다. `0x0000000000000000000000000000000000001100`디폴트 + +--- + + +## 연산자 명령어 {#operator-commands} + +### 피어 명령어 {#peer-commands} + +| **명령어** | **설명** | +|------------------------|-------------------------------------------------------------------------------------| +| peers add | libp2p 주소를 사용하여 새 피어를 추가합니다. | +| peers list | libp2p를 통해 클라이언트가 연결된 모든 피어를 나열합니다. | +| peers status | libp2p 주소를 사용하여 피어 목록에 있는 특정 피어의 상태를 반환합니다. | + +

피어 추가 플래그

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +multiaddr 형식의 피어 libp2p 주소입니다. + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +gRPC API 주소입니다. 기본값은 `127.0.0.1:9632`입니다. + +

피어 나열 플래그

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +gRPC API 주소입니다. 기본값은 `127.0.0.1:9632`입니다. + +

피어 상태 플래그

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +p2p 네트워크 내 특정 피어의 libp2p 노드 ID입니다. + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +gRPC API 주소입니다. 기본값은 `127.0.0.1:9632`입니다. + +### IBFT 명령어 {#ibft-commands} + +| **명령어** | **설명** | +|------------------------|-------------------------------------------------------------------------------------| +| ibft snapshot | IBFT 스냅샷을 반환합니다. | +| ibft candidates | 현재 제안된 후보 집합과 아직 포함되지 않은 후보를 쿼리합니다. | +| ibft propose | 검사기 세트에서 추가/삭제해야 할 새 후보를 제안합니다. | +| ibft status | IBFT 클라이언트 전체 상태를 반환합니다. | +| ibft switch | IBFT 유형을 전환하기 위해 포크 구성을 genesis.json 파일에 추가합니다. | +| ibft quorum | 블록 번호를 지정한 후, 합의에 도달하기 위한 최적의 쿼럼 크기 메서드가 사용됩니다. | + + +

IBFT 스냅샷 플래그

+ +

number

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +스냅샷의 블록 높이(번호)입니다. + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +gRPC API 주소입니다. 기본값은 `127.0.0.1:9632`입니다. + +

IBFT 후보 플래그

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +gRPC API 주소입니다. 기본값은 `127.0.0.1:9632`입니다. + +

IBFT 제안 플래그

+ +

vote

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +검사기 세트에 변경 사항을 제안합니다. 가능한 값은 `[auth, drop]`입니다. + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +투표할 계정의 주소입니다. + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +투표할 계정의 BLS 공개 키로, BLS 모드에서만 필요합니다. + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +gRPC API 주소입니다. 기본값은 `127.0.0.1:9632`입니다. + +

IBFT 상태 플래그

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +gRPC API 주소입니다. 기본값은 `127.0.0.1:9632`입니다. + +

IBFT 전환 플래그

+ +

chain

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +업데이트할 제네시스 파일을 지정합니다. 기본값은 `./genesis.json`입니다. + +--- + +

유형

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +전환할 IBFT 유형을 지정합니다. 가능한 값은 `[PoA, PoS]`입니다. + +--- + +

deployment

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +배포 계약의 높이를 지정합니다. PoS에만 사용 가능합니다. + +--- + +

from

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +블록 헤더의 검증 모드를 지정합니다. 가능한 값은 `[ecdsa, bls]`입니다. 기본값은 `bls`입니다. + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +새 검사기 디렉터리의 프리픽스 경로입니다. `ibft-validator` 플래그를 생략하는 경우 이 플래그가 있어야 합니다. IBFT 모드가 PoA인 경우에만 사용 가능합니다(`--pos` 플래그 생략됨). + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +전달된 주소를 포크 후 사용할 IBFT 검사기로 설정합니다. `ibft-validators-prefix-path` 플래그를 생략하는 경우 이 플래그가 있어야 합니다. PoA 모드에서만 사용 가능합니다. +1. 네트워크가 ECDSA와 함께 실행되는 경우 `--ibft-validator [ADDRESS]` 형식입니다. +2. 네트워크가 BLS와 함께 실행중인 경우 `--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]` 형식입니다. + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +PoS 합의에서 검사기 세트에 포함할 수 있는 최대 스테이커 수입니다. +MAX_SAFE_INTEGER(2^53 - 2) 값을 초과할 수 없습니다. + +--- + +

min-validator-count

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +PoS 합의에 설정된 검사기 세트에 포함해야 할 최소 스테이커 수입니다. +최대 검사기 수의 값을 초과할 수 없습니다. +기본값은 1입니다. + +포크의 시작 높이를 지정합니다. + +--- + +

IBFT 쿼럼 플래그

+ +

from

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +쿼럼 계산을 최적 쿼럼으로 전환하기 위한 높이입니다. `(2/3 * N)` 공식을 사용하며, 여기서 `N`은 검사기 노드 수입니다. 하위 호환성을 위한 플래그로, 특정 블록 높이까지 쿼럼 기존 계산을 사용한 체인에만 사용합니다. + +--- + +

chain

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +업데이트할 제네시스 파일을 지정합니다. 기본값은 `./genesis.json`입니다. + +### 트랜잭션 풀 명령어 {#transaction-pool-commands} + +| **명령어** | **설명** | +|------------------------|--------------------------------------------------------------------------------------| +| txpool status | 풀의 트랜잭션 수를 반환합니다. | +| txpool subscribe | 트랜잭션 풀의 이벤트를 구독합니다. | + +

트랜잭션 풀 상태 플래그

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +gRPC API 주소입니다. 기본값은 `127.0.0.1:9632`입니다. + +

트랜잭션 풀 구독 플래그

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +gRPC API 주소입니다. 기본값은 `127.0.0.1:9632`입니다. + +--- + +

promoted

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +트랜잭션 풀에서 승격된 트랜잭션 이벤트를 구독합니다. + +--- + +

dropped

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +트랜잭션 풀에서 삭제된 트랜잭션 이벤트를 구독합니다. + +--- + +

demoted

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +트랜잭션 풀에서 강등된 트랜잭션 이벤트를 구독합니다. + +--- + +

added

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +트랜잭션 풀 이벤트에 추가된 트랜잭션 이벤트를 구독합니다. + +--- + +

enqueued

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +계정 대기열에 추가된 트랜잭션 이벤트를 구독합니다. + +--- + +### 블록체인 명령어 {#blockchain-commands} + +| **명령어** | **설명** | +|------------------------|-------------------------------------------------------------------------------------| +| status | 클라이언트 상태를 반환합니다. 자세한 응답은 아래에서 확인할 수 있습니다. | +| monitor | 블록체인 이벤트 스트림을 구독합니다. 자세한 응답은 아래에서 확인할 수 있습니다. | +| version | 클라이언트의 현재 버전을 반환합니다. | + +

상태 플래그

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +gRPC API 주소입니다. 기본값은 `127.0.0.1:9632`입니다. + +

모니터링 플래그

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +gRPC API 주소입니다. 기본값은 `127.0.0.1:9632`입니다. + +--- +

버전 명령

+ + + + + + version + + + + +릴리스 버전, git 지점의 표시, 해시 커밋 및 빌드 시간을 표시합니다. + +## 보안 비밀 명령어 {#secrets-commands} + +| **명령어** | **설명** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| secrets init | 해당 보안 비밀 관리자의 비공개 키를 초기화합니다. | +| secrets generate | 폴리곤 엣지로부터 지정될 수 있는 기밀 관리자 파일을 생성합니다. | +| 비밀 출력 | BLS 공개 키 주소, 유효자 공개 키 주소 및 참조 노드 ID를 인쇄하십시오. | + +### 기밀 이니트 플래그 {#secrets-init-flags} + +

config

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +보안 비밀 관리자 구성 파일 경로를 설정합니다. Hashicorp Vault에 사용됩니다. 생략하는 경우, 로컬 FS 보안 비밀 관리자가 사용됩니다. + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +로컬 FS가 사용되는 경우 Polygon 엣지 데이터 디렉터리를 설정합니다. + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +ECDSA 키 생성 여부를 나타내는 플래그를 설정합니다. 기본값은 `true`입니다. + +--- + +

network

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +Libp2p 네트워크 키 생성 여부를 나타내는 플래그를 설정합니다. 기본값은 `true`입니다. + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +BLS 키 생성 여부를 나타내는 플래그를 설정합니다. 기본값은 `true`입니다. + +### 보안 비밀 생성 플래그 {#secrets-generate-flags} + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +보안 비밀 관리자 구성 파일의 디렉터리를 설정합니다. 기본값은 `./secretsManagerConfig.json`입니다. + +--- + +

유형

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +보안 비밀 관리자의 유형([`hashicorp-vault`])을 지정합니다. 기본값은 `hashicorp-vault`입니다. + +--- + +

token

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +서비스 액세스 토큰을 지정합니다. + +--- + +

server-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +서비스 서버 URL을 지정합니다. + +--- + +

name

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +서비스 기록 보관을 위한 노드 이름을 지정합니다. 기본값은 `polygon-edge-node`입니다. + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Hashicorp Vault 보안 비밀 관리자에 사용할 네임스페이스을 지정합니다. 디폴트:`admin` + +### 비밀 출력 플래그 {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +BLS 공개 키만 출력할지 여부를 나타내는 플래그를 설정합니다. 디폴트:`true` + +--- + +

config

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +보안 비밀 관리자 구성 파일 경로를 설정합니다. 생략되는 경우 로컬 FS 기밀 관리자가 사용됩니다. + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +로컬 FS가 사용되는 경우 Polygon 엣지 데이터 디렉터리를 설정합니다. + +--- + +

node -id

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +네트워크 노드 ID를 출력할지 여부를 나타내는 플래그를 설정합니다. 디폴트:`true` + +--- + +

유효성 검사기

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +유효자 주소를 출력할지 여부를 나타내는 플래그를 설정합니다. 디폴트:`true` + +--- + +## 응답 {#responses} + +### 상태 응답 {#status-response} + +응답 객체는 프로토콜 버퍼를 사용해 정의합니다. +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### 모니터링 응답 {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## 유틸리티 {#utilities} + +### 허용 목록 명렁어 {#whitelist-commands} + +| **명령어** | **설명** | +|------------------------|-------------------------------------------------------------------------------------| +| whitelist show | 허용 목록 정보를 표시합니다. | +| whitelist deployment | 스마트 계약 배포 허용 목록을 업데이트합니다. | + +

허용 목록 표시

+ + + + + whitelist show + + + + +허용 목록 정보를 표시합니다. + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +업데이트할 제네시스 파일을 지정합니다. 기본값은 `./genesis.json`입니다. + +--- + +

허용 목록 배포

+ +

chain

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +업데이트할 제네시스 파일을 지정합니다. 기본값은 `./genesis.json`입니다. + +--- + +

add

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +계약 배포된 허용 목록에 새로운 주소를 추가합니다. 계약 배포 허용 목록의 주소만 계약을 배포할 수 있습니다. 비어 있는 경우, 모든 주소가 계약 배포를 실행할 수 있습니다. + +--- + +

remove

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +계약 배포 허용 목록에서 주소를 삭제합니다. 계약 배포 허용 목록의 주소만 계약을 배포할 수 있습니다. 비어 있는 경우, 모든 주소가 계약 배포를 실행할 수 있습니다. + +--- + +### 백업 플래그 {#backup-flags} + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +gRPC API 주소입니다. 기본값은 `127.0.0.1:9632`입니다. + +--- + +

out

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +저장할 보관 파일의 경로입니다. + +--- + +

from

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +보관 처리된 블록의 시작 높이입니다. 기본값은 0입니다. + +--- + +

to

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +보관 처리된 블록의 끝 높이입니다. + +--- + +## 제네시스 템플릿 {#genesis-template} +블록체인의 초기 상태를 설정하기 위해 제네시스 파일을 사용해야 합니다(예: 일부 계정에 초기 잔액이 있어야 하는 경우). + +다음 *./genesis.json* 파일이 생성됩니다. +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### 데이터 디렉터리 {#data-directory} + +*data-dir* 플래그를 실행하면 **test-chain** 폴더가 생성됩니다. +폴더 구조는 다음 하위 폴더로 구성됩니다. +* **blockchain** - 블록체인 객체의 LevelDB를 저장합니다. +* **trie리** - Merkle 트리의 LevelDB를 저장합니다. +* **keystore** - 클라이언트의 비공개 키를 저장합니다. 여기에는 libp2p 비공개 키 및 봉인/검사기 비공개 키가 포함됩니다. +* **consensus** - 클라이언트 작업 중 필요할 수 있는 모든 합의 정보를 저장합니다. + +## 리소스 {#resources} +* **[프로토콜 버퍼](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/ko-edge/get-started/installation.md b/archive/edge/ko-edge/get-started/installation.md new file mode 100644 index 0000000000..ada375eb79 --- /dev/null +++ b/archive/edge/ko-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: 설치 +description: "Polygon 엣지 설치 방법." +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +적절한 설치 방법을 참조하세요. + +사전 빌드된 릴리스를 사용하고 제공된 체크섬을 확인하는 것을 권장합니다. + +## 사전 빌드된 릴리스 {#pre-built-releases} + +릴리스 목록은 [GitHub 릴리스](https://github.com/0xPolygon/polygon-edge/releases) 페이지를 참조하세요. + +Polygon 엣지는 Darwin 및 Linux용으로 교차 컴파일된 AMD64/ARM64 바이너리와 함께 제공됩니다. + +--- + +## Docker 이미지 {#docker-image} + +공식 Docker 이미지는 [hub.docker.com 레지스트리](https://hub.docker.com/r/0xpolygon/polygon-edge)에서 호스팅됩니다. + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## 소스에서 빌드하기 {#building-from-source} + +`go install`을 사용하기 전에 Go `>=1.18`을 설치하고 적절히 구성했는지 확인하세요. + +안정적인 지점은 최신 릴리스의 지점입니다. + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## `go install` 사용하기 + +`go install`을 사용하기 전에 Go `>=1.17`을 설치하고 적절히 구성했는지 확인하세요. + +`go install github.com/0xPolygon/polygon-edge@release/` + +바이너리 변수는 `GOBIN`환경 변수에 사용할 수 있으며, 최신 릴리스의 변경을 포함합니다. [GitHub를](https://github.com/0xPolygon/polygon-edge/releases) 체크 아웃하여 최신 중 어느 것이 있는지 알 수 있습니다. diff --git a/archive/edge/ko-edge/get-started/set-up-ibft-locally.md b/archive/edge/ko-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..fa4075fca9 --- /dev/null +++ b/archive/edge/ko-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,404 @@ +--- +id: set-up-ibft-locally +title: 로컬 설정 +description: "단계별 로컬 설정 가이드." +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution 테스트용 가이드입니다 + +아래 가이드는 테스트 및 개발 목적으로 로컬 머신에 Polygon 엣지 네트워크를 설정하는 방법에 대해 안내합니다. + +이 절차는 실제 사용 시나리오에 Polygon 엣지 네트워크를 설정하는 클라우드 공급자: **[클라우드 설치](/docs/edge/get-started/set-up-ibft-on-the-cloud)** + +::: + + +## 요구사항 {#requirements} + +Polygon 엣지를 설치하려면 [설치](/docs/edge/get-started/installation)를 참조하세요. + +## 개요 {#overview} + +![로컬 설정](/img/edge/ibft-setup/local.svg) + +본 가이드에서 우리의 목표는 [IBFT 합의 프로토콜](https://github.com/ethereum/EIPs/issues/650)과 함께 작동하는 `polygon-edge` 블록체인 네트워크를 설정하는 것입니다. +블록체인 네트워크는 4개의 노드로 구성되고 모든 노드가 검사기 노드이므로, 블록 제안과 다른 제안자의 블록 검증에 모두 적합합니다. +본 가이드의 목적은 최소한의 시간 내에 완전하게 작동하는 IBFT 클러스터를 제공하는 것이므로 4개 노드가 모두 같은 머신에서 실행됩니다. + +이를 위해 간단한 4가지 단계를 안내합니다. + +1. 데이터 디렉터리를 초기화하면 4개 노드에 각각 검사기 키가 모두 생성되고 빈 블록체인 데이터 디렉터리가 초기화됩니다. 검사기 키는 초기 검사기 세트로 제네시스 블록을 부트스트랩할 때 사용해야 하므로 중요합니다. +2. 부트노드의 연결 문자열을 준비하는 것은 처음 시작할 때 연결할 모든 노드에 실행할 중요한 정보가 됩니다. +3. `genesis.json` 파일을 생성하려면 제네시스 블록 네트워크의 초기 검사기를 설정하는 데 사용되는 **1단계**에서 생성된 검사기 키와 **2단계**의 부트노드 연결 문자열이 모두 입력되어야 합니다. +4. 모든 노드를 실행하는 것이 본 가이드의 최종 목표이며 마지막 단계가 될 것이므로, 노드에 사용할 데이터 디렉터리와 초기 네트워크 상태를 부트스트랩하는 `genesis.json`의 위치를 알려드립니다. + +4개 노드가 모두 로컬 호스트에서 실행되므로 설정 프로세스 중 각 노드의 모든 데이터 디렉터리가 같은 상위 디렉터리에 있어야 합니다. + +:::info 검사기 수 + +클러스터의 노드 수에는 최솟값이 없어, 검사기 노드가 1개뿐인 클러스터가 있을 수 있습니다. +_단일_ 노드 클러스터에는 **비정상 종료 내결함성**과 **BFT 보장**이 없다는 없다는 점에 유의하세요. + +BFT 보장을 받기 위한 최소 권장 노드 수는 4개입니다. 노드가 4개인 클러스터에서는 나머지 3개 노드가 정상 작동하기에 노드 1개의 장애는 허용될 수 있기 때문입니다. + +::: + +## 1단계: IBF용 데이터 폴더 초기화 및 검사기 키 생성 {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +IBFT를 통해 시작하고 실행하려면 각 노드에 하나씩 데이터 폴더를 초기화해야 합니다. + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +각 명령어는 검사기 키, BLS 공개 키, [노드 ID](https://docs.libp2p.io/concepts/peer-id/)를 출력합니다. 다음 단계에 첫 번째 노드의 노드 ID가 필요합니다. + +### 비밀 퍼팅 {#outputting-secrets} +필요한 경우 비밀 출력이 다시 검색 될 수 있습니다. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## 2단계: 부트노드의 Multiaddr 연결 문자열 준비 {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +노드가 연결을 완료하려면, 네트워크의 나머지 모든 노드에 대한 정보를 얻기 위해 어떤 `bootnode` 서버를 연결해야 하는지 알아야 합니다. `bootnode`는 p2p 전문 용어로 `rendezvous` 서버라고도 합니다. + +`bootnode`는 polygon-엣지 노드의 특별한 인스턴스가 아닙니다. 모든 polygon-엣지 노드는 `bootnode` 역할을 할 수 있지만, 모든 Polygon 엣지 노드는 네트워크의 나머지 모든 노드와 연결하는 방법에 관한 정보 제공을 위해 연결할 부트노드 세트를 지정해야 합니다. + +부트노드를 지정할 연결 문자열을 생성하려면 다음 [Multiaddr 형식](https://docs.libp2p.io/concepts/addressing/)을 따라야 합니다. +``` +/ip4//tcp//p2p/ +``` + +본 가이드에서는 첫 번째 노드와 두 번째 노드를 다른 모든 노드의 부트노드로 취급합니다. 이 시나리오에서는 상호 연결된 부트노드를 통해 `node 1`이나 `node 2`에 연결된 노드가 서로 연결하는 방법에 대한 정보를 얻을 수 있습니다. + +:::info 노드를 시작하려면 부트노드를 하나 이상 지정해야 합니다 + +네트워크의 다른 노드가 서로를 탐색할 수 있도록 **하나** 이상의 부트노드가 필요합니다. 부트노드는 많을수록 좋습니다. 서비스 중단 시 네트워크 복원력을 제공하기 때문입니다. 본 가이드에는 두 개의 노드가 나와 있지만, `genesis.json` 파일의 유효성에 영향을 주지 않고 즉석에서 변경할 수 있습니다. + +::: + +Localhost에서 실행 중이므로 ``는 `127.0.0.1`로 가정하는 것이 안전합니다. + +``의 경우, 이후 이 포트에서 수신 대기하도록 `node 1`의 libp2p 서버를 구성할 것이므로 `10001`을 사용할 것입니다. + +마지막으로, 이전에 실행한 `polygon-edge secrets init --data-dir test-chain-1` 명령어(`node1`의 키와 데이터 디렉터리 생성에 사용)의 출력에서 가져올 수 있는 ``가 필요합니다. + +조합을 마친 후 부트노드로 사용할 `node 1`에 대한 Multiaddr 연결 문자열은 다음과 같습니다(마지막에 있는 ``만 달라야 함). +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +마찬가지로, 아래와 같이 두 번째 부트노드의 Multiaddr를 구성합니다. +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info IPS 대신 DNS 호스트 이름 + +Polygon 엣지에서는 노드 구성에 DNS 호스트 이름을 사용할 수 있습니다. 다양한 이유로 노드의 IP가 변경될 수 있어, 이는 클라우드 기반 배포에 매우 유용한 기능입니다. + +DNS 호스트 이름을 사용하는 중 연결 문자열의 Multiaddr 형식은 다음과 같습니다. +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## 3단계: 4개 노드가 검사기인 제네시스 파일 생성 {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +다음 명령어가 수행하는 작업: + +* `--ibft-validators-prefix-path`는 프리픽스 폴더 경로를 Polygon 엣지의 IBFT가 사용할 수 있는 지정된 경로로 설정합니다. 이 디렉터리는 검사기의 비공개 키가 보관되는 `consensus/` 폴더를 저장하는 데 사용됩니다. 부트스트랩 노드의 초기 목록인 제네시스 파일을 빌드하려면 검사기의 공개 키가 필요합니다. +이 플래그는 실제 시나리오에서 모든 노드의 데이터 디렉터리가 공개 키를 쉽게 읽을 수 있는 동일 파일 시스템에 있을 것으로 기대할 수 없으므로 localhost에서 네트워크를 설정할 때만 의미가 있습니다. +* `--bootnode` 세트는 노드가 서로를 찾을 수 있도록 부트노드의 주소를 설정합니다. +**2단계**에서 언급한 대로 `node 1`의 Multiaddr 문자열을 사용합니다. + +이 명령어의 결과는 새 블록체인의 제네시스 블록이 포함된 `genesis.json` 파일로, 미리 정의된 유효성 검사자 세트 및 연결 설정을 위해 먼저 연결할 노드의 구성이 포함되어 있습니다. + +:::info ECSA로 전환 + +BLS는 블록 헤더의 기본 유효성 검사 모드입니다. ECDSA 모드에서 체인이 실행되기를 원한다면 인수와 함께 `—ibft-validator-type`플래그를 사용할 수 `ecdsa`있습니다. + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info 계정 잔액 사전 채굴 + +'사전 채굴된' 잔액이 있는 일부 주소로 블록체인 네트워크를 구성해야 할 수 있습니다. + +이를 위해 블록체인의 특정 잔액으로 초기화하려는 주소당 원하는 만큼 `--premine` 플래그를 전달하세요. + +예를 들어, 제네시스 블록에서 주소 `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862`를 지정해 1000ETH를 사전 채굴하려면 다음 인수를 제공해야 합니다. + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**사전 채굴된 금액은 ETH가 아닌 WEI로 표시됩니다.** + +::: + +:::info 블록 가스 한도 설정 + +각 블록의 기본 가스 한도는 `5242880`입니다. 이 값은 제네시스 파일에 기록되지만, 증감해야 할 수 있습니다. + +아래와 같이 플래그 `--block-gas-limit` 다음에 원하는 값을 입력하여 증감하면 됩니다. + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info 시스템 파일 설명자 한도 설정 + +일부 운영체제에서는 기본 파일 설명자 한도(열린 파일의 최대 수)가 매우 적습니다. +노드의 처리량이 많을 것으로 예상되면 OS 수준에서 이 한도를 늘리는 것을 고려할 수 있습니다. + +Ubuntu 배포판의 경우 절차는 다음과 같습니다(Ubuntu/Debian 배포판을 사용하지 않는다면 OS의 공식 문서를 확인하세요). +- 현재 운영체제 한도(열린 파일) 확인 +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- 열린 파일 한도 늘리기 + - 로컬 - 현재 세션에만 영향을 미칩니다. + ```shell + ulimit -u 65535 + ``` + - 전역 또는 사용자별(/etc/security/limits.conf 파일 끝에 한도 추가) + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +필요한 경우 추가 매개변수를 수정하고 파일을 저장한 후 시스템을 다시 시작하세요. +다시 시작한 후 파일 설명자 한도를 다시 확인하세요. +limits.conf 파일에서 정의한 값으로 설정해야 합니다. +::: + + +## 4단계: 모든 클라이언트 실행 {#step-4-run-all-the-clients} + +4개 노드로 구성된 Polygon 엣지 네트워크를 모두 같은 머신에서 실행하려고 하므로 포트 충돌이 발생하지 않게 주의해야 합니다. 따라서 노드의 각 서버의 수신 대기 포트를 결정할 때 다음 추론을 사용합니다. + +- `node 1`의 gRPC 서버는 `10000`, `node 2`의 GRPC 서버는 `20000` 등. +- `node 1`의 libp2p 서버는 `10001`, `node 2`의 libp2p 서버는 `20001` 등. +- `node 1`의 JSON-RPC 서버는 `10002`, `node 2`의 JSON-RPC 서버는 `20002` 등. + +**첫 번째** 클라이언트를 실행하려면(노드 1의 노드 ID와 함께 **2단계**에서 libp2p multiaddr의 일부로 사용된 포트 `10001`을 기록해 두세요) + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +**두 번째** 클라이언트를 실행하려면, + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +**세 번째** 클라이언트를 실행하려면, + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +**네 번째** 클라이언트를 실행하려면, + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +지금까지의 과정을 요약하겠습니다. + +* 클라이언트 데이터의 디렉터리가 **./test-chain-\***으로 지정되었습니다 +* GRPC 서버가 각 노드의 포트 **10000**, **20000**, **30000**, **40000**에서 시작되었습니다 +* libp2p 서버가 각 노드의 포트 **10001**, **20001**, **30001**, **40001**에서 시작되었습니다 +* JSON-RPC 서버가 각 노드의 포트 **10002**, **20002**, **30002**, **40002**에서 시작되었습니다 +* *봉인* 플래그는 시작되고 있는 노드가 블록 봉인에 참여한다는 것을 의미합니다 +* *체인* 플래그는 체인 구성에 사용할 제네시스 파일을 지정합니다 + +제네시스 파일의 구조는 [CLI 명령어](/docs/edge/get-started/cli-commands) 섹션에서 다룹니다. + +이전 명령어를 실행한 후, 블록을 봉인하고 노드 장애에서 복구할 수 있는 4-노드 Polygon 엣지 네트워크를 설정했습니다. + +:::info 구성 파일을 통해 클라이언트 시작 + +모든 구성 매개변수를 CLI 인수로 지정하는 대신, 다음 명령어를 실행하여 구성 파일을 통해 클라이언트를 시작할 수도 있습니다. + +````bash +polygon-edge server --config +```` +예시: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +현재 우리는 지원 `yaml`및 `json`기반 구성 파일을 지원하고 있습니다. 샘플 구성 파일이 **[여기에서](/docs/edge/configuration/sample-config)** 확인할 수 있습니다. + +::: + +:::info 비 유효성 검사자 노드 실행 단계 + +비 검사기는 항상 검사기 노드에서 수신한 최신 블록을 동기화합니다. 다음 명령어를 실행해 비 검사기 노드를 시작할 수 있습니다. + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +예를 들어, 다음 명령어를 실행하여 **다섯 번째** 비 검사기 클라이언트를 추가할 수 있습니다. + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info 가격 제한 지정 + +수신 트랜잭션에 **가격 제한**을 설정해 Polygon 엣지 노드를 시작할 수 있습니다. + +가격 제한 단위는 `wei`입니다. + +가격 제한을 설정하면 현재 노드에서 처리되는 모든 트랜잭션의 가스 가격이 설정된 가격 제한보다 **높아야** 하며, 그렇지 않으면 블록에 포함되지 않습니다. + +대다수의 노드가 특정 가격 제한을 준수하도록 하면 네트워크의 트랜잭션이 특정 가격 임계값보다 낮을 수 없다는 규칙이 적용됩니다. + +가격 제한의 기본값은 `0`이며, 기본적으로는 적용되지 않는다는 의미입니다. + +`--price-limit` 플래그 사용 예시: +````bash +polygon-edge server --price-limit 100000 ... +```` + +가격 제한은 **로컬이 아닌 트랜잭션에만 적용되므로**, 노드에 로컬로 추가된 트랜잭션에는 적용되지 않습니다. + +::: + +:::info 웹소켓 URL + +기본적으로 Polygon 엣지를 실행할 때는 체인 위치를 기반으로 웹소켓 URL이 생성됩니다. +HTTPS 링크에 사용되는 URL 체계는 `wss://`, HTTP 링크의 경우 `ws://`입니다. + +Localhost 웹소켓 URL은 다음과 같습니다. +````bash +ws://localhost:10002/ws +```` +포트 번호는 노드를 위해 선택한 JSON-RPC 포트에 따라 결정됩니다. + +Edgenet 웹소켓 URL은 다음과 같습니다. +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## 5단계: Polygon 엣지 네트워크와 상호작용 {#step-5-interact-with-the-polygon-edge-network} + +이제 실행 중인 클라이언트를 1개 이상 설정했으니, 위에서 사전 채굴한 계정을 사용해 4개 노드 중 하나에 JSON-RPC URL을 지정해 블록체인과 상호작용할 수 있습니다. +- 노드 1: `http://localhost:10002` +- 노드 2: `http://localhost:20002` +- 노드 3: `http://localhost:30002` +- 노드 4: `http://localhost:40002` + +[연산자 정보를 쿼리하는 방법](/docs/edge/working-with-node/query-operator-info) 가이드를 따라, 새로 빌드된 클러스터에 연산자 명령어를 실행하세요. (빌드한 클러스터의 노드별 GRPC 포트는 각각 `10000`/`20000`/`30000`/`40000`입니다.) diff --git a/archive/edge/ko-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/ko-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..a7f34c6eeb --- /dev/null +++ b/archive/edge/ko-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,429 @@ +--- +id: set-up-ibft-on-the-cloud +title: 클라우드 설정 +description: "단계별 클라우드 설정 가이드." +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info 메인넷 또는 테스트넷 설정을 위한 가이드입니다 + +아래 가이드에서는 테스트넷 또는 메인넷의 프로덕션 설정을 위해 클라우드 제공업체에서 Polygon 엣지 네트워크를 설정하는 방법을 설명합니다. + +프로덕션용 설정에 앞서 `polygon-edge`를 신속하게 테스트하기 위해 Polygon 엣지 네트워크를 로컬로 설정하려면 다음을 참조하시기 바랍니다. **[로컬 설치](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## 요구사항 {#requirements} + +Polygon 엣지를 설치하려면 [설치](/docs/edge/get-started/installation)를 참조하세요. + +### VM 연결 설정 {#setting-up-the-vm-connectivity} + +선택한 클라우드 제공업체에 따라 방화벽, 보안 그룹, 액세스 제어 목록을 사용하여 VM 간의 연결 및 규칙을 설정할 수 있습니다. + +`polygon-edge`에서 다른 VM에 노출되어야 하는 유일한 부분은 libp2p 서버이므로, 기본 libp2p 포트 `1478`에서 VM 간의 모든 통신을 허용하는 것으로 충분합니다. + +## 개요 {#overview} + +![클라우드 설정](/img/edge/ibft-setup/cloud.svg) + +본 가이드에서 우리의 목표는 [IBFT 합의 프로토콜](https://github.com/ethereum/EIPs/issues/650)과 함께 작동하는 `polygon-edge` 블록체인 네트워크를 설정하는 것입니다. +블록체인 네트워크는 4개의 노드로 구성되고 모든 노드가 검사기 노드이므로, 블록 제안과 다른 제안자의 블록 검증에 모두 적합합니다. +이 가이드의 목적은 신뢰 보증이 필요 없는 네트워크 설정을 위해 검사기 키를 비공개로 유지하면서 완전히 작동하는 Polygon 엣지 네트워크를 제공하는 것이므로, 4개의 노드 각각은 자체 VM에서 실행됩니다. + +이를 위해 간단한 4가지 단계를 안내합니다. + +0. 위의 **요구사항** 목록을 확인합니다. +1. 각 검사기의 비공개 키를 생성하고 데이터 디렉터리를 초기화합니다. +2. 공유 `genesis.json` 노드에 들어갈 부트노드의 연결 문자열을 준비합니다. +3. 로컬 머신에 `genesis.json`을 생성하고 각 노드로 전송합니다. +4. 모든 노드를 시작합니다. + +:::info 검사기 수 + +클러스터의 노드 수에는 최솟값이 없어, 검사기 노드가 1개뿐인 클러스터가 있을 수 있습니다. +_단일_ 노드 클러스터에는 **비정상 종료 내결함성**과 **BFT 보장**이 없다는 없다는 점에 유의하세요. + +BFT 보장을 받기 위한 최소 권장 노드 수는 4개입니다. 노드가 4개인 클러스터에서는 나머지 3개 노드가 정상 작동하기에 노드 1개의 장애는 허용될 수 있기 때문입니다. + +::: + +## 1단계: 데이터 폴더 초기화 및 검사기 키 생성 {#step-1-initialize-data-folders-and-generate-validator-keys} + +Polygon 엣지를 시작하고 실행하려면 각 노드에서 데이터 폴더를 초기화해야 합니다. + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +각 명령어는 검사기 키, BLS 공개 키, [노드 ID](https://docs.libp2p.io/concepts/peer-id/)를 출력합니다. 다음 단계에 첫 번째 노드의 노드 ID가 필요합니다. + +### 비밀 퍼팅 {#outputting-secrets} +필요한 경우 비밀 출력이 다시 검색 될 수 있습니다. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning 데이터 디렉터리를 비밀로 유지하십시오! + +위에서 생성된 데이터 디렉터리는 블록체인 상태를 유지하기 위해 디렉터리를 초기화하는 것 외에 검사기의 비공개 키도 생성합니다. +**이 키는 보안 비밀로 유지되어야 합니다. 만약 도용된다면 네트워크에서 검사기로 가장할 수 있기 때문입니다!** + +::: + +## 2단계: 부트노드의 Multiaddr 연결 문자열 준비 {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +노드가 연결을 완료하려면, 네트워크의 나머지 모든 노드에 관한 정보를 얻기 위해 어떤 `bootnode` 서버를 연결해야 하는지 알아야 합니다. `bootnode`는 p2p 전문 용어로 `rendezvous` 서버라고도 합니다. + +`bootnode`는 Polygon 엣지 노드의 특별한 인스턴스가 아닙니다. 모든 Polygon 엣지 노드는 `bootnode` 역할을 할 수 있으며, +모든 Polygon 엣지 노드는 네트워크의 나머지 모든 노드와 연결하는 방법에 관한 정보 제공을 위해 연결할 부트노드 세트를 지정해야 합니다. + +부트노드를 지정할 연결 문자열을 생성하려면 다음 [Multiaddr 형식](https://docs.libp2p.io/concepts/addressing/)을 따라야 합니다. +``` +/ip4//tcp//p2p/ +``` + +본 가이드에서는 첫 번째 노드와 두 번째 노드를 다른 모든 노드의 부트노드로 취급합니다. 이 시나리오에서는 상호 연결된 부트노드를 통해 `node 1`이나 `node 2`에 연결된 노드가 서로 연결하는 방법에 대한 정보를 얻을 수 있습니다. + +:::info 노드를 시작하려면 부트노드를 하나 이상 지정해야 합니다 + +네트워크의 다른 노드가 서로를 탐색할 수 있도록 **하나** 이상의 부트노드가 필요합니다. 부트노드는 많을수록 좋습니다. 서비스 중단 시 네트워크 복원력을 제공하기 때문입니다. 본 가이드에는 두 개의 노드가 나와 있지만, `genesis.json` 파일의 유효성에 영향을 주지 않고 즉석에서 변경할 수 있습니다. + +::: + +Multiaddr 연결 문자열의 첫 번째 부분이 ``이므로 다른 노드가 연결할 수 있는 IP 주소를 입력해야 하며, 사용자 설정에 따라 `127.0.0.1`이 아닌 공개 또는 비공개 IP 주소를 입력할 수 있습니다. + +``의 경우 기본 libp2p 포트인 `1478`을 사용합니다. + +마지막으로, 이전에 실행한 `polygon-edge secrets init --data-dir data-dir` 명령어(`node 1`의 키와 데이터 디렉터리 생성에 사용)의 출력에서 가져올 수 있는 ``가 필요합니다. + +조합을 마친 후 부트노드로 사용할 `node 1`에 대한 Multiaddr 연결 문자열은 다음과 같습니다(마지막에 있는 ``만 달라야 함). +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +마찬가지로, 아래와 같이 두 번째 부트노드의 Multiaddr를 구성합니다. +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info IPS 대신 DNS 호스트 이름 + +Polygon 엣지에서는 노드 구성에 DNS 호스트 이름을 사용할 수 있습니다. 다양한 이유로 노드의 IP가 변경될 수 있어, 이는 클라우드 기반 배포에 매우 유용한 기능입니다. + +DNS 호스트 이름을 사용하는 중 연결 문자열의 Multiaddr 형식은 다음과 같습니다. +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## 3단계: 4개 노드가 검사기인 제네시스 파일 생성 {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +이 단계는 로컬 머신에서 실행할 수 있지만, 4개의 검사기 각각에 대해 공개 검사기 키가 필요합니다. + +아래에 표시된 바와 같이 검사기는 자체 `secrets init` 명령어에 대한 출력에서 `Public key (address)`를 안전하게 공유할 수 있으므로 최초 검사기 세트에서 공개 키로 식별되는 검사기들로 genesis.json을 안전하게 생성할 수 있습니다. + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +검사기의 공개 키 4개를 모두 받았다면 다음 명령어를 실행하여 `genesis.json`을 생성할 수 있습니다. + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +다음 명령어가 수행하는 작업: + +* `--ibft-validator`는 제네시스 블록에 설정된 최초 검사기 세트에 포함되어야 하는 검사기의 공개 키를 설정합니다. 여러 개의 최초 검사기가 있을 수 있습니다. +* `--bootnode` 세트는 노드가 서로를 찾을 수 있도록 부트노드의 주소를 설정합니다. +**2단계**에서 언급한 바와 같이, 우리는 `node 1`의 multiaddr 문자열을 사용할 것이지만, 위에 표시된 것처럼 원하는 만큼 부트노드를 추가할 수 있습니다. + +:::info ECSA로 전환 + +BLS는 블록 헤더의 기본 유효성 검사 모드입니다. ECDSA 모드에서 체인이 실행되기를 원한다면 인수와 함께 `—ibft-validator-type`플래그를 사용할 수 `ecdsa`있습니다. + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info 계정 잔액 사전 채굴 + +'사전 채굴된' 잔액이 있는 일부 주소로 블록체인 네트워크를 구성해야 할 수 있습니다. + +이를 위해 블록체인의 특정 잔액으로 초기화하려는 주소당 원하는 만큼 `--premine` 플래그를 전달하세요. + +예를 들어, 제네시스 블록에서 주소 `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862`를 지정해 1000ETH를 사전 채굴하려면 다음 인수를 제공해야 합니다. + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**사전 채굴된 금액은 ETH가 아닌 WEI로 표시됩니다.** + +::: + +:::info 블록 가스 한도 설정 + +각 블록의 기본 가스 한도는 `5242880`입니다. 이 값은 제네시스 파일에 기록되지만, 증감해야 할 수 있습니다. + +아래와 같이 플래그 `--block-gas-limit` 다음에 원하는 값을 입력하여 증감하면 됩니다. + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info 시스템 파일 설명자 한도 설정 + +일부 운영체제에서는 기본 파일 설명자 한도(열린 파일의 최대 수)가 매우 적습니다. +노드의 처리량이 많을 것으로 예상되면 OS 수준에서 이 한도를 늘리는 것을 고려할 수 있습니다. + +Ubuntu 배포판의 경우 절차는 다음과 같습니다(Ubuntu/Debian 배포판을 사용하지 않는다면 OS의 공식 문서를 확인하세요). +- 현재 운영체제 한도(열린 파일) 확인 +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- 열린 파일 한도 늘리기 + - 로컬 - 현재 세션에만 영향을 미칩니다. + ```shell + ulimit -u 65535 + ``` + - 전역 또는 사용자별(/etc/security/limits.conf 파일 끝에 한도 추가) + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +필요한 경우 추가 매개변수를 수정하고 파일을 저장한 후 시스템을 다시 시작하세요. +다시 시작한 후 파일 설명자 한도를 다시 확인하세요. +limits.conf 파일에서 정의한 값으로 설정해야 합니다. + +::: + +먼저 다음 사항을 지정합니다. +1. 검사기 세트로 제네시스 블록에 포함될 검사기의 공개 키 +2. 부트노드 multiaddr 연결 문자열 +3. 제네시스 블록에 포함될 사전 채굴 계정 및 잔액 + +그런 다음 `genesis.json`을 생성하고, 이를 네트워크 내의 모든 VM에 복사해야 합니다. 설정에 따라, 복사하여 붙여 넣거나, 노드 연산자에 보내거나, 간단히 SCP/FTP로 보낼 수 있습니다. + +제네시스 파일의 구조는 [CLI 명령어](/docs/edge/get-started/cli-commands) 섹션에서 다룹니다. + +## 4단계: 모든 클라이언트 실행 {#step-4-run-all-the-clients} + +:::note 클라우드 제공업체의 네트워킹 + +대부분의 클라우드 제공업체는 IP 주소(특히 공개 주소)를 VM의 직접적인 네트워크 인터페이스로 노출하지 않으며, 표시되지 않는 NAT 프록시를 설정합니다. + + +이 경우 노드들이 서로 연결될 수 있게 하려면, `0.0.0.0` IP 주소를 수신 대기하여 모든 인터페이스에서 바인딩해야 할 필요가 있지만, 다른 노드들이 인스턴스에 연결하기 위해 사용할 수 있는 IP 주소 또는 DNS 주소를 지정해야 합니다. 각각 외부 IP 또는 DNS 주소를 지정할 수 있는 `--nat` 또는 `--dns` 인수를 사용하면 됩니다. + +#### 예시 {#example} + +수신 대기하려는 관련 IP 주소는 `192.0.2.1`이지만, 네트워크 인터페이스에 직접 바인딩되지 않습니다. + +노드가 연결되게 하려면 다음 매개변수를 전달해야 합니다. + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +또는, DNS 주소 `dns/example.io`를 지정하려면 다음 매개변수를 전달하세요. + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +이렇게 하면 노드가 모든 인터페이스에서 수신 대기하며, 지정된 `--nat` 또는 `--dns` 주소를 통해 클라이언트가 노드에 연결하고 있음을 인식하게 됩니다. + +::: + +**첫 번째** 클라이언트를 실행하려면, + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +**두 번째** 클라이언트를 실행하려면, + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +**세 번째** 클라이언트를 실행하려면, + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +**네 번째** 클라이언트를 실행하려면, + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +이전 명령어를 실행한 후, 블록을 봉인하고 노드 장애에서 복구할 수 있는 4-노드 Polygon 엣지 네트워크를 설정했습니다. + +:::info 구성 파일을 통해 클라이언트 시작 + +모든 구성 매개변수를 CLI 인수로 지정하는 대신, 다음 명령어를 실행하여 구성 파일을 통해 클라이언트를 시작할 수도 있습니다. + +````bash +polygon-edge server --config +```` +예시: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +현재 우리는 단지 지원 구성 파일만을 `json`사용하고 있습니다. 샘플 구성 파일이 **[여기에서](/docs/edge/configuration/sample-config)** 찾을 수 있습니다. + +::: + +:::info 비 검사기 노드 실행 단계 + +비 검사기는 항상 검사기 노드에서 수신한 최신 블록을 동기화합니다. 다음 명령어를 실행해 비 검사기 노드를 시작할 수 있습니다. + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +예를 들어, 다음 명령어를 실행하여 **다섯 번째** 비 검사기 클라이언트를 추가할 수 있습니다. + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info 가격 제한 지정 + +수신 트랜잭션에 **가격 제한**을 설정해 Polygon 엣지 노드를 시작할 수 있습니다. + +가격 제한 단위는 `wei`입니다. + +가격 제한을 설정하면 현재 노드에서 처리되는 모든 트랜잭션의 가스 가격이 설정된 가격 제한보다 **높아야** 하며, 그렇지 않으면 블록에 포함되지 않습니다. + +대다수의 노드가 특정 가격 제한을 준수하도록 하면 네트워크의 트랜잭션이 특정 가격 임계값보다 낮을 수 없다는 규칙이 적용됩니다. + +가격 제한의 기본값은 `0`이며, 기본적으로는 적용되지 않는다는 의미입니다. + +`--price-limit` 플래그 사용 예시: +````bash +polygon-edge server --price-limit 100000 ... +```` + +가격 제한은 **로컬이 아닌 트랜잭션에만 적용되므로**, 노드에 로컬로 추가된 트랜잭션에는 적용되지 않습니다. + +::: + +:::info 웹소켓 URL + +기본적으로 Polygon 엣지를 실행할 때는 체인 위치를 기반으로 웹소켓 URL이 생성됩니다. +HTTPS 링크에 사용되는 URL 체계는 `wss://`, HTTP 링크의 경우 `ws://`입니다. + +Localhost 웹소켓 URL은 다음과 같습니다. +````bash +ws://localhost:10002/ws +```` +포트 번호는 노드를 위해 선택한 JSON-RPC 포트에 따라 결정됩니다. + +EdgeNet 웹소켓 URL은 다음과 같습니다. +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/ko-edge/get-started/terraform-aws-deployment.md b/archive/edge/ko-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..ba6354b6f0 --- /dev/null +++ b/archive/edge/ko-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,170 @@ +--- +id: terraform-aws-deployment +title: Terraform AWS 배포 +description: "Terraform을 사용하여 AWS 클라우드 공급업체에 Polygon 엣지 네트워크 배포하기" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info 프로덕션 배포 가이드 + +프로덕션용으로 완전 자동화된 공식 AWS 배포 가이드입니다. + +***[클라우드](set-up-ibft-on-the-cloud)*** 또는 ***[로컬](set-up-ibft-locally)***에 대한 수동 배포는 테스트 목적이거나 AWS 외의 클라우드 공급업체를 이용하는 경우에 적합합니다. + +::: + +:::info + +이 배포는 PoA에 한정됩니다. +PoS 메커니즘이 필요한 경우, 본 ***[가이드](/docs/edge/consensus/migration-to-pos)***를 따라 PoA에서 PoS로 전환하면 됩니다. + +::: + +이 가이드에서는 검사기 노드가 여러 가용 영역에 걸쳐 있어 프로덕션 준비가 완료된 AWS 클라우드 공급업체에 Polygon 엣지 블록체인 네트워크를 배포하는 과정을 자세히 설명합니다. + +## 기본 요건 {#prerequisites} + +### 시스템 도구 {#system-tools} +* [Terraform](https://www.terraform.io/) +* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [AWS 액세스 키 ID 및 보안 비밀 액세스 키](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Terraform 변수 {#terraform-variables} +배포하기 전에 두 개의 변수가 제공되어야 합니다. + +* `alb_ssl_certificate`- ALB가 https 프로토콜에 사용할 AWS Certificate Manager 인증서의 ARN. +인증서는 배포 시작 전에 생성되어야 하며, **발급 완료** 상태여야 합니다. +* `premine` - 사전 채굴된 기본 화폐를 수령할 계정. +값은 공식 [CLI](/docs/edge/get-started/cli-commands#genesis-flags) 플래그 사양을 따라야 합니다. + +## 배포 정보 {#deployment-information} +### 배포된 리소스 {#deployed-resources} +배포될 리소스에 대한 상위 수준 개요는 다음과 같습니다. + +* 전용 VPC +* 4개의 검사기 노드(부트 노드이기도 함) +* 노드 아웃바운드 인터넷 트래픽을 허용하는 4개의 NAT 게이트웨이 +* 첫 (제네시스) 블록을 생성하고 체인을 시작하는 데 사용되는 람다 함수 +* 전용 보안 그룹 및 IAM 역할 +* genesis.json 파일 저장에 사용되는 S3 버킷 +* JSON-RPC 엔드포인트 노출에 사용되는 애플리케이션 부하 분산기 + +### 내결함성 {#fault-tolerance} + +4개의 가용 영역이 있는 지역만 이 배포에 필요합니다. 각 노드는 단일 가용 영역에 배포됩니다. + +각 노드를 단일 가용 영역에 배치하면 Polygon 엣지가 4개의 검사기 노드 클러스터에서 단일 노드의 실패를 허용하는 IBFT 합의를 구현하므로, 전체 블록체인 클러스터가 단일 노드(가용 영역) 장애에 대해 내결함성을 갖습니다. + +### 명령줄 액세스 {#command-line-access} + +검사기 노드는 어떤 방식으로도 공용 인터넷에 노출되지 않으며(JSON-PRC는 ALB를 통해서만 액세스됨), 공개 IP 주소가 연결되어 있지도 않습니다. +노드 명령줄은 [AWS Systems Manager - Session Manager](https://aws.amazon.com/systems-manager/features/)를 통해서만 액세스할 수 있습니다. + +### 기본 AMI 업그레이드 {#base-ami-upgrade} + +이 배포는 `ubuntu-focal-20.04-amd64-server` AWS AMI를 사용합니다. AWS AMI가 업데이트되는 경우 EC2 *재배포*를 트리거하지 **않습니다**. + +어떤 이유로 기본 AMI를 업데이트해야 하는 경우, `terraform apply`에 앞서 각 인스턴스에 `terraform taint` 명령어를 실행하여 업데이트할 수 있습니다. + `terraform taint module.instances[].aws_instance.polygon_edge_instance` 명령어를 실행하면 인스턴스가 테인트(taint)될 수 있습니다. + +예시: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info + +프로덕션 환경에서 `terraform taint`는 블록체인 네트워크 기능을 유지하기 위해 하나씩 실행되어야 합니다. + +::: + +## 배포 절차 {#deployment-procedure} + +### 사전 배포 단계 {#pre-deployment-steps} +* [polygon-technology-edge](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) Terraform 레지스트리 리드미를 자세히 읽습니다. +* 모듈 readme 페이지의 *프로비저닝 지침*을 따라, `main.tf` 파일에 `polygon-technology-edge` 모듈을 추가합니다. +* `terraform init` 명령어를 실행하여 필요한 Terraform 종속 항목을 모두 설치합니다. +* [AWS Certificate Manager](https://aws.amazon.com/certificate-manager/)에 새로운 인증서를 제공합니다. +* 제공된 인증서가 **발급 완료** 상태임을 확인하고 인증서의 **ARN**을 기록합니다. +* CLI에서 모듈 출력을 가져오려면 출력 문을 설정합니다. + +#### `main.tf` 예시 {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### `terraform.tfvars` 예시 {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### 배포 단계 {#deployment-steps} +* `terraform.tfvars` 파일을 생성합니다. +* 필요한 Terraform 변수를 이 파일에 설정합니다(위에서 설명함). +:::info + +이 배포를 완전히 사용자 정의할 수 있는 다른 비필수 변수가 있습니다. +`terraform.tfvars` 파일에 자체 값을 입력하여 기본 값을 재정의할 수 있습니다. + +사용 가능한 모든 변수의 사양은 모듈의 Terraform ***[레지스트리](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)***에서 확인할 수 있습니다. + +::: +* `aws s3 ls`를 실행하여 AWS CLI 인증을 올바르게 설정했는지 확인하세요. 오류가 없어야 합니다. +* `terraform apply` 인프라를 배포합니다. + +### 배포 후 단계 {#post-deployment-steps} +* 배포가 끝나면 CLI에 출력된 `json_rpc_dns_name` 변수 값을 기록합니다. +* 도메인 이름이 제공된 `json_rpc_dns_name` 값을 가리키는 공개 DNS CNAME 레코드를 생성합니다. 예시: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* CNAME 레코드가 전파되면 JSON-PRC 엔드포인트를 호출하여 체인이 제대로 작동하는지 확인합니다. +위의 예시에서: + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## 폐기 절차 {#destroy-procedure} +:::warning + +다음 절차를 따르면 Terraform 스크립트를 이용해 배포한 전체 인프라가 영구적으로 삭제됩니다. +적절한 [블록체인 데이터 백업](docs/edge/working-with-node/backup-restore)이 있어야 하며, 테스트 환경에서 작업해야 합니다. + +::: + +전체 인프라를 삭제해야 하는 경우 `terraform destroy` 명령어를 실행하세요. +또한 배포가 이루어진 지역에 대해 AWS [Parameter Store](https://aws.amazon.com/systems-manager/features/)에 저장되어 있는 보안 비밀을 수동으로 삭제해야 합니다. diff --git a/archive/edge/ko-edge/overview.md b/archive/edge/ko-edge/overview.md new file mode 100644 index 0000000000..9328f8259b --- /dev/null +++ b/archive/edge/ko-edge/overview.md @@ -0,0 +1,35 @@ +--- +id: overview +title: Polygon 엣지 +sidebar_label: What is Edge +description: "Polygon 엣지 소개." +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +Polygon 엣지는 이더리움 호환 블록체인 네트워크, 사이드체인 및 일반 확장 솔루션 구축을 위한 모듈식 확장형 프레임워크입니다. + +주요 용도는 이더리움 스마트 계약 및 트랜잭션과의 완전한 호환성을 제공하면서 새로운 블록체인 네트워크를 부트스트랩하는 것입니다. Polygon 엣지는 IBFT(Istanbul Byzantine Fault Tolerant) 합의 메커니즘을 사용하며, [PoA(권한증명)](/docs/edge/consensus/poa) 및 [PoS(지분증명)](/docs/edge/consensus/pos-stake-unstake)의 두 가지 방식으로 지원됩니다. + +또한 여러 블록체인 네트워크와의 통신을 지원하므로, [중앙 집중식 브리지 솔루션](/docs/edge/additional-features/chainbridge/overview)을 활용해 [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20)과 [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) 토큰을 모두 전송할 수 있습니다. + +업계 표준 지갑을 사용해 [JSON-RPC](/docs/edge/working-with-node/query-json-rpc) 엔드포인트를 통해 Polygon 엣지와 상호작용할 수 있으며, 노드 연산자는 [gRPC](/docs/edge/working-with-node/query-operator-info) 프로토콜을 통해 노드에서 다양한 작업을 수행할 수 있습니다. + +Polygon에 관한 자세한 내용은 [공식 웹사이트](https://polygon.technology)를 참조하시기 바랍니다. + +**[GitHub 저장소](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +현재 작업 진행 중이므로, 향후 아키텍처가 변경될 수 있습니다. 아직 코드에 대한 감사가 완료되지 않았으므로, 프로덕션에 사용하려면 Polygon 팀에 문의하시기 바랍니다. + +::: + + + +`polygon-edge` 네트워크를 로컬로 실행하여 시작하려면 [설치](/docs/edge/get-started/installation) 및 [로컬 설정](/docs/edge/get-started/set-up-ibft-locally)을 확인하시기 바랍니다. diff --git a/archive/edge/ko-edge/performance-reports/overview.md b/archive/edge/ko-edge/performance-reports/overview.md new file mode 100644 index 0000000000..00d2b5e44b --- /dev/null +++ b/archive/edge/ko-edge/performance-reports/overview.md @@ -0,0 +1,32 @@ +--- +id: overview +title: 개요 +description: "Polygon 엣지 테스트 소개." +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +이러한 테스트를 수행하는 데 사용되는 `loadbot`사용자가 이제 감가 상각된다는 점에 유의하십시오. +::: + +| 유형 | 값 | 테스트 링크 | +| ---- | ----- | ------------ | +| 일반 전송 | 1428 tps | [2022년 7월 4일](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| ERC-20 전송 | 1111 tps | [2022년 7월 4일](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| NFT 발행 | 714 tps | [2022년 7월 4일](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +Polygon의 목표는 풍부한 기능을 갖추고 설정과 유지 관리가 쉬운 고성능 블록체인 클라이언트 소프트웨어를 만드는 것입니다. +모든 테스트는 Polygon 엣지 로드봇을 사용하여 수행했습니다. +본 섹션의 모든 성능 보고서는 날짜, 환경, 테스트 방법을 명확하게 설명하고 있습니다. + +이 성능 테스트의 목표는 Polygon 엣지 블록체인 네트워크의 실제 성능을 보여주는 것입니다. +누구든 동일한 환경에서 Polygon 로드봇을 사용하여 여기에 게시된 것과 동일한 결과를 얻을 수 있습니다. + +모든 성능 테스트는 AWS 플랫폼에서 EC2 인스턴스 노드로 구성된 체인에 대해 수행했습니다. \ No newline at end of file diff --git a/archive/edge/ko-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/ko-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..5dbd247164 --- /dev/null +++ b/archive/edge/ko-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,131 @@ +--- +id: test-2022-01-21 +title: 2022년 1월 21일 +description: "1월 21일에 수행된 성능 테스트입니다." +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## 2022년 1월 21일 {#january-21st-2022} + +### 요약 {#summary} + +:::caution +이러한 테스트를 수행하는 데 사용되는 `loadbot`사용자가 이제 감가 상각된다는 점에 유의하십시오. +::: + +이 테스트는 성능을 크게 향상시킨 TxPool 리팩터링([v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0)으로 릴리스) 이후에 수행되었습니다. + +테스트의 목표는 활발하게 참여하는 30개의 검사기로 구성된 대규모 네트워크를 설정하여 +모든 트랜잭션이 단일 노드의 JSON-RPC로 전송되었을 때 합의 및 TxPool 트랜잭션 가십핑에 대해 부하 테스트를 적절히 수행하는 것이었습니다. + +가능한 최대 TPS에 도달하는 것을 목적으로 하지는 않았습니다. 네트워크 규모가 성능에 부정적인 영향을 미치고, 블록 가스 한도와 블록 시간은 시스템 리소스를 많이 소모하지 않으면서 상용 하드웨어에서 실행할 수 있도록 하는 합리적인 값으로 설정되기 때문입니다. + +### 결과 {#results} + +| 측정항목 | 값 | +| ------ | ----- | +| 초당 트랜잭션 | 344 | +| 트랜잭션 실패 | 0 | +| 트랜잭션 성공 | 10000 | +| 총 실행 시간 | 30초 | + +### 환경 {#environment} + +
+ 호스트 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
클라우드 제공업체AWS
인스턴스 크기t2.xlarge
네트워킹비공개 서브넷
운영체제Linux Ubuntu 20.04 LTS - Focal Fossa
파일 설명자 한도65535
최대 사용자 프로세스65535
+
+
+
+
+ +
+ 블록체인 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon 엣지 버전개발 분기에 8377162281d1a2e4342ae27cd4e5367c4364aee2 커밋
검사기 노드30
비 검사기 노드0
합의IBFT PoA
블록 시간2000밀리초
블록 가스 한도5242880
+
+
+
+
+ +
+ 로드봇 구성 +
+
+ + + + + + + + + + + + + +
총 트랜잭션10000
초당 전송된 트랜잭션400
트랜잭션 유형EOA에서 EOA로 전송
+
+
+
+
diff --git a/archive/edge/ko-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/ko-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..aca773d81d --- /dev/null +++ b/archive/edge/ko-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,390 @@ +--- +id: test-2022-03-02 +title: 2022년 3월 2일 +description: "3월 2일부터 성능 테스트." +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### 요약 {#summary} + +:::caution +이러한 테스트를 수행하는 데 사용되는 `loadbot`사용자가 이제 감가 상각된다는 점에 유의하십시오. +::: + +이 테스트는 부하가 크고 트랜잭션 속도가 빠른 SC ERC20 토큰 전송 및 SC ERC721 토큰 발행 기능 측정을 위해 수행되었습니다. + +목표는 과부하 중에 모든 작업이 예상대로 수행되는지 확인하는 것이었습니다. 이는 로드봇 출력에 가스 측정항목을 도입한 이유이기도 하며, 블록이 트랜잭션으로 제대로 채워졌는지 보여줍니다. + +모든 트랜잭션이 GRPC API를 통해 단일 노드로 전송되었고, 영수증은 JSON-RPC API로 수신되었습니다. 모든 트랜잭션이 완료된 후 eth_getBlockByNumber JSON-RPC 메서드를 통해 각 블록에서 가스 정보를 읽었습니다. + +블록 가스 한도와 블록 시간은 시스템 리소스를 많이 소모하지 않으면서 +상용 하드웨어에서 실행될 수 있게 해주는 정상적인 값으로 설정되기 때문에, 가능한 최대 TPS에 도달하려 노력하는 것을 목적으로 하진 않았습니다. + +### ERC20 결과 {#results-erc20} + +| 측정항목 | 값 | +| ------ | ----- | +| 트랜잭션 유형 | ERC20 | +| 초당 트랜잭션 | 65 | +| 트랜잭션 실패 | 0 | +| 트랜잭션 성공 | 5000 | +| ERC20 트랜잭션 실행 시간 | 76.681690초 | +| SC 배포 시간 | 4.048250초 | + +### ERC721 결과 {#results-erc721} + +| 측정항목 | 값 | +| ------ | ----- | +| 트랜잭션 유형 | ERC721 | +| 초당 트랜잭션 | 20 | +| 트랜잭션 실패 | 0 | +| 트랜잭션 성공 | 2000 | +| ERC721 트랜잭션 실행 시간 | 97.239920초 | +| SC 배포 시간 | 3.048970초 | + +### ERC20 환경 {#environment-erc20} + +
+ 호스트 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
클라우드 제공업체AWS
인스턴스 크기t2.micro
네트워킹비공개 서브넷
운영체제Linux Ubuntu 20.04 LTS - Focal Fossa
파일 설명자 한도65535
최대 사용자 프로세스65535
+
+
+
+
+ +
+ 블록체인 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon 엣지 버전개발 분기에 8a033aa1afb191abdac04636d318f83f32511f3c 커밋
검사기 노드6
비 검사기 노드0
합의IBFT PoA
블록 시간2초
블록 가스 한도5242880
평균 블록 사용률95%
+
+
+
+
+ +
+ 로드봇 구성 +
+
+ + + + + + + + + + + + + +
총 트랜잭션5000
초당 전송된 트랜잭션200
트랜잭션 유형ERC20에서 ERC20으로 전송
+
+
+
+
+ +
+ 로드봇 로그 + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### ERC721 환경 {#environment-erc721} + +
+ 호스트 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
클라우드 제공업체AWS
인스턴스 크기t2.micro
네트워킹비공개 서브넷
운영체제Linux Ubuntu 20.04 LTS - Focal Fossa
파일 설명자 한도65535
최대 사용자 프로세스65535
+
+
+
+
+ +
+ 블록체인 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon 엣지 버전개발 분기에 8a033aa1afb191abdac04636d318f83f32511f3c 커밋
검사기 노드6
비 검사기 노드0
합의IBFT PoA
블록 시간2초
블록 가스 한도5242880
평균 블록 사용률94%
+
+
+
+
+ +
+ 로드봇 구성 +
+
+ + + + + + + + + + + + + +
총 트랜잭션2000
초당 전송된 트랜잭션200
트랜잭션 유형ERC721 토큰 발행
+
+
+
+
+ +
+ 로드봇 로그 + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/ko-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/ko-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..4ae3e9252e --- /dev/null +++ b/archive/edge/ko-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,960 @@ +--- +id: test-2022-03-23 +title: 2022년 3월 23일 +description: "3월 23일에 수행한 성능 테스트입니다." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### 요약 {#summary} + +:::caution +이러한 테스트를 수행하는 데 사용되는 `loadbot`사용자가 이제 감가 상각된다는 점에 유의하십시오. +::: + +이 테스트는 하드웨어 리소스 수준이 더 높은 노드에서 과부하 및 트랜잭션 속도를 기반으로 SC ERC20 토큰 전송, SC ERC721 토큰 발행 및 EOA에서 EOA로의 트랜잭션 기능을 측정하기 위해 수행되었습니다. + +테스트의 목표는 과부하 중에도 모든 것이 예상대로 작동하는지 확인하는 것입니다. 이런 이유로 블록에 트랜잭션이 제대로 채워지는지 보여주는 로드봇 출력에 가스 측정항목도 도입했습니다. + +모든 트랜잭션은 GRPC API를 통해 단일 노드로 전송되었고, 영수증은 JSON-RPC API로 수신되었습니다. 모든 트랜잭션이 완료된 후 eth_getBlockByNumber JSON-RPC 메서드를 통해 각 블록에서 가스 정보를 읽었습니다. + +목적은 사용할 수 있는 하드웨어 리소스에서 가능한 최대 TPS에 도달하려는 것이었습니다. +이를 달성하기 위해 가능한 최상의 TPS 결과를 도출하고 시스템의 무결성과 안정성을 유지하도록 블록 가스 한도와 블록 시간 매개변수를 수정했습니다. + +:::info 블록 가스 한도 + +트랜잭션 실행에 많은 가스가 사용되는 경우 블록 가스 한도를 상대적으로 높은 숫자로 올릴 수 있습니다. +아래 예에서 ERC721 토큰 발행은 블록 가스 한도가 (2천만 대신) 80000000으로 설정되었을 때 훨씬 빨리 수행되었지만, ERC20 토큰 전송의 경우 블록 가스 한도가 8천만이면 서버 충돌이 발생했습니다. + +::: + +:::info 프로덕션 환경 + +체인의 높은 성능을 달성하려면 프로덕션 환경을 구성할 때 신중해야 합니다. +블록 가스 한도 매개변수가 높은 값으로 설정되어 있고, 블록 시간이 1초로 설정되어 있으며, 단일 노드에 트랜잭션 로드가 많으면 이 노드가 모든 또는 많은 양의 RAM을 소모하여 서버 충돌이 발생할 수 있습니다. +로드봇을 사용하여 모든 항목을 면밀히 테스트하고, 시스템 리소스 사용을 모니터링하면서 그에 따라 구성 매개변수를 적절히 설정하세요. + +::: + +:::info 메모리 부족 오류 + +일부 Linux 배포판에서는 시스템 안정성을 유지하기 위해 RAM 사용량이 높은(메모리 부족 오류) 프로세스를 자동으로 종료시킵니다. +이런 메모리 부족 오류의 로그 출력은 아래와 유사하게 표시됩니다. +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### EOA에서 EOA로의 전송 결과 {#results-of-eoa-to-eoa-transfers} +| 측정항목 | 값 | +| ------ | ----- | +| 트랜잭션 유형 | EOA에서 EOA로 | +| 초당 트랜잭션 | 689 | +| 트랜잭션 실패 | 0 | +| 트랜잭션 성공 | 20000 | +| 사용된 총 블록 수 | 25 | +| 총 실행 시간 | 29.921110초 | + +### ERC20 토큰 전송의 결과 {#results-of-erc20-token-transfers} + +| 측정항목 | 값 | +| ------ | ----- | +| 트랜잭션 유형 | ERC20 | +| 초당 트랜잭션 | 500 | +| 트랜잭션 실패 | 0 | +| 트랜잭션 성공 | 20000 | +| 사용된 총 블록 수 | 33 | +| ERC20 트랜잭션 실행 시간 | 40.402900초 | +| SC 배포 시간 | 2.004140초 | + +### ERC721 토큰 발행의 결과 {#results-of-erc721-token-minting} + +| 측정항목 | 값 | +| ------ | ----- | +| 트랜잭션 유형 | ERC721 | +| 초당 트랜잭션 | 157 | +| 트랜잭션 실패 | 0 | +| 트랜잭션 성공 | 20000 | +| 사용된 총 블록 수 | 124 | +| ERC721 트랜잭션 실행 시간 | 127.537340초 | +| SC 배포 시간 | 2.004420초 | + + +### 블록 가스 한도가 매우 높은(8천만) ERC721 토큰 발행의 결과 {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| 측정항목 | 값 | +| ------ | ----- | +| 트랜잭션 유형 | ERC721 | +| 초당 트랜잭션 | 487 | +| 트랜잭션 실패 | 0 | +| 트랜잭션 성공 | 20000 | +| 사용된 총 블록 수 | 34 | +| ERC721 트랜잭션 실행 시간 | 41.098410초 | +| SC 배포 시간 | 2.004300초 | + + +### EOA에서 EOA로의 환경 {#environment-eoa-to-eoa} +
+ 호스트 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
클라우드 제공업체AWS
인스턴스 크기c5.2xlarge
네트워킹비공개 서브넷
운영체제Amazon Linux 2 AMI(HVM) - 커널 5.10
파일 설명자 한도65535
최대 사용자 프로세스65535
+
+
+
+
+ +
+ 블록체인 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon 엣지 버전개발 분기에 06e11eac8da98c79c938fc53dda2da3318cfbe04 커밋
검사기 노드4
비 검사기 노드0
합의IBFT PoA
블록 시간1초
블록 가스 한도20000000
최대 슬롯1000000
평균 블록 사용률84.00%
+
+
+
+
+ +
+ 로드봇 구성 +
+
+ + + + + + + + + + + + + +
총 트랜잭션20000
초당 전송된 트랜잭션689
트랜잭션 유형EOA에서 EOA로의 전송
+
+
+
+
+ +
+ 로드봇 로그 + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### ERC20 환경 {#environment-erc20} +
+ 호스트 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
클라우드 제공업체AWS
인스턴스 크기c5.2xlarge
네트워킹비공개 서브넷
운영체제Amazon Linux 2 AMI(HVM) - 커널 5.10
파일 설명자 한도65535
최대 사용자 프로세스65535
+
+
+
+
+ +
+ 블록체인 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon 엣지 버전개발 분기에 06e11eac8da98c79c938fc53dda2da3318cfbe04 커밋
검사기 노드4
비 검사기 노드0
합의IBFT PoA
블록 시간1초
블록 가스 한도20000000
최대 슬롯1000000
평균 블록 사용률88.38%
+
+
+
+
+ +
+ 로드봇 구성 +
+
+ + + + + + + + + + + + + +
총 트랜잭션20000
초당 전송된 트랜잭션500
트랜잭션 유형ERC20에서 ERC20으로 전송
+
+
+
+
+ +
+ 로드봇 로그 + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### ERC721 환경 {#environment-erc721} +
+ 호스트 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
클라우드 제공업체AWS
인스턴스 크기c5.2xlarge
네트워킹비공개 서브넷
운영체제Amazon Linux 2 AMI(HVM) - 커널 5.10
파일 설명자 한도65535
최대 사용자 프로세스65535
+
+
+
+
+ +
+ 블록체인 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon 엣지 버전개발 분기에 06e11eac8da98c79c938fc53dda2da3318cfbe04 커밋
검사기 노드4
비 검사기 노드0
합의IBFT PoA
블록 시간1초
블록 가스 한도20000000
최대 슬롯1000000
평균 블록 사용률92.90%
+
+
+
+
+ +
+ 로드봇 구성 +
+
+ + + + + + + + + + + + + +
총 트랜잭션20000
초당 전송된 트랜잭션157
트랜잭션 유형ERC721 토큰 발행
+
+
+
+
+ +
+ 로드봇 로그 + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### ERC20 환경 - 매우 높은 블록 가스 한도 {#environment-erc20-very-high-block-gas-limit} +
+ 호스트 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
클라우드 제공업체AWS
인스턴스 크기c5.2xlarge
네트워킹비공개 서브넷
운영체제Amazon Linux 2 AMI(HVM) - 커널 5.10
파일 설명자 한도65535
최대 사용자 프로세스65535
+
+
+
+
+ +
+ 블록체인 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon 엣지 버전개발 분기에 06e11eac8da98c79c938fc53dda2da3318cfbe04 커밋
검사기 노드4
비 검사기 노드0
합의IBFT PoA
블록 시간1초
블록 가스 한도80000000
최대 슬롯1000000
평균 블록 사용률---
+
+
+
+
+ +
+ 로드봇 구성 +
+
+ + + + + + + + + + + + + +
총 트랜잭션20000
초당 전송된 트랜잭션---
트랜잭션 유형ERC20에서 ERC20으로 전송
+
+
+
+
+ +
+ 메모리 부족 오류 로그 + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### ERC721 환경 - 매우 높은 블록 가스 한도 {#environment-erc721-very-high-block-gas-limit} +
+ 호스트 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
클라우드 제공업체AWS
인스턴스 크기c5.2xlarge
네트워킹비공개 서브넷
운영체제Amazon Linux 2 AMI(HVM) - 커널 5.10
파일 설명자 한도65535
최대 사용자 프로세스65535
+
+
+
+
+ +
+ 블록체인 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon 엣지 버전개발 분기에 06e11eac8da98c79c938fc53dda2da3318cfbe04 커밋
검사기 노드4
비 검사기 노드0
합의IBFT PoA
블록 시간1초
블록 가스 한도80000000
최대 슬롯1000000
평균 블록 사용률84.68%
+
+
+
+
+ +
+ 로드봇 구성 +
+
+ + + + + + + + + + + + + +
총 트랜잭션20000
초당 전송된 트랜잭션487
트랜잭션 유형ERC721 토큰 발행
+
+
+
+
+ +
+ 로드봇 로그 + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/ko-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/ko-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..12f677fa90 --- /dev/null +++ b/archive/edge/ko-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,568 @@ +--- +id: test-2022-07-04 +title: 2022년 7월 4일 +description: "7월 4일부터의 성능 테스트." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### 요약 {#summary} + +:::caution +이러한 테스트를 수행하는 데 사용되는 `loadbot`사용자가 이제 감가 상각된다는 점에 유의하십시오. +::: + +이 테스트는 하드웨어 리소스 수준이 더 높은 노드에서 과부하 및 트랜잭션 속도를 기반으로 SC ERC20 토큰 전송, SC ERC721 토큰 발행 및 EOA에서 EOA로의 트랜잭션 기능을 측정하기 위해 수행되었습니다. + +테스트의 목표는 과부하 중에도 모든 것이 예상대로 작동하는지 확인하는 것입니다. 이런 이유로 블록에 트랜잭션이 제대로 채워지는지 보여주는 로드봇 출력에 가스 측정항목도 도입했습니다. + +모든 트랜잭션은 GRPC API를 통해 단일 노드로 전송되었고, 영수증은 JSON-RPC API로 수신되었습니다. 모든 트랜잭션이 완료된 후 eth_getBlockByNumber JSON-RPC 메서드를 통해 각 블록에서 가스 정보를 읽었습니다. + +목적은 사용할 수 있는 하드웨어 리소스에서 가능한 최대 TPS에 도달하려는 것이었습니다. +이를 달성하기 위해 가능한 최상의 TPS 결과를 도출하고 시스템의 무결성과 안정성을 유지하도록 블록 가스 한도와 블록 시간 매개변수를 수정했습니다. + + +:::info 프로덕션 환경 + +체인의 높은 성능을 달성하려면 프로덕션 환경을 구성할 때 신중해야 합니다. +블록 가스 한도 매개변수가 높은 값으로 설정되어 있고, 블록 시간이 1초로 설정되어 있으며, 단일 노드에 트랜잭션 로드가 많으면 이 노드가 모든 또는 많은 양의 RAM을 소모하여 서버 충돌이 발생할 수 있습니다. +로드봇을 사용하여 모든 항목을 면밀히 테스트하고, 시스템 리소스 사용을 모니터링하면서 그에 따라 구성 매개변수를 적절히 설정하세요. + +::: + + + +### EOA에서 EOA로의 전송 결과 {#results-of-eoa-to-eoa-transfers} +| 측정항목 | 값 | +| ------ | ----- | +| 트랜잭션 유형 | EOA에서 EOA로 | +| 초당 트랜잭션 | 1428 | +| 트랜잭션 실패 | 0 | +| 트랜잭션 성공 | 30000 | +| 사용된 총 블록 수 | 15 | +| 총 실행 시간 | 21.374620초 | + +### ERC20 토큰 전송의 결과 {#results-of-erc20-token-transfers} + +| 측정항목 | 값 | +| ------ | ----- | +| 트랜잭션 유형 | ERC20 | +| 초당 트랜잭션 | 1111 | +| 트랜잭션 실패 | 0 | +| 트랜잭션 성공 | 50000 | +| 사용된 총 블록 수 | 38 | +| ERC20 트랜잭션 실행 시간 | 45.906450초 | +| SC 배포 시간 | 2.006580초 | + +### ERC721 토큰 발행의 결과 {#results-of-erc721-token-minting} + +| 측정항목 | 값 | +| ------ | ----- | +| 트랜잭션 유형 | ERC721 | +| 초당 트랜잭션 | 714 | +| 트랜잭션 실패 | 0 | +| 트랜잭션 성공 | 30000 | +| 사용된 총 블록 수 | 39 | +| ERC721 트랜잭션 실행 시간 | 42.864140초 | +| SC 배포 시간 | 2.005500초 | + + + + +### EOA에서 EOA로의 환경 {#environment-eoa-to-eoa} +
+ 호스트 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
클라우드 제공업체AWS EC2
인스턴스 크기c6a.48xlarge
네트워킹비공개 서브넷
운영체제Linux Ubuntu 20.04 LTS - Focal Fossa
파일 설명자 한도65535
최대 사용자 프로세스65535
+
+
+
+
+ +
+ 블록체인 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon 엣지 버전릴리스 v0.4.1
검사기 노드4
비 검사기 노드0
합의IBFT PoA
블록 시간1초
블록 가스 한도70778880
최대 슬롯276480
평균 블록 사용률59.34%
+
+
+
+
+ +
+ 로드봇 구성 +
+
+ + + + + + + + + + + + + +
총 트랜잭션30000
초당 전송된 트랜잭션1428
트랜잭션 유형EOA에서 EOA로의 전송
+
+
+
+
+ +
+ 로드봇 로그 + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### ERC20 환경 {#environment-erc20} +
+ 호스트 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
클라우드 제공업체AWS EC2
인스턴스 크기c6a.48xlarge
네트워킹비공개 서브넷
운영체제Linux Ubuntu 20.04 LTS - Focal Fossa
파일 설명자 한도65535
최대 사용자 프로세스65535
+
+
+
+
+ +
+ 블록체인 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon 엣지 버전릴리스 v0.4.1
검사기 노드4
비 검사기 노드0
합의IBFT PoA
블록 시간1초
블록 가스 한도47185920
최대 슬롯184320
평균 블록 사용률81.29%
+
+
+
+
+ +
+ 로드봇 구성 +
+
+ + + + + + + + + + + + + +
총 트랜잭션50000
초당 전송된 트랜잭션1111
트랜잭션 유형ERC20에서 ERC20으로 전송
+
+
+
+
+ +
+ 로드봇 로그 + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### ERC721 환경 {#environment-erc721} +
+ 호스트 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
클라우드 제공업체AWS EC2
인스턴스 크기c6a.48xlarge
네트워킹비공개 서브넷
운영체제Linux Ubuntu 20.04 LTS - Focal Fossa
파일 설명자 한도65535
최대 사용자 프로세스65535
+
+
+
+
+ +
+ 블록체인 구성 +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon 엣지 버전릴리스 v0.4.1
검사기 노드4
비 검사기 노드0
합의IBFT PoA
블록 시간1초
블록 가스 한도94371840
최대 슬롯1000000
평균 블록 사용률93.88%
+
+
+
+
+ +
+ 로드봇 구성 +
+
+ + + + + + + + + + + + + +
총 트랜잭션30000
초당 전송된 트랜잭션714
트랜잭션 유형ERC721 토큰 발행
+
+
+
+
+ +
+ 로드봇 로그 + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/ko-edge/troubleshooting.md b/archive/edge/ko-edge/troubleshooting.md new file mode 100644 index 0000000000..40dcec46ce --- /dev/null +++ b/archive/edge/ko-edge/troubleshooting.md @@ -0,0 +1,71 @@ +--- +id: troubleshooting +title: 문제 해결 +description: "Polygon 엣지의 문제 해결 섹션입니다." +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# 문제 해결 {#troubleshooting} + +## `method=eth_call err="invalid signature"` 오류 {#error} + +Polygon 엣지에서 트랜잭션에 지갑을 사용하는 경우, 지갑의 로컬 네트워크가 다음과 같이 설정되어 있는지 확인하세요. + +1. `chainID`가 올바른지 확인합니다. 엣지의 기본 `chainID`는 `100`이지만, 제네시스 플래그 `--chain-id`를 사용하여 원하는 대로 변경할 수 있습니다. + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. 'RPC URL' 필드에서 연결하려는 대상 노드의 JSON RPC 포트를 사용하는지 확인합니다. + + +## 웹소켓 URL을 가져오는 방법 {#how-to-get-a-websocket-url} + +기본적으로 Polygon 엣지를 실행할 때는 체인 위치를 기반으로 웹소켓 엔드포인트가 노출됩니다. +HTTPS 링크에 사용되는 URL 스키마는 `wss://`, HTTP 링크의 경우 `ws://`입니다. + +Localhost 웹소켓 URL은 다음과 같습니다. +````bash +ws://:/ws +```` +포트 번호는 노드를 위해 선택한 JSON-RPC 포트에 따라 결정됩니다. + +Edgenet 웹소켓 URL은 다음과 같습니다. +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## 계약 배포 시도 시 `insufficient funds` 오류 {#error-when-trying-to-deploy-a-contract} + +이 오류가 표시되면 원하는 주소에 자금이 충분한지 그리고 사용된 주소가 정확한지 확인합니다.
+사전 채굴된 잔액을 설정하려면 제네시스 파일을 생성할 때 제네시스 플래그 `genesis [--premine ADDRESS:VALUE]`를 사용할 수 있습니다. +이 플래그를 사용한 예는 다음과 같습니다. +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +이 플래그가 1000000000000000000000WEI를 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862에 사전 채굴합니다. + + +## ChainBridge 사용 시 ERC20 토큰이 해제되지 않는 경우 {#erc20-tokens-not-released-while-using-chainbridge} + +Polygon PoS와 로컬 엣지 네트워크 간에 ERC20 토큰을 이전하려는 경우, ERC20 토큰이 입금되고 제안도 릴레이어에서 실행되지만 토큰이 엣지 네트워크에서 해제되지 않으면 Polygon 엣지 체인의 ERC20 핸들러에 해제할 토큰이 충분한지 확인하세요.
+대상 체인의 핸들러 계약에는 잠금-해제 모드를 위한 토큰이 충분해야 합니다. 로컬 엣지 네트워크의 ERC20 핸들러에 ERC20 토큰이 전혀 없으면 새 토큰을 발행하여 ERC20 핸들러로 이전하세요. + +## ChainBridge 사용 시 `Incorrect fee supplied` 오류 {#error-when-using-chainbridge} + +Mumbai Polygon PoS 체인과 로컬 Polygon 엣지 설정 간에 ERC20 토큰을 이전하려는 경우에 이 오류가 발생할 수 있습니다. `--fee` 플래그를 사용하여 배포에 대한 비용을 설정할 때 입금 트랜잭션에 동일한 값을 설정하지 않으면 이런 오류가 나타납니다. +아래 명령어를 사용하여 요금을 변경할 수 있습니다. +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +[여기에서](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md) 이 국기에 대한 자세한 정보를 확인할 수 있습니다. + + + + + diff --git a/archive/edge/ko-edge/validator-hosting.md b/archive/edge/ko-edge/validator-hosting.md new file mode 100644 index 0000000000..c7861d1ba6 --- /dev/null +++ b/archive/edge/ko-edge/validator-hosting.md @@ -0,0 +1,250 @@ +--- +id: validator-hosting +title: 검사기 호스팅 +description: "Polygon 엣지의 호스팅 요구사항" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +Polygon 엣지 네트워크에서 검사기 노드를 적절하게 호스팅하기 위한 제안 사항을 알려드립니다. 아래 나열된 모든 항목에 유의하여 검사기가 안전하고 안정적으로 성능을 발휘하도록 설정되었는지 확인하세요. + +## Knowledge Base {#knowledge-base} + +검사기 노드를 실행하기 전에 이 문서를 자세히 읽으시기 바랍니다. 아래 문서도 유용할 수 있습니다. + +- [설치](get-started/installation) +- [클라우드 설정](get-started/set-up-ibft-on-the-cloud) +- [CLI 명령어](get-started/cli-commands) +- [서버 구성 파일](configuration/sample-config) +- [비공개 키](configuration/manage-private-keys) +- [Prometheus 측정항목](configuration/prometheus-metrics) +- [보안 비밀 관리자](/docs/category/secret-managers) +- [백업/복원](working-with-node/backup-restore) + +## 최소 시스템 요구사항 {#minimum-system-requirements} + +| 유형 | 값 | 영향을 미치는 요소 | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 코어 2개 |
  • JSON-RPC 쿼리 수
  • 블록체인 상태의 크기
  • 블록 가스 한도
  • 블록 시간
| +| RAM | 2GB |
  • JSON-RPC 쿼리 수
  • 블록체인 상태의 크기
  • 블록 가스 한도
| +| 디스크 |
  • 10GB 루트 파티션
  • 30GB 루트 파티션과 디스크 확장을 위한 LVM
|
  • 블록체인 상태의 크기
| + + +## 서비스 구성 {#service-configuration} + +`polygon-edge` 바이너리는 설정된 네트워크 연결에서 시스템 서비스로 자동 실행되어야 하며 시작/중지/재시작 기능이 있어야 합니다. `systemd.`와 같은 서비스 관리자 사용을 권장합니다. + +예시 `systemd` 시스템 구성 파일: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### 바이너리 {#binary} + +프로덕션 워크로드의 경우, `polygon-edge` 바이너리는 수동 컴파일이 아닌 사전 빌드된 GitHub 릴리스 바이너리에서 배포해야 합니다. +:::info + +`develop` GitHub 분기를 수동으로 컴파일하면, 환경에 호환성을 손상하는 변경 사항이 발생할 수 있습니다. +따라서 호환성을 손상하는 변경 사항 및 해결 방법에 관한 정보가 포함된 릴리스를 통해서만 Polygon 엣지 바이너리를 배포하는 것을 권장합니다. + +::: + +설치 방법에 대한 전체 개요는 [설치](/docs/edge/get-started/installation)를 참조하세요. + +### 데이터 스토리지 {#data-storage} + +전체 블록체인 상태를 포함하는 `data/` 폴더는 자동 디스크 백업, 볼륨 확장이 가능하고 필요에 따라 장애 발생 시 해당 디스크/볼륨을 다른 인스턴스에 마운팅할 수 있도록 전용 디스크 / 볼륨에 마운트되어야 합니다. + + +### 로그 파일 {#log-files} + +로그 파일은 (`logrotate` 같은 도구를 통해) 매일 로테이션 처리되어야 합니다. +:::warning + +로그 로테이션 없이 구성되는 경우, 로그 파일은 모든 가용 디스크 공간을 차지하여 검사기 가동 시간에 지장을 줄 수 있습니다. + +::: + +예시 `logrotate` 구성: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +로그 스토리지에 대한 권장 사항은 아래 [로깅](#logging) 섹션을 참조하시기 바랍니다. + +### 추가 종속 항목 {#additional-dependencies} + +`polygon-edge`는 정적으로 컴파일되어 추가적인 호스트 OS 종속 항목이 필요하지 않습니다. + +## 유지 보수 {#maintenance} + +다음은 Polygon 엣지 네트워크에서 실행 중인 검사기 노드의 유지 보수 모범 사례입니다. + +### 백업 {#backup} + +Polygon 엣지 노드에 권장되는 두 가지 백업 절차가 있습니다. + +가능한 한 항상 두 가지 모두 사용하고, Polygon 엣지 백업은 상시 사용 가능하도록 하는 옵션을 권장합니다. + +* ***볼륨 백업***: Polygon 엣지 노드의 `data/` 볼륨, 또는 가능한 경우 전체 VM을 일일 증분 백업합니다. + + +* ***Polygon 엣지 백업***: +Polygon 엣지의 정기적인 백업을 수행하고 `.dat` 파일을 외부 위치 또는 안전한 클라우드 객체 스토리지로 이동하는 일일 크론 작업을 권장합니다. + +Polygon 엣지 백업은 위에서 설명한 볼륨 백업과 겹치지 않는 것이 이상적입니다. + +Polygon 엣지 백업 방법에 관한 지침은 [노드 인스턴스 백업/복원](working-with-node/backup-restore)을 참조하시기 바랍니다. + +### 로깅 {#logging} + +Polygon 엣지 노드에서 출력된 로그는 다음과 같아야 합니다. +- 색인 지정 및 검색 기능이 있는 외부 데이터 스토리지로 전송됩니다. +- 30일의 로그 보존 기간이 있습니다. + +Polygon 엣지 검사기를 처음 설정하는 경우, 발생할 수 있는 문제를 신속하게 디버그할 수 있도록 `--log-level=DEBUG` 옵션으로 노드를 시작할 것을 권장합니다. + +:::info + +`--log-level=DEBUG`를 사용하면 노드 로그를 최대한 자세히 출력할 수 있습니다. +디버그 로그는 로그 로테이션 솔루션을 설정할 때 고려해야 하는 로그 파일의 크기를 크게 증가시킵니다. + +::: +### OS 보안 패치 {#os-security-patches} + +관리자는 검사기 인스턴스 OS가 최신 패치를 통해 매달 1회 이상 업데이트되도록 해야 합니다. + +## 측정항목 {#metrics} + +### 시스템 측정항목 {#system-metrics} + +관리자는 시스템 측정항목 모니터링(예: Telegraf + InfluxDB + Grafana 또는 타사 SaaS)을 설정해야 합니다. + +모니터링 및 알림 설정이 필요한 측정항목 + +| 측정항목 이름 | 알림 임계값 | +|-----------------------|-------------------------------| +| CPU 사용량(%) | 5분 이상 90% 초과 | +| RAM 사용률(%) | 5분 이상 90% 초과 | +| 루트 디스크 사용률 | 90% 초과 | +| 데이터 디스크 사용률 | 90% 초과 | + +### 검사기 측정항목 {#validator-metrics} + +관리자는 블록체인 성능을 모니터링할 수 있도록 Polygon 엣지의 Prometheus API의 측정항목 모음을 설정해야 합니다. + +노출되는 측정항목과 Prometheus 측정항목 모음 설정 방법을 이해하려면 [Prometheus 측정항목](configuration/prometheus-metrics)을 참조하시기 바랍니다. + + +다음 측정항목에 특히 유의해야 합니다. +- ***블록 생성 시간*** - 블록 생성 시간이 평소보다 길면 네트워크에 잠재적인 문제가 있는 것입니다 +- ***합의 라운드 수*** - 라운드가 2회 이상인 경우, 네트워크에 설정된 검사기에 잠재적인 문제가 있는 것입니다 +- 피어 ***수*** - 피어 수가 감소하면 네트워크에 연결 문제가 있는 것입니다 + +## 보안 {#security} + +다음은 Polygon 엣지 네트워크에서 실행 중인 검사기 노드를 보호하는 모범 사례입니다. + +### API 서비스 {#api-services} + +- ***JSON-RPC*** - +(부하 분산기를 통해 또는 직접) 일반에 공개되어야 하는 API 서비스만 해당합니다. 이 API는 모든 인터페이스나 특정 IP 주소(예: `--json-rpc 0.0.0.0:8545`또는 `--json-prc 192.168.1.1:8545`)에서 실행되어야 합니다. +:::info + +일반에 공개되는 API이므로, 부하 분산기/역방향 프록시를 앞에 두어 보안 및 속도 제한을 제공하는 것이 좋습니다. + +::: + + +- ***LibP2P*** - +피어 통신을 위해 노드에서 사용하는 네트워킹 API로서, 모든 인터페이스나 특정 IP 주소 (`--libp2p 0.0.0.0:1478` 또는 `--libp2p 192.168.1.1:1478`)에서 실행되어야 합니다. 이 API는 공개적으로 노출하면 안 되지만, 다른 모든 노드를 통해 도달할 수 있습니다. +:::info + +Localhost(`--libp2p 127.0.0.1:1478`)에서 실행되는 경우에는 다른 노드가 연결할 수 없습니다. + +::: + + +- ***GRPC*** - +이 API는 연산자 명령어를 실행하고 기타 사항을 언급하기 위해서만 사용됩니다. 따라서 localhost(`--grpc-address 127.0.0.1:9632`)에서만 실행되어야 합니다. + +### Polygon 엣지 보안 비밀 {#polygon-edge-secrets} + +Polygon 엣지 보안 비밀(`ibft` 및 `libp2p` 키)는 로컬 파일 시스템에 저장하면 안 됩니다. +대신, 지원되는 [비밀 관리자](configuration/secret-managers/set-up-aws-ssm)를 사용해야 합니다. +로컬 파일 시스템에 보안 비밀을 저장하는 것은 비프로덕션 환경에서만 사용해야 합니다. + +## 업데이트 {#update} + +아래에서는 검사기 노드 업데이트 기본 절차를 단계별 지침으로 설명합니다. + +### 업데이트 절차 {#update-procedure} + +- 공식 GitHub [릴리스](https://github.com/0xPolygon/polygon-edge/releases)에서 최신 Polygon 엣지 바이너리를 다운로드합니다. +- Polygon 엣지 서비스(예: `sudo systemctl stop polygon-edge.service`)를 중지합니다. +- 기존 `polygon-edge` 바이너리를 다운로드한 바이너리(예: `sudo mv polygon-edge /usr/local/bin/`)로 교체합니다. +- `polygon-edge version`을 실행하여 올바른 `polygon-edge` 버전인지 확인합니다. 릴리스 버전과 일치해야 합니다. +- `polygon-edge` 서비스 시작 전에 수행해야 할 이전 버전과의 호환성 단계가 있는지 릴리스 문서를 확인하세요. +- `polygon-edge` 서비스(예: `sudo systemctl start polygon-edge.service`)를 시작합니다. +- 마지막으로 `polygon-edge` 로그 출력을 확인하고 모든 것이 `[ERROR]` 로그 없이 실행되고 있는지 확인합니다. + +:::warning + +호환성을 손상하는 릴리스가 있는 경우, 현재 실행 중인 바이너리가 새 릴리스와 호환되지 않으므로 이 업데이트 절차를 모든 노드에서 수행해야 합니다. + +이는 짧은 시간 동안(즉, `polygon-edge` 바이너리가 교체되고 서비스가 재시작될 때까지) 체인이 중단되어야 함을 의미하므로, 사전에 계획하시기 바랍니다. + +**[Ansible](https://www.ansible.com/)** 또는 일부 사용자 정의 스크립트와 같은 도구를 사용하여 업데이트를 효율적으로 수행하고 체인 가동 중지 시간을 최소화할 수 있습니다. + +::: + +## 시작 절차 {#startup-procedure} + +아래에서는 Polygon 엣지 검사기의 시작 절차 기본 흐름을 설명합니다. + +- [Knowledge Base](#knowledge-base) 섹션에 나열된 문서를 모두 읽으시기 바랍니다. +- 검사기 노드에 최신 OS 패치를 적용합니다. +- 공식 GitHub [릴리스](https://github.com/0xPolygon/polygon-edge/releases)에서 최신 `polygon-edge` 바이너리를 다운로드하여 로컬 인스턴스 `PATH`에 배치합니다. +- 지원되는 [비밀 관리자](/docs/category/secret-managers) 중 하나를 `polygon-edge secrets generate` CLI 명령어를 사용하여 초기화합니다. +- `polygon-edge secrets init`[CLI 명령어](/docs/edge/get-started/cli-commands#secrets-init-flags)를 사용하여 보안 비밀을 생성하고 저장합니다. +- `NodeID` 및 `Public key (address)` 값을 기록합니다. +- `polygon-edge genesis`[CLI 명령어](/docs/edge/get-started/cli-commands#genesis-flags)를 사용하여 [클라우드 설정](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators)에서 설명하는 대로 `genesis.json` 파일을 생성합니다. +- `polygon-edge server export`[CLI 명령어](/docs/edge/configuration/sample-config)를 사용하여 기본 구성 파일을 생성합니다. +- 로컬 검사기 노드 환경(파일 경로 등)을 수용하도록 `default-config.yaml` 파일을 편집합니다. +- `polygon-edge` 바이너리가 `default-config.yaml` 파일에서 서버를 실행하는 Polygon 엣지 서비스(`systemd`또는 이와 유사한 것)를 생성합니다. +- 해당 서비스(예: `systemctl start polygon-edge`)를 시작하여 Polygon 엣지 서버를 시작합니다. +- `polygon-edge` 로그 출력을 확인하고, 블록이 생성되고 있는지 그리고 `[ERROR]` 로그가 없는지 확인합니다. +- [`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid) 같은 JSON-RPC 메서드를 호출하여 체인 기능을 확인합니다. diff --git a/archive/edge/ko-edge/working-with-node/backup-restore.md b/archive/edge/ko-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..8e6f9d0b50 --- /dev/null +++ b/archive/edge/ko-edge/working-with-node/backup-restore.md @@ -0,0 +1,89 @@ +--- +id: backup-restore +title: 노드 인스턴스 백업/복원 +description: "Polygon 엣지 노드 인스턴스를 백업하고 복원하는 방법." +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## 개요 {#overview} + +이 가이드에서는 Polygon 엣지 노드 인스턴스를 백업하고 복원하는 방법에 관해 자세히 설명합니다. +기본 폴더 및 기본 폴더에 포함된 항목, 성공적인 백업 및 복원에 중요한 파일을 다룹니다. + +## 기본 폴더 {#base-folders} + +Polygon 엣지는 LevelDB를 스토리지 엔진으로 활용합니다. +Polygon 엣지 노드를 시작하면, 지정된 작업 디렉터리에 다음 하위 폴더들이 생성됩니다. +* **blockchain** - 블록체인 데이터 저장 +* **trie** - Merkle 트리 저장(월드 상태 데이터) +* **keystore** - 클라이언트의 비공개 키 저장. 여기에는 libp2p 비공개 키 및 봉인/검사기 비공개 키가 포함됩니다. +* **consensus** - 작업 중 클라이언트가 필요로 할 수 있는 합의 정보 저장. 지금은 노드의 *비공개 검사기 키*를 저장합니다. + +Polygon 엣지 인스턴스의 원활한 실행을 위해 이 폴더들을 보존하는 것이 중요합니다. + +## 실행 중인 노드에서 백업을 생성하고 새 노드에 복원하기 {#create-backup-from-a-running-node-and-restore-for-new-node} + +이 섹션에서는 실행 중인 노드에서 블록체인의 보관 데이터를 생성하고 다른 인스턴스에서 이를 복원하는 방법을 설명합니다. + +### 백업 {#backup} + +`backup` 명령어는 gRPC로 실행 중인 노드에서 블록을 가져오고 보관 파일을 생성합니다. 명령어에 `--from`과 `--to`가 지정되지 않는 경우, 이 명령어는 제네시스부터 최근 노드까지의 블록을 가져옵니다. + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### 복원 {#restore} + +`--restore` 플래그로 시작할 때 서버는 아카이브에서 블록을 가져옵니다. 새 노드의 키가 있는지 확인하세요. 키 가져오기 또는 키 생성에 관해 자세히 알아보려면, [Secret Managers 섹션](/docs/edge/configuration/secret-managers/set-up-aws-ssm)을 확인하세요. + +```bash +$ polygon-edge server --restore archive.dat +``` + +## 전체 데이터 백업/복원 {#back-up-restore-whole-data} + +이 섹션에서는 상태 데이터 및 키를 포함한 데이터를 백업하고 새 인스턴스로 복원하는 과정을 설명합니다. + +### 1단계: 실행 중인 클라이언트 중지 {#step-1-stop-the-running-client} + +Polygon 엣지는 데이터 스토리지로 **LevelDB**를 사용하므로 백업이 진행되는 동안 해당 노드를 중지시켜야 합니다. **LevelDB**가 데이터베이스 파일에 대한 동시 액세스를 허용하지 않기 때문입니다. + +또한 Polygon 엣지를 닫을 때 데이터 플러시도 진행됩니다. + +첫 단계에서는 (서비스 관리자를 통하거나 SIGINT 신호를 프로세스에 보내는 다른 메커니즘을 통해) 실행 중인 클라이언트를 중지하며, 그 결과 정상적으로 종료되는 동안 2개의 이벤트를 트리거할 수 있습니다. +* 디스크로 데이터 플러시 실행하기 +* LevelDB에 의한 DB 파일 잠금 해제 + +### 2단계: 디렉터리 백업 {#step-2-backup-the-directory} + +이제 클라이언트가 실행 중이 아니므로 데이터 디렉터리를 다른 매체에 백업할 수 있습니다. +확장자가 `.key`인 파일에는 현재 노드를 대리하는 데 사용할 수 있는 비공개 키 데이터가 포함되어 있습니다. 이를 제3자나 알려지지 않은 당사자와 절대로 공유해서는 안 됩니다. + +:::info + +생성된 `genesis` 파일을 수동으로 백업하고 복원하세요. 그래야 복원된 노드가 완전하게 작동할 수 있습니다. + +::: + +## 복원 {#restore-1} + +### 1단계: 실행 중인 클라이언트 중지 {#step-1-stop-the-running-client-1} + +Polygon 엣지의 인스턴스가 실행 중인 경우, 인스턴스를 중지해야 2단계를 성공적으로 완료할 수 있습니다. + +### 2단계: 백업된 데이터 디렉터리를 원하는 폴더에 복사하기 {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +일단 클라이언트가 실행 중이 아니면, 이전에 백업한 데이터 디렉터리를 원하는 폴더로 복사할 수 있습니다. +그리고, 이전에 복사한 `genesis` 파일을 복원합니다. + +### 3단계: 올바른 데이터 디렉터리를 지정하면서 Polygon 엣지 클라이언트 실행하기 {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +Polygon 엣지가 복원된 데이터 디렉터리를 사용하려면 시작 시 사용자가 데이터 디렉터리 경로를 지정해야 합니다. `data-dir` 플래그에 관한 정보는 [CLI 명령어](/docs/edge/get-started/cli-commands) 섹션을 참조하시기 바랍니다. diff --git a/archive/edge/ko-edge/working-with-node/query-json-rpc.md b/archive/edge/ko-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..e11db2119d --- /dev/null +++ b/archive/edge/ko-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,93 @@ +--- +id: query-json-rpc +title: JSON RPC 엔드포인트 쿼리 +description: "데이터를 쿼리하고 사전 채굴된 계정으로 체인을 시작합니다." +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## 개요 {#overview} + +Polygon 엣지의 JSON-RPC 레이어 덕분에 개발자는 HTTP 요청을 통해 블록체인과 간편하게 +상호작용할 수 있습니다. + +이 예에는 **curl**과 같은 도구를 사용해 정보 쿼리, 사전 채굴된 계정으로 체인 시작, +트랜잭션 전송에 대해 다룹니다. + +## 1단계: 사전 채굴된 계정으로 제네시스 파일 생성 {#step-1-create-a-genesis-file-with-a-premined-account} + +제네시스 파일을 생성하려면 다음의 명령어를 실행하세요. +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +**사전 채굴** 플래그는 **제네시스** 파일에 초기 잔액과 함께 포함되어야 하는 주소를 설정합니다.
+이 경우 주소 `0x1010101010101010101010101010101010101010`에는 시작 **기본 잔액** +`0xD3C21BCECCEDA1000000`이 (100만 개의 네이티브 통화 토큰). + +잔액을 지정하려는 경우에는 다음과 같이 `:`을 이용하여 잔액과 주소를 구분할 수 있습니다. +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +잔액은 `hex` 또는 `uint256` 값입니다. + +:::warning 비공개 키가 있는 사전 채굴 계정만 가능! + +사전 채굴 계정은 있지만 이에 액세스할 비공개 키가 없으면 사전 채굴된 잔액을 사용할 수 없습니다. + +::: + +## 2단계: Polygon 엣지를 개발 모드로 시작 {#step-2-start-the-polygon-edge-in-dev-mode} + +Polygon 엣지를 [CLI 명령어](/docs/edge/get-started/cli-commands) 섹션에서 설명하는 개발 모드로 시작하려면 +다음을 실행하세요. +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## 3단계: 계정 잔액 쿼리 {#step-3-query-the-account-balance} + +이제 클라이언트가 **1단계**에서 생성된 제네시스 파일 통해 개발 모드에서 실행되고 있으므로 +**curl**과 같은 도구를 사용하여 계정 잔액을 쿼리할 수 있습니다. +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +이 명령어는 다음과 같은 출력을 반환합니다. +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## 4단계: 이전 트랜잭션 전송 {#step-4-send-a-transfer-transaction} + +이제 사전 채굴로 설정한 계정에 정확한 잔액이 있음을 확인했으니 이더를 이전할 수 있습니다. + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/ko-edge/working-with-node/query-operator-info.md b/archive/edge/ko-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..40678dbe1e --- /dev/null +++ b/archive/edge/ko-edge/working-with-node/query-operator-info.md @@ -0,0 +1,85 @@ +--- +id: query-operator-info +title: 연산자 정보 쿼리하기 +description: "연산자 정보를 쿼리하는 방법." +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## 기본 요건 {#prerequisites} + +이 가이드에서는 사용자가 [로컬 설정](/docs/edge/get-started/set-up-ibft-locally) 또는 [클라우드에서 IBFT 클러스터를 설정하는 방법에 관한 가이드](/docs/edge/get-started/set-up-ibft-on-the-cloud)를 따랐다고 가정합니다. + +어떤 종류의 연산자 정보를 쿼리하든 정상적으로 작동하는 노드가 필요합니다. + +Polygon 엣지에서 노드 연산자는 연산 노드의 작업을 제어하고 이에 관한 정보를 얻습니다.
+언제든지 gRPC 기반의 노드 정보 레이어를 사용하고 의미 있는 정보를 얻을 수 있으므로 로그 전달이 필요하지 않습니다. + +:::note + +노드가 `127.0.0.1:8545`에서 실행되고 있지 않다면 이 문서에 나열된 명령어에 `--grpc-address ` 플래그를 추가해야 합니다. + +::: + +## 피어 정보 {#peer-information} + +### 피어 목록 {#peers-list} + +연결된 피어의 전체 목록(실행 중인 노드 자체 포함)을 가져오려면 다음 명령어를 실행하세요. +````bash +polygon-edge peers list +```` + +실행 중인 클라이언트의 현재 피어인 libp2p 주소 목록이 반환됩니다. + +### 피어 상태 {#peer-status} + +특정 피어의 상태를 확인하려면 다음을 실행하세요. +````bash +polygon-edge peers status --peer-id
+```` +*주소* 매개변수가 해당 피어의 libp2p 주소가 됩니다. + +## IBFT 정보 {#ibft-info} + +연산자가 IBFT 합의의 연산 노드 상태에 관해 알아야 하는 경우가 많습니다. + +Polygon 엣지에서 이 정보를 쉽게 확인할 수 있습니다. + +### 스냅샷 {#snapshots} + +다음 명령어를 실행하면 최근 스냅샷을 반환합니다. +````bash +polygon-edge ibft snapshot +```` +특정 높이(블록 번호)의 스냅샷을 쿼리하려면 연산자가 다음을 실행하면 됩니다. +````bash +polygon-edge ibft snapshot --num +```` + +### 후보 {#candidates} + +후보에 관한 최신 정보를 얻으려면 연산자가 다음을 실행하면 됩니다. +````bash +polygon-edge ibft candidates +```` +이 명령어는 아직 포함되지 않은 후보는 물론 제안된 후보의 현재 집합도 쿼리합니다. + +### 상태 {#status} + +다음 명령어는 실행 중인 IBFT 클라이언트의 현재 검사기 키를 반환합니다. +````bash +polygon-edge ibft status +```` + +## 트랜잭션 풀 {#transaction-pool} + +트랜잭션 풀의 현재 트랜잭션 수를 확인하려면 연산자가 다음을 실행하면 됩니다. +````bash +polygon-edge txpool status +```` diff --git a/docs/edge/additional-features/blockscout.md b/archive/edge/main-edge/additional-features/blockscout.md similarity index 100% rename from docs/edge/additional-features/blockscout.md rename to archive/edge/main-edge/additional-features/blockscout.md diff --git a/docs/edge/additional-features/chainbridge/definitions.md b/archive/edge/main-edge/additional-features/chainbridge/definitions.md similarity index 100% rename from docs/edge/additional-features/chainbridge/definitions.md rename to archive/edge/main-edge/additional-features/chainbridge/definitions.md diff --git a/docs/edge/additional-features/chainbridge/overview.md b/archive/edge/main-edge/additional-features/chainbridge/overview.md similarity index 100% rename from docs/edge/additional-features/chainbridge/overview.md rename to archive/edge/main-edge/additional-features/chainbridge/overview.md diff --git a/docs/edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/main-edge/additional-features/chainbridge/setup-erc20-transfer.md similarity index 100% rename from docs/edge/additional-features/chainbridge/setup-erc20-transfer.md rename to archive/edge/main-edge/additional-features/chainbridge/setup-erc20-transfer.md diff --git a/docs/edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/main-edge/additional-features/chainbridge/setup-erc721-transfer.md similarity index 100% rename from docs/edge/additional-features/chainbridge/setup-erc721-transfer.md rename to archive/edge/main-edge/additional-features/chainbridge/setup-erc721-transfer.md diff --git a/docs/edge/additional-features/chainbridge/setup.md b/archive/edge/main-edge/additional-features/chainbridge/setup.md similarity index 100% rename from docs/edge/additional-features/chainbridge/setup.md rename to archive/edge/main-edge/additional-features/chainbridge/setup.md diff --git a/docs/edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/main-edge/additional-features/chainbridge/use-case-erc20-bridge.md similarity index 100% rename from docs/edge/additional-features/chainbridge/use-case-erc20-bridge.md rename to archive/edge/main-edge/additional-features/chainbridge/use-case-erc20-bridge.md diff --git a/docs/edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/main-edge/additional-features/chainbridge/use-case-erc721-bridge.md similarity index 100% rename from docs/edge/additional-features/chainbridge/use-case-erc721-bridge.md rename to archive/edge/main-edge/additional-features/chainbridge/use-case-erc721-bridge.md diff --git a/docs/edge/additional-features/permission-contract-deployment.md b/archive/edge/main-edge/additional-features/permission-contract-deployment.md similarity index 100% rename from docs/edge/additional-features/permission-contract-deployment.md rename to archive/edge/main-edge/additional-features/permission-contract-deployment.md diff --git a/docs/edge/additional-features/predeployment.md b/archive/edge/main-edge/additional-features/predeployment.md similarity index 100% rename from docs/edge/additional-features/predeployment.md rename to archive/edge/main-edge/additional-features/predeployment.md diff --git a/archive/edge/main-edge/api/json-rpc-debug.md b/archive/edge/main-edge/api/json-rpc-debug.md new file mode 100644 index 0000000000..be71ecc9ec --- /dev/null +++ b/archive/edge/main-edge/api/json-rpc-debug.md @@ -0,0 +1,215 @@ +--- +id: json-rpc-debug +title: Debug +description: "List of Debug JSON RPC commands for Polygon Edge." +keywords: + - docs + - polygon + - edge + - json + - rpc + - commands +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import {useState} from 'react'; + +export const JsonRpcTerminal = (props) => { + const [value, setValue] = useState(""); + const { method, params, network } = props; + return ( +
+
+ {value != "" ?
{value}
: null} +
+
+ {value == "" ? ( + + ) : ( + + )} +
+
+ ); +}; + +## debug_traceBlockByNumber + +Executes all transactions in the block specified by number with a tracer and returns the tracing result. + +--- + +

Parameters:

+ +* QUANTITY|TAG - integer of a block number, or the string "latest" +* Object - The tracer options: + + + enableMemory: Boolean - (optional, default: false) The flag indicating enabling memory capture. + + disableStack: Boolean - (optional, default: false) The flag indicating disabling stack capture. + + disableStorage: Boolean - (optional, default: false) The flag indicating disabling storage capture. + + enableReturnData: Boolean - (optional, default: false) The flag indicating enabling return data capture. + + timeOut: String - (optional, default: "5s") The timeout for cancellation of execution. + +

Returns:

+ Array - Array of trace objects with the following fields: + + * failed: Boolean - the tx is successful or not + * gas: QUANTITY - the total consumed gas in the tx + * returnValue: DATA - the return value of the executed contract call + * structLogs: Array - the trace result of each step with the following fields: + + + pc: QUANTITY - the current index in bytecode + + op: String - the name of current executing operation + + gas: QUANTITY - the available gas ßin the execution + + gasCost: QUANTITY - the gas cost of the operation + + depth: QUANTITY - the number of levels of calling functions + + error: String - the error of the execution + + stack: Array - array of values in the current stack + + memory: Array - array of values in the current memory + + storage: Object - mapping of the current storage + + refund: QUANTITY - the total of current refund value + +

Example:

+ +Run the command and see live results from our testnet. + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"debug_traceBlockByNumber","params":["latest"],"id":1}' +```` + + + +## debug_traceBlockByHash + +Executes all transactions in the block specified by block hash with a tracer and returns the tracing result. + +--- + +

Parameters:

+ +* DATA , 32 Bytes - Hash of a block. +* Object - The tracer options. See debug_traceBlockByNumber for more details. + +

Returns:

+ Array - Array of trace objects. See debug_traceBlockByNumber for more details. + +

Example:

+ +Run the command and see live results from our testnet. + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"debug_traceBlockByHash","params":["0xdc0818cf78f21a8e70579cb46a43643f78291264dda342ae31049421c82d21ae"],"id":1}' +```` + + + +## debug_traceBlock + +Executes all transactions in the block given from the first argument with a tracer and returns the tracing result. + +--- + +

Parameters:

+ +* DATA - RLP Encoded block bytes +* Object - The tracer options. See debug_traceBlockByNumber for more details. + +

Returns:

+ Array - Array of trace objects. See debug_traceBlockByNumber for more details. + +

Example:

+ +Run the command and see live results from our testnet. + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"debug_traceBlock","params":["0xf9....",{}],"id":1}' +```` + + + +## debug_traceTransaction + +Executes the transaction specified by transaction hash with a tracer and returns the tracing result. + +--- + +

Parameters:

+ +* DATA , 32 Bytes - Hash of a transaction. +* Object - The tracer options. See debug_traceBlockByNumber for more details. + +

Returns:

+ Object - Trace object. See debug_traceBlockByNumber for more details. + +

Example:

+ +Run the command and see live results from our testnet. + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"debug_traceTransaction","params":["0xdc0818cf78f21a8e70579cb46a43643f78291264dda342ae31049421c82d21ae"],"id":1}' +```` + + + +## debug_traceCall + +Executes a new message call with a tracer and returns the tracing result. + +--- + +

Parameters:

+ +* Object - The transaction call object + + + from: DATA, 20 Bytes - (optional) The address the transaction is sent from. + + to: DATA, 20 Bytes - The address the transaction is directed to. + + gas: QUANTITY - (optional) Integer of the gas provided for the transaction execution. eth_call consumes zero gas, but this parameter may be needed by some executions. + + gasPrice: QUANTITY - (optional) Integer of the gasPrice used for each paid gas + + value: QUANTITY - (optional) Integer of the value sent with this transaction + + data: DATA - (optional) Hash of the method signature and encoded parameters. For details see Ethereum Contract ABI in the Solidity documentation + +* QUANTITY|TAG - integer block number, or the string "latest" +* Object - The tracer options. See debug_traceBlockByNumber for more details. + +

Returns:

+ Object - Trace object. See debug_traceBlockByNumber for more details. + +

Example:

+ +Run the command and see live results from our testnet. + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"debug_traceCall","params":[{"to": "0x1234", "data": "0x1234"}, "latest", {}],"id":1}' +```` + + diff --git a/archive/edge/main-edge/api/json-rpc-eth.md b/archive/edge/main-edge/api/json-rpc-eth.md new file mode 100644 index 0000000000..29d6d825c5 --- /dev/null +++ b/archive/edge/main-edge/api/json-rpc-eth.md @@ -0,0 +1,697 @@ +--- +id: json-rpc-eth +title: Ethereum +description: "List of ETH JSON RPC commands for Polygon Edge." +keywords: + - docs + - polygon + - edge + - json + - rpc + - commands +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import {useState} from 'react'; + +export const JsonRpcTerminal = (props) => { + const [value, setValue] = useState(""); + const { method, params, network } = props; + return ( +
+
+ {value != "" ?
{value}
: null} +
+
+ {value == "" ? ( + + ) : ( + + )} +
+
+ ); +}; + +## eth_chainId + +Returns the currently configured chain id, a value used in replay-protected transaction signing as introduced by EIP-155. + +--- + +

Parameters:

+ +* None + +

Returns:

+ +* QUANTITY - big integer of the current chain id. + +

Example:

+ +Run the command and see live results from our testnet. + + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' +```` + + + +## eth_syncing + +Returns information about the sync status of the node + +--- + +

Parameters:

+ +* None + +

Returns:

+ +* Boolean (FALSE) - if the node isn't syncing (which means it has fully synced) + +* Object - an object with sync status data if the node is syncing + * startingBlock: QUANTITY - The block at which the import started (will only be reset, after the sync reached his head) + * currentBlock: QUANTITY - The current block, same as eth_blockNumber + * highestBlock: QUANTITY - The estimated highest block + +

Example:

+ +Run the command and see live results from our testnet. + + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}' +```` + + + +## eth_getBlockByNumber + +Returns block information by number. + +--- + +

Parameters:

+ +* QUANTITY|TAG - integer of a block number, or the string "latest" +* Boolean - If true it returns the full transaction objects, if false only the hashes of the transactions. + +

Returns:

+Object - A block object, or null when no block was found: + +* number: QUANTITY - the block number. +* hash: DATA, 32 Bytes - hash of the block. +* parentHash: DATA, 32 Bytes - hash of the parent block. +* nonce: DATA, 8 Bytes - hash of the generated proof-of-work. +* sha3Uncles: DATA, 32 Bytes - SHA3 of the uncles data in the block. +* logsBloom: DATA, 256 Bytes - the bloom filter for the logs of the block. +* transactionsRoot: DATA, 32 Bytes - the root of the transaction trie of the block. +* stateRoot: DATA, 32 Bytes - the root of the final state trie of the block. +* receiptsRoot: DATA, 32 Bytes - the root of the receipts trie of the block. +* miner: DATA, 20 Bytes - the address of the beneficiary to whom the mining rewards were given. +* difficulty: QUANTITY - integer of the difficulty for this block. +* totalDifficulty: QUANTITY - integer of the total difficulty of the chain until this block. +* extraData: DATA - the “extra data” field of this block. +* size: QUANTITY - integer the size of this block in bytes. +* gasLimit: QUANTITY - the maximum gas allowed in this block. +* gasUsed: QUANTITY - the total used gas by all transactions in this block. +* timestamp: QUANTITY - the unix timestamp for when the block was collated. +* transactions: Array - Array of transaction objects, or 32 Bytes transaction hashes depending on the last given parameter. +* uncles: Array - Array of uncle hashes. + +

Example:

+ +Run the command and see live results from our testnet. + + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["latest", true],"id":1}' +```` + + + +## eth_getBlockByHash + +Returns block information by hash. + +--- + +

Parameters:

+ +* DATA , 32 Bytes - Hash of a block. +* Boolean - If true it returns the full transaction objects, if false only the hashes of the transactions. + +

Returns:

+ Object - A block object, or null when no block was found: + +* number: QUANTITY - the block number. +* hash: DATA, 32 Bytes - hash of the block. +* parentHash: DATA, 32 Bytes - hash of the parent block. +* nonce: DATA, 8 Bytes - hash of the generated proof-of-work. +* sha3Uncles: DATA, 32 Bytes - SHA3 of the uncles data in the block. +* logsBloom: DATA, 256 Bytes - the bloom filter for the logs of the block. +* transactionsRoot: DATA, 32 Bytes - the root of the transaction trie of the block. +* stateRoot: DATA, 32 Bytes - the root of the final state trie of the block. +* receiptsRoot: DATA, 32 Bytes - the root of the receipts trie of the block. +* miner: DATA, 20 Bytes - the address of the beneficiary to whom the mining rewards were given. +* difficulty: QUANTITY - integer of the difficulty for this block. +* totalDifficulty: QUANTITY - integer of the total difficulty of the chain until this block. +* extraData: DATA - the “extra data” field of this block. +* size: QUANTITY - integer the size of this block in bytes. +* gasLimit: QUANTITY - the maximum gas allowed in this block. +* gasUsed: QUANTITY - the total used gas by all transactions in this block. +* timestamp: QUANTITY - the unix timestamp for when the block was collated. +* transactions: Array - Array of transaction objects, or 32 Bytes transaction hashes depending on the last given parameter. +* uncles: Array - Array of uncle hashes. + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getBlockByHash","params":["0xdc0818cf78f21a8e70579cb46a43643f78291264dda342ae31049421c82d21ae",false],"id":1}' +```` + +## eth_blockNumber + +Returns the number of the most recent block. + +--- + +

Parameters:

+ +None + +

Returns:

+ +* QUANTITY - integer of the current block number the client is on. + +

Example:

+ +Run the command and see live results from our testnet. + + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' +```` + + + +## eth_gasPrice + +Returns the current price of gas in wei. +If minimum gas price is enforced by setting the `--price-limit` flag, +this endpoint will return the value defined by this flag as minimum gas price. + +--- + +

Parameters:

+ +None + +

Returns:

+ +* QUANTITY - integer of the current gas price in wei. + +

Example:

+ +Run the command and see live results from our testnet. + + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":1}' +```` + + + +## eth_getBalance + +Returns the balance of the account of the given address. + +--- + +

Parameters:

+ +* DATA, 20 Bytes - address to check for balance. +* QUANTITY|TAG - integer block number, or the string "latest" + +

Returns:

+ +* QUANTITY - integer of the current balance in wei. + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x407d73d8a49eeb85d32cf465507dd71d507100c1", "latest"],"id":1}' +```` + +## eth_sendRawTransaction + +Creates new message call transaction or a contract creation for signed transactions. + +--- + +

Parameters:

+ +* DATA - The signed transaction data. + +

Returns:

+ +* DATA, 32 Bytes - the transaction hash, or the zero hash if the transaction is not yet available. + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_sendRawTransaction","params":["0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"],"id":1}' +```` + +## eth_getTransactionByHash + +Returns the information about a transaction requested by transaction hash. + +--- + +

Parameters:

+ +* DATA, 32 Bytes - hash of a transaction + +

Returns:

+ Object - A transaction object, or null when no transaction was found: + +* blockHash: DATA, 32 Bytes - hash of the block where this transaction was in. +* blockNumber: QUANTITY - block number where this transaction was in. +* from: DATA, 20 Bytes - address of the sender. +* gas: QUANTITY - gas provided by the sender. +* gasPrice: QUANTITY - gas price provided by the sender in Wei. +* hash: DATA, 32 Bytes - hash of the transaction. +* input: DATA - the data send along with the transaction. +* nonce: QUANTITY - the number of transactions made by the sender prior to this one. +* to: DATA, 20 Bytes - address of the receiver. null when its a contract creation transaction. +* transactionIndex: QUANTITY - integer of the transactions index position in the block. +* value: QUANTITY - value transferred in Wei. +* v: QUANTITY - ECDSA recovery id +* r: DATA, 32 Bytes - ECDSA signature r +* s: DATA, 32 Bytes - ECDSA signature s + +

Example:

+ + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getTransactionByHash","params":["0x88df016429689c079f3b2f6ad39fa052532c56795b733da78a91ebe6a713944b"],"id":1}' +```` + +## eth_getTransactionReceipt + +Returns the receipt of a transaction by transaction hash. + +Note That the receipt is not available for pending transactions. + +--- + +

Parameters:

+ +* DATA, 32 Bytes - hash of a transaction + +

Returns:

+ Object - A transaction receipt object, or null when no receipt was found: + +* transactionHash : DATA, 32 Bytes - hash of the transaction. +* transactionIndex: QUANTITY - integer of the transactions index position in the block. +* blockHash: DATA, 32 Bytes - hash of the block where this transaction was in. +* blockNumber: QUANTITY - block number where this transaction was in. +* from: DATA, 20 Bytes - address of the sender. +* to: DATA, 20 Bytes - address of the receiver. null when its a contract creation transaction. +* cumulativeGasUsed : QUANTITY - The total amount of gas used when this transaction was executed in the block. +* gasUsed : QUANTITY - The amount of gas used by this specific transaction alone. +* contractAddress : DATA, 20 Bytes - The contract address created, if the transaction was a contract creation, otherwise null. +* logs: Array - Array of log objects, which this transaction generated. +* logsBloom: DATA, 256 Bytes - Bloom filter for light clients to quickly retrieve related logs. + +It also returns either : + +* root : DATA 32 bytes - post-transaction stateroot (pre Byzantium) +* status: QUANTITY - either 1 (success) or 0 (failure) + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getTransactionReceipt","params":["0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"],"id":1}' +```` + +## eth_getTransactionCount + +Returns the number of transactions sent from an address. + +--- + +

Parameters:

+ +* DATA, 20 Bytes - address. +* QUANTITY|TAG - integer block number, or the string "latest" + +

Returns:

+ +* QUANTITY - integer of the number of transactions send from this address. + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getTransactionCount","params":["0x407d73d8a49eeb85d32cf465507dd71d507100c1","latest"],"id":1}' +```` + +## eth_getBlockTransactionCountByNumber + +Returns the number of transactions in a block matching the given block number. + +--- + +

Parameters:

+ +* QUANTITY|TAG - integer of a block number, or the string "latest" + +

Returns:

+ +* QUANTITY - integer of the number of transactions in this block. + +

Example:

+ +Run the command and see live results from our testnet. + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getBlockTransactionCountByNumber","params":["latest"],"id":1}' +```` + + + +## eth_getLogs + +Returns an array of all logs matching a given filter object. + +--- + +

Parameters:

+ Object - The filter options: + +* fromBlock: QUANTITY|TAG - (optional, default: "latest") Integer block number, or "latest" for the last mined block +* toBlock: QUANTITY|TAG - (optional, default: "latest") Integer block number, or "latest" for the last mined block +* address: DATA|Array, 20 Bytes - (optional) Contract address or a list of addresses from which logs should originate. +* topics: Array of DATA - (optional) Array of 32 Bytes DATA topics. Topics are order-dependent. Each topic can also be an array of DATA with “or” options. +* blockhash: DATA, 32 Bytes - (optional, future) With the addition of EIP-234, blockHash will be a new filter option which restricts the logs returned to the single block with the 32-byte hash blockHash. Using blockHash is equivalent to fromBlock = toBlock = the block number with hash blockHash. If blockHash is present in the filter criteria, then neither fromBlock nor toBlock is allowed. + +

Returns:

+ +* QUANTITY - integer of the number of transactions send from this address. + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getLogs","params":[{"topics": ["0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b"]}],"id":1}' +```` + +## eth_getCode + +Returns code at a given address. + +--- + +

Parameters:

+ +* DATA, 20 Bytes - address +* QUANTITY|TAG - integer block number, or the string "latest" + +

Returns:

+ +* DATA - the code from the given address. + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getCode","params":["0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b", "0x2"],"id":1}' +```` + +## eth_call + +Executes a new message call immediately without creating a transaction on the blockchain. + +--- + +

Parameters:

+ Object - The transaction call object + +* from: DATA, 20 Bytes - (optional) The address the transaction is sent from. +* to: DATA, 20 Bytes - The address the transaction is directed to. +* gas: QUANTITY - (optional) Integer of the gas provided for the transaction execution. eth_call consumes zero gas, but this parameter may be needed by some executions. +* gasPrice: QUANTITY - (optional) Integer of the gasPrice used for each paid gas +* value: QUANTITY - (optional) Integer of the value sent with this transaction +* data: DATA - (optional) Hash of the method signature and encoded parameters. For details see Ethereum Contract ABI in the Solidity documentation +* QUANTITY|TAG - integer block number, or the string "latest", see the default block paramete + +

Returns:

+ +* DATA - the return value of executed contract. + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_call","params":[{see above}],"id":1}' +```` + +## eth_getStorageAt + +Returns the value from a storage position at a given address. + +--- + +

Parameters:

+ +* DATA, 20 Bytes - address of the storage. +* QUANTITY - integer of the position in the storage. +* QUANTITY|TAG - integer block number, or the string "latest" + +

Returns:

+ +* DATA - the value at this storage position. + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getStorageAt","params":["0x295a70b2de5e3953354a6a8344e616ed314d7251", "0x0", "latest"],"id":1}' +```` + +## eth_estimateGas + +Generates and returns an estimate of how much gas is necessary to allow the transaction to complete. The transaction will not be added to the blockchain. Note that the estimate may be significantly more than the amount of gas actually used by the transaction, for a variety of reasons including EVM mechanics and node performance. + +--- + +

Parameters:

+ +Expect that all properties are optional. + + Object - The transaction call object + +* from: DATA, 20 Bytes - The address the transaction is sent from. +* to: DATA, 20 Bytes - The address the transaction is directed to. +* gas: QUANTITY - Integer of the gas provided for the transaction execution. eth_call consumes zero gas, but this parameter may be needed by some executions. +* gasPrice: QUANTITY - Integer of the gasPrice used for each paid gas +* value: QUANTITY - Integer of the value sent with this transaction +* data: DATA - Hash of the method signature and encoded parameters. For details see Ethereum Contract ABI in the Solidity documentation +* QUANTITY|TAG - integer block number, or the string "latest", see the default block paramete + +

Returns:

+ +* QUANTITY - the amount of gas used. + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_estimateGas","params":[{see above}],"id":1}' +```` + +## eth_newFilter + +Creates a filter object, based on filter options. +To get all matching logs for specific filter, call eth_getFilterLogs. +To check if the state has changed, call eth_getFilterChanges. + +--- + +

Parameters:

+ Object - The filter options: + +* fromBlock: QUANTITY|TAG - (optional, default: "latest") Integer block number, or "latest" for the last mined block +* toBlock: QUANTITY|TAG - (optional, default: "latest") Integer block number, or "latest" for the last mined block +* address: DATA|Array, 20 Bytes - (optional) Contract address or a list of addresses from which logs should originate. +* topics: Array of DATA - (optional) Array of 32 Bytes DATA topics. Topics are order-dependent. Each topic can also be an array of DATA with “or” options. + +

Returns:

+ +* QUANTITY - A filter id. + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_newFilter","params":[{"topics":["0x12341234"]}],"id":1}' +```` + +## eth_newBlockFilter + +Creates a filter in the node, to notify when a new block arrives. +To check if the state has changed, call eth_getFilterChanges. + +--- + +

Parameters:

+ +None + +

Returns:

+ +1. QUANTITY - A filter id. + +

Example:

+ +Run the command and see live results from our testnet. + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_newBlockFilter","params":[],"id":1}' +```` + + + +## eth_getFilterLogs + +Returns an array of all logs matching filter with given id. + +:::caution eth_getLogs vs. eth_getFilterLogs +These 2 methods will return the same results for same filter options: +1. eth_getLogs with params [options] +2. eth_newFilter with params [options], getting a [filterId] back, then calling eth_getFilterLogs with [filterId] +::: + +

Parameters:

+ +* QUANTITY - the filter id. + +

Returns:

+ Array - Array of log objects, or an empty array + +* For filters created with eth_newFilter logs are objects with the following params: + * removed: TAG - true when the log was removed, due to a chain reorganization. false if its a valid log. + * logIndex: QUANTITY - integer of the log index position in the block. null when its pending log. + * transactionIndex: QUANTITY - integer of the transactions index position log was created from. null when its pending log. + * transactionHash: DATA, 32 Bytes - hash of the transactions this log was created from. null when its pending log. + * blockHash: DATA, 32 Bytes - hash of the block where this log was in. null when its pending log. + * blockNumber: QUANTITY - the block number where this log was in. null when its pending log. + * address: DATA, 20 Bytes - address from which this log originated. + * data: DATA - contains one or more 32 Bytes non-indexed arguments of the log. + * topics: Array of DATA - Array of 0 to 4 32 Bytes DATA of indexed log arguments. (In solidity: The first topic is the hash of the signature of the event (e.g. Deposit(address,bytes32,uint256)), except you declared the event with the anonymous specifier.) + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getFilterLogs","params":["0x16"],"id":1}' +```` + +## eth_getFilterChanges + +Polling method for a filter, which returns an array of logs that occurred since the last poll. + +--- + +

Parameters:

+ +* QUANTITY - the filter id. + +

Returns:

+ Array - Array of log objects, or an empty array if nothing has changed since last poll. + +* For filters created with eth_newBlockFilter the return are block hashes (DATA, 32 Bytes), e.g. ["0x3454645634534..."]. +* For filters created with eth_newFilter logs are objects with the following params: + * removed: TAG - true when the log was removed, due to a chain reorganization. false if its a valid log. + * logIndex: QUANTITY - integer of the log index position in the block. null when its pending log. + * transactionIndex: QUANTITY - integer of the transactions index position log was created from. null when its pending log. + * transactionHash: DATA, 32 Bytes - hash of the transactions this log was created from. null when its pending log. + * blockHash: DATA, 32 Bytes - hash of the block where this log was in. null when its pending log. + * blockNumber: QUANTITY - the block number where this log was in. null when its pending log. + * address: DATA, 20 Bytes - address from which this log originated. + * data: DATA - contains one or more 32 Bytes non-indexed arguments of the log. + * topics: Array of DATA - Array of 0 to 4 32 Bytes DATA of indexed log arguments. (In solidity: The first topic is the hash of the signature of the event (e.g. Deposit(address,bytes32,uint256)), except you declared the event with the anonymous specifier.) + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getFilterChanges","params":["0x16"],"id":1}' +```` + +## eth_uninstallFilter + +Uninstalls a filter with a given id. Should always be called when a watch is no longer needed. +Additionally, filters timeout when they aren’t requested with eth_getFilterChanges for some time. + +--- + +

Parameters:

+ +* QUANTITY - The filter id. + +

Returns:

+ +* Boolean - true if the filter was successfully uninstalled, otherwise false. + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_uninstallFilter","params":["0xb"],"id":1}' +```` + +## eth_unsubscribe + +Subscriptions are cancelled with a regular RPC call with eth_unsubscribe as a method and the subscription id as the first parameter. It returns a bool indicating if the subscription was cancelled successfully. + +--- + +

Parameters:

+ +* SUBSCRIPTION ID + +

Returns:

+ +* UNSUBSCRIBED FLAG - true if the subscription was cancelled successful. + +

Example:

+ +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_unsubscribe","params":["0x9cef478923ff08bf67fde6c64013158d"],"id":1}' +```` diff --git a/archive/edge/main-edge/api/json-rpc-net.md b/archive/edge/main-edge/api/json-rpc-net.md new file mode 100644 index 0000000000..ca1d443978 --- /dev/null +++ b/archive/edge/main-edge/api/json-rpc-net.md @@ -0,0 +1,139 @@ +--- +id: json-rpc-net +title: Net +description: "List of Net JSON RPC commands for Polygon Edge." +keywords: + - docs + - polygon + - edge + - json + - rpc + - commands +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import {useState} from 'react'; + +export const JsonRpcTerminal = (props) => { + const [value, setValue] = useState(""); + const { method, params, network } = props; + return ( +
+
+ {value != "" ?
{value}
: null} +
+
+ {value == "" ? ( + + ) : ( + + )} +
+
+ ); +}; + +## net_version + +Returns the current network id. + +--- + +

Parameters:

+ +None + +

Returns:

+ +* String - The current network id. + +

Example:

+ +Run the command and see live results from our testnet. + + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"net_version","params":[],"id":83}' +```` + + + +## net_listening + +Returns true if a client is actively listening for network connections. + +--- + +

Parameters:

+ +None + +

Returns:

+ +* Boolean - true when listening, otherwise false. + +

Example:

+ +Run the command and see live results from our testnet. + + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"net_listening","params":[],"id":83}' +```` + + + +## net_peerCount + +Returns number of peers currently connected to the client. + +--- + +

Parameters:

+ +None + +

Returns:

+ +* QUANTITY - integer of the number of connected peers. + +

Example:

+ +Run the command and see live results from our testnet. + + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"net_peerCount","params":[],"id":1}' +```` + + diff --git a/archive/edge/main-edge/api/json-rpc-txpool.md b/archive/edge/main-edge/api/json-rpc-txpool.md new file mode 100644 index 0000000000..5898f59d7e --- /dev/null +++ b/archive/edge/main-edge/api/json-rpc-txpool.md @@ -0,0 +1,129 @@ +--- +id: json-rpc-txpool +title: TxPool +description: "List of TxPool JSON RPC commands for Polygon Edge." +keywords: + - docs + - polygon + - edge + - json + - rpc + - commands +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import {useState} from 'react'; + +export const JsonRpcTerminal = (props) => { + const [value, setValue] = useState(""); + const { method, params, network } = props; + return ( +
+
+ {value != "" ?
{value}
: null} +
+
+ {value == "" ? ( + + ) : ( + + )} +
+
+ ); +}; + +## txpool_content + +Returns a list with the exact details of all the transactions currently pending for inclusion in the next block(s), as well as the ones that are being scheduled for future execution only. + +--- + +

Parameters:

+ +None + + +

Example:

+ +Run the command and see live results from our testnet. + + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"txpool_content","params":[],"id":1}' +```` + + + +## txpool_inspect + +Returns a list with a textual summary of all the transactions currently pending for inclusion in the next block(s), as well as the ones that are being scheduled for future execution only. This is a method specifically tailored to developers to quickly see the transactions in the pool and find any potential issues. + +--- + +

Parameters:

+ +None + + +

Example:

+ +Run the command and see live results from our testnet. + + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"txpool_inspect","params":[],"id":1}' +```` + + + +## txpool_status + +Returns the number of transactions currently pending for inclusion in the next block(s), as well as the ones that are being scheduled for future execution only. + +--- + +

Parameters:

+ +None + +

Example:

+ +Run the command and see live results from our testnet. + + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"txpool_status","params":[],"id":1}' +```` + + diff --git a/archive/edge/main-edge/api/json-rpc-web3.md b/archive/edge/main-edge/api/json-rpc-web3.md new file mode 100644 index 0000000000..ae0b9ae8b4 --- /dev/null +++ b/archive/edge/main-edge/api/json-rpc-web3.md @@ -0,0 +1,114 @@ +--- +id: json-rpc-web3 +title: Web3 +description: "List of Web3 JSON RPC commands for Polygon Edge." +keywords: + - docs + - polygon + - edge + - json + - rpc + - commands +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import {useState} from 'react'; + +export const JsonRpcTerminal = (props) => { + const [value, setValue] = useState(""); + const { method, params, network } = props; + return ( +
+
+ {value != "" ?
{value}
: null} +
+
+ {value == "" ? ( + + ) : ( + + )} +
+
+ ); +}; + +## web3_clientVersion + +Returns the current client version. + +--- + +

Parameters:

+ +None + +

Returns:

+ +* String - The current client version + +

Example:

+ +Run the command and see live results from our testnet. + + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":1}' +```` + + + +## web3_sha3 + +Returns Keccak-256 (not the standardized SHA3-256) of the given data. + +--- + +

Parameters:

+ +* DATA - the data to convert into a SHA3 hash + +

Returns:

+ +* DATA - The SHA3 result of the given string. + +

Example:

+ +Run the command and see live results from our testnet. + + +````bash +curl https://rpc.poa.psdk.io:8545 -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"web3_sha3","params":["0x68656c6c6f20776f726c64"],"id":1}' +```` + + diff --git a/docs/edge/architecture/modules/blockchain.md b/archive/edge/main-edge/architecture/modules/blockchain.md similarity index 100% rename from docs/edge/architecture/modules/blockchain.md rename to archive/edge/main-edge/architecture/modules/blockchain.md diff --git a/docs/edge/architecture/modules/consensus.md b/archive/edge/main-edge/architecture/modules/consensus.md similarity index 100% rename from docs/edge/architecture/modules/consensus.md rename to archive/edge/main-edge/architecture/modules/consensus.md diff --git a/docs/edge/architecture/modules/json-rpc.md b/archive/edge/main-edge/architecture/modules/json-rpc.md similarity index 100% rename from docs/edge/architecture/modules/json-rpc.md rename to archive/edge/main-edge/architecture/modules/json-rpc.md diff --git a/docs/edge/architecture/modules/minimal.md b/archive/edge/main-edge/architecture/modules/minimal.md similarity index 100% rename from docs/edge/architecture/modules/minimal.md rename to archive/edge/main-edge/architecture/modules/minimal.md diff --git a/docs/edge/architecture/modules/networking.md b/archive/edge/main-edge/architecture/modules/networking.md similarity index 100% rename from docs/edge/architecture/modules/networking.md rename to archive/edge/main-edge/architecture/modules/networking.md diff --git a/docs/edge/architecture/modules/other-modules.md b/archive/edge/main-edge/architecture/modules/other-modules.md similarity index 100% rename from docs/edge/architecture/modules/other-modules.md rename to archive/edge/main-edge/architecture/modules/other-modules.md diff --git a/docs/edge/architecture/modules/sealer.md b/archive/edge/main-edge/architecture/modules/sealer.md similarity index 100% rename from docs/edge/architecture/modules/sealer.md rename to archive/edge/main-edge/architecture/modules/sealer.md diff --git a/docs/edge/architecture/modules/state.md b/archive/edge/main-edge/architecture/modules/state.md similarity index 100% rename from docs/edge/architecture/modules/state.md rename to archive/edge/main-edge/architecture/modules/state.md diff --git a/docs/edge/architecture/modules/storage.md b/archive/edge/main-edge/architecture/modules/storage.md similarity index 100% rename from docs/edge/architecture/modules/storage.md rename to archive/edge/main-edge/architecture/modules/storage.md diff --git a/archive/edge/main-edge/architecture/modules/syncer.md b/archive/edge/main-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..d61cf869eb --- /dev/null +++ b/archive/edge/main-edge/architecture/modules/syncer.md @@ -0,0 +1,64 @@ +--- +id: syncer +title: Syncer +description: Explanation for the syncer module of Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## Overview + +This module contains the logic for the synchronization protocol. It is used for syncing a new node with the running network, or validating/inserting new blocks for the nodes which do not participate in the consensus (non-validators). + +The Polygon Edge uses **libp2p** as the networking layer, and on top of that runs **gRPC**. + +There are essentially 2 sync types in Polygon Edge: +* Bulk Sync - sync a large range of blocks at a time +* Watch Sync - sync on a per-block basis + +### Bulk Sync + +The steps for Bulk Syncing are pretty straightforward to accomodate the goal of Bulk Sync - sync as many blocks as possible (available) from the other peer in order to catch up, as quickly as possible. + +This is the flow of the Bulk Sync process: + +1. ** Determine if the node needs to Bulk Sync ** - In this step, the node checks the peer map to see if there is anyone who has a bigger block number than what the node has locally +2. ** Find the best peer (using the sync peer map) ** - In this step the node finds the best peer to sync with based on the criteria mentioned in the example above. +3. ** Open a bulk sync stream ** - In this step the node opens a gRPC stream to the best peer in order to bulk sync blocks from the common block number +4. ** The best peer closes the stream when done bulk sending ** - In this step the best peer the node is syncing with will close the stream as soon as it sends all available blocks that it has +5. ** When done bulk syncing, check if the node is a validator ** - In this step, the stream is closed by the best peer, and the node needs to check if they are a validator after bulk syncing. + * If they are, they jump out of sync state and start participating in the consensus + * If they are not, they continue to ** Watch Sync ** + +### Watch Sync + +:::info +The step for Watch Syncing is only executed if the node is not a validator, but a regular non-validator node in the network that just listens for oncoming blocks. +::: + +The behavior of Watch Sync is pretty straightforward, the node is already synced up with the rest of the network and only needs to parse new blocks that are coming in. + +This is the flow of the Watch Sync process: + +1. ** Add a new block when a peer's status is updated ** - In this step the nodes listen for the new block events, when it has a new block it will run a gRPC function call, get the block and update the local state. +2. ** Check if the node is a validator after syncing the latest block ** + * If it is, jump out of sync state + * If it is not, continue listening for new block events + +## Performance report + +:::info +Performance was measured on a local machine by syncing a ** million blocks ** +::: + +| Name | Result | +|----------------------|----------------| +| Syncing 1M blocks | ~ 25 min | +| Tranfering 1M blocks | ~ 1 min | +| Number of GRPC calls | 2 | +| Test coverage | ~ 93% | diff --git a/docs/edge/architecture/modules/txpool.md b/archive/edge/main-edge/architecture/modules/txpool.md similarity index 100% rename from docs/edge/architecture/modules/txpool.md rename to archive/edge/main-edge/architecture/modules/txpool.md diff --git a/docs/edge/architecture/modules/types.md b/archive/edge/main-edge/architecture/modules/types.md similarity index 100% rename from docs/edge/architecture/modules/types.md rename to archive/edge/main-edge/architecture/modules/types.md diff --git a/archive/edge/main-edge/architecture/overview.md b/archive/edge/main-edge/architecture/overview.md new file mode 100644 index 0000000000..d4e34d264a --- /dev/null +++ b/archive/edge/main-edge/architecture/overview.md @@ -0,0 +1,62 @@ +--- +id: overview +title: Architecture Overview +sidebar_label: Overview +description: Introduction to the architecture of Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +We started with the idea of making software that is *modular*. + +This is something that is present in almost all parts of the Polygon Edge. Below, you will find a brief overview of the +built architecture and its layering. + +## Polygon Edge Layering + +![Polygon Edge Architecture](/img/edge/Architecture.jpg) + +## Libp2p + +It all starts at the base networking layer, which utilizes **libp2p**. We decided to go with this technology because it +fits into the designing philosophies of Polygon Edge. Libp2p is: + +- Modular +- Extensible +- Fast + +Most importantly, it provides a great foundation for more advanced features, which we'll cover later on. + + +## Synchronization & Consensus +The separation of the synchronization and consensus protocols allows for modularity and implementation of **custom** sync and consensus mechanisms - depending on how the client is being run. + +Polygon Edge is designed to offer off-the-shelf pluggable consensus algorithms. + +The current list of supported consensus algorithms: + +* IBFT PoA +* IBFT PoS + +## Blockchain +The Blockchain layer is the central layer that coordinates everything in the Polygon Edge system. It is covered in depth in the corresponding *Modules* section. + +## State +The State inner layer contains state transition logic. It deals with how the state changes when a new block is included. It is covered in depth in the corresponding *Modules* section. + +## JSON RPC +The JSON RPC layer is an API layer that dApp developers use to interact with the blockchain. It is covered in depth in the corresponding *Modules* section. + +## TxPool +The TxPool layer represents the transaction pool, and it is closely linked with other modules in the system, as transactions can be added from multiple entry points. + +## gRPC +gRPC, or Google Remote Procedure Call, is a robust open-source RPC framework that Google initially created to build scalable and fast APIs. +The gRPC layer is vital for operator interactions. Through it, node operators can easily interact with the client, providing an enjoyable UX. diff --git a/docs/edge/community/propose-new-feature.md b/archive/edge/main-edge/community/propose-new-feature.md similarity index 100% rename from docs/edge/community/propose-new-feature.md rename to archive/edge/main-edge/community/propose-new-feature.md diff --git a/docs/edge/community/report-bug.md b/archive/edge/main-edge/community/report-bug.md similarity index 100% rename from docs/edge/community/report-bug.md rename to archive/edge/main-edge/community/report-bug.md diff --git a/docs/edge/configuration/manage-private-keys.md b/archive/edge/main-edge/configuration/manage-private-keys.md similarity index 100% rename from docs/edge/configuration/manage-private-keys.md rename to archive/edge/main-edge/configuration/manage-private-keys.md diff --git a/archive/edge/main-edge/configuration/prometheus-metrics.md b/archive/edge/main-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..008926e36b --- /dev/null +++ b/archive/edge/main-edge/configuration/prometheus-metrics.md @@ -0,0 +1,37 @@ +--- +id: prometheus-metrics +title: Prometheus metrics +description: "How to enable Prometheus metrics for Polygon Edge." +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## Overview + +Polygon Edge can report and serve the Prometheus metrics, which in their turn can be consumed using Prometheus collector(s). + +Prometheus metrics are disabled by default. +It can be enabled by specifying the listener address using `--prometheus` [flag](/docs/edge/get-started/cli-commands#prometheus) or `Telemetry.prometheus` field in the config file. +Metrics will be served under `/metrics` on the specified address. + +## Available metrics + +The following metrics are available: + +| **Name** | **Type** | **Description** | +|-------------------------------------------------|----------|---------------------------------------------| +| edge_txpool_pending_transactions | Gauge | Number of pending transactions in TxPool | +| edge_consensus_validators | Gauge | Number of Validators | +| edge_consensus_rounds | Gauge | Number of Rounds | +| edge_consensus_num_txs | Gauge | Number of Transactions in the latest block | +| edge_consensus_block_interval | Gauge | Time between this and last block in seconds | +| edge_network_peers | Gauge | Number of Connected peers | +| edge_network_outbound_connections_count | Gauge | Number of outbound connections | +| edge_network_inbound_connections_count | Gauge | Number of inbound connections | +| edge_network_pending_inbound_connections_count | Gauge | Number of pending outbound connections | +| edge_network_pending_outbound_connections_count | Gauge | Number of pending inbound connections | +| edge_consensus_epoch_number | Gauge | Current epoch number | \ No newline at end of file diff --git a/docs/edge/configuration/sample-config.md b/archive/edge/main-edge/configuration/sample-config.md similarity index 100% rename from docs/edge/configuration/sample-config.md rename to archive/edge/main-edge/configuration/sample-config.md diff --git a/docs/edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/main-edge/configuration/secret-managers/set-up-aws-ssm.md similarity index 100% rename from docs/edge/configuration/secret-managers/set-up-aws-ssm.md rename to archive/edge/main-edge/configuration/secret-managers/set-up-aws-ssm.md diff --git a/docs/edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/main-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md similarity index 100% rename from docs/edge/configuration/secret-managers/set-up-gcp-secrets-manager.md rename to archive/edge/main-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md diff --git a/docs/edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/main-edge/configuration/secret-managers/set-up-hashicorp-vault.md similarity index 100% rename from docs/edge/configuration/secret-managers/set-up-hashicorp-vault.md rename to archive/edge/main-edge/configuration/secret-managers/set-up-hashicorp-vault.md diff --git a/archive/edge/main-edge/consensus/bls.md b/archive/edge/main-edge/consensus/bls.md new file mode 100644 index 0000000000..70593d6117 --- /dev/null +++ b/archive/edge/main-edge/consensus/bls.md @@ -0,0 +1,142 @@ +--- +id: bls +title: BLS +description: "Explanation and instructions regarding BLS mode." +keywords: + - docs + - polygon + - edge + - bls +--- + +## Overview + +BLS also known as Boneh–Lynn–Shacham (BLS)—is a cryptographic signature scheme which allows a user to verify that a signer is authentic. It is a signature scheme that can aggregate multiple signatures. In Polygon Edge, BLS is used by default in order to provide better security in the IBFT consensus mode. BLS can aggregate signatures into a single byte array and reduce the block header size. Each chain can choose whether to use BLS or not. The ECDSA key is used regardless of whether the BLS mode is enabled or not. + +## Video presentation + +[![bls - video](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## How to setup a new chain using BLS + +Refer to the [Local Setup](/docs/edge/get-started/set-up-ibft-locally) / [Cloud Setup](/docs/edge/get-started/set-up-ibft-on-the-cloud) sections for detailed setup instructions. + +## How to migrate from an existing ECDSA PoA chain to BLS PoA chain + +This section describes how to use the BLS mode in an existing PoA chain. +the following steps are required in order to enable BLS in a PoA chain. + +1. Stop all nodes +2. Generate the BLS keys for validators +3. Add a fork setting into genesis.json +4. Restart all nodes + +### 1. Stop all nodes + +Terminate all processes of the validators by pressing Ctrl + c (Control + c). Please remember the latest block height (the highest sequence number in block committed log). + +### 2. Generate the BLS key + +`secrets init` with the `--bls` generates a BLS key. In order to keep the existing ECDSA and Network key and add a new BLS key, `--ecdsa` and `--network` need to be disabled. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Add fork setting + +`ibft switch` command adds a fork setting, which enables BLS in the existing chain, into `genesis.json`. + +For PoA networks, validators need to be given in the command. As with the way of `genesis` command, `--ibft-validators-prefix-path` or `--ibft-validator` flags can be used to specify the validator. + +Specify the height from which the chain starts using BLS with the `--from` flag. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. Restart all nodes + +Restart all nodes by `server` command. After the block at the `from` specified in the previous step is created, the chain enables the BLS and shows logs as below: + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +Also the logs shows which verification mode is used to generate each block after the block is created. + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## How to migrate from an existing ECDSA PoS chain to a BLS PoS chain + +This section describes how to use the BLS mode in an existing PoS chain. +The following steps are required in order to enable BLS in the PoS chain. + +1. Stop all nodes +2. Generate the BLS keys for validators +3. Add a fork setting into genesis.json +4. Call the staking contract to register BLS Public Key +5. Restart all nodes + +### 1. Stop all nodes + +Terminate all processes of the validators by pressing Ctrl + c (Control + c). Please remember the latest block height (the highest sequence number in block committed log). + +### 2. Generate the BLS key + +`secrets init` with the `--bls` flag generates the BLS key. In order to keep existing ECDSA and Network key and add a new BLS key, `--ecdsa` and `--network` need to be disabled. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Add fork setting + +`ibft switch` command adds a fork setting, which enables BLS from the middle of the chain, into `genesis.json`. + +Specify the height from which the chain starts using the BLS mode with the `from` flag, and the height at which the contract is updated with the `development` flag. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. Register BLS Public Key in staking contract + +After the fork is added and validators are restarted, each validator needs to call `registerBLSPublicKey` in the staking contract to register the BLS Public Key. This must be done after the height specified in `--deployment` before the height specified in `--from`. + +The script to register BLS Public Key is defined in [Staking Smart Contract repo](https://github.com/0xPolygon/staking-contracts). + +Set `BLS_PUBLIC_KEY` to be registered into `.env` file. Refer [pos-stake-unstake](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) for more details about other parameters. + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +The following command registers the BLS Public Key given in `.env` to the contract. + +```bash +npm run register-blskey +``` + +:::warning Validators need to register the BLS Public Key manually +In BLS mode, validators must have their own address and the BLS public key. The consensus layer ignores the validators that have not registered BLS public key in the contract when the consensus fetches validator info from the contract. +::: + +### 5. Restart all nodes + +Restart all nodes by `server` command. The chain enables the BLS after the block at the `from` specified in the previous step is created. diff --git a/archive/edge/main-edge/consensus/migration-to-pos.md b/archive/edge/main-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..020f171444 --- /dev/null +++ b/archive/edge/main-edge/consensus/migration-to-pos.md @@ -0,0 +1,40 @@ +--- +id: migration-to-pos +title: Migration from PoA to PoS +description: "How to migrate from PoA to PoS IBFT mode, and vice versa." +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## Overview + +This section guides you through the migration from PoA to PoS IBFT modes, and vice versa, for a running cluster - without the need to reset the blockchain. + +## How to migrate to PoS + +You will need to stop all nodes, add fork configuration into genesis.json by `ibft switch` command, and restart the nodes. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution Switching while using ECDSA +When using ECDSA, the `--ibft-validator-type` flag must be added to the switch, mentioning that ECDSA is used. If not included, Edge will automatically switch to BLS. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +::: +To switch to PoS, you will need to specify 2 block heights: `deployment` and `from`. `deployment` is the height to deploy the staking contract and `from` is the height of beginning of PoS. The staking contract will be deployed at the address `0x0000000000000000000000000000000000001001` at the `deployment`, like as the case of pre-deployed contract. + +Please check [Proof of Stake](/docs/edge/consensus/pos-concepts) for more details about Staking contract. + +:::warning Validators need to stake manually +Each validator needs to stake after contract is deployed at `deployment` and before `from` in order to be a validator at the beginning of PoS. Each validator will update own validator set by the set in the staking contract at the beginning of PoS. + +To find out more about Staking, visit the **[Set up and use Proof of Stake ](/docs/edge/consensus/pos-stake-unstake)**. +::: diff --git a/archive/edge/main-edge/consensus/poa.md b/archive/edge/main-edge/consensus/poa.md new file mode 100644 index 0000000000..26aa6fc830 --- /dev/null +++ b/archive/edge/main-edge/consensus/poa.md @@ -0,0 +1,104 @@ +--- +id: poa +title: Proof of Authority (PoA) +description: "Explanation and instructions regarding Proof of Autority." +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## Overview + +The IBFT PoA is the default consensus mechanism in the Polygon Edge. In PoA, validators are the ones responsible for creating the blocks and adding them to the blockchain in a series. + +All of the validators make up a dynamic validator-set, where validators can be added to or removed from the set by employing a voting mechanism. This means that validators can be voted in/out from the validators-set if the majority (51%) of the validator nodes vote to add/drop a certain validator to/from the set. In this way, malicious validators can be recognized and removed from the network, while new trusted validators can be added to the network. + +All of the validators take turns in proposing the next block (round-robin), and for the block to be validated/inserted in the blockchain, a supermajority (more than 2/3) of the validators must approve the said block. + +Besides validators, there are non-validators who do not participate in the block creation but do participate in the block validation process. + +## Adding a validator to the validator-set + +This guide describes how to add a new validator node to an active IBFT network with 4 validator nodes. +If you need help setting up the network refer to the [Local Setup](/edge/get-started/set-up-ibft-locally.md) / [Cloud Setup](/edge/get-started/set-up-ibft-on-the-cloud.md) sections. + +### Step 1: Initialize data folders for IBFT and generate validator keys​ for the new node + +In order to get up and running with IBFT on the new node, you first need to initialize the data folders and generate the keys: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +This command will print the validator key (address) and the node ID. You will need the validator key (address) for the next step. + +### Step 2: Propose a new candidate from other validator nodes + +For a new node to become a validator at least 51% of validators need to propose him. + +Example of how to propose a new validator (`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`) from the existing validator node on grpc address: 127.0.0.1:10000: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +The structure of the IBFT commands is covered in the [CLI Commands](/docs/edge/get-started/cli-commands) section. + +:::info BLS public key +BLS public key is only necessary if the network is running with the BLS, for the network not running in BLS mode `--bls` is unnecessary +::: + +### Step 3: Run the client node + +Because in this example we are attempting to run the network where all nodes are on the same machine, we need to take care to avoid port conflicts. + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +After fetching all blocks, inside your console you will notice that a new node is participating in the validation + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info Promoting a non-validator to a validator +Naturally, a non-validator can become a validator by the voting process, but for it to be successfully included in the validator-set after the voting process, the node has to be restarted with the `--seal` flag. +::: + +## Removing a validator from the validator-set + +This operation is fairly simple. To remove a validator node from the validator-set, this command needs to be performed for the majority of the validator nodes. + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info BLS public key +BLS public key is only necessary if the network is running with the BLS, for the network not running in BLS mode `--bls` is unnecessary +::: + +After the commands are performed, observe that the number of validators has dropped (in this log example from 4 to 3). + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/main-edge/consensus/polybft.md b/archive/edge/main-edge/consensus/polybft.md new file mode 100644 index 0000000000..ebcb088605 --- /dev/null +++ b/archive/edge/main-edge/consensus/polybft.md @@ -0,0 +1,240 @@ +--- +id: polybft +title: PolyBFT +description: "Explanation about PolyBFT, the consensus mechanism for Polygon Edge." +keywords: + - docs + - polygon + - edge + - consensus + - polybft + - pos +--- + +:::caution + +All the client-based documentation is being revamped due to the new +client updates to Polygon Edge and is subject to change. Please stay +tuned! + +Please also feel free to raise an issue or pull request if you have any +queries or suggestions. + +::: + +## Overview + +PolyBFT is the consensus mechanism of Polygon Edge. It is composed of two +core parts, a consensus engine and a consensus protocol. + + + +```plaintext + +----------------------------+ + | PolyBFT | + | Consensus | + +----------------------------+ + | + | + -------------------------------- + | | + | | + +--------------------------+ +--------------------------+ + | IBFT | | Core | + | Consensus | | Smart | + | Engine | | Contracts | + +--------------------------+ +--------------------------+ +``` + +PolyBFT uses an adaptation of PBFT (Practical Byzantine Fault Tolerance) consensus, +known as IBFT (Istanbul Byzantine Fault Tolerance), in combination with the Tendermint-based +re-locking mechanism. + +> Recall that a Byzantine Fault Tolerance network is a +> network that is resilient enough to function correctly +> even if some nodes are dishonest or malicious. +> A PBFT implementation, which IBFT is one of, +> can tolerate up to *f* faulty nodes in a +> network of 3f + 1 nodes. The network remains fault tolerant so long as two-thirds of +> nodes are honest. This is sometimes referred to as a “super-majority rules” algorithm. + +Each PolyBFT node maintains a local copy of the blockchain. The PolyBFT blockchain can be modeled +as a list of blocks, like the Ethereum blockchain. The height of a block is defined as the number +of parent links that separate the block from the genesis block, with height 0. The protocol runs +sequential instances of a block finalization protocol, where the objective of the h-th instance is +to decide which Ethereum block is to be added at height `h` of the blockchain. In PolyBFT, the height +is referred to as the *sequence*. + +## Consensus Engine: IBFT + +Specifically, Polygon Edge uses [IBFT 2.0](https://github.com/0xPolygon/go-ibft) as a consensus +engine to seal blocks. + +IBFT includes a validator pool (or set) responsible for validating candidate blocks proposed +by a randomly selected block proposer who is part of the validator pool. The proposer is responsible +for constructing a block at the block interval. The proposer mechanism is based on Tendermint, where +a proposer is chosen based a deterministic selection algorithm. The frequency in selection is also +proportional to the voting power of the validator. + + > The amount of voting power a validator has is proportional to the amount of stake that they have locked + > up on the network. This means that validators with more stake will have more voting power and, therefore, + > more influence over the decision-making process on the network. + +Each block in IBFT requires multiple rounds of voting +by the validator to arrive at consensus, which is recorded as a collection of signatures on the block +content. A super-majority of validators must validate the block to be added to the blockchain. + +:::note + +The validator selection algorithm still needs to be determined. It will resemble the diagram, +where x, y, z are input parameters related to the selection, the "Round #" is the current +Round Number of the system, and "validator n" is the selected validator. + + + +```plaintext + __________ __________ __________ __________ + | | | | | | | | + | x | | y | | z | | Round # | + |__________| |__________| |__________| |__________| + | | | | + | | | | + | | | | + _______________________________________________________________________ + | | + | validator proposer selection algorithm | + |_______________________________________________________________________| + | + | + _______________________ + | | + | validator n | + |_______________________| +``` + +::: + +### Benefits of IBFT + +- **Immediate block finality**: Only one block is proposed at a given chain height. Thus, the + single chain removes forking, + uncle blocks, and the risk that a transaction may be “undone” once on the chain later. +- **The reduced time between blocks**: The effort needed to construct and validate blocks is + decreased significantly and increases the chain's throughput. +- **High data integrity and fault tolerance**: IBFT uses a pool of validators to ensure the + integrity of each proposed block. A super-majority (~66%) of these validators are required to + sign the block before insertion to the chain, making block forgery very difficult. Also, the + proposer of the pool rotates over time — ensuring a faulty node cannot exert long-term influence + over the chain. +- **Operationally flexible**: The validators can be modified in time, ensuring the group contains + only full-trusted nodes. + +## Tendermint-based re-locking mechanism + +It has been proved that IBFT does not guarantee Byzantine-fault-tolerant persistence nor liveness +when operating on an eventually synchronous network. As a result, PolyBFT uses a +[re-locking mechanism inspired by Tendermint](https://docs.tendermint.com/v0.34/introduction/what-is-tendermint.html). + +When a validator proposes a new block, their stake is locked up for a predetermined time. This +helps to ensure that the validator cannot create conflicting transactions during this time since any such +attempts would result in losing their locked stake. After the lockup period has expired, the validator's +stake is "re-locked" for another predetermined time. This helps prevent the validator from attempting to +create additional conflicting transactions after the proposed first block. The re-locking mechanism helps +to ensure the safety and integrity of the network by aligning the incentives of validators with the network's +best interests. + +### Benefits + +- **Liveness**: It has been proven that IBFT does not guarantee BFT persistence nor liveness + when operating on a synchronous network. If a validator receives enough confirmation about a block, + it can lock the proposed block (assuming it has not locked any prior). If a change were to occur + because of a fault in the network, it could trigger the activation of the round change protocol, + where the protocol would expect to commit the locked block at that specific height. + +- **Persistence**: If, for instance, there is a faulty network condition present where two different + node subsets lock to two different blocks, the system enters into an infinite cycle of state transitions + that cannot converge states and finalize the block. + +## Consensus protocol: PolyBFT + +The consensus protocol uses the IBFT consensus engine and proof-of-stake architecture to seal blocks, +provide specific network capabilities, and govern the network. The consensus engine works with a set of +core smart contracts that implements a staking solution and incentivization scheme which defines all the +network's proof-of-stake rules. + +Polygon Edge follows [delegated proof of stake consensus](/maintain/delegate/delegate.md), where +delegators delegate their MATIC to back validators on the network. + +The consensus protocol follows a set of state transitions. While things are still being finalized, the +process will typically follow the steps below. + +1. A validator proposes a new block to be added to Polygon. This block contains a list of transactions + that the validator would like to include in the next update to the blockchain's state. + +2. Other validators in the active set will vote on whether to accept the proposed block. A + certain number of validators must agree to accept the block to reach consensus. The voting weight of + each validator influences voting. The protocol refers to block height as a *sequence*. + + The process to finalize a block in PolyBFT is known as *sealing*. The sealing of blocks is instant + and final. All nodes in the network exchange information for a given sequence. + + When a validator proposes a new block, other validators on the network will vote on whether to + accept the block. This process is typically repeated several times; each repetition is known as a + *round*. During each round, a certain number of validators must agree to seal the proposed block + for it to be added to the blockchain. If the required number of votes is not reached during a + particular round, the voting process will continue into the next round, and thus, the protocol + "increases the round". Another validator will attempt to seal the sequence in the new round. + > The best case for a proposed block is that it is sealed at round 0. If blocks are repeatedly being + > sealed at a high-order round, which usually indicates a problem with the network. + +3. If the proposed block is accepted, it will be added to the blockchain, and the state of the blockchain + will be updated to reflect the changes introduced by the transactions in the block. + > If a malicious actor attempted to fork the network, they would need to obtain control of 2/3 of + > the network, which PolyBFT prevents. + +4. Once the state of the blockchain has been updated, the next proposer will propose a new block, and + the process repeats. + +IBFT limits network participation to around 100 validators. A variable amount of stake is used as a fixed +stake criterion to limit the system's security and can make the system economically vulnerable. The +validator set in the PolyBFT does not update on each block but is fixed during `n` block periods known as +an `epoch`. + +> The `n` block period to define one epoch is to be determined by governance. Until then, validators will +> remain the same. At the end of the epoch, a special `state transaction` to `ChildValidatorSet` +> is emitted, notifying the system about validators’ uptime during the `epoch`. It is up to the smart contract +> to reward validators by their uptime and **update the validator set** for the next `epoch`. There is a +> function `getValidatorSet` which returns the current validator set at any time. + +Staking is governed by staking contracts directly on Polygon. To be clear, the staking module validates on +Polygon and does not rely on Ethereum's security, but in principle, two chains are securing the network, PoS +client and Ethereum. Transaction checkpoints still occur on Ethereum, but Ethereum does not validate staking +on Polygon. + +:::note + +Note that in Tendermint, an epoch is set to 1. However, PolyBFT includes the logic to set a custom +epoch time, with the intent of each epoch being one day in blocks, or around 14000 blocks. + +::: + +A reward calculation occurs at the end of the epoch to reward the active validators in that epoch. + +:::caution Slashing + +Like in other proof-of-stake systems, validators are subject to slashing for malicious activity or +poor performance. The slashing mechanics are still being determined, but PolyBFT will undoubtedly +include a mechanism to penalize bad actors. Slashing a validator typically involves a penalty, such +as losing some or all of their stake on the network. + +Examples of malicious activities are double-signing and equivocation. + +Double-signing refers to the act of signing two conflicting transactions. When a validator double-signs, +it creates a situation where the network is unable to reach consensus on the state of the blockchain, +which can lead to problems such as an attempt to fork or network instability. + +Equivocation is another behavior that can lead to validator slashing in a PoS network. Equivocation +refers to the act of a validator attempting to create two conflicting versions of the blockchain, +which can also lead to problems such as fork or network instability. + +::: diff --git a/archive/edge/main-edge/consensus/pos-concepts.md b/archive/edge/main-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..c1e3a13b86 --- /dev/null +++ b/archive/edge/main-edge/consensus/pos-concepts.md @@ -0,0 +1,119 @@ +--- +id: pos-concepts +title: Proof of Stake +description: "Explanation and instructions regarding Proof of Stake." +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## Overview + +This section aims to give a better overview of some concepts currently present in the Proof of Stake (PoS) +implementation of the Polygon Edge. + +The Polygon Edge Proof of Stake (PoS) implementation is meant to be an alternative to the existing PoA IBFT implementation, +giving node operators the ability to easily choose between the two when starting a chain. + +## PoS Features + +The core logic behind the Proof of Stake implementation is situated within +the **[Staking Smart Contract](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)**. + +This contract is pre-deployed whenever a PoS mechanism Polygon Edge chain is initialized, and is available on the address +`0x0000000000000000000000000000000000001001` from block `0`. + +### Epochs + +Epochs are a concept introduced with the addition of PoS to the Polygon Edge. + +Epochs are considered to be a special time frame (in blocks) in which a certain set of validators can produce blocks. +Their lengths are modifiable, meaning node operators can configure the length of an epoch during genesis generation. + +At the end of each epoch, an _epoch block_ is created, and after that event a new epoch starts. To learn more about +epoch blocks, see the [Epoch Blocks](/docs/edge/consensus/pos-concepts#epoch-blocks) section. + +Validator sets are updated at the end of each epoch. Nodes query the validator set from the Staking Smart Contract +during the creation of the epoch block, and save the obtained data to local storage. This query and save cycle is +repeated at the end of each epoch. + +Essentially, it ensures that the Staking Smart Contract has full control over the addresses in the validator set, and +leaves nodes with only 1 responsibility - to query the contract once during an epoch for fetching the latest validator +set information. This alleviates the responsibility from individual nodes from taking care of validator sets. + +### Staking + +Addresses can stake funds on the Staking Smart Contract by invoking the `stake` method, and by specifying a value for +the staked amount in the transaction: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +By staking funds on the Staking Smart Contract, addresses can enter the validator set and thus be able to participate in +the block production process. + +:::info Threshold for staking +Currently, the minimum threshold for entering the validator set is staking `1 ETH` +::: + +### Unstaking + +Addresses that have staked funds can only **unstake all of their staked funds at once**. + +Unstaking can be invoked by calling the `unstake` method on the Staking Smart Contract: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +After unstaking their funds, addresses are removed from the validator set on the Staking Smart Contract, and will not be +considered validators during the next epoch. + +## Epoch Blocks + +**Epoch Blocks** are a concept introduced in the PoS implementation of IBFT in Polygon Edge. + +Essentially, epoch blocks are special blocks that contain **no transactions** and occur only at **the end of an epoch**. +For example, if the **epoch size** is set to `50` blocks, epoch blocks would be considered to be blocks `50`, `100`, `150` and so on. + +They are used to performing additional logic that shouldn't occur during regular block production. + +Most importantly, they are an indication to the node that **it needs to fetch the latest validator set** information +from the Staking Smart Contract. + +After updating the validator set at the epoch block, the validator set (either changed or unchanged) +is used for the subsequent `epochSize - 1` blocks, until it gets updated again by pulling the latest information from +the Staking Smart Contract. + +Epoch lengths (in blocks) are modifiable when generating the genesis file, by using a special flag `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +The default size of an epoch is `100000` blocks in the Polygon Edge. + +## Contract pre-deployment + +The Polygon Edge _pre-deploys_ +the [Staking Smart Contract](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol) +during **genesis generation** to the address `0x0000000000000000000000000000000000001001`. + +It does so without a running EVM, by modifying the blockchain state of the Smart Contract directly, using the passed in +configuration values to the genesis command. diff --git a/archive/edge/main-edge/consensus/pos-stake-unstake.md b/archive/edge/main-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..5b56df4b67 --- /dev/null +++ b/archive/edge/main-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,174 @@ +--- +id: pos-stake-unstake +title: Set up and use Proof of Stake (PoS) +description: "Stake, unstake and other staking-related instructions." +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## Overview + +This guide goes into detail on how to set up a Proof of Stake network with the Polygon Edge, how to stake funds for nodes +to become validators and how to unstake funds. + +It is **highly encouraged** to read and go through +the [Local Setup](/docs/edge/get-started/set-up-ibft-locally) +/ [Cloud Setup](/docs/edge/get-started/set-up-ibft-on-the-cloud) sections, before going along +with this PoS guide. These sections outline the steps needed to start a Proof of Authority (PoA) cluster with the +Polygon Edge. + +Currently, there is no limit to the number of validators that can stake funds on the Staking Smart Contract. + +## Staking Smart Contract + +The repo for the Staking Smart Contract is located [here](https://github.com/0xPolygon/staking-contracts). + +It holds the necessary testing scripts, ABI files and most importantly the Staking Smart Contract itself. + +## Setting up an N node cluster + +Setting up a network with the Polygon Edge is covered in +the [Local Setup](/docs/edge/get-started/set-up-ibft-locally) +/ [Cloud Setup](/docs/edge/get-started/set-up-ibft-on-the-cloud) sections. + +The **only difference** between setting up a PoS and PoA cluster is in the genesis generation part. + +**When generating the genesis file for a PoS cluster, an additional flag is needed `--pos`**: + +```bash +polygon-edge genesis --pos ... +``` + +## Setting the length of an epoch + +Epochs are covered in detail in the [Epoch Blocks](/docs/edge/consensus/pos-concepts#epoch-blocks) section. + +To set the size of an epoch for a cluster (in blocks), when generating the genesis file, an additional flag is +specified `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +This value specified in the genesis file that the epoch size should be `50` blocks. + +The default value for the size of an epoch (in blocks) is `100000`. + +:::info Lowering the epoch length +As outlined in the [Epoch Blocks](/docs/edge/consensus/pos-concepts#epoch-blocks) section, +epoch blocks are used to update the validator sets for nodes. + +The default epoch length in blocks (`100000`) may be a long time to way for validator set updates. Considering that new +blocks are added ~2s, it would take ~55.5h for the validator set to possibly change. + +Setting a lower value for the epoch length ensures that the validator set is updated more frequently. +::: + +## Using the Staking Smart Contract scripts + +### Prerequisites + +The Staking Smart Contract repo is a Hardhat project, which requires NPM. + +To initialize it correctly, in the main directory run: + +```bash +npm install +```` + +### Setting up the provided helper scripts + +Scripts for interacting with the deployed Staking Smart Contract are located on +the [Staking Smart Contract repo](https://github.com/0xPolygon/staking-contracts). + +Create an `.env` file with the following parameters in the Smart Contracts repo location: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +Where the parameters are: + +* **JSONRPC_URL** - the JSON-RPC endpoint for the running node +* **PRIVATE_KEYS** - private keys of the staker address. +* **STAKING_CONTRACT_ADDRESS** - the address of the staking smart contract ( + default `0x0000000000000000000000000000000000001001`) +* **BLS_PUBLIC_KEY** - BLS public key of the staker. Only needed if the network is running with BLS + +### Staking funds + +:::info Staking address +The Staking Smart Contract is pre-deployed at +address `0x0000000000000000000000000000000000001001`. + +Any kind of interaction with the staking mechanism is done through the Staking Smart Contract at the specified address. + +To learn more about the Staking Smart Contract, please visit +the **[Staking Smart Contract](/docs/edge/consensus/pos-concepts#contract-pre-deployment)** +section. +::: + +In order to become part of the validator set, an address needs to stake a certain amount of funds above a threshold. + +Currently, the default threshold for becoming part of the validator set is `1 ETH`. + +Staking can be initiated by calling the `stake` method of the Staking Smart Contract, and specifying a value `>= 1 ETH`. + +After the `.env` file mentioned in +the [previous section](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) has been set up, and a +chain has been started in PoS mode, staking can be done with the following command in the Staking Smart Contract repo: + +```bash +npm run stake +``` + +The `stake` Hardhat script stakes a default amount of `1 ETH`, which can be changed by modifying the `scripts/stake.ts` +file. + +If the funds being staked are `>= 1 ETH`, the validator set on the Staking Smart Contract is updated, and the address +will be part of the validator set starting from the next epoch. + +:::info Registering BLS keys +If the network is running in BLS mode, in order for nodes to become validators, they need to register their BLS public keys after staking + +This can be done with the following command: + +```bash +npm run register-blskey +``` +::: + +### Unstaking funds + +Addresses that have a stake can **only unstake all of their funds** at once. + +After the `.env` file mentioned in +the [previous section](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) +has been set up, and a chain has been started in PoS mode, unstaking can be done with the following command in the +Staking Smart Contract repo: + +```bash +npm run unstake +``` + +### Fetching the list of stakers + +All addresses that stake funds are saved to the Staking Smart Contract. + +After the `.env` file mentioned in +the [previous section](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) +has been set up, and a chain has been started in PoS mode, fetching the list of validators can be done with the +following command in the Staking Smart Contract repo: + +```bash +npm run info +``` diff --git a/docs/edge/faq/Contracts.md b/archive/edge/main-edge/faq/Contracts.md similarity index 100% rename from docs/edge/faq/Contracts.md rename to archive/edge/main-edge/faq/Contracts.md diff --git a/docs/edge/faq/Gas.md b/archive/edge/main-edge/faq/Gas.md similarity index 100% rename from docs/edge/faq/Gas.md rename to archive/edge/main-edge/faq/Gas.md diff --git a/archive/edge/main-edge/faq/Tokens.md b/archive/edge/main-edge/faq/Tokens.md new file mode 100644 index 0000000000..7729b57a13 --- /dev/null +++ b/archive/edge/main-edge/faq/Tokens.md @@ -0,0 +1,25 @@ +--- +id: tokens +title: Tokens FAQ +description: "FAQ for Polygon Edge tokens" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## Does Polygon Edge support EIP-1559? +At the moment, Polygon Edge does not support EIP-1559. + +## How to set the currency(token) symbol? + +The token symbol is just a UI thing, so it cannot be configured or hardcoded anywhere in the network. +But you can change it when you add the network to a wallet, like Metamask, for example. + +## What happens to transactions when a chain halts? + +All the transactions that haven't been processed are inside the TxPool(enqueued or promoted queue). If the chain halts(all block production stops), these transactions will never go into blocks.
+This is not only the case when the chain halts. If the nodes are stopped or restarted, all the transactions that haven't been executed, and are still in TxPool, will silently get removed.
+The same thing will happen to transactions when a breaking change is introduced, as it is required for the nodes to be restarted. diff --git a/archive/edge/main-edge/faq/Validators.md b/archive/edge/main-edge/faq/Validators.md new file mode 100644 index 0000000000..900c720fbe --- /dev/null +++ b/archive/edge/main-edge/faq/Validators.md @@ -0,0 +1,86 @@ +--- +id: validators +title: Validators FAQ +description: "FAQ for Polygon Edge validators" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## How to add/remove a validator? + +### PoA +Adding/removing validators is done by voting. You can find [here](/docs/edge/consensus/poa) a full guide about this. + +### PoS +You can find a guide on how to stake funds [here](/docs/edge/consensus/pos-stake-unstake), so that a node can become a validator, and how to unstake (remove the validator). + +Please note that: +- You can use the genesis flag `--max-validator-count` to set a maximum number of stakers that can join the validator set. +- You can use the genesis flag `--min-validator-count ` to set the minimum number of stakers needed to join the validator set(`1` by default). +- When the maximum validator number is met, you cannot add another validator until you remove an existing one from the set (doesn't matter if the staked amount of the new one is higher). If you remove a validator, the number of validators remaining cannot be lower than `--min-validator-count`. +- There is a default threshold of `1` unit of native network(gas) currency for becoming a validator. + + + +## How much disk space is recommended for a validator? + +We recommend starting with 100G as a conservatively estimated runway, and making sure that it is possible to scale the disk afterwards. + + +## Is there a limit to the number of validators? + +If we are talking about technical limitations, Polygon Edge doesn't explicitly have the cap on the number of nodes you can have in a network. You can set connection caps (inbound / outbound connection counts) on a per-node basis. + +If we are talking about practical limitations, you're going to see a more degraded performance with a 100 node cluster than with a 10 node cluster. By increasing the number of nodes in your cluster, you increase the communication complexity and just the networking overhead in general. It all depends on what kind of network you are running, and what kind of network topology you have. + +## How to switch from PoA to PoS? + +PoA is the default consensus mechanism. For a new cluster, to switch to PoS, you will need to add the `--pos` flag when generating the genesis file. If you have a running cluster, you can find [here](/docs/edge/consensus/migration-to-pos) how to make the switch. All the info you need about our consensus mechanisms and setup can be found on our [consensus section](/docs/edge/consensus/poa). + +## How do I update my nodes when there's a breaking change? + +You can find a detailed guide on how to do this procedure [here](/docs/edge/validator-hosting#update). + +## Is the minimum staking amount configurable for PoS Edge? + +The minimum staking amount by default is `1 ETH`, and it’s not configurable. + +## Why do the JSON RPC commands `eth_getBlockByNumber` and `eth_getBlockByHash` not return the miner's address? + +The consensus used currently in Polygon Edge is IBFT 2.0, which, in turn, builds upon the voting mechanism explained in Clique PoA: [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225). + +Looking at the EIP-225 (Clique PoA), this is the relevant part that explains what the `miner` (aka `beneficiary`) is used for: + +
+We repurpose the ethash header fields as follows: +
    +
  • beneficiary / miner: Address to propose modifying the list of authorized signers with.
  • +
      +
    • Should be filled with zeroes normally, modified only while voting.
    • +
    • Arbitrary values are permitted nonetheless (even meaningless ones such as voting out non signers) to avoid extra complexity in implementations around voting mechanics.
    • +
    • Must be filled with zeroes on checkpoint (i.e. epoch transition) blocks.
    • +
    + +
+ +
+ +Thus, the `miner` field is used for proposing a vote for a certain address, not to show the proposer of the block. + +The information about the proposer of the block can be found by recovering the pubkey from the Seal field of the RLP encoded Istanbul extra data field in the block headers. + +## Which parts and values of Genesis can safely be modified? + +:::caution + +Please make sure to create a manual copy of the existing genesis.json file before attempting to edit it. +Also, the entire chain has to be stopped before editing the genesis.json file. Once the genesis file is modified, the newer version of it has to distributed across all non-validator and valdiator nodes. + +::: + +**Only the bootnodes section of the genesis file can safely be modified**, where you can add or remove bootnodes from the list. \ No newline at end of file diff --git a/archive/edge/main-edge/get-started/cli-commands.md b/archive/edge/main-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..449b25afb9 --- /dev/null +++ b/archive/edge/main-edge/get-started/cli-commands.md @@ -0,0 +1,2222 @@ +--- +id: cli-commands +title: CLI Commands +description: "List of CLI commands and command flags for Polygon Edge." +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +This section details the present commands, command flags in the Polygon Edge, and how they're used. + +:::tip JSON output support + +The `--json` flag is supported on some commands. This flag instructs the command to print the output in JSON format + +::: + +## Startup Commands + +| **Command** | **Description** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| server | The default command that starts the blockchain client, by bootstrapping all modules together | +| genesis | Generates a *genesis.json* file, which is used to set a predefined chain state before starting the client. The structure of the genesis file is described below | +| genesis predeploy | Predeploys a Smart Contract for fresh networks | + +### server flags + + +| **All server flags** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +|[grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [prometheus](/docs/edge/get-started/cli-commands#prometheus) | [block-gas-target](/docs/edge/get-started/cli-commands#block-gas-target) | +| [max-peers](/docs/edge/get-started/cli-commands#max-peers) | [max-inbound-peers](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [max-outbound-peers](/docs/edge/get-started/cli-commands#max-outbound-peers) | [max-enqueued](/docs/edge/get-started/cli-commands#max-enqueued) | +| [log-level](/docs/edge/get-started/cli-commands#log-level) | [log-to](/docs/edge/get-started/cli-commands#log-to) | +| [chain](/docs/edge/get-started/cli-commands#chain) | [join](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [price-limit](/docs/edge/get-started/cli-commands#price-limit) | [max-slots](/docs/edge/get-started/cli-commands#max-slots) | +| [config](/docs/edge/get-started/cli-commands#config) | [secrets-config](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-interval](/docs/edge/get-started/cli-commands#dev-interval) | +| [no-discover](/docs/edge/get-started/cli-commands#no-discover) | [restore](/docs/edge/get-started/cli-commands#restore) | +| [block-time](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir

+ + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +Used to specify the data directory used for storing Polygon Edge client data. Default: `./test-chain`. + +--- + + +####

jsonrpc

+ + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +Sets the address and port for the JSON-RPC service `address:port`. +If only port is defined `:10001` it will bind to all interfaces `0.0.0.0:10001`. +If omitted the service will bind to the default `address:port`. +Default address: `0.0.0.0:8545`. + +--- + +####

json-rpc-block-range-limit

+ + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +Sets the maximum block range to be considered when executing json-rpc requests that include fromBlock/toBlock values (e.g. eth_getLogs). +This limit can be completely disabled by setting the value to `0`. Default:`1000`. + +--- + +####

json-rpc-batch-request-limit

+ + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +Sets the maximum length to be considered when handling json-rpc batch requests. +This limit can be completely disabled by setting the value to `0`. Default: `20`. + +--- + +####

grpc

+ + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +Sets the address and port for the gRPC service `address:port`. Default address: `127.0.0.1:9632`. + +--- + +####

libp2p

+ + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +Sets the address and port for the libp2p service `address:port`. Default address: `127.0.0.1:1478`. + +--- + +####

prometheus

+ + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +Sets the address and port for the prometheus server `address:port`. +If only port is defined `:5001` the service will bind to all interfaces `0.0.0.0:5001`. +If omitted the service will not be started. + +--- + +####

block-gas-target

+ + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +Sets the target block gas limit for the chain. Default (not enforced): `0`. + +A more detailed explanation on the block gas target can be found in the [TxPool section](/docs/edge/architecture/modules/txpool#block-gas-target). + +--- + +####

max-peers

+ + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +Sets the client's maximum peer count. Default: `40`. + +Peer limit should be specified either by using `max-peers` or `max-inbound/outbound-peers` flag. + +--- + +####

max-inbound-peers

+ + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +Sets the client's maximum inbound peer count. If `max-peers` is set, max-inbound-peer limit is calculated using the following formulae. + +`max-inbound-peer = InboundRatio * max-peers`, where `InboundRatio` is `0.8`. + +--- + +####

max-outbound-peers

+ + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +Sets the client's maximum outbound peer count. If `max-peers` is set, max-outbound-peer count is calculated using the following formulae. + +`max-outbound-peer = OutboundRatio * max-peers`, where `OutboundRatio` is `0.2`. + +--- + +####

max-enqueued

+ + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +Sets the maximum number of enqueued transactions per account. Default:`128`. + +--- + +####

log-level

+ + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +Sets the log level for console output. Default: `INFO`. + +--- + +####

log-to

+ + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +Defines log file name that will hold all log output from the server command. +By default, all server logs will be outputted to console (stdout), +but if the flag is set, there will be no output to the console when running server command. + +--- + +####

chain

+ + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +Specifies the genesis file used for starting the chain. Default: `./genesis.json`. + +--- + +####

join

+ + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Specifies the address of the peer that should be joined. + +--- + +####

nat

+ + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +Sets the external IP address without the port, as it can be seen by peers. + +--- + +####

dns

+ + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +Sets the host DNS address. This can be used to advertise an external DNS. Supports `dns`,`dns4`,`dns6`. + +--- + +####

price-limit

+ + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +Sets minimum gas price limit to enforce for acceptance into the pool. Default: `1`. + +--- + +####

max-slots

+ + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +Sets maximum slots in the pool. Default: `4096`. + +--- + +####

config

+ + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +Specifies the path to the CLI config. Supports `.json`. + +--- + +####

secrets-config

+ + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +Sets the path to the SecretsManager config file. Used for Hashicorp Vault, AWS SSM and GCP Secrets Manager. If omitted, the local FS secrets manager is used. + +--- + +####

dev

+ + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +Sets the client to dev mode. Default: `false`. In dev mode, peer discovery is disabled by default. + +--- + +####

dev-interval

+ + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +Sets the client's dev notification interval in seconds. Default: `0`. + +--- + +####

no-discover

+ + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +Prevents the client from discovering other peers. Default: `false`. + +--- + +####

restore

+ + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +Restore blocks from the specified archive file + +--- + +####

block-time

+ + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +Sets block production time in seconds. Default: `2` + +--- + +####

access-control-allow-origins

+ + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +Sets the authorized domains to be able to share responses from JSON-RPC requests. +Add multiple flags `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"` to authorize multiple domains. +If omitted Access-Control-Allow-Origins header will be set to `*` and all domains will be authorized. + +--- + +### genesis flags +| **All genesis flags** | +|---------------------------------------|---------------------------------------------| +| [dir](/docs/edge/get-started/cli-commands#dir) | [name](/docs/edge/get-started/cli-commands#name) | +| [pos](/docs/edge/get-started/cli-commands#pos) | [epoch-size](/docs/edge/get-started/cli-commands#epoch-size) | +| [premine](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [ibft-validator-type](/docs/edge/get-started/cli-commands#ibft-validator-type) | [ibft-validators-prefix-path](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [ibft-validator](/docs/edge/get-started/cli-commands#ibft-validator) | [block-gas-limit](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [consensus](/docs/edge/get-started/cli-commands#consensus) | [bootnode](/docs/edge/get-started/cli-commands#bootnode) | +| [max-validator-count](/docs/edge/get-started/cli-commands#max-validator-count) | [min-validator-count](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

dir

+ + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +Sets the directory for the Polygon Edge genesis data. Default: `./genesis.json`. + +--- + +####

name

+ + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +Sets the name for the chain. Default: `polygon-edge`. + +--- + +####

pos

+ + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +Sets the flag indicating that the client should use Proof of Stake IBFT. +Defaults to Proof of Authority if flag is not provided or `false`. + +--- + +####

epoch-size

+ + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +Sets the epoch size for the chain. Default `100000`. + +--- + +####

premine

+ + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +Sets the premined accounts and balances in the format `address:amount`. +The amount can be in either decimal or hex. +Default premined balance: `0xD3C21BCECCEDA1000000`(1 million native currency tokens). + +--- + +####

chainid

+ + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +Sets the ID of the chain. Default: `100`. + +--- + +####

ibft-validator-type

+ + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +Specifies the validation mode of block headers. Possible values: `[ecdsa, bls]`. Default: `bls`. + +--- + +####

ibft-validators-prefix-path

+ + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +Prefix path for validator folder directory. Needs to be present if the flag `ibft-validator` is omitted. + +--- + +####

ibft-validator

+ + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Sets passed addresses as IBFT validators. Needs to be present if the flag `ibft-validators-prefix-path` is omitted. +1. If the network is running with ECDSA, the format is `--ibft-validator [ADDRESS]`. +2. If the network is running with BLS, the format is `--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]`. + +--- + +####

block-gas-limit

+ + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +Refers to the maximum amount of gas used by all operations in a block. Default: `5242880`. + +--- + +####

consensus

+ + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +Sets consensus protocol. Default: `pow`. + +--- + +####

bootnode

+ + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Multiaddr URL for p2p discovery bootstrap. This flag can be used multiple times. +Instead of an IP address, the DNS address of the bootnode can be provided. + +--- + +####

max-validator-count

+ + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +The maximum number of stakers able to join the validator set in a PoS consensus. +This number cannot exceed the value of MAX_SAFE_INTEGER (2^53 - 2). + +--- + +####

min-validator-count

+ + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +The minimum number of stakers needed to join the validator set in a PoS consensus. +This number cannot exceed the value of max-validator-count. +Defaults to 1. + +--- + +### genesis predeploy flags + +

artifacts-path

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +Sets the path to the contract artifacts JSON that contains the `abi`, `bytecode` and `deployedBytecode`. + +--- + +

chain

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +Sets the path to the `genesis.json` file that should be updated. Default `./genesis.json`. + +--- + +

constructor-args

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +Sets the Smart Contract constructor arguments, if any. For a detailed guide on how these arguments should look like, please reference [predeployment article](/docs/edge/additional-features/predeployment). + +--- + +

predeploy-address

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +Sets the address to predeploy to. Default `0x0000000000000000000000000000000000001100`. + +--- + + +## Operator Commands + +### Peer Commands + +| **Command** | **Description** | +|------------------------|-------------------------------------------------------------------------------------| +| peers add | Adds a new peer using their libp2p address | +| peers list | Lists all the peers the client is connected to through libp2p | +| peers status | Returns the status of a specific peer from the peers list, using the libp2p address | + +

peers add flags

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Peer's libp2p address in the multiaddr format. + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +Address of the gRPC API. Default: `127.0.0.1:9632`. + +

peers list flags

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +Address of the gRPC API. Default: `127.0.0.1:9632`. + +

peers status flags

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Libp2p node ID of a specific peer within p2p network. + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +Address of the gRPC API. Default: `127.0.0.1:9632`. + +### IBFT Commands + +| **Command** | **Description** | +|------------------------|-------------------------------------------------------------------------------------| +| ibft snapshot | Returns the IBFT snapshot | +| ibft candidates | Queries the current set of proposed candidates, as well as candidates that have not been included yet | +| ibft propose | Proposes a new candidate to be added/removed from the validator set | +| ibft status | Returns the overall status of the IBFT client | +| ibft switch | Add fork configurations into genesis.json file to switch IBFT type | +| ibft quorum | Specifies the block number after which the optimal quorum size method will be used for reaching consensus | + + +

ibft snapshot flags

+ +

number

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +The block height (number) for the snapshot. + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +Address of the gRPC API. Default: `127.0.0.1:9632`. + +

ibft candidates flags

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Address of the gRPC API. Default: `127.0.0.1:9632`. + +

ibft propose flags

+ +

vote

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +Proposes a change to the validator set. Possible values: `[auth, drop]`. + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +Address of the account to be voted for. + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +BLS Public Key of the account to be voted for, necessary only in BLS mode. + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Address of the gRPC API. Default: `127.0.0.1:9632`. + +

ibft status flags

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +Address of the gRPC API. Default: `127.0.0.1:9632`. + +

ibft switch flags

+ +

chain

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +Specifies the genesis file to update. Default: `./genesis.json`. + +--- + +

type

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +Specifies the IBFT type to switch. Possible values: `[PoA, PoS]`. + +--- + +

deployment

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +Specifies the height of contract deployment. Only available with PoS. + +--- + +

from

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +Specifies the validation mode of block headers. Possible values: `[ecdsa, bls]`. Default: `bls`. + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +Prefix path for the directories of new validators. Needs to be present if the flag `ibft-validator` is omitted. Available only when the IBFT mode is PoA (`--pos` flag is omitted). + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Sets passed in addresses as IBFT validators used after the fork. Needs to be present if the flag `ibft-validators-prefix-path` is omitted. Available only in PoA mode. +1. If the network is running with ECDSA, the format is `--ibft-validator [ADDRESS]`. +2. If the network is running with BLS, the format is `--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]`. + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +The maximum number of stakers able to join the validator set in a PoS consensus. +This number cannot exceed the value of MAX_SAFE_INTEGER (2^53 - 2). + +--- + +

min-validator-count

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +The minimum number of stakers needed to join the validator set in a PoS consensus. +This number cannot exceed the value of max-validator-count. +Defaults to 1. + +Specifies the beginning height of the fork. + +--- + +

ibft quorum flags

+ +

from

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +The height to switch the quorum calculation to QuorumOptimal, which uses the formula `(2/3 * N)`, `N` being the number of validator nodes. Please note that this is for backwards compatibility, ie. only for chains that used a Quorum legacy calculation up to a certain block height. + +--- + +

chain

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +Specifies the genesis file to update. Default: `./genesis.json`. + +### Transaction Pool Commands + +| **Command** | **Description** | +|------------------------|--------------------------------------------------------------------------------------| +| txpool status | Returns the number of transactions in the pool | +| txpool subscribe | Subscribes for events in the transaction pool | + +

txpool status flags

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +Address of the gRPC API. Default: `127.0.0.1:9632`. + +

txpool subscribe flags

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +Address of the gRPC API. Default: `127.0.0.1:9632`. + +--- + +

promoted

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +Subscribes for promoted tx events in the TxPool. + +--- + +

dropped

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +Subscribes for dropped tx events in the TxPool. + +--- + +

demoted

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +Subscribes for demoted tx events in the TxPool. + +--- + +

added

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +Subscribes for added tx events to the TxPool. + +--- + +

enqueued

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +Subscribes for enqueued tx events in the account queues. + +--- + +### Blockchain commands + +| **Command** | **Description** | +|------------------------|-------------------------------------------------------------------------------------| +| status | Returns the status of the client. The detailed response can be found below | +| monitor | Subscribes to a blockchain event stream. The detailed response can be found below | +| version | Returns the current version of the client | + +

status flags

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +Address of the gRPC API. Default: `127.0.0.1:9632`. + +

monitor flags

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +Address of the gRPC API. Default: `127.0.0.1:9632`. + +--- +

version command

+ + + + + + version + + + + +Displays release version, git branch, commit hash and build time. + +## Secrets Commands + +| **Command** | **Description** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| secrets init | Initializes the private keys to the corresponding secrets manager | +| secrets generate | Generates a secrets manager configuration file which can be parsed by the Polygon Edge | +| secrets output | Prints the BLS public key address, validator public key address, and node id for reference | + +### secrets init flags + +

config

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +Sets the path to the SecretsManager config file. Used for Hashicorp Vault. If omitted, the local FS secrets manager is used. + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +Sets the directory for the Polygon Edge data if the local FS is used. + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +Sets the flag indicating whether to generate an ECDSA key. Default: `true`. + +--- + +

network

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +Sets the flag indicating whether to generate a Libp2p Network key. Default: `true`. + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +Sets the flag indicating whether to generate a BLS key. Default: `true`. + +### secrets generate flags + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +Sets the directory for the secrets manager configuration file Default: `./secretsManagerConfig.json` + +--- + +

type

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +Specifies the type of the secrets manager [`hashicorp-vault`]. Default: `hashicorp-vault` + +--- + +

token

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +Specifies the access token for the service + +--- + +

server-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +Specifies the server URL for the service + +--- + +

name

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +Specifies the name of the node for on-service record keeping. Default: `polygon-edge-node` + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Specifies the namespace used for the Hashicorp Vault secrets manager. Default: `admin` + +### secrets output flags + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +Sets the flag indicating whether to only output the BLS public key. Default: `true` + +--- + +

config

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +Sets the path to the SecretsManager config file. If omitted, the local FS secrets manager is used. + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +Sets the directory for the Polygon Edge data if the local FS is used. + +--- + +

node-id

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +Sets the flag indicating whether to only output the network node ID. Default: `true` + +--- + +

validator

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +Sets the flag indicating whether to only output the validator address. Default: `true` + +--- + +## Responses + +### Status Response + +The response object is defined using Protocol Buffers. +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### Monitor Response +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## Utilities + +### whitelist commands + +| **Command** | **Description** | +|------------------------|-------------------------------------------------------------------------------------| +| whitelist show | Displays whitelist information | +| whitelist deployment | Updates the smart contract deployment whitelist | + +

whitelist show

+ + + + + whitelist show + + + + +Displays whitelist information. + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +Specifies the genesis file to update. Default: `./genesis.json`. + +--- + +

whitelist deployment

+ +

chain

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +Specifies the genesis file to update. Default: `./genesis.json`. + +--- + +

add

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Adds a new address to the contract deployment whitelist. Only the addresses in the contract deployment whitelist can deploy contracts. If empty, any address can execute the contract deployment + +--- + +

remove

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Removes an address from the contract deployment whitelist. Only the addresses in the contract deployment whitelist can deploy contracts. If empty, any address can execute the contract deployment + +--- + +### backup flags + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +Address of the gRPC API. Default: `127.0.0.1:9632`. + +--- + +

out

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +Path of archive file to save. + +--- + +

from

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +The beginning height of blocks in archive. Default: 0. + +--- + +

to

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +The end height of blocks in archive. + +--- + +## Genesis Template +The genesis file should be used to set the initial state of the blockchain (ex. if some accounts should have a starting balance). + +The following *./genesis.json* file is generated: +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### Data Directory + +When executing the *data-dir* flag, a **test-chain** folder is generated. +The folder structure consists of the following sub-folders: +* **blockchain** - Stores the LevelDB for blockchain objects +* **trie** - Stores the LevelDB for the Merkle tries +* **keystore** - Stores private keys for the client. This includes the libp2p private key and the sealing/validator private key +* **consensus** - Stores any consensus information that the client might need while working + +## Resources +* **[Protocol Buffers](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/main-edge/get-started/gcp-marketplace-deployment.md b/archive/edge/main-edge/get-started/gcp-marketplace-deployment.md new file mode 100644 index 0000000000..fb9356e3fc --- /dev/null +++ b/archive/edge/main-edge/get-started/gcp-marketplace-deployment.md @@ -0,0 +1,190 @@ +--- +id: gcp-marketplace-deployment +title: Google Cloud Marketplace Deployment +sidebar_label: Google Cloud Deployment +description: Deploy Polygon Edge network using Google Cloud Marketplace offering. +keywords: + - docs + - polygon + - edge + - deployment + - gcp + - marketplace + - google cloud +--- + +# Google Cloud Marketplace Deployment & Post Deployment Script Manual + +## Before We Start + +Here are a few quick pointers to keep in mind while deploying the Polygon Edge network from [Google Cloud Marketplace](https://cloud.google.com/marketplace). + +- This product is offered in the form of four node architecture. Four nodes spanning across four availability zones spanning two or more regions give higher tolerance in case of any issues with the either availability zone or region. +- The customer can launch: + - all four nodes in a single region spanning multiple availability zones, or + - two nodes in one region and another two nodes in another region, or + - each node in one availability zone belonging to one region thus spanning across all four regions. +- There is a bootstrap node that gets provisioned as part of the deployment process, performs its job, and gets terminated. The rest of the four nodes viz. Node1, Node2, Node3, and Node4 serve the traffic. +- Five service accounts will be created and they get attached to the five nodes. When you run the deployment for the first time from a marketplace in your GCP project, it is obvious that you won’t be having the service accounts with the necessary roles. +- You are supposed to choose the **Create a New Service Account** option for every node and give the service account a name, ID, and description of your choice. However, to ease the relationship between the node and the service account, we strongly recommend using the node names in the service account. Ex: bootstrap-node-sa, node1-sa, node2-sa etc. +- The bootstrap node service account has more privileges than other node service accounts. Due to that reason, once the application bootstrapping process is done, the node gets terminated automatically to avoid its misuse. +- You are allowed to choose the VPC in which you need to run the nodes. However, make sure that you are selecting the same VPC for all the nodes. In case you choose different VPCs for different nodes then you need to make sure that you have routing established between the VPCs and their respective subnets. Otherwise, it would lead to a breakage of communication between the nodes. +- By default, the Deployment Manager form selects Default VPC. If you decide to go with a custom VPC, then it is your responsibility to choose the custom VPC explicitly. Based on the node region selected, automatic subnet selection happens from the VPC. In case the region selected for the node doesn’t have a subnet, then it remains blank. So you have to either change the node region or create a new subnet in that region. +- By default, all nodes are allowed to get an **Ephemeral Public IP** address. If you choose not to have a public IP address then it is your responsibility to set the **Public IP** address to `NONE`. +- To avoid unauthorized entries into your blockchain nodes, it is strongly recommended that you go without Public IPs for the nodes. This product also provides a post-deployment script that provisions a Load Balancer which makes the necessity of the public IP obsolete. +- If the source IP ranges for ports 8545 and 1478 are left blank, then the deployment automatically takes 0.0.0.0/0. If you wish to go with public IPs to the nodes, it is recommended to give specific source IP ranges for port 8545 so that you will have better security. Port 1478 is for communication between the four nodes. It is recommended to use the CIDR ranges of the subnets in which the nodes are going to be provisioned. +- The GCS bucket is used only to share a few files for bootstrapping the Edge application. Once the application is up and running then it is no more required. Please note that it doesn’t contain any sensitive information related to the blockchain. +- In order to have a successful deployment of the application, a unique GCS name has to be passed to the deployment form. So, you must add your Project ID as a suffix to your bucket name. Bucket names must follow Google GCS naming guidelines. Caps and Special Characters (except **-** and **_** ) are not allowed. +- The genesis file can be generated by inputting some initial premine addresses and balances in CSV format e.g. `address1:balance,address2:balance`. A maximum of 200 premine addresses are allowed due to the deployment form field limitations of Google Cloud Marketplace. +- With 150 premine addresses, It takes ~5 mins for the entire deployment process to complete and get the application up and running. It would go to a maximum of ~6 mins if you have given a total of 200 premine addresses. + +## Post Deployment Script Manual for Polygon Edge + +### Prerequisites +- Successful completion of Polygon Edge VM’s deployment from the marketplace. +- For a production-grade setup, a public DNS domain with privileges to modify the nameservers is required. +- The operator who executes the post-deployment script must have the following roles - **roles/compute.admin, roles/dns.admin**. Basic roles such as **Editor** or **Owner** roles can also be given. +- Cloud DNS API should be enabled. +- gcloud CLI installed with the latest version. Access [Google Cloud Docs](https://cloud.google.com/sdk/docs/install) for instructions. +- gcloud CLI configured under the same project where the Polygon Edge product has been deployed. Access [Google Cloud configuration docs](https://cloud.google.com/sdk/docs/configurations) for configuration steps. + +### Components +The below components get provisioned when the post-deployment script gets executed successfully: +- SSL Certificate (If you don’t have one) +- Network Endpoint Groups (NEG’s) +- Global Load Balancer +- Managed Zone (if you don’t have one) + +### SSL Certificate +- Users can use an existing certificate created within GCP by giving the certificate name when the post deployment script asks. +- Users might have a certificate that was created using third-party providers like Letsencrypt or Zerossl etc. Users can pass the **certificate .pem file** and private key files absolute paths which were saved on the local file system where the script is getting executed. The script then creates a certificate in the GCP using those files. The created certificate will then be associated with the load balancer and makes the requests secure. +- Users can create a new certificate within GCP and this can be done by letting the script know that the user doesn’t have an existing certificate or doesn’t have a **certificate .pem and private key files** while running the script. + +### Managed Zone +The script is designed to either use an existing Managed Zone or create a new Managed Zone in the project. +- Users can create a new Managed Zone by letting the script know that the user doesn’t have an existing zone created for the domain. +- Users can also input the name of the existing managed zone to the script. + +## Script Execution + ```$ bash gcp-marketplace-postdeployment.sh``` +- The script code is available for download [here](/img/edge/assets/gcp-marketplace-postdeployment.sh). +- The script is interactive with a couple of questions. The script might take around 4 minutes to complete. +- The below screenshot shows how the script behaves when a user gives invalid inputs (or) input the script that the user doesn’t have a domain name. + + ![](/img/edge/assets/images/image1.png) + + +- The below screenshot shows the creation of a new SSL certificate. + + ![](/img/edge/assets/images/image2.png) + + +- The below screenshot shows the creation of a new SSL certificate by importing the user-provided certificate .pem and private key files. + + ![](/img/edge/assets/images/image3.png) + + +- The below screenshot shows how an existing SSL certificate can be inputted into the script. + + ![](/img/edge/assets/images/image4.png) + + +- The below screenshots show the Load Balancer creation process. + + ![](/img/edge/assets/images/image5.png) + + ![](/img/edge/assets/images/image6.png) + + ![](/img/edge/assets/images/image7.png) + + +- The below screenshot shows the creation of a new Managed Zone. + + ![](/img/edge/assets/images/image8.png) + + +- The below screenshots show the created Managed Zone and its name server details. + + ![](/img/edge/assets/images/image9.png) + + + ![](/img/edge/assets/images/image10.png) + + +- The name servers of the created Managed Zone + + ![](/img/edge/assets/images/image11.png) + + + ![](/img/edge/assets/images/image12.png) + +- The below screenshot shows the domain name servers were updated with managed zone name servers. + + ![](/img/edge/assets/images/image13.png) + +:::info NOTE +It is your responsibility to update the managed zone name servers' details in your domain registrar Nameservers section. If you chose to create a new SSL certificate in GCP then the certificate won’t be provisioned successfully for the domain until the Managed Zone Nameservers are updated in your Domain Registrar Nameservers section. The certificate issuing process and domain name propagation might take a few hours to a maximum of 3 days. Although it gets completed in a couple of hours in most cases. +::: + +## Destroying the created resources +Created resources are categorized into two types: +- Resources created from Marketplace deployment (the VM’s in this case) +- Resources created by executing the post-deployment script (LB ,SSL, and DNS record sets) + +Destroying the resources should happen in order. We have described the flow of deletion in the below steps. + +### Delete resources created using the Post-deployment script +- The below screenshot shows the options that display when **Destroy** is selected. + + ![](/img/edge/assets/images/image14.png) + +- The below screenshot shows the destroying process when **LoadBalancer** is selected. + + ![](/img/edge/assets/images/image15.png) + +- The below screenshot shows the destroying process when **SSL Certificate** is selected. + + ![](/img/edge/assets/images/image16.png) + +- The below screenshot shows the destroying process when **DNS Record Set** is selected. + + ![](/img/edge/assets/images/image17.png) + +- The below screenshot shows the destroying process when **DNS Record Set & Managed Zone** is selected. + + ![](/img/edge/assets/images/image18.png) + +- The below screenshots show the destroying process when **All of the above** options are selected. + + ![](/img/edge/assets/images/image19.png) + + ![](/img/edge/assets/images/image20.png) + + +### Delete resources created from the Marketplace + The below screenshot shows how those resources can be deleted from the Deployment manager. + + ![](/img/edge/assets/images/image21.png) + + +### Deleting secrets created in the Secrets Manager + Each Node will have two secrets viz. **Network Key** and **Validator Key**. So for four nodes, a total of eight secrets need to be deleted. The below screenshot shows the deletion of secrets from the secrets manager console. + + ![](/img/edge/assets/images/image22.png) + + +### Delete the temporary bucket storing the Node details & Genesis file +In order to delete a bucket, first it should be made empty, so delete the objects first and then delete the bucket. The below two screenshots shows the objects deletion and bucket deletion process. + + ![](/img/edge/assets/images/image23.png) + + ![](/img/edge/assets/images/image24.png) + + +### Remove access to the Service Accounts and Delete +The below two screenshots show the steps to remove roles from a service account and then delete the service accounts. + + ![](/img/edge/assets/images/image25.png) + + + ![](/img/edge/assets/images/image26.png) \ No newline at end of file diff --git a/archive/edge/main-edge/get-started/installation.md b/archive/edge/main-edge/get-started/installation.md new file mode 100644 index 0000000000..a6e4615e4d --- /dev/null +++ b/archive/edge/main-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: Installation +description: "How to install Polygon Edge." +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +Please refer to the installation method more applicable to you. + +Our recommendation is to use the pre-built releases and verify the provided checksums. + +## Pre-built releases + +Please refer to the [GitHub Releases](https://github.com/0xPolygon/polygon-edge/releases) page for a list of releases. + +Polygon Edge comes with cross-compiled AMD64/ARM64 binaries for Darwin and Linux. + +--- + +## Docker image + +Official Docker images are hosted under the [hub.docker.com registry](https://hub.docker.com/r/0xpolygon/polygon-edge). + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## Building from source + +Prior to using `go install` make sure that you have Go `>=1.18` installed and properly configured. + +The stable branch is the branch of the latest release. + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## Using `go install` + +Prior to using `go install` make sure that you have Go `>=1.17` installed and properly configured. + +`go install github.com/0xPolygon/polygon-edge@release/` + +The binary will be available in your `GOBIN` environment variable, and will include the changes from the latest release. You can checkout out [GitHub Releases](https://github.com/0xPolygon/polygon-edge/releases) to find out which one is the latest. diff --git a/archive/edge/main-edge/get-started/set-up-ibft-locally.md b/archive/edge/main-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..b9c588a4f4 --- /dev/null +++ b/archive/edge/main-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,366 @@ +--- +id: set-up-ibft-locally +title: Local Setup +description: "Step-by-step local setup guide." +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution This guide is for testing purposes only + +The below guide will instruct you on how to set up a Polygon Edge network on your local machine for testing and development +purposes. + +The procedure differs greatly from the way you would want to set up Polygon Edge network for a real use scenario on +a cloud provider: **[Cloud Setup](/docs/edge/get-started/set-up-ibft-on-the-cloud)** + +::: + + +## Requirements + +Refer to [Installation](/docs/edge/get-started/installation) to install Polygon Edge. + +## Overview + +![Local Setup](/img/edge/ibft-setup/local.svg) + +In this guide, our goal is to establish a working `polygon-edge` blockchain network working with [IBFT consensus protocol](https://github.com/ethereum/EIPs/issues/650). +The blockchain network will consist of 4 nodes of whom all 4 are validator nodes, and as such are eligible for both proposing block, and validating blocks that came from other proposers. +All 4 nodes will run on the same machine, as the idea of this guide is to give you a fully functional IBFT cluster in the least amount of time. + +To achieve that, we will guide you through 4 easy steps: + +1. Initializing data directories will generate both the validator keys for each of the 4 nodes, and initialize empty blockchain data directories. The validator keys are important as we need to bootstrap the genesis block with the initial set of validators using these keys. +2. Preparing the connection string for the bootnode will be the vital information for every node we will run as to which node to connect to when starting for the first time. +3. Generating the `genesis.json` file will require as input both the validator keys generated in **step 1** used for setting the initial validators of the network in the genesis block and the bootnode connection string from **step 2**. +4. Running all the nodes is the end goal of this guide and will be the last step we do, we will instruct the nodes which data directory to use and where to find the `genesis.json` which bootstraps the initial network state. + +As all four nodes will be running on localhost, during the setup process it is expected that all the data directories +for each of the nodes are in the same parent directory. + +:::info Number of validators + +There is no minimum to the number of nodes in a cluster, which means clusters with only 1 validator node are possible. +Keep in mind that with a _single_ node cluster, there is **no crash tolerance** and **no BFT guarantee**. + +The minimum recommended number of nodes for achieving a BFT guarantee is 4 - since in a 4 node cluster, the failure of +1 node can be tolerated, with the remaining 3 functioning normally. + +::: + +## Step 1: Initialize data folders for IBFT and generate validator keys + +In order to get up and running with IBFT, you need to initialize the data folders, +one for each node: + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +Each of these commands will print the validator key, bls public key and the [node ID](https://docs.libp2p.io/concepts/peer-id/). You will need the Node ID of the first node for the next step. + +### Outputting Secrets +The secrets output can be retrieved again, if needed. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## Step 2: Prepare the multiaddr connection string for the bootnode + +For a node to successfully establish connectivity, it must know which `bootnode` server to connect to in order to gain +information about all the remaining nodes on the network. The `bootnode` is sometimes also known as the `rendezvous` server in p2p jargon. + +`bootnode` is not a special instance of the polygon-edge node. Every polygon-edge node can serve as a `bootnode`, but +every polygon-edge node needs to have a set of bootnodes specified which will be contacted to provide information on how to connect with +all remaining nodes in the network. + +To create the connection string for specifying the bootnode, we will need to conform +to the [multiaddr format](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +In this guide, we will treat the first and second nodes as the bootnodes for all other nodes. What will happen in this scenario +is that nodes that connect to the `node 1` or `node 2` will get information on how to connect to one another through the mutually +contacted bootnode. + +:::info You need to specify at least one bootnode to start a node + +At least **one** bootnode is required, so other nodes in the network can discover each other. More bootnodes are recommended, as +they provide resilience to the network in case of outages. +In this guide we will list two nodes, but this can be changed on the fly, with no impact on the validity of the `genesis.json` file. +::: + +Since we are running on localhost, it is safe to assume that the `` is `127.0.0.1`. + +For the `` we will use `10001` since we will configure the libp2p server for `node 1` to listen on this port later. + +And lastly, we need the `` which we can get from the output of the previously ran command `polygon-edge secrets init --data-dir test-chain-1` command (which was used to generate keys and data directories for the `node1`) + +After the assembly, the multiaddr connection string to the `node 1` which we will use as the bootnode will look something like this (only the `` which is at the end should be different): +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Similarly, we construct the multiaddr for second bootnode as shown below +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info DNS hostnames instead of ips + +Polygon Edge supports using DNS hostnames for the nodes configuration. This is a very helpful feature for cloud based deployments, as the node's ip may change due to various reasons. + +The multiaddr format for the connection string while using DNS hostnames is as it follows: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## Step 3: Generate the genesis file with the 4 nodes as validators + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +What this command does: + +* The `--ibft-validators-prefix-path` sets the prefix folder path to the one specified which IBFT in Polygon Edge can + use. This directory is used to house the `consensus/` folder, where the validator's private key is kept. The + validator's public key is needed in order to build the genesis file - the initial list of bootstrap nodes. + This flag only makes sense when setting up the network on localhost, as in a real-world scenario we cannot expect all + the nodes' data directories to be on the same filesystem from where we can easily read their public keys. +* The `--bootnode` sets the address of the bootnode that will enable the nodes to find each other. + We will use the multiaddr string of the `node 1`, as mentioned in **step 2**. + +The result of this command is the `genesis.json` file which contains the genesis block of our new blockchain, with the predefined validator set and the configuration for which node to contact first in order to establish connectivity. + +:::info Switch to ECDSA + +BLS is the default validation mode of block headers. If you want your chain to run in ECDSA mode, you can use use the flag `—ibft-validator-type`, with the argument `ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info Premining account balances + +You will probably want to set up your blockchain network with some addresses having "premined" balances. + +To achieve this, pass as many `--premine` flags as you want per address that you want to be initialized with a certain balance +on the blockchain. + +For example, if we would like to premine 1000 ETH to address `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` in our genesis block, then we would need to supply the following argument: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Note that the premined amount is in WEI, not ETH.** + +::: + +:::info Set the block gas limit + +The default gas limit for each block is `5242880`. This value is written in the genesis file, but you may want to +increase / decrease it. + +To do so, you can use the flag `--block-gas-limit` followed by the desired value as shown below : + +```shell +--block-gas-limit 1000000000 +``` +::: + +:::info Set system file descriptor limit + +The default file descriptor limit (maximum number of open files) can be low, and on Linux, everything is a file. +If the nodes are expected to have high throughput, you might consider increasing this limit. +Check the official docs of your linux distro for more details. + +#### Check current os limits ( open files ) +```shell title="ulimit -n" +1024 # Ubuntu default +``` + +#### Increase open files limit +- Running `polygon-edge` in foreground (shell) + ```shell title="Set FD limit for the current session" + ulimit -n 65535 # affects only current session, limit won't persist after logging out + ``` + + ```shell title="Edit /etc/security/limits.conf" + # add the following lines to the end of the file to modify FD limits + * soft nofile 65535 # sets FD soft limit for all users + * hard nofile 65535 # sets FD hard limit for all users + + # End of file + ``` + Save the file and restart the system. + +- Running `polygon-edge` in the background as a service + + If `polygon-edge` is run as a system service, using the tool like `systemd`, file descriptor limits + should be managed using `systemd`. + ```shell title="Edit /etc/systemd/system/polygon-edge.service" + [Service] + ... + LimitNOFILE=65535 + ``` + +### Troubleshooting +```shell title="Watch FD limits of polygon edge running process" +watch -n 1 "ls /proc/$(pidof polygon-edge)/fd | wc -l" +``` + +```shell title="Check max FD limits for polygon-edge running process" +cat /proc/$(pidof polygon-edge)/limits +``` +::: + + +## Step 4: Run all the clients + +Because we are attempting to run a Polygon Edge network consisting of 4 nodes all on the same machine, we need to take care to +avoid port conflicts. This is why we will use the following reasoning for determining the listening ports of each server of a node: + +- `10000` for the gRPC server of `node 1`, `20000` for the GRPC server of `node 2`, etc. +- `10001` for the libp2p server of `node 1`, `20001` for the libp2p server of `node 2`, etc. +- `10002` for the JSON-RPC server of `node 1`, `20002` for the JSON-RPC server of `node 2`, etc. + +To run the **first** client (note the port `10001` since it was used as a part of the libp2p multiaddr in **step 2** alongside node 1's Node ID): + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +To run the **second** client: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +To run the **third** client: + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +To run the **fourth** client: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +To briefly go over what has been done so far: + +* The directory for the client data has been specified to be **./test-chain-\*** +* The GRPC servers have been started on ports **10000**, **20000**, **30000** and **40000**, for each node respectively +* The libp2p servers have been started on ports **10001**, **20001**, **30001** and **40001**, for each node respectively +* The JSON-RPC servers have been started on ports **10002**, **20002**, **30002** and **40002**, for each node respectively +* The *seal* flag means that the node which is being started is going to participate in block sealing +* The *chain* flag specifies which genesis file should be used for chain configuration + +The structure of the genesis file is covered in the [CLI Commands](/docs/edge/get-started/cli-commands) section. + +After running the previous commands, you have set up a 4 node Polygon Edge network, capable of sealing blocks and recovering +from node failure. + +:::info Start the client using config file + +Instead of specifying all configuration parameters as CLI arguments, the Client can also be started using a config file by executing the following command: + +````bash +polygon-edge server --config +```` +Example: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Currently, we support `yaml` and `json` based configuration files, sample config files can be found **[here](/docs/edge/configuration/sample-config)** + +::: + +:::info Steps to run a non-validator node + +A Non-validator will always sync the latest blocks received from the validator node, you can start a non-validator node by running the following command. + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +For example, you can add **fifth** Non-validator client by executing the following command : + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info Specify the price limit +A Polygon Edge node can be started with a set **price limit** for incoming transactions. + +The unit for the price limit is `wei`. + +Setting a price limit means that any transaction processed by the current node will need to have a gas price **higher** +then the set price limit, otherwise it will not be included in a block. + +Having the majority of nodes respect a certain price limit enforces the rule that transactions in the network +cannot be below a certain price threshold. + +The default value for the price limit is `0`, meaning it is not enforced at all by default. + +Example of using the `--price-limit` flag: +````bash +polygon-edge server --price-limit 100000 ... +```` + +It is worth noting that price limits **are enforced only on non-local transactions**, meaning +that the price limit does not apply to transactions added locally on the node. +::: + +:::info WebSocket URL +By default, when you run the Polygon Edge, it generates a WebSocket URL based on the chain location. +The URL scheme `wss://` is used for HTTPS links, and `ws://` for HTTP. + +Localhost WebSocket URL: +````bash +ws://localhost:10002/ws +```` +Please note that the port number depends on the chosen JSON-RPC port for the node. + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## Step 5: Interact with the polygon-edge network + +Now that you've set up at least 1 running client, you can go ahead and interact with the blockchain using the account you premined above +and by specifying the JSON-RPC URL to any of the 4 nodes: +- Node 1: `http://localhost:10002` +- Node 2: `http://localhost:20002` +- Node 3: `http://localhost:30002` +- Node 4: `http://localhost:40002` + +Follow this guide to issue operator commands to the newly built cluster: [How to query operator information](/docs/edge/working-with-node/query-operator-info) (the GRPC ports for the cluster we have built are `10000`/`20000`/`30000`/`40000` for each node respectively) diff --git a/archive/edge/main-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/main-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..4b4623b655 --- /dev/null +++ b/archive/edge/main-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,385 @@ +--- +id: set-up-ibft-on-the-cloud +title: Cloud Setup +description: "Step-by-step cloud setup guide." +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info This guide is for mainnet or testnet setups + +The below guide will instruct you on how to set up a Polygon Edge network on a cloud provider for a production setup of your testnet or mainnet. + +If you would like to setup a Polygon Edge network locally to quickly test the `polygon-edge` before doing a production-like setup, please refer to +**[Local Setup](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## Requirements + +Refer to [Installation](/docs/edge/get-started/installation) to install Polygon Edge. + +### Setting up the VM connectivity + +Depending on your choice of cloud provider, you may set up connectivity and rules between the VMs using a firewall, +security groups, or access control lists. + +As the only part of the `polygon-edge` that needs to be exposed to other VMs is the libp2p server, simply allowing +all communication between VMs on the default libp2p port `1478` is enough. + +## Overview + +![Cloud setup](/img/edge/ibft-setup/cloud.svg) + +In this guide, our goal is to establish a working `polygon-edge` blockchain network working with [IBFT consensus protocol](https://github.com/ethereum/EIPs/issues/650). +The blockchain network will consist of 4 nodes of whom all 4 are validator nodes, and as such are eligible for both proposing block, and validating blocks that came from other proposers. +Each of the 4 nodes will run on their own VM, as the idea of this guide is to give you a fully functional Polygon Edge network while keeping the validator keys private to ensure a trustless network setup. + +To achieve that, we will guide you through 4 easy steps: + +0. Take a look at the list of **Requirements** above +1. Generate the private keys for each of the validators, and initialize the data directory +2. Prepare the connection string for the bootnode to be put into the shared `genesis.json` +3. Create the `genesis.json` on your local machine, and send/transfer it to each of the nodes +4. Start all the nodes + +:::info Number of validators + +There is no minimum to the number of nodes in a cluster, which means clusters with only 1 validator node are possible. +Keep in mind that with a _single_ node cluster, there is **no crash tolerance** and **no BFT guarantee**. + +The minimum recommended number of nodes for achieving a BFT guarantee is 4 - since in a 4 node cluster, the failure of +1 node can be tolerated, with the remaining 3 functioning normally. + +::: + +## Step 1: Initialize data folders and generate validator keys + +To get up and running with Polygon Edge, you need to initialize the data folders, on each node: + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +Each of these commands will print the validator key, bls public key and the [node ID](https://docs.libp2p.io/concepts/peer-id/). You will need the Node ID of the first node for the next step. + +### Outputting Secrets +The secrets output can be retrieved again, if needed. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning Keep your data directory to yourself! + +The data directories generated above, besides initializing the directories for holding the blockchain state, will also generate your validator's private keys. +**This key should be kept as a secret, as stealing it would render somebody capable of impersonating you as the validator in the network!** +::: + +## Step 2: Prepare the multiaddr connection string for the bootnode + +For a node to successfully establish connectivity, it must know which `bootnode` server to connect to gain +information about all the remaining nodes on the network. The `bootnode` is sometimes also known as the `rendezvous` server in p2p jargon. + +`bootnode` is not a special instance of a Polygon Edge node. Every Polygon Edge node can serve as a `bootnode` and +every Polygon Edge node needs to have a set of bootnodes specified which will be contacted to provide information on how to connect with +all remaining nodes in the network. + +To create the connection string for specifying the bootnode, we will need to conform +to the [multiaddr format](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +In this guide, we will treat the first and second nodes as the bootnodes for all other nodes. What will happen in this scenario +is that nodes that connect to the `node 1` or `node 2` will get information on how to connect to one another through the mutually +contacted bootnode. + +:::info You need to specify at least one bootnode to start a node + +At least **one** bootnode is required, so other nodes in the network can discover each other. More bootnodes are recommended, as +they provide resilience to the network in case of outages. +In this guide we will list two nodes, but this can be changed on the fly, with no impact on the validity of the `genesis.json` file. +::: + +As the first part of the multiaddr connection string is the ``, here you will need to enter the IP address as reachable by other nodes, depending on your setup this might be a private or a public IP address, not `127.0.0.1`. + +For the `` we will use `1478`, since it is the default libp2p port. + +And lastly, we need the `` which we can get from the output of the previously ran command `polygon-edge secrets init --data-dir data-dir` command (which was used to generate keys and data directories for the `node 1`) + +After the assembly, the multiaddr connection string to the `node 1` which we will use as the bootnode will look something like this (only the `` which is at the end should be different): +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Similarly, we construct multiaddr for the second bootnode as shown below +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info DNS hostnames instead of ips + +Polygon Edge supports using DNS hostnames for the nodes configuration. This is a very helpful feature for cloud based deployments, as the node's ip may change due to various reasons. + +The multiaddr format for the connection string while using DNS hostnames is as it follows: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## Step 3: Generate the genesis file with the 4 nodes as validators + +This step can be run on your local machine, but you will need the public validator keys for each of the 4 validators. + +Validators can safely share the `Public key (address)` as displayed below in the output to their `secrets init` commands, so that +you may securely generate the genesis.json with those validators in the initial validator set, identified by their public keys: + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +Given that you have received all 4 of the validators' public keys, you can run the following command to generate the `genesis.json` + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +What this command does: + +* The `--ibft-validator` sets the public key of the validator that should be included in the initial validator set in the genesis block. There can be many initial validators. +* The `--bootnode` sets the address of the bootnode that will enable the nodes to find each other. + We will use the multiaddr string of the `node 1`, as mentioned in **step 2**, although you can add as many bootnodes as you want, as displayed above. + +:::info Switch to ECDSA + +BLS is the default validation mode of block headers. If you want your chain to run in ECDSA mode, you can use use the flag `—ibft-validator-type`, with the argument `ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info Premining account balances + +You will probably want to set up your blockchain network with some addresses having "premined" balances. + +To achieve this, pass as many `--premine` flags as you want per address that you want to be initialized with a certain balance +on the blockchain. + +For example, if we would like to premine 1000 ETH to address `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` in our genesis block, then we would need to supply the following argument: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Note that the premined amount is in WEI, not ETH.** + +::: + +:::info Set the block gas limit + +The default gas limit for each block is `5242880`. This value is written in the genesis file, but you may want to +increase / decrease it. + +To do so, you can use the flag `--block-gas-limit` followed by the desired value as shown below : + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Set system file descriptor limit + +The default file descriptor limit (maximum number of open files) can be low, and on Linux, everything is a file. +If the nodes are expected to have high throughput, you might consider increasing this limit. +Check the official docs of your linux distro for more details. + +#### Check current os limits ( open files ) +```shell title="ulimit -n" +1024 # Ubuntu default +``` + +#### Increase open files limit +- Running `polygon-edge` in foreground (shell) + ```shell title="Set FD limit for the current session" + ulimit -n 65535 # affects only current session, limit won't persist after logging out + ``` + + ```shell title="Edit /etc/security/limits.conf" + # add the following lines to the end of the file to modify FD limits + * soft nofile 65535 # sets FD soft limit for all users + * hard nofile 65535 # sets FD hard limit for all users + + # End of file + ``` + Save the file and restart the system. + +- Running `polygon-edge` in the background as a service + + If `polygon-edge` is run as a system service, using the tool like `systemd`, file descriptor limits + should be managed using `systemd`. + ```shell title="Edit /etc/systemd/system/polygon-edge.service" + [Service] + ... + LimitNOFILE=65535 + ``` + +### Troubleshooting +```shell title="Watch FD limits of polygon edge running process" +watch -n 1 "ls /proc/$(pidof polygon-edge)/fd | wc -l" +``` + +```shell title="Check max FD limits for polygon-edge running process" +cat /proc/$(pidof polygon-edge)/limits +``` +::: + +After specifying the: +1. Public keys of the validators to be included in the genesis block as the validator set +2. Bootnode multiaddr connection strings +3. Premined accounts and balances to be included in the genesis block + +and generating the `genesis.json`, you should copy it over to all of the VMs in the network. Depending on your setup you may +copy/paste it, send it to the node operator, or simply SCP/FTP it over. + +The structure of the genesis file is covered in the [CLI Commands](/docs/edge/get-started/cli-commands) section. + +## Step 4: Run all the clients + +:::note Networking on Cloud providers + +Most cloud providers don't expose the IP addresses (especially public ones) as a direct network interface on your VM but rather setup an invisible NAT proxy. + + +To allow the nodes to connect to each other in this case you would need to listen on the `0.0.0.0` IP address to bind on all interfaces, but you would still need to specify the IP address or DNS address which other nodes can use to connect to your instance. This is achieved either by using the `--nat` or `--dns` argument where you can specify your external IP or DNS address respectively. + +#### Example + +The associated IP address that you wish to listen on is `192.0.2.1`, but it is not directly bound to any of your network interfaces. + +To allow the nodes to connect you would pass the following parameters: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +Or, if you wish to specify a DNS address `dns/example.io`, pass the following parameters: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +This would make your node listen on all interfaces, but also make it aware that the clients are connecting to it through the specified `--nat` or `--dns` address. + +::: + +To run the **first** client: + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +To run the **second** client: + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +To run the **third** client: + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +To run the **fourth** client: + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +After running the previous commands, you have set up a 4 node Polygon Edge network, capable of sealing blocks and recovering +from node failure. + +:::info Start the client using config file + +Instead of specifying all configuration parameters as CLI arguments, the Client can also be started using a config file by executing the following command: + +````bash +polygon-edge server --config +```` +Example : + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Currently, we only support `json` based configuration file, sample config file can be found **[here](/docs/edge/configuration/sample-config)** + +::: + +:::info Steps to run a non-validator node + +A Non-validator will always sync the latest blocks received from the validator node, you can start a non-validator node by running the following command. + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +For example, you can add **fifth** Non-validator client by executing the following command : + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info Specify the price limit +A Polygon Edge node can be started with a set **price limit** for incoming transactions. + +The unit for the price limit is `wei`. + +Setting a price limit means that any transaction processed by the current node will need to have a gas price **higher** +than the set price limit, otherwise it will not be included into a block. + +Having the majority of nodes respect a certain price limit enforces the rule that transactions in the network +cannot be below a certain price threshold. + +The default value for the price limit is `0`, meaning it is not enforced at all by default. + +Example of using the `--price-limit` flag: +````bash +polygon-edge server --price-limit 100000 ... +```` + +It is worth noting that price limits **are enforced only on non-local transactions**, meaning +that the price limit does not apply to transactions added locally on the node. +::: + +:::info WebSocket URL +By default, when you run the Polygon Edge, it generates a WebSocket URL based on the chain location. +The URL scheme `wss://` is used for HTTPS links, and `ws://` for HTTP. + +Localhost WebSocket URL: +````bash +ws://localhost:10002/ws +```` +Please note that the port number depends on the chosen JSON-RPC port for the node. + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/main-edge/get-started/terraform-aws-deployment.md b/archive/edge/main-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..e178f82ba0 --- /dev/null +++ b/archive/edge/main-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,167 @@ +--- +id: terraform-aws-deployment +title: Terraform AWS Deployment +description: "Deploy Polygon Edge network on AWS cloud provider using Terraform" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info Production deployment guide +This is the official, production ready, fully automated, AWS deployment guide. + +Manual deployments to the ***[Cloud](set-up-ibft-on-the-cloud)*** or ***[Local](set-up-ibft-locally)*** +are recommended for testing and/or if your cloud provider is not AWS. +::: + +:::info +This deployment is PoA only. +If PoS mechanism is needed, just follow this ***[guide](/docs/edge/consensus/migration-to-pos)*** on now to make a switch from PoA to PoS. +::: + +This guide will, in detail, describe the process of deploying a Polygon Edge blockchain network on the AWS cloud provider, +that is production ready as the validator nodes are spanned across multiple availability zones. + +## Prerequisites + +### System tools +* [terraform](https://www.terraform.io/) +* [aws cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [aws access key ID and secret access key](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Terraform variables +Two variables that must be provided, before running the deployment: + +* `alb_ssl_certificate` - the ARN of the certificate from AWS Certificate Manager to be used by ALB for https protocol. + The certificate must be generated before starting the deployment, and it must have **Issued** status +* `premine` - the account that will receive pre mined native currency. + Value must follow the official [CLI](/docs/edge/get-started/cli-commands#genesis-flags) flag specification + +## Deployment information +### Deployed resources +High level overview of the resources that will be deployed: + +* Dedicated VPC +* 4 validator nodes (which are also boot nodes) +* 4 NAT gateways to allow nodes outbound internet traffic +* Lambda function used for generating the first (genesis) block and starting the chain +* Dedicated security groups and IAM roles +* S3 bucket used for storing genesis.json file +* Application Load Balancer used for exposing the JSON-RPC endpoint + +### Fault tolerance + +Only regions that have 4 availability zones are required for this deployment. Each node is deployed in a single AZ. + +By placing each node in a single AZ, the whole blockchain cluster is fault-tolerant to a single node (AZ) failure, as Polygon Edge implements IBFT +consensus which allows a single node to fail in a 4 validator node cluster. + +### Command line access + +Validator nodes are not exposed in any way to the public internet (JSON-PRC is accessed only via ALB) +and they don't even have public IP addresses attached to them. +Node command line access is possible only via [AWS Systems Manager - Session Manager](https://aws.amazon.com/systems-manager/features/). + +### Base AMI upgrade + +This deployment uses `ubuntu-focal-20.04-amd64-server` AWS AMI. It will **not** trigger EC2 *redeployment* if the AWS AMI gets updated. + +If, for some reason, base AMI is required to get updated, +it can be achieved by running the `terraform taint` command for each instance, before `terraform apply`. +Instances can be tainted by running the +`terraform taint module.instances[].aws_instance.polygon_edge_instance` command. + +Example: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info +In a production environment `terraform taint` should be run one-by-one in order to keep the blockchain network functional. +::: + +## Deployment procedure + +### Pre deployment steps +* read through the [polygon-technology-edge](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) terraform registry readme +* add the `polygon-technology-edge` module to your `main.tf` file using *provision instructions* on the modules' readme page +* run the `terraform init` command to install all necessary Terraform dependencies +* provide a new certificate in [AWS Certificate Manager](https://aws.amazon.com/certificate-manager/) +* make sure that the provided certificate is in the **Issued** state and take a note of the certificate's **ARN** +* set up your output statement in order to get modules' output in the cli + +#### `main.tf` example +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### `terraform.tfvars` example +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### Deployment steps +* create the `terraform.tfvars` file +* set the required terraform variables in this file (as explained above). + :::info + There are other non-mandatory variables that can fully customize this deployment. + You can override the default values by adding your own to the `terraform.tfvars` file. + + Specification of all available variables can be found in modules' Terraform ***[registry](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)*** + ::: +* make sure that you've set up an aws cli authentication properly by running `aws s3 ls` - there should be no errors +* deploy the infrastructure `terraform apply` + +### Post deployment steps +* once the deployment is finished, take note of the `json_rpc_dns_name` variable value printed in the cli +* create a public dns cname record pointing your domain name to the provided `json_rpc_dns_name` value. For example: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* once the cname record propagates, check if the chain is working properly by calling your JSON-PRC endpoint. + From the example above: + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## Destroy procedure +:::warning +The following procedure will permanently delete your entire infrastructure deployed with these terraform scripts. +Make sure you have proper [blockchain data backups](docs/edge/working-with-node/backup-restore) and/or you're working with a testing environment. +::: + +If you need to remove the whole infrastructure, run the following command `terraform destroy`. +Additionally, you will need to manually remove secrets stored in AWS [Parameter Store](https://aws.amazon.com/systems-manager/features/) +for the region the deployment took place. diff --git a/archive/edge/main-edge/overview.md b/archive/edge/main-edge/overview.md new file mode 100644 index 0000000000..9ac963cb8e --- /dev/null +++ b/archive/edge/main-edge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Polygon Edge +sidebar_label: What is Edge +description: "An introduction to Polygon Edge." +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +Polygon Edge is a modular and extensible framework for building Ethereum-compatible blockchain networks, sidechains, and general scaling solutions. + +Its primary use is to bootstrap a new blockchain network while providing full compatibility with Ethereum smart contracts and transactions. It uses IBFT (Istanbul Byzantine Fault Tolerant) consensus mechanism, supported in two flavours as [PoA (proof of authority)](/docs/edge/consensus/poa) and [PoS (proof of stake)](/docs/edge/consensus/pos-stake-unstake). + +Polygon Edge also supports communication with multiple blockchain networks, enabling transfers of both [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) and [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) tokens, by utilising the [centralised bridge solution](/docs/edge/additional-features/chainbridge/overview). + +Industry standard wallets can be used to interact with Polygon Edge through the [JSON-RPC](/docs/edge/working-with-node/query-json-rpc) endpoints and node operators can perform various actions on the nodes through the [gRPC](/docs/edge/working-with-node/query-operator-info) protocol. + +To find out more about Polygon, visit the [official website](https://polygon.technology). + +**[GitHub repository](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +This is a work in progress so architectural changes may happen in the future. The code has not been audited +yet, so please contact the Polygon team if you would like to use it in production. + +::: + + + +To get started by running a `polygon-edge` network locally, please read: [Installation](/docs/edge/get-started/installation) and [Local Setup](/docs/edge/get-started/set-up-ibft-locally). diff --git a/archive/edge/main-edge/performance-reports/overview.md b/archive/edge/main-edge/performance-reports/overview.md new file mode 100644 index 0000000000..33966e0c02 --- /dev/null +++ b/archive/edge/main-edge/performance-reports/overview.md @@ -0,0 +1,32 @@ +--- +id: overview +title: Overview +description: "Introduction to Polygon Edge testing." +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +Please note that our `loadbot`, which was used for performing these tests, is now depreciated. +::: + +| Type | Value | Link to test | +| ---- | ----- | ------------ | +| Regular Transfers | 1428 tps | [July 4th 2022](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| ERC-20 Transfers | 1111 tps | [July 4th 2022](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| NFT Minting | 714 tps | [July 4th 2022](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +Our goal is to make a highly-performant, feature-rich and easy to setup and maintain blockchain client software. +All tests were done using the Polygon Edge Loadbot. +Every performance report you will find in this section is properly dated, environment clearly described and the testing method clearly explained. + +The goal of these performance tests is to show a real world performance of Polygon Edge blockchain network. +Anyone should be able to get the same results as posted here, on the same environment, using our loadbot. + +All of the performance tests were conducted on the AWS platform on a chain consisting of EC2 instance nodes. \ No newline at end of file diff --git a/archive/edge/main-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/main-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..f6c34e0f4c --- /dev/null +++ b/archive/edge/main-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,132 @@ +--- +id: test-2022-01-21 +title: January 21st 2022 +description: "Performance test from January 21st." +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## January 21st 2022 + +### Summary + +:::caution +Please note that our `loadbot`, which was used for performing these tests, is now depreciated. +::: + +This test was done after the TxPool refactor which significantly improved performance (released in [v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0)). + +The goal was to setup a large network consisting of 30 actively participating validators in order to properly stress test the +consensus and TxPool transaction gossiping as all transactions were sent to a single node's JSON-RPC. + +Our aim was not to strive to reach a maximum possible TPS, as the network size negatively impacts the performance, +and since block gas limit & block time are set to sane values that don't consume much system resources, and would allow this to run on commodity hardware. + +### Results + +| Metric | Value | +| ------ | ----- | +| Transactions per second | 344 | +| Transactions failed | 0 | +| Transactions succeeded | 10000 | +| Total run time | 30s | + +### Environment + +
+ Host Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Instance sizet2.xlarge
Networkingprivate subnet
Operating systemLinux Ubuntu 20.04 LTS - Focal Fossa
File descriptor limit65535
Max user processes65535
+
+
+
+
+ +
+ Blockchain Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge versionCommit 8377162281d1a2e4342ae27cd4e5367c4364aee2 on develop branch
Validator nodes30
Non-validator nodes0
ConsensusIBFT PoA
Block time2000ms
Block gas limit5242880
+
+
+
+
+ +
+ Loadbot Configuration +
+
+ + + + + + + + + + + + + +
Total Transactions10000
Transactions sent per second400
Type of transactionsEOA to EOA transfers
+
+
+
+
diff --git a/archive/edge/main-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/main-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..e0950f27f4 --- /dev/null +++ b/archive/edge/main-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,390 @@ +--- +id: test-2022-03-02 +title: March 2nd 2022 +description: "Performance test from March 2nd." +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### Summary + +:::caution +Please note that our `loadbot`, which was used for performing these tests, is now depreciated. +::: + +This test was done to measure the SC ERC20 token transfers and SC ERC721 token minting functionality with heavy loads and speed of the transactions. + +The goal was to check if everything was working as expected during heavy loads. That was also the reason we’ve introduced gas metrics in the loadbot output, which shows us if the blocks are filled with transactions properly. + +All transactions were sent to the single node via GRPC API, and the receipts were received via JSON-RPC API. After all transactions were done, gas information was read from each block, using the eth_getBlockByNumber JSON-RPC method. + +Our aim was not to strive to reach a maximum possible TPS, +since block gas limit & block time are set to sane values that don't consume much system resources, and would allow this to run on commodity hardware. + +### Results ERC20 + +| Metric | Value | +| ------ | ----- | +| Transaction type | ERC20 | +| Transactions per second | 65 | +| Transactions failed | 0 | +| Transactions succeeded | 5000 | +| ERC20 transaction run time | 76.681690s | +| SC Deploy time | 4.048250s | + +### Results ERC721 + +| Metric | Value | +| ------ | ----- | +| Transaction type | ERC721 | +| Transactions per second | 20 | +| Transactions failed | 0 | +| Transactions succeeded | 2000 | +| ERC721 transaction run time | 97.239920s | +| SC Deploy time | 3.048970s | + +### Environment ERC20 + +
+ Host Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Instance sizet2.micro
Networkingprivate subnet
Operating systemLinux Ubuntu 20.04 LTS - Focal Fossa
File descriptor limit65535
Max user processes65535
+
+
+
+
+ +
+ Blockchain Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge versionCommit 8a033aa1afb191abdac04636d318f83f32511f3c on develop branch
Validator nodes6
Non-validator nodes0
ConsensusIBFT PoA
Block time2s
Block gas limit5242880
Average block utilization95%
+
+
+
+
+ +
+ Loadbot Configuration +
+
+ + + + + + + + + + + + + +
Total Transactions5000
Transactions sent per second200
Type of transactionsERC20 to ERC20 transfers
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### Environment ERC721 + +
+ Host Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Instance sizet2.micro
Networkingprivate subnet
Operating systemLinux Ubuntu 20.04 LTS - Focal Fossa
File descriptor limit65535
Max user processes65535
+
+
+
+
+ +
+ Blockchain Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge versionCommit 8a033aa1afb191abdac04636d318f83f32511f3c on develop branch
Validator nodes6
Non-validator nodes0
ConsensusIBFT PoA
Block time2s
Block gas limit5242880
Average block utilization94%
+
+
+
+
+ +
+ Loadbot Configuration +
+
+ + + + + + + + + + + + + +
Total Transactions2000
Transactions sent per second200
Type of transactionsERC721 token mint
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/main-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/main-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..d957e694b3 --- /dev/null +++ b/archive/edge/main-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,955 @@ +--- +id: test-2022-03-23 +title: March 23rd 2022 +description: "Performance test from March 23rd." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### Summary + +:::caution +Please note that our `loadbot`, which was used for performing these tests, is now depreciated. +::: + +This test was done to measure the SC ERC20 token transfers, SC ERC721 token minting and EOA to EOA transactions functionality with heavy loads and speed of the transactions on the nodes with higher hardware resources. + +The goal was to check if everything is working as expected during heavy loads. That was also the reason we’ve introduced gas metrics in the loadbot output, which show us if the blocks are filled with transactions properly. + +All transactions were sent to the single node via GRPC API, and the receipts were received via JSON-RPC API. After all transactions were done, gas information was read from each block, using the eth_getBlockByNumber JSON-RPC method. + +Our aim was to strive to reach a maximum possible TPS on the hardware resources available. +To acheive this, we've modified the block gas limit and block time parameters, to give us the best possible tps results and keep the system integrity and stability. + +:::info Block Gas Limit +Block gas limit can be increased to a relatively high number if the transactions are using a lot of gas to execute. +In the example stated bellow, ERC721 token minting worked much faster with a block gas limit set to 80 000 000 ( instead of 20 Mil. ), but with ERC20 token transfers with 80 Mil. block gas limit, the server crashed. +::: + +:::info Production Environments +When configuring a production environment, you need to be carefull if you're trying to acheive high performance of the chain. +If block gas limit parameter is set to a high value, block time is set to 1s, and there is a high transaction load on a single node, that node will consume a lot ( if not all available ) RAM and can cause server crash. +Use the loadbot to test everything thoroughly, monitor the system resource utilization and set your configuration parameters accordingly. +::: + +:::info Out of Memory Errors +Some linux distros will automaticaly kill the process that has a very high RAM usage ( OOM error ) , in order to preserve the system stability. +The log output of this OOM error looks something like bellow. +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### Results of EOA to EOA transfers +| Metric | Value | +| ------ | ----- | +| Transaction type | EOA to EOA | +| Transactions per second | 689 | +| Transactions failed | 0 | +| Transactions succeeded | 20000 | +| Total blocks used | 25 | +| Total run time | 29.921110s | + +### Results of ERC20 token transfers + +| Metric | Value | +| ------ | ----- | +| Transaction type | ERC20 | +| Transactions per second | 500 | +| Transactions failed | 0 | +| Transactions succeeded | 20000 | +| Total blocks used | 33 | +| ERC20 transaction run time | 40.402900s | +| SC Deploy time | 2.004140s | + +### Results of ERC721 token minting + +| Metric | Value | +| ------ | ----- | +| Transaction type | ERC721 | +| Transactions per second | 157 | +| Transactions failed | 0 | +| Transactions succeeded | 20000 | +| Total blocks used | 124 | +| ERC721 transaction run time | 127.537340s | +| SC Deploy time | 2.004420s | + + +### Results of ERC721 token minting with a very high block gas limit (80 Mil.) +| Metric | Value | +| ------ | ----- | +| Transaction type | ERC721 | +| Transactions per second | 487 | +| Transactions failed | 0 | +| Transactions succeeded | 20000 | +| Total blocks used | 34 | +| ERC721 transaction run time | 41.098410s | +| SC Deploy time | 2.004300s | + + +### Environment EOA to EOA +
+ Host Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Instance sizec5.2xlarge
Networkingprivate subnet
Operating systemAmazon Linux 2 AMI (HVM) - Kernel 5.10
File descriptor limit65535
Max user processes65535
+
+
+
+
+ +
+ Blockchain Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge versionCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 on develop branch
Validator nodes4
Non-validator nodes0
ConsensusIBFT PoA
Block time1s
Block gas limit20000000
Max slots1000000
Average block utilization84.00%
+
+
+
+
+ +
+ Loadbot Configuration +
+
+ + + + + + + + + + + + + +
Total Transactions20000
Transactions sent per second689
Type of transactionsEOA to EOA transfers
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### Environment ERC20 +
+ Host Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Instance sizec5.2xlarge
Networkingprivate subnet
Operating systemAmazon Linux 2 AMI (HVM) - Kernel 5.10
File descriptor limit65535
Max user processes65535
+
+
+
+
+ +
+ Blockchain Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge versionCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 on develop branch
Validator nodes4
Non-validator nodes0
ConsensusIBFT PoA
Block time1s
Block gas limit20000000
Max slots1000000
Average block utilization88.38%
+
+
+
+
+ +
+ Loadbot Configuration +
+
+ + + + + + + + + + + + + +
Total Transactions20000
Transactions sent per second500
Type of transactionsERC20 to ERC20 transfers
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### Environment ERC721 +
+ Host Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Instance sizec5.2xlarge
Networkingprivate subnet
Operating systemAmazon Linux 2 AMI (HVM) - Kernel 5.10
File descriptor limit65535
Max user processes65535
+
+
+
+
+ +
+ Blockchain Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge versionCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 on develop branch
Validator nodes4
Non-validator nodes0
ConsensusIBFT PoA
Block time1s
Block gas limit20000000
Max slots1000000
Average block utilization92.90%
+
+
+
+
+ +
+ Loadbot Configuration +
+
+ + + + + + + + + + + + + +
Total Transactions20000
Transactions sent per second157
Type of transactionsERC721 token mint
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### Environment ERC20 - very high block gas limit +
+ Host Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Instance sizec5.2xlarge
Networkingprivate subnet
Operating systemAmazon Linux 2 AMI (HVM) - Kernel 5.10
File descriptor limit65535
Max user processes65535
+
+
+
+
+ +
+ Blockchain Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge versionCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 on develop branch
Validator nodes4
Non-validator nodes0
ConsensusIBFT PoA
Block time1s
Block gas limit80000000
Max slots1000000
Average block utilization---
+
+
+
+
+ +
+ Loadbot Configuration +
+
+ + + + + + + + + + + + + +
Total Transactions20000
Transactions sent per second---
Type of transactionsERC20 to ERC20 transfers
+
+
+
+
+ +
+ OOM Error log + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### Environment ERC721 - very high block gas limit +
+ Host Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Instance sizec5.2xlarge
Networkingprivate subnet
Operating systemAmazon Linux 2 AMI (HVM) - Kernel 5.10
File descriptor limit65535
Max user processes65535
+
+
+
+
+ +
+ Blockchain Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge versionCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 on develop branch
Validator nodes4
Non-validator nodes0
ConsensusIBFT PoA
Block time1s
Block gas limit80000000
Max slots1000000
Average block utilization84.68%
+
+
+
+
+ +
+ Loadbot Configuration +
+
+ + + + + + + + + + + + + +
Total Transactions20000
Transactions sent per second487
Type of transactionsERC721 token mint
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/main-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/main-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..e421ac5215 --- /dev/null +++ b/archive/edge/main-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,566 @@ +--- +id: test-2022-07-04 +title: July 4th 2022 +description: "Performance test from July 4th." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### Summary + +:::caution +Please note that our `loadbot`, which was used for performing these tests, is now depreciated. +::: + +This test was done to measure the SC ERC20 token transfers, SC ERC721 token minting and EOA to EOA transactions functionality with heavy loads and speed of the transactions on the nodes with higher hardware resources. + +The goal was to check if everything is working as expected during heavy loads. That was also the reason we’ve introduced gas metrics in the loadbot output, which show us if the blocks are filled with transactions properly. + +All transactions were sent to the single node via GRPC API, and the receipts were received via JSON-RPC API. After all transactions were done, gas information was read from each block, using the eth_getBlockByNumber JSON-RPC method. + +Our aim was to strive to reach a maximum possible TPS on the hardware resources available. +To acheive this, we've modified the block gas limit and block time parameters, to give us the best possible tps results and keep the system integrity and stability. + + +:::info Production Environments +When configuring a production environment, you need to be carefull if you're trying to acheive high performance of the chain. +If block gas limit parameter is set to a high value, block time is set to 1s, and there is a high transaction load on a single node, that node will consume a lot ( if not all available ) RAM and can cause server crash. +Use the loadbot to test everything thoroughly, monitor the system resource utilization and set your configuration parameters accordingly. +::: + + + +### Results of EOA to EOA transfers +| Metric | Value | +| ------ | ----- | +| Transaction type | EOA to EOA | +| Transactions per second | 1428 | +| Transactions failed | 0 | +| Transactions succeeded | 30000 | +| Total blocks used | 15 | +| Total run time | 21.374620s | + +### Results of ERC20 token transfers + +| Metric | Value | +| ------ | ----- | +| Transaction type | ERC20 | +| Transactions per second | 1111 | +| Transactions failed | 0 | +| Transactions succeeded | 50000 | +| Total blocks used | 38 | +| ERC20 transaction run time | 45.906450s | +| SC Deploy time | 2.006580s | + +### Results of ERC721 token minting + +| Metric | Value | +| ------ | ----- | +| Transaction type | ERC721 | +| Transactions per second | 714 | +| Transactions failed | 0 | +| Transactions succeeded | 30000 | +| Total blocks used | 39 | +| ERC721 transaction run time | 42.864140s | +| SC Deploy time | 2.005500s | + + + + +### Environment EOA to EOA +
+ Host Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS EC2
Instance sizec6a.48xlarge
Networkingprivate subnet
Operating systemLinux Ubuntu 20.04 LTS - Focal Fossa
File descriptor limit65535
Max user processes65535
+
+
+
+
+ +
+ Blockchain Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge versionRelease v0.4.1
Validator nodes4
Non-validator nodes0
ConsensusIBFT PoA
Block time1s
Block gas limit70778880
Max slots276480
Average block utilization59.34%
+
+
+
+
+ +
+ Loadbot Configuration +
+
+ + + + + + + + + + + + + +
Total Transactions30000
Transactions sent per second1428
Type of transactionsEOA to EOA transfers
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### Environment ERC20 +
+ Host Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS EC2
Instance sizec6a.48xlarge
Networkingprivate subnet
Operating systemLinux Ubuntu 20.04 LTS - Focal Fossa
File descriptor limit65535
Max user processes65535
+
+
+
+
+ +
+ Blockchain Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge versionRelease v0.4.1
Validator nodes4
Non-validator nodes0
ConsensusIBFT PoA
Block time1s
Block gas limit47185920
Max slots184320
Average block utilization81.29%
+
+
+
+
+ +
+ Loadbot Configuration +
+
+ + + + + + + + + + + + + +
Total Transactions50000
Transactions sent per second1111
Type of transactionsERC20 to ERC20 transfers
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### Environment ERC721 +
+ Host Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS EC2
Instance sizec6a.48xlarge
Networkingprivate subnet
Operating systemLinux Ubuntu 20.04 LTS - Focal Fossa
File descriptor limit65535
Max user processes65535
+
+
+
+
+ +
+ Blockchain Configuration +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge versionRelease v0.4.1
Validator nodes4
Non-validator nodes0
ConsensusIBFT PoA
Block time1s
Block gas limit94371840
Max slots1000000
Average block utilization93.88%
+
+
+
+
+ +
+ Loadbot Configuration +
+
+ + + + + + + + + + + + + +
Total Transactions30000
Transactions sent per second714
Type of transactionsERC721 token mint
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/main-edge/troubleshooting.md b/archive/edge/main-edge/troubleshooting.md new file mode 100644 index 0000000000..d6a450d817 --- /dev/null +++ b/archive/edge/main-edge/troubleshooting.md @@ -0,0 +1,71 @@ +--- +id: troubleshooting +title: Troubleshooting +description: "Troubleshooting section for Polygon Edge" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# Troubleshooting + +## `method=eth_call err="invalid signature"` error + +When you are using a wallet to make a transaction with Polygon Edge, please make sure that in your wallet's local network setup: + +1. The `chainID` is the right one. The default `chainID` for Edge is `100`, but it can be customized by using the genesis flag `--chain-id`. + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. Make sure that, on the “RPC URL”, field you use the JSON RPC port of the node you are connecting to. + + +## How to get a WebSocket URL + +By default, when you run the Polygon Edge, it exposes a WebSocket endpoint based on the chain location. +The URL scheme `wss://` is used for HTTPS links, and `ws://` for HTTP. + +Localhost WebSocket URL: +````bash +ws://:/ws +```` +Please note that the port number depends on the chosen JSON-RPC port for the node. + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## `insufficient funds` error when trying to deploy a contract + +If you get this error, please make sure you have enough funds on the desired address, and the address used is the correct one.
+To set the premined balance, you can use the genesis flag `genesis [--premine ADDRESS:VALUE]` while generating the genesis file. +Example of using this flag: +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +This premines 1000000000000000000000 WEI to 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862. + + +## ERC20 tokens not released while using Chainbridge + +If you try to transfer ERC20 tokens between Polygon PoS and a local Edge network, and your ERC20 tokens are deposited, also proposal is executed at relayer, but the tokens are not released in your Edge network, please make sure the ERC20 Handler in Polygon Edge chain has enough tokens to release.
+The Handler contract in the destination chain must have enough tokens to release for lock-release mode. If you don't have any ERC20 tokens in the ERC20 Handler of your local Edge network, please mint new tokens and transfer them to the ERC20 Handler. + +## `Incorrect fee supplied` error when using Chainbridge + +You might get this error when trying to transfer ERC20 tokens between Mumbai Polygon PoS chain and a local Polygon Edge setup. This error appears when you set the fee on deploying using the `--fee` flag, but you don't set the same value in the deposit transaction. +You can use the below command to change the fee: +```` bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +You can find more information about this flag [here](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md). + + + + + diff --git a/archive/edge/main-edge/validator-hosting.md b/archive/edge/main-edge/validator-hosting.md new file mode 100644 index 0000000000..b1fa086478 --- /dev/null +++ b/archive/edge/main-edge/validator-hosting.md @@ -0,0 +1,253 @@ +--- +id: validator-hosting +title: Validator Hosting +description: "Hosting requirements for Polygon Edge" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +Below are the suggestions for properly hosting a validator node in a Polygon Edge network. Please pay careful attention to all the items listed below to make sure +that your validator setup is properly configured to be secure, stable and performant. + +## Knowledge base + +Before trying to run the validator node, please read through this document thoroughly. +Additional docs that might be helpful are: + +- [Installation](get-started/installation) +- [Cloud setup](get-started/set-up-ibft-on-the-cloud) +- [CLI commands](get-started/cli-commands) +- [Server config file](configuration/sample-config) +- [Private keys](configuration/manage-private-keys) +- [Prometheus metrics](configuration/prometheus-metrics) +- [Secret managers](/docs/category/secret-managers) +- [Backup/Restore](working-with-node/backup-restore) + +## Minimum system requirements + +| Type | Value | Influenced by | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 2 cores |
  • Number of JSON-RPC queries
  • Size of the blockchain state
  • Block gas limit
  • Block time
| +| RAM | 2 GB |
  • Number of JSON-RPC queries
  • Size of the blockchain state
  • Block gas limit
| +| Disk |
  • 10 GB root patition
  • 30 GB root partition with LVM for disk extension
|
  • Size of the blockchain state
| + + +## Service configuration + +`polygon-edge` binary needs to run as a system service automatically upon established network connectivity and have start / stop / restart +functionalities. We recommend using a service manager like `systemd.` + +Example `systemd` system configuration file: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### Binary + +In production workloads `polygon-edge` binary should only be deployed from pre-built GitHub release binaries - not by manually compiling. +:::info +By manually compiling `develop` GitHub branch, you may introduce breaking changes to your environment. +For that reason it is recommended to deploy Polygon Edge binary exclusively from releases, as it will contain +information about breaking changes and how to overcome them. +::: + +Please refer to [Installation](/docs/edge/get-started/installation) for a complete overview of installation method. + +### Data storage + +The `data/` folder containing the entire blockchain state should be mounted on a dedicated disk / volume allowing for +automatic disk backups, volume extension and optionally mounting the disk/volume to another instance in case of failure. + + +### Log files + +Log files need to be rotated on a daily basis (with a tool like `logrotate`). +:::warning +If configured without log rotation, log files could use up all the available disk space which could disrupt the validator uptime. +::: + +Example `logrotate` configuration: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +Refer to the [Logging](#logging) section below for recommendations on log storage. + +### Additional dependencies + +`polygon-edge` is statically compiled, requiring no additional host OS dependencies. + +## Maintenance + +Below are the best practices for maintaining a running validator node of a Polygon Edge network. + +### Backup + +There are two types of backup procedures recommended for Polygon Edge nodes. + +The suggestion is to use both, whenever possible, with the Polygon Edge backup being an always available option. + +* ***Volume backup***: + Daily incremental backup of the `data/` volume of the Polygon Edge node, or of the complete VM if possible. + + +* ***Polygon Edge backup***: + Daily CRON job which does regular backups of Polygon Edge and moves the `.dat` files to an offsite location or to a secure cloud object storage is recommended. + +The Polygon Edge backup should ideally not overlap with the Volume backup described above. + +Refer to [Backup/restore node instance](working-with-node/backup-restore) for instructions on how to perform backups of Polygon Edge. + +### Logging + +The logs outputted by the Polygon Edge nodes should: +- be sent to an external data store with indexing and searching capabilities +- have a log retention period of 30 days + +If this is your first time setting up a Polygon Edge validator, we recommend to start the node +with the `--log-level=DEBUG` option to be able to quickly debug any issues you might face. + +:::info +The `--log-level=DEBUG` will make the node's log output be as verbose as possible. +Debug logs will drastically increase the size of the log file which must be taken into account when setting up +log rotation solution. +::: +### OS security patches + +Administrators need to ensure that the validator instance OS is always updated with the latest patches at least once every month. + +## Metrics + +### System metrics + +Administrators need to setup some kind of system metrics monitor, (e.g. Telegraf + InfluxDB + Grafana or a 3rd party SaaS). + +Metrics that need to be monitored and that need to have alarm notifications setup: + +| Metric name | Alarm threshold | +|-----------------------|-------------------------------| +| CPU usage (%) | > 90% for more than 5 minutes | +| RAM utilization (%) | > 90% for more than 5 minutes | +| Root disk utilization | > 90% | +| Data disk utilization | > 90% | + +### Validator metrics + +Administrators need to setup collection of metrics from Polygon Edge's Prometheus API to be able to +monitor the blockchain performance. + +Refer to [Prometheus metrics](configuration/prometheus-metrics) to understand which metrics are being exposed and how to set up Prometheus metric collection. + + +Extra attention needs to be paid to the following metrics: +- ***Block production time*** - if block production time is higher than normal, there is a potential problem with the network +- ***Number of consensus rounds*** - if there is more than 1 round, there is a potential problem with the validator set in the network +- ***Number of peers*** - if the number of peers drop, there is a connectivity issue in the network + +## Security + +Below are the best practices for securing a running validator node of a Polygon Edge network. + +### API services + +- ***JSON-RPC*** - +Only API service that needs to be exposed to the public ( via load balancer or directly ). +This API should run on all interfaces or on a specific IP address ( example: `--json-rpc 0.0.0.0:8545` or `--json-prc 192.168.1.1:8545` ). +:::info +As this is publicly facing API it is recommended to have a load balancer / reverse proxy in front of it to provide security and rate limiting. +::: + + +- ***LibP2P*** - +This is the networking API used by nodes for peer communication. It needs to run on all interfaces or on a specific ip address +( `--libp2p 0.0.0.0:1478` or `--libp2p 192.168.1.1:1478` ). This API should not be publicly exposed, +but it should be reachable from all other nodes. +:::info +If ran on localhost ( `--libp2p 127.0.0.1:1478` ) other nodes will not be able to connect. +::: + + +- ***GRPC*** - +This API is used only for running operator commands and noting else. As such it should run exclusively on localhost ( `--grpc-address 127.0.0.1:9632` ). + +### Polygon Edge secrets + +Polygon Edge secrets ( `ibft` and `libp2p` keys ) should not be stored on a local file system. +Instead, a supported [Secret Manager](configuration/secret-managers/set-up-aws-ssm) should be used. +Storing secrets to local file system should only be used in non-production environments. + +## Update + +Following is the desired update procedure for validator nodes, described as step-by-step instructions. + +### Update procedure + +- Download the latest Polygon Edge binary from the official GitHub [releases](https://github.com/0xPolygon/polygon-edge/releases) +- Stop the Polygon Edge service ( example: `sudo systemctl stop polygon-edge.service` ) +- Replace the existing `polygon-edge` binary with the downloaded one ( example: `sudo mv polygon-edge /usr/local/bin/` ) +- Check if correct `polygon-edge` version is in place by running `polygon-edge version` - it should correspond to the release version +- Check the release documentation if there are any backwards compatibility steps needed to be done before starting `polygon-edge` service +- Start `polygon-edge` service ( example: `sudo systemctl start polygon-edge.service` ) +- Finally, check the `polygon-edge` log output and make sure everything is running without any `[ERROR]` logs + +:::warning +When there is a breaking release, this update procedure must be performed on all nodes as +the currently running binary is not compatible with the new release. + +This means that the chain must be halted for a short period of time ( until `polygon-edge` binaries are replaced and service restarted ) +so plan accordingly. + +You can use tools like **[Ansible](https://www.ansible.com/)** or some custom script to perform the update efficiently +and minimize chain downtime. +::: + +## Startup procedure + +Following is the desired flow of the startup procedure for Polygon Edge validator + +- Read through the docs listed in [Knowlege Base](#knowledge-base) section +- Apply the latest OS patches on the validator node +- Download the latest `polygon-edge` binary from the official GitHub [releases](https://github.com/0xPolygon/polygon-edge/releases) and place it in local instance `PATH` +- Initialize one of the supported [secrets managers](/docs/category/secret-managers) using `polygon-edge secrets generate` CLI command +- Generate and store secrets using `polygon-edge secrets init` [CLI command](/docs/edge/get-started/cli-commands#secrets-init-flags) +- Take note of `NodeID` and `Public key (address)` values +- Generate `genesis.json` file as described in [cloud setup](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators) using `polygon-edge genesis` [CLI command](/docs/edge/get-started/cli-commands#genesis-flags) +- Generate default config file using `polygon-edge server export` [CLI command](/docs/edge/configuration/sample-config) +- Edit `default-config.yaml` file to accommodate local validator node environment ( file paths, etc. ) +- Create a Polygon Edge service ( `systemd` or similar ) where `polygon-edge` binary will run the server from a `default-config.yaml` file +- Start Polygon Edge server by starting the service ( example: `systemctl start polygon-edge` ) +- Check the `polygon-edge` log output and make sure the blocks are being generated and that there are no `[ERROR]` logs +- Check the chain functionality by calling a JSON-RPC method like [`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid) diff --git a/docs/edge/working-with-node/backup-restore.md b/archive/edge/main-edge/working-with-node/backup-restore.md similarity index 100% rename from docs/edge/working-with-node/backup-restore.md rename to archive/edge/main-edge/working-with-node/backup-restore.md diff --git a/docs/edge/working-with-node/query-json-rpc.md b/archive/edge/main-edge/working-with-node/query-json-rpc.md similarity index 100% rename from docs/edge/working-with-node/query-json-rpc.md rename to archive/edge/main-edge/working-with-node/query-json-rpc.md diff --git a/docs/edge/working-with-node/query-operator-info.md b/archive/edge/main-edge/working-with-node/query-operator-info.md similarity index 100% rename from docs/edge/working-with-node/query-operator-info.md rename to archive/edge/main-edge/working-with-node/query-operator-info.md diff --git a/archive/edge/pt-edge/additional-features/blockscout.md b/archive/edge/pt-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..5aff05fed4 --- /dev/null +++ b/archive/edge/pt-edge/additional-features/blockscout.md @@ -0,0 +1,417 @@ +--- +id: blockscout +title: Blockscout +description: Como configurar uma instância Blockscout para trabalhar com o Polygon Edge. +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## Visão geral {#overview} +Este guia especifica em detalhes como compilar e implantar a instância Blockscout para trabalhar com o Polygon-Edge. +O Blockscout tem a sua própria [documentação](https://docs.blockscout.com/for-developers/manual-deployment), mas este guia concentra-se em instruções passo-a-passo simples, embora detalhadas, sobre como configurar a instância Blockscout. + +## Ambiente {#environment} +* Sistema operativo: [faça o download do link](https://releases.ubuntu.com/20.04/) do Ubuntu Server 20.04 LTS com permissões sudo +* Hardware do servidor: 8CPU / 16GB de RAM / 50GB HDD (LVM) +* Servidor de base de dados: servidor dedicado com 2 CPU / 4GB de RAM / SSD 100GB / PostgreSQL 13.4 + +### Servidor BD {#db-server} +O requisito para seguir este guia é ter um servidor de base de dados pronto, uma base de dados e um utilizador de base de dados configurado. +Este guia não irá entrar em detalhes sobre como implantar e configurar o servidor PostgreSQL. +Existem muitos guias disponíveis para isso como, por exemplo, [o Guia DigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart) + +:::info EXCLUSÃO DE RESPONSABILIDADE + +Este guia destina-se apenas a ajuda colocar o Blockscout em funcionamento numa única instância, o que não é a configuração de produção ideal. +Para produção, é provavelmente aconselhável introduzir o proxy reverso, o balanceador de carga, as opções de escalabilidade etc. na arquitetura. + +::: + +# Procedimento de implantação do Blockscout {#blockscout-deployment-procedure} + +## Parte 1 - instalar as dependências {#part-1-install-dependencies} +Antes do início, precisamos de ter certeza de que temos instalados todos binários de que o Blockscout depende. + +### Atualizar e fazer upgrade do sistema {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### Adicionar repos de erlang {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### Adicionar repo NodeJS {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### Instalar o Rust {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### Instalar versão necessária do Erlang {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### Instalar versão necessária do Elixir {#install-required-version-of-elixir} +A versão do Elixir deve ser `1.13`. Se tentarmos instalar esta versão do repositório oficial, +o `erlang` irá atualizar para `Erlang/OTP 25` e não queremos isso. +Por isso, precisamos instalar a `elixir`versão pré-compilada específica da página de lançamentos do GitHub. + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +Agora precisamos configurar corretamente `exlixir` binários do sistema. +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +Verifique se `elixir` e `erlang` estão devidamente instalados executando `elixir -v`. +A saída deve ser: +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning + +`Erlang/OTP` deve ser versão `24` e `Elixir` deve ser versão `1.13.*`. +Se não for esse o caso, RUN vai ter problemas para compilar o Blockscout e/ou executá-lo. + +::: +:::info + +Confira a página oficial ***[de requisitos do Blockscout](https://docs.blockscout.com/for-developers/information-and-settings/requirements)*** + +::: + +### instalar NodeJS {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### Instalar Cargo {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### Instalar outras dependências {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### Opcionalmente, instale cliente postgresql para verificar a sua conexão de banco de dados {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## Parte 2 - definir variáveis do ambiente {#part-2-set-environment-variables} +Precisamos definir as variáveis do ambiente antes de começar com a compilação Blockscout. +Neste guia, definiremos apenas o mínimo básico para fazê-lo funcionar. +A lista completa de variáveis que podem ser definidas é fornecida [aqui](https://docs.blockscout.com/for-developers/information-and-settings/env-variables) + +### Definir conexão de base de dados como variável de ambiente {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +Teste agora sua conexão de base de dados com parâmetros fornecidos. +Como forneceu vars de PG env, deve ser capaz conectar à base de dados apenas executando: +```bash +psql +``` + +Se a base de dados estiver configurada corretamente, deve ser exibido um prompt de psql: +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +Caso contrário, pode ver um erro como este: +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +Se for este o caso, [estes documentos](https://ubuntu.com/server/docs/databases-postgresql) podem ajudar. + +:::info Conexão de base de dados + +Verifique se todos os problemas de conexão da base de dados foram classificados antes de prosseguir para a próxima parte. É necessário fornecer privilégios de superutilizador para o utilizador do Blockscout. + +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## Parte 3 - faça clone e compile o Blockscout {#part-3-clone-and-compile-blockscout} +Agora finalmente começamos a instalação do Blockscout. + +### Faça o clone do repositório do Blockscout {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### Gere uma base de chave secreta para proteger a construção da produção {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +Na última linha, deve existir uma string longa de caracteres aleatórios . +Isso deve ser definido como sua variável de ambiente `SECRET_KEY_BASE`, antes da etapa seguinte. +Por exemplo: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### Definir o modo de produção {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### Compilar {#compile} +Cd para o diretório do clone e inicie a compilação + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info + +Se tiver implantado anteriormente, remova os ativos estáticos da compilação anterior ***mix phx.digest.clean***. + +::: + +### Migrar bases de dados {#migrate-databases} +:::info + +Esta parte falhará se sua conexão de base de dados não tiver sido configurada corretamente e os +parâmetros na variável de ambiente DATABASE_URL não tiverem sido definidos ou estiverem errados. +O utilizador da base de dados precisa de privilégios de superutilizador. + +::: +```bash +mix do ecto.create, ecto.migrate +``` + +Se precisar largar a base de dados primeiro, execute +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### Instale as dependências NPM e compile os ativos frontend {#install-npm-dependencies-and-compile-frontend-assets} +É necessário alterar o diretório para a pasta que contém os ativos frontend. + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info Seja paciente + +A compilação destes ativos pode levar alguns minutos e não será exibida nenhuma saída. +Pode parecer que o processo está empacado. Por favor, seja paciente e aguarde. +Quando o processo de compilar for concluído, ele deve produzir algo semelhante a: `webpack 5.69.1 compiled with 3 warnings in 104942 ms` + +::: + +### Construir ativos estáticos {#build-static-assets} +Para esta etapa, é necessário retornar à raiza da sua pasta do clone Blockscout. +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### Gerar certificados autoassinados {#generate-self-signed-certificates} +:::info + +Pode ignorar esta etapa se não for usar `https`. + +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## Parte 4 - crie e execute o serviço Blockscout {#part-4-create-and-run-blockscout-service} +Nesta parte, precisamos configurar um serviço de sistema da forma que queremos que o Blockscout seja executado no segundo plano e persista após a reinicialização do sistema. + +### Criar ficheiro de serviço {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### Editar ficheiro de serviço {#edit-service-file} +Use o seu editor de texto Linux favorito para editar este ficheiro e configurar serviço +```bash +sudo vi /etc/systemd/system/explorer.service +``` +O conteúdo do ficheiro explorer.service deve ser semelhante a este: +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### Ativar serviço na inicialização do sistema {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### Mova a sua pasta do clone Blockscout para a localização em todo o sistema {#move-your-blockscout-clone-folder-to-system-wide-location} +O serviço Blockscout precisa ter acesso à pasta que foi clonada no repositório Blockscout e compilou todos os ativos. +```bash +sudo mv ~/blockscout /usr/local +``` + +### Crie ficheiro env vars que será usado pelo serviço Blockscout {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info + +Use `SECRET_KEY_BASE` que foi gerado na Parte 3. + +::: +Salve o ficheiro e saia. + +### Finalmente, inicie o serviço Blockscout {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## Parte 5 - teste a funcionalidade da sua instância Blockscout {#part-5-test-out-the-functionality-of-your-blockscout-instance} +Agora tudo o que resta a fazer é verificar se o serviço Blockscout está em execução. +Verifique o status do serviço com: +```bash +sudo systemctl status explorer.service +``` + +Para verificar a saída do serviço: +```bash +sudo journalctl -u explorer.service -f +``` + +É possível verificar se existem novas portas de escuta: +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +Obtenha uma lista de portas de escuta. Na lista, deve haver algo assim: +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +Serviço web do Blockscout executa a porta e o protocolo definidos no ficheiro env. Neste exemplo, ele é executado em `4000`(http). . +Se estiver tudo bem, ele deve ser capaz de acessar o portal web do Blockscout com `http://:4000`. + +## Considerações {#considerations} +Para melhor desempenho, é aconselhável ter um nó não validador de arquivo completo de `polygon-edge` dedicado/local +que será usado exclusivamente para consultas do Blockscout. +A `json-rpc`API deste nó não precisa ser exposta publicamente, já que o Blockscout executa todas as consultas a partir do backend. + + +## Conclusões finais {#final-thoughts} +Acabamos de implantar uma única instância do Blockscout, que funciona bem. No entanto, para produção, é aconselhável colocar esta instância atrás de um proxy reverso como o Nginx. +Também deve pensar na escalabilidade da base de dados e da instância, dependendo do seu caso de uso. + +Definitivamente, recomendamos consultar a [documentação oficial do Blockscout](https://docs.blockscout.com/) visto que há muitas opções de personalização. \ No newline at end of file diff --git a/archive/edge/pt-edge/additional-features/chainbridge/definitions.md b/archive/edge/pt-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..eee5dbfd50 --- /dev/null +++ b/archive/edge/pt-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,221 @@ +--- +id: definitions +title: Definições gerais +description: Definições gerais para termos usados na ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## Relayer {#relayer} +A Chainbridge é uma bridge tipo relayer. O papel de um relayer consiste em votar a execução de uma solicitação (quantos tokens queimar/emitir, por exemplo). +Monitoriza eventos de todas as chains e vota a favor de uma proposta no contrato Bridge da chain de destino quando recebe um evento `Deposit` de uma chain. Um relayer chama um método no contrato Bridge para executar a proposta depois de ter sido apresentado o número necessário de votos. A bridge delega a execução no contrato Handler. + + +## Tipos de contratos {#types-of-contracts} +Na ChainBridge, existem três tipos de contratos em cada chain, denominados Bridge/Handler/Target. + +| **Tipo** | **Descrição** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Contrato Bridge | Em cada chain é necessário implantar um contrato Bridge que gere solicitações, votos e execuções. Os utilizadores solicitam o `deposit` na Bridge para iniciar uma transferência e a Bridge delega o processo no contrato Handler correspondente ao contrato Target. Assim que o contrato Handler tiver conseguido chamar o contrato Target, o contrato Bridge emite um evento de `Deposit` para notificar os relayers. | +| Contrato Handler | Este contrato interage com o contrato Target para executar um depósito ou proposta. Valida a solicitação do utilizador, chama o contrato Target e ajuda com algumas definições para o contrato Target. Existem certos contratos Handler para chamar cada contrato Target que tenha uma interface diferente. As chamadas indiretas pelo contrato Handler fazem com que a bridge viabilize a transferência de qualquer tipo de ativos ou dados. Atualmente, a ChainBridge implementa três tipos de contratos Handler: ERC20Handler, ERC721Handler e GenericHandler. | +| Contrato Target | Contrato que gere os ativos a serem trocados ou as mensagens transferidas entre chains. A interação com este contrato será feita a partir de cada sidechain da bridge. | + +
+ +![Arquitetura da ChainBridge](/img/edge/chainbridge/architecture.svg) +*Arquitetura da ChainBridge* + +
+ +
+ +![Fluxo de trabalho para transferência de tokens ERC-20](/img/edge/chainbridge/erc20-workflow.svg) +*ex.: fluxo de trabalho para transferência de um token ERC-20* + +
+ +## Tipos de contas {#types-of-accounts} + +Antes de começar, certifique-se de que as contas têm uma quantidade suficiente de tokens nativos para criar transações. No Polygon Edge, pode atribuir saldos pré-minerados às contas ao gerar o bloco de génese. + +| **Tipo** | **Descrição** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Admin | A esta conta será atribuído, por defeito, o papel de administrador. | +| User | Conta do remetente/destinatário que envia/recebe ativos. A conta do remetente paga as taxas de gás ao aprovar a transferência de tokens e solicitar o depósito no contrato Bridge para iniciar uma transferência. | + +:::info O papel de administrador + +Determinadas ações só podem ser executadas pela conta com funções de administrador. Por defeito, o implementador do contrato Bridge assume o papel de administrador. Pode ver abaixo como atribuir o papel de administrador a outra conta ou como o remover. + +### Add admin role {#add-admin-role} + +Adiciona um administrador + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### Revoke admin role {#revoke-admin-role} + +Remove um administrador + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## As operações permitidas pela conta de `admin` são indicadas abaixo. {#account-are-as-below} + +### Definir um recurso {#set-resource} + +Registe a identificação de um recurso com um endereço de contrato para um handler. + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Tornar um contrato queimável/minerável {#make-contract-burnable-mintable} + +Defina o contrato de um token como minerável/queimável num handler. + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Cancelar proposta {#cancel-proposal} + +Cancele a proposta para execução + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### Pausar/Anular pausa {#pause-unpause} + +Pause temporariamente depósitos, a criação de propostas, a votação e a execução de depósitos. + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### Alterar taxa {#change-fee} + +Altere a taxa que será paga ao contrato Bridge + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### Adicionar/Remover um relayer {#add-remove-a-relayer} + +Adicione uma conta como novo relayer ou remova uma conta dos relayers + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### Alterar limite do relayer {#change-relayer-threshold} + +Altere o número de votos necessários para a execução de uma proposta + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## ID da chain {#chain-id} + +A `chainId`da Chainbridge é um valor arbitrário usado na bridge para fazer a distinção entre as redes blockchain e tem de estar no intervalo de uint8. Não deve ser confundida com a ID da chain da rede; não são a mesma coisa. Este valor tem de ser exclusivo, mas não tem de ser o mesmo que a identificação da rede. + +Neste exemplo, definimos `99` na `chainId`, porque a identificação da chain do testnet Mumbai é `80001`, o qual não pode ser representado com um uint8. + +## ID do recurso {#resource-id} + +A identificação do recurso é um valor exclusivo de 32 bytes num ambiente cross-chain, associado a um determinado ativo (recurso) que está a ser transferido entre redes. + +A identificação do recurso é arbitrária, mas, como convenção, geralmente o último byte contém a identificação da chain de origem (a rede que deu origem a este ativo). + +## URL JSON-RPC para Polygon PoS {#json-rpc-url-for-polygon-pos} + +Neste guia, usaremos https://rpc-mumbai.matic.today, um URL JSON-RPC público fornecido pela Polygon, que pode ter limites de tráfego ou taxa. Este será usado apenas para ligação ao testnet Mumbai da Polygon. Recomendamos que obtenha o seu URL JSON-RPC através de um serviço externo como a Infura, pois a implantação de contratos irá enviar muitas consultas/solicitações para a JSON-RPC. + +## Formas de processar a transferência de tokens {#ways-of-processing-the-transfer-of-tokens} +Ao transferir tokens ERC-20 entre chains, eles podem ser processados de dois modos diferentes: + +### Modo de bloqueio/desbloqueio {#lock-release-mode} +Chain de origem: os tokens que está a enviar serão bloqueados no Contrato Handler.
+Chain de destino: a mesma quantidade de tokens que enviou na chain de origem será desbloqueada e transferida do contrato Handler para a conta do destinatário na chain de destino. + +### Modo de queima/mineração {#burn-mint-mode} +Chain de origem: os tokens que está a enviar serão queimados.
+Chain de destino: a mesma quantidade de tokens que enviou e queimou na chain de origem será minerada na chain de destino e enviada para a conta do destinatário. + +Pode usar modos diferentes em cada chain. Isto significa que pode bloquear um token na chain principal enquanto minera um token na subchain para transferência. Por exemplo, pode fazer sentido bloquear/desbloquear tokens se a oferta total ou o calendário de mineração forem controlados. Os tokens serão minerados/queimados se o contrato na subchain tiver de seguir a oferta na chain principal. + +O modo padrão é o modo de bloqueio/desbloqueio. Se quiser tornar os tokens mineráveis/queimáveis, precisa de chamar o método `adminSetBurnable`. Se pretende minerar tokens aquando da execução, terá de conceder a função de `minter` ao contrato ERC20Handler. + + diff --git a/archive/edge/pt-edge/additional-features/chainbridge/overview.md b/archive/edge/pt-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..e47a3d635b --- /dev/null +++ b/archive/edge/pt-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Visão geral +description: Visão geral da ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## O que é a ChainBridge? {#what-is-chainbridge} + +A ChainBridge é uma bridge de blockchain modular, multidirecional que suporta chains compatíveis com EVM e Substrate, criada pela ChainSafe. Permite que os utilizadores transfiram todo o tipo de ativos ou mensagens entre duas chains diferentes. + +Para saber mais sobre a ChainBridge, visite primeiro os [documentos oficiais](https://chainbridge.chainsafe.io/) fornecidos pelos respetivos programadores. + +Este guia foi criado para o ajudar a integrar a Chainbridge no Polygon Edge. Ele segue a configuração de uma bridge entre um Polygon PoS (testnet Mumbai) em execução e uma rede Polygon Edge local. + +## Requisitos {#requirements} + +Neste guia, irá executar nós do Polygon Edge, um relayer ChainBridge (mais sobre este assunto [aqui](/docs/edge/additional-features/chainbridge/definitions)) e a ferramenta cb-sol-cli, que é uma ferramenta CLI para implantar contratos localmente, registando o recurso e alterando as configurações da bridge (veja também [aqui](https://chainbridge.chainsafe.io/cli-options/#cli-options)). Antes de iniciar a configuração, são necessários os seguintes ambientes: + +* Go: >= 1.17 +* Node.js >= 16.13.0 +* Git + + +Além disso, terá de clonar os seguintes repositórios com as versões para executar algumas aplicações. + +* [Polygon Edge](https://github.com/0xPolygon/polygon-edge): no ramo `develop` +* [ChainBridge](https://github.com/ChainSafe/ChainBridge): v1.1.5 +* [Ferramentas de Implantação ChainBridge](https://github.com/ChainSafe/chainbridge-deploy): `f2aa093` no ramo `main` + + +É necessário configurar uma rede Polygon Edge antes de continuar para a seção seguinte. Visite a página [Configuração Local](/docs/edge/get-started/set-up-ibft-locally) ou [Configuração na Nuvem](/docs/edge/get-started/set-up-ibft-on-the-cloud) para mais detalhes. \ No newline at end of file diff --git a/archive/edge/pt-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/pt-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..1928eba4a3 --- /dev/null +++ b/archive/edge/pt-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,142 @@ +--- +id: setup-erc20-transfer +title: Transferência de tokens ERC-20 +description: Como configurar a transferência de ERC-20 na ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Até agora, configuramos a bridge para a troca de ativos/dados entre as chains Polygon PoS e Polygon Edge. Esta secção irá orientá-lo através da configuração de uma bridge ERC-20 e do envio de tokens entre diferentes blockchains. + +## Etapa 1: registar a ID do recurso {#step-1-register-resource-id} + +Em primeiro lugar, irá registar uma identificação que associe os recursos num ambiente cross-chain. A identificação de um recurso é um valor de 32 bytes que tem de ser exclusivo para o recurso que estamos a transferir entre estas blockchains. As identificações dos recursos são arbitrárias, mas podem ter a identificação da home chain no último byte, como convenção (a home chain é a rede de origem de tais recursos). + +Para registar a identificação dos recursos, pode utilizar o comando `cb-sol-cli bridge register-resource`. Terá de fornecer a chave privada da conta de `admin`. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (Opcional) Tornar os contratos mineráveis/queimáveis {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## Etapa 2: transferir tokens ERC-20 {#step-2-transfer-erc20-token} + +Iremos enviar tokens ERC-20 da chain Polygon PoS para a chain Polygon Edge. + +Primeiro, irá obter tokens por mineração. Os novos tokens podem ser minerados por uma conta com a função de `minter`. Por defeito, a conta que implantou o contrato ERC-20 tem a função de `minter`. Para especificar outras contas como membros da função de `minter`, é necessário executar o comando `cb-sol-cli erc20 add-minter`. + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +Para verificar o saldo atual, pode usar o comando `cb-sol-cli erc20 balance`. + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +Em seguida, é necessária a aprovação da transferência de tokens ERC-20 pelo Handler ERC-20 + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +Para transferir tokens para as chains Polygon Edge, iremos chamar um `deposit`. + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Depois de concluir a transação de depósito, o relayer irá obter o evento e votar a proposta. Ele executa uma transação para enviar tokens para a conta do destinatário na chain Polygon Edge depois de ter sido apresentado o número necessário de votos. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Assim que a execução da transação tiver sido bem-sucedida, irá obter tokens na chain Polygon Edge. + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/pt-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/pt-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..1b7b5e5835 --- /dev/null +++ b/archive/edge/pt-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,134 @@ +--- +id: setup-erc721-transfer +title: Transferência de NFT ERC-721 +description: Como configurar a transferência de ERC-721 na ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Esta secção irá orientá-lo através da configuração de uma bridge ERC-721 e do envio de tokens entre redes de blockchain. + +## Etapa 1: registar a ID do recurso {#step-1-register-resource-id} + +Primeiro terá de registar a identificação de recursos para o token ERC-721 nos contratos Bridge de ambas as chains. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (Opcional): Tornar os contratos mineráveis/queimáveis {#optional-make-contracts-mintable-burnable} + +Para tornar os tokens mineráveis/queimáveis, terá de chamar os seguintes comandos: + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## Etapa 2: transferir NFT {#step-2-transfer-nft} + +Em primeiro lugar, irá minerar um NFT, se precisar. + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Para verificar o proprietário do NFT, pode usar `cb-sol-cli erc721 owner` + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Em seguida, irá aprovar a transferência do NFT pelo Handler ERC-721 + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Por fim, irá iniciar a transferência + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +O relayer irá obter o evento e votar a proposta. Ele executa uma transação para enviar NFTs para a conta do destinatário na chain Polygon Edge depois de ter sido apresentado o número necessário de votos. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Pode verificar o proprietário do NFT na rede Polygon Edge depois de concluir a execução. + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/pt-edge/additional-features/chainbridge/setup.md b/archive/edge/pt-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..3fe7c18455 --- /dev/null +++ b/archive/edge/pt-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,198 @@ +--- +id: setup +title: Configuração +description: Como configurar o chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Implantação de contratos {#contracts-deployment} + +Nesta seção, vamos implantar os contratos necessários para a chain do Polygon PoS e do Polygon Edge com `cb-sol-cli`. + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +Em primeiro lugar, vamos implantar contratos para chain Polygon PoS por `cb-sol-cli deploy`comando. O sinalizador `--all` faz com que o comando implante todos os contratos, incluindo Bridge, Handler ERC-20, Handler ERC-721, Generic Handler, ERC-20 e ERC-721. Além disso, ele irá definir o endereço de conta de relayer padrão e o limiar + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +Saiba mais sobre o chainID e o URL JSON-RPC [aqui](/docs/edge/additional-features/chainbridge/definitions) + +:::caution + +O preço padrão do gás em `cb-sol-cli` é `20000000` (`0.02 Gwei`). Para definir o preço do gás numa transação, defina o valor usando o argumento `--gasPrice`. + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +O contrato Bridge consome aproximadamente gás 0x3f97b8 (4167608) para ser implantado. Certifique-se de que os blocos que estão sendo gerados tenham um limite de gás de bloqueio para conter a transação de criação de contratos. Para saber mais sobre o limite de gás de bloqueio no Polygon Edge, visite +a [Configuração Local](/docs/edge/get-started/set-up-ibft-locally) + +::: + +Depois que os contratos tiverem sido implantados, receberá o seguinte resultado: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +Agora podemos implantar os contratos na chain Polygon Edge. + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Salve as saídas de terminal com os endereços de contrato inteligente, visto que iremos precisar deles para a etapa seguinte. + +## Configuração do relayer {#relayer-setup} + +Nesta secção, vamos iniciar um relayer para trocar dados entre 2 chains. + +Primeiro, precisamos clonar e construir o repositório ChainBridge. + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +Em seguida, é necessário criar `config.json` e definir os URLs JSON-RPC, endereço de relayer e endereço de contratos para chain. + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +Para iniciar um relayer, é necessário importar a chave privada correspondente ao endereço de conta de relayer. Terá de inserir a senha quando importar a chave privada. Assim que a importação tiver sido bem-sucedida, a chave será armazenada em `keys/
.key`. + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +Em seguida, pode inciar o relayer. Terá de inserir a mesma senha que escolheu para armazenar a chave no início. + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +Assim que o relayer é iniciado, ele começa a observar novos blocos na chain. diff --git a/archive/edge/pt-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/pt-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..59bbbd4f28 --- /dev/null +++ b/archive/edge/pt-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,256 @@ +--- +id: use-case-erc20-bridge +title: Caso de utilização - Bridge ERC-20 +description: Exemplo para contrato do Bridge ERC-20 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +Esta secção visa fornecer um fluxo de configuração do Bridge ERC-721 para um caso de utilização prático. + +Neste guia, irá usar a testnet Mumbai da Polygon PoS e a chain local Polygon Edge. Certifique-se de que tem o endpoint JSON-RPC para Mumbai e de que configurou o Polygon Edge no ambiente local. Consulte a [Configuração Local](/docs/edge/get-started/set-up-ibft-locally) ou [Configuração na Nuvem](/docs/edge/get-started/set-up-ibft-on-the-cloud) para mais detalhes. + +## Cenário {#scenario} + +Este cenário é configurar um Bridge para o token ERC-20 que foi implantado na chain pública (Polygon PoS) para possibilitar uma transferência de baixo custo em chain privada (Polygon Edge) para utilizadores em um caso regular. Neste caso, o fornecimento de total de token foi definido na chain pública e apenas o valor do token que foi transferido da chain pública para a chain privada deve existir na chain privada. Por este motivo, terá de usar o modo de bloqueio/desbloqueio na chain pública e o modo de queima/mineração na chain privada. + +Ao enviar NFTs da chain pública para a chain privada, o NFT será bloqueado no contrato Handler ERC20 da chain pública e o mesmo valor de token será minerado na chain privada. Por outro lado, e no caso de transferência da chain privada para a pública, o token da chain privada será queimado e o mesmo valor de token será desbloqueado do contrato Handler ERC20 da chain pública. + +## Contratos {#contracts} + +Explicação com um contrato ERC20 simples, em vez do contrato desenvolvido pela ChainBridge. Para o modo queimar/minerar, o contrato ERC-20 deve ter os métodos `mint` e `burnFrom`, além de métodos ERC-20 como este: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +Encontra todos os códigos e scripts no repositótio do Github [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Etapa 1: Implantar contratos de Bridge e Handler ERC20 {#step1-deploy-bridge-and-erc20-handler-contracts} + +Em primeiro lugar, terá de implantar contratos de Bridge e ERC720Handler nas duas chains usando `cb-sol-cli`. + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Irá obter endereços dos contratos de Bridge e ERC20Handler como: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Etapa 2: implantar contrato ERC20 {#step2-deploy-your-erc20-contract} + +Irá implantar seu contrato ERC20. Este exemplo orienta-o com base no projeto hardhat [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Crie o ficheiro `.env` e defina os seguintes valores. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Em seguida, irá implantar o contrato ERC20 nas duas chains. + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +Depois de uma implantação bem-sucedida, obterá um endereço do contrato, como segue: + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## Etapa 3: registar a identificação do recurso na Bridge {#step3-register-resource-id-in-bridge} + +Irá registar uma identificação que associe o recurso num ambiente cross-chain. É necessário definir a mesma identificação de recurso nas duas chains. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## Etapa 4: definir o modo de queima/mineração na bridge ERC20 do Edge {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +O bridge espera funcionar como modo para queimar/minerar no Polygon Edge. Irá definir o modo queimar/minerar usando `cb-sol-cli`. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +E é necessário conceder uma função de minerador e queimador ao contrato Handler ERC20. + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Etapa 5: minerar token {#step5-mint-token} + +Os novos tokens ERC-20 serão minerados na chain Mumbai. + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +A conta terá o token minerado depois de concluída a transação. + +## Etapa 6: iniciar transferência do ERC20 {#step6-start-erc20-transfer} + +Antes de iniciar esta etapa, certifique-se de que foi iniciado um relayer. Consulte a [Configuração](/docs/edge/additional-features/chainbridge/setup) para mais detalhes. + +Durante a transferência de token de Mumbai para Edge, o contrato do Handler ERC20 no Mumbai retira tokens da sua conta. Irá chamar a aprovação antes da transferência: + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +Finalmente, você inicia a transferência de tokens do Mumbai para o Edge usando o `cb-sol-cli`. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Depois de concluir a transação de depósito, o relayer irá obter o evento e votar a proposta. +Ele executa uma transação para enviar tokens para a conta do destinatário na chain Polygon Edge depois de ter sido apresentado o número necessário de votos. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Assim que a execução da transação for bem-sucedida, irá obter os tokens na chain Polygon Edge. diff --git a/archive/edge/pt-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/pt-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..3abeae7203 --- /dev/null +++ b/archive/edge/pt-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,308 @@ +--- +id: use-case-erc721-bridge +title: Caso de utilização - Bridge ERC-721 +description: Exemplo para contrato Bridge ERC-721 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +Esta secção visa fornecer um fluxo de configuração do Bridge ERC-721 para um caso de utilização prático. + +Neste guia, irá usar a testnet Mumbai da Polygon PoS e a chain local Polygon Edge. Certifique-se de que tem o endpoint JSON-RPC para Mumbai e de que configurou o Polygon Edge no ambiente local. Consulte a [Configuração Local](/docs/edge/get-started/set-up-ibft-locally) ou [Configuração na Nuvem](/docs/edge/get-started/set-up-ibft-on-the-cloud) para mais detalhes. + +## Cenário {#scenario} + +Este cenário consiste em configurar uma Bridge para o NFT ERC-721 que já foi implantado na chain pública (Polygon PoS) para permitir a transferência de baixo custo numa chain privada (Polygon Edge), numa situação normal. Neste caso, os metadados originais foram definidos na chain pública e os únicos NFTs que foram transferidos da chain pública podem existir na chain privada. Por este motivo, terá de usar o modo de bloqueio/desbloqueio na chain pública e o modo de queima/mineração na chain privada. + +Ao enviar NFTs da chain pública para a chain privada, o NFT será bloqueado no contrato Handler ERC-721 da chain pública e o mesmo NFT será minerado na chain privada. Por outro lado, e no caso de transferência da chain privada para a pública, o NFT da chain privada será queimado e o mesmo NFT será desbloqueado do contrato Handler ERC-721 da chain pública. + +## Contratos {#contracts} + +Explicação com um contrato ERC-721 simples, em vez do contrato desenvolvido pela ChainBridge. Para o modo de queima/mineração, o contrato ERC-721 deve ter os métodos `burn` e `mint`, além dos métodos definidos em ERC-721, nomeadamente: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +Encontra todos os códigos e scripts no repositótio do Github [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Etapa 1: implantar contratos Bridge e Handler ERC-721 {#step1-deploy-bridge-and-erc721-handler-contracts} + +Em primeiro lugar, terá de implantar contratos Bridge e ERC721Handler nas duas chains usando `cb-sol-cli`. + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Irá obter endereços dos contratos Bridge e ERC721Handler como mostrado abaixo: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Etapa 2: implantar o seu contrato ERC-721 {#step2-deploy-your-erc721-contract} + +Irá implantar o seu contrato ERC-721. Este exemplo orienta-o com base no projeto hardhat [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Crie o ficheiro `.env` e defina os seguintes valores. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Em seguida, irá implantar o contrato ERC-721 nas duas chains. + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +Depois de uma implantação bem-sucedida, obterá o endereço do contrato, como segue: + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## Etapa 3: registar a ID do recurso na Bridge {#step3-register-resource-id-in-bridge} + +Irá registar uma identificação que associe os recursos num ambiente cross-chain. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## Etapa 4: definir o modo de queima/mineração na bridge ERC-721 do Edge {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +A Bridge espera trabalhar como modo de queima/mineração no Edge. Irá definir o modo de queima/mineração. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +E é necessário conceder um papel de minerador e queimador ao contrato Handler ERC-721. + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Etapa 5: minerar o NFT {#step5-mint-nft} + +Irá minerar o novo NFT ERC-721 na chain Mumbai. + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +A conta terá o NFT minerado depois de concluída a transação. + +## Etapa 6: iniciar a transferência do ERC-721 {#step6-start-erc721-transfer} + +Antes de iniciar esta etapa, certifique-se de que começou o relayer. Consulte a [Configuração](/docs/edge/additional-features/chainbridge/setup) para mais detalhes. + +Durante a transferência do NFT da Mumbai para o Edge, o contrato Handler ERC-721 em Mumbai retira o NFT da sua conta. Irá chamar a aprovação antes da transferência: + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +Por fim, deverá iniciar a transferência do NFT da Mumbai para o Edge. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +Depois de concluir a transação de depósito, o relayer irá obter o evento e votar a proposta. +Ele executa uma transação para enviar o NFT para a conta do destinatário na chain Polygon Edge depois de ter sido apresentado o número necessário de votos. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Assim que a execução da transação for bem-sucedida, irá obter o NFT na chain Polygon Edge. diff --git a/archive/edge/pt-edge/additional-features/permission-contract-deployment.md b/archive/edge/pt-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..cf0fbb427a --- /dev/null +++ b/archive/edge/pt-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,86 @@ +--- +id: permission-contract-deployment +title: Permissão para implantação de contratos inteligentes +description: Como adicionar a permissão para implantação de contratos inteligentes. +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## Visão geral {#overview} + +Este guia indica, em detalhe, como criar uma lista de permissões de endereços que podem implantar contratos inteligentes. +Por vezes, os operadores de rede pretendem evitar que os utilizadores implantem contratos inteligentes que não estejam relacionados com o propósito da rede. Os operadores de rede podem: + +1. Incluir endereços na lista de permissões para implantação de contratos inteligentes +2. Remover os endereços da lista de permissões para implantação de contratos inteligentes + +## Apresentação de vídeo {#video-presentation} + +[![implantação do contrato de permissão](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## Como usá-la? {#how-to-use-it} + + +Encontra todos os comandos cli relacionados com a lista de permissões de implantação na página [Comandos CLI](/docs/edge/get-started/cli-commands#whitelist-commands). + +* `whitelist show`: Mostra informações da lista de permissões +* `whitelist deployment --add`: Adiciona um endereço novo à lista de permissões de implantação de contratos +* `whitelist deployment --remove`: Remove um endereço novo da lista de permissões de implantação de contratos + +#### Mostrar todos os endereços na lista de permissões de implantação {#show-all-addresses-in-the-deployment-whitelist} + +Existem 2 maneiras de encontrar endereços na lista de permissões de implantação. +1. Procurar na `genesis.json` onde as listas de permissões são guardadas +2. Executar `whitelist show`, que imprime informação para todas as listas de permissões suportadas pelo Polygon Edge + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### Adicionar um endereço à lista de permissões de implantação {#add-an-address-to-the-deployment-whitelist} + +Para adicionar um endereço novo à lista de permissões de implantação, execute o comando CLI `whitelist deployment --add [ADDRESS]`. Não há limite para o número de endereços presentes na lista de permissões. Os contratos só podem ser implantados pelos endereços que constam da lista de permissões de implantação. Se a lista de permissões estiver vazia, qualquer endereço poderá efetuar a implantação + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### Remover um endereço da lista de permissões de implantação {#remove-an-address-from-the-deployment-whitelist} + +Para remover um endereço da lista de permissões de implantação, execute o comando CLI `whitelist deployment --remove [ADDRESS]`. Os contratos só podem ser implantados pelos endereços que constam da lista de permissões de implantação. Se a lista de permissões estiver vazia, qualquer endereço poderá efetuar a implantação + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/pt-edge/architecture/modules/blockchain.md b/archive/edge/pt-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..ac3b117687 --- /dev/null +++ b/archive/edge/pt-edge/architecture/modules/blockchain.md @@ -0,0 +1,159 @@ +--- +id: blockchain +title: Blockchain +description: Explicação para módulos de blockchain e estado da Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## Visão geral {#overview} + +Um dos principal módulos do Polygon Edge são **blockchain** e **Estado**.
+ +**Blockchain** é a potência que lida com reorganizações de blocos. Isso significa que ele controla toda a lógica seguida quando um bloco for incluído na blockchain. + +**Estado** representa o objeto de *transição de estado*. Ele gerencia as mudanças de estado quando um novo bloco é incluído.
Entre outras coisas, o **Estado** controla: +* Transações em execução +* Execução do EVM +* Alteração de tentativas do Merkle +* Muito mais, o que é coberto na seção **Estado** correspondente 🙂 + +A principal conclusão é que essas duas partes estão muito conectadas e trabalham em conjunto para que o cliente continue a operar.
Por exemplo, quando a camada **Blockchain** recebe um novo bloco (e não ocorre nenhuma reorganização), ele chama o **Estado** para realizar uma transição de estado. + +O **Blockchain** também tem de lidar com algumas partes relacionadas ao consenso (ex. *este ethHash está correto?*, *este PoW está correto?*).
Numa frase, é **o principal núcleo de lógica através do qual todos os blocos são incluídos**. + +## *WriteBlocks* + +Uma das partes mais importantes relacionadas à camada **blockchain** é o método *WriteBlocks*: + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +O método *WriteBlocks* é o ponto de entrada para escrever blocos na blockchain. Como parâmetro, ele aceita uma variedade de blocos.
+Em primeiro lugar, os blocos são validados. Depois, eles são gravados na chain. + +A *transição de estado* real é realizada chamando o método *processBlock* no *WriteBlocks*. + +Vale ressaltar que, como é o ponto de entrada para gravar blocos na blockchain, outros módulos (como o **Sealer**) utilizam este método. + +## Assinaturas do blockchain {#blockchain-subscriptions} + +Tem de haver uma maneira de monitorar as alterações relacionadas ao blockchain.
+É aqui que as **Assinaturas** entram. + +As assinaturas são uma maneira de aproveitar os fluxos de eventos blockchain e receber um volume de dados consideráveis instantaneamente. + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +Os **Eventos de Blockchain** contêm informações sobre as alterações realizadas na chain real. Isso inclui reorganizações, bem como novos blocos: + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip Atualizador +Lembra-se quando mencionamos o comando do ***monitor*** no [Comando CLI](/docs/edge/get-started/cli-commands)? + +Os eventos blockchain são eventos originais que ocorrem no Polygon Edge e são mapeados posteriormente para uma mensagem de buffers de protocolo para fácil transferência. + +::: \ No newline at end of file diff --git a/archive/edge/pt-edge/architecture/modules/consensus.md b/archive/edge/pt-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..bae205f6e3 --- /dev/null +++ b/archive/edge/pt-edge/architecture/modules/consensus.md @@ -0,0 +1,512 @@ +--- +id: consensus +title: Consenso +description: Explicação para o módulo Consenso do Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## Visão geral {#overview} + +O módulo **Consenso** fornece uma interface para os mecanismos de consenso. + +Atualmente, os mecanismos de consenso a seguir estão disponíveis: +* **PoA do IBFT** +* **PoS do IBFT** + +O Polygon Edge quer manter um estado de modularidade e plugabilidade.
+É por isso que a lógica do consenso principal foi eliminada, para que os novos mecanismos de consenso possam ser construídos sobre ela, +sem comprometer a usabilidade e a facilidade de uso. + +## Interface de consenso {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + +A interface de ***Consenso*** é o núcleo da abstração mencionada.
+* O método **VerifyHeader** representa uma função auxiliar, que a camada de consenso expõe à camada **blockchain** +Seu objetivo é realizar a verificação do cabeçalho +* O método **Iniciar** simplesmente inicia o processo de consenso e tudo que está associado a ele. Isso inclui a sincronização, +selagem, tudo o que precisa ser feito +* O método **Fechar** fecha a conexão de consenso + +## Configuração do consenso {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +Em alguns momentos, você pode querer passar um local personalizado para o protocolo de consenso armazenar dados, ou talvez, +um mapa de valores chaves personalizados que você deseja que o mecanismo de consenso use. Isso pode ser realizado através da estrutura ***Config*** +que é lida quando uma nova instância do consenso é criada. + +## IBFT {#ibft} + +### ExtraData {#extradata} + +O objeto do cabeçalho do blockchain, entre outros campos, tem um campo chamado **ExtraData**. + +O IBFT usa este campo adicional para armazenar informações operacionais sobre o bloco, respondendo perguntas como: +* "Quem assinou este bloco?" +* "Quem são os validadores deste bloco?" + +Estes campos adicionais do IBFT são definidos da seguinte forma: +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### Dados da assinatura {#signing-data} + +Para o nó assinar informações no IBFT, ele usa o método *signHash*: +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +Outro método notável é o *VerifyCommittedFields*, que verifica se as selagens comprometidas são de validadores válidos: +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### Snapshots {#snapshots} + +Os Snapshots, como o próprio nome indica, estão lá para fornecer um *snapshot*, ou o *estado* de sistema em qualquer altura do bloco (número). + +Os Snapshots contêm um conjunto de nós que são validadores, bem como informações de votação (os validadores podem votar em outros validadores). +Os validadores incluem informações de votação no cabeçalho **do minerador** arquivado e alteram o valor do **nonce**: +* O nonce é **composto apenas de números 1** se o nó quiser remover um validador +* O nonce é **inteiramente de números 0** se o nó quiser adicionar um validador + +Os Snapshots são calculados usando o método ***processHeaders***: + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +Em geral, este método é chamado com 1 cabeçalho, mas o fluxo é igual, até mesmo com múltiplos cabeçalhos.
+Para cada cabeçalho aprovado, o IBFT precisa verificar se o proponente do cabeçalho é o validador. Isso pode ser feito facilmente +utilizando o snapshot mais recente e verificando se o nó está no conjunto de validadores. + +Em seguida, o nonce é verificado. O voto é incluído e calculado e, se houver votos suficientes, o nó é adicionado/removido do +conjunto de validadores e, em seguida, o novo snapshot é salvo. + +#### Armazenamento de Snapshots {#snapshot-store} + +O serviço de snapshots gerencia e atualiza uma entidade chamada **snapshotStore**, que armazena a lista de todos os snapshots disponíveis. +Usando isso, o serviço é capaz de descobrir rapidamente com o que o snapshot está associado a que altura do bloco. +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### Inicialização do IBFT {#ibft-startup} + +Para iniciar o IBFT, o Polygon Edge precisa primeiramente configurar o transporte do IBFT: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +Essencialmente, cria um novo tópico com o protocolo IBFT, com uma mensagem do novo protocolo Buff.
+As mensagens destinam-se a ser usadas por validadores. O Polygon Edge assina o tópico e controla as mensagens em conformidade com ele. + +#### MessageReq {#messagereq} + +A mensagem trocada por validadores: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +O campo **Exibir** no **MessageReq** representa a posição atual do nó dentro da chain. +Ele tem uma *rodada* e um atributo de *sequência*. +* A **rodada** representa a rodada do proponente para a altura +* A **sequência** representa a altura do blockchain + +O *msgQueue* arquivado na implantação do IBFT tem o objetivo de armazenar solicitações de mensagem. Ele ordena as mensagens pela +*Visualização* (em primeiro lugar por sequência, em seguida, por rodada). A implementação do IBFT também possui filas diferentes para estados diferentes no sistema. + +### Estados do IBFT {#ibft-states} + +Depois que o mecanismo de consenso é iniciado usando o método **Iniciar**, ele é executado em um loop infinito que simula uma máquina de estado: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### SyncState {#syncstate} + +Inicialmente, todos os nós começam no estado **Sincr**. + +Isso ocorre porque novos dados precisam ser obtidos do blockchain. O cliente precisa descobrir se é o validador, +encontrar o snapshot atual. Este estado resolve qualquer bloco pendente. + +Depois que a sincronização terminar e o cliente determinar que ele realmente é um validador, ele precisa transferir para **AcceptState**. +Se o cliente **não** for um validador, ele continuará sincronizando e permanecerá no **SyncState** + +#### AcceptState {#acceptstate} + +O estado **Aceitar** sempre verifica o snapshot e o conjunto de validadores. Se o nó atual não estiver no conjunto de validadores, +ele retorna ao estado **Sync**. + +Por outro lado, se o nó **for** um validador, ele calcula o proponente. Se for descoberto que o nó atual é o +proponente, ele constrói um bloco e envia um pré-preparo. Em seguida, prepara mensagens. + +* Mensagens pré-preparadas: as mensagens enviadas por proponentes a validadores, para permitir que eles conheçam a proposta +* Mensagens preparadas: as mensagens em que os validadores concordam com uma proposta. Todos os nós recebem todas as mensagens preparadas +* Mensagens de compromisso - mensagens que contêm informações de compromisso para a proposta + +Se o nó atual **não for** um validador, ele usa o método *getNextMessage* para ler mensagem da fila exibida anteriormente.
+Ele aguarda as mensagens pré-preparadas. Assim que for confirmado que tudo está correto, o nó se move para o estado **Validar**. + +#### ValidateState {#validatestate} + +O estado **Validar** é bastante simples - a única coisa que os nós fazem neste estado é ler as mensagens e adicioná-las ao estado local do snapshot. diff --git a/archive/edge/pt-edge/architecture/modules/json-rpc.md b/archive/edge/pt-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..b857f5daa6 --- /dev/null +++ b/archive/edge/pt-edge/architecture/modules/json-rpc.md @@ -0,0 +1,181 @@ +--- +id: json-rpc +title: JSON RPC +description: Explicação para o módulo JSON RPC do Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## Visão geral {#overview} + +O módulo **JSON RPC** implementa a **camada API JSON RPC**, algo que os programadores dApp usam para interagir com o +blockchain. + +Ele inclui suporte para **[endpoints json-rpc](https://eth.wiki/json-rpc/API)** padrão, bem como endpoints de +websockets. + +## Interface de blockchain {#blockchain-interface} + +O Polygon Edge usa a ***interface de blockchain*** para definir todos os métodos que o módulo JSON RPC precisa usar, +para fornecer os seus endpoints. + +A interface do blockchain é implantada pelo servidor **[Mínimo](/docs/edge/architecture/modules/minimal)**. É a implantação de base +que é transmitida para a camada JSON RPC. + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## Endpoints ETH {#eth-endpoints} + +Todos os endpoints de JSON RPC padrão são implantados em: + +````bash +jsonrpc/eth_endpoint.go +```` + +## Gerenciador de filtros {#filter-manager} + +O **Gerenciador de filtros** é um serviço que é executado com o servidor JSON RPC. + +Ele permite filtrar blocos no blockchain.
+Especificamente, ele inclui um **log** e um filtro no nível dos **blocos**. + +O Gerenciador de filtros se baseia fortemente em eventos de assinatura, mencionados +na seção [Blockchain](blockchain#blockchain-subscriptions) + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +Os eventos do Gerenciador de filtros são enviados no método *Execução*: + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## 📜 Recursos {#resources} +* **[Ethereum JSON-RPC](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/pt-edge/architecture/modules/minimal.md b/archive/edge/pt-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..dfdce31c2a --- /dev/null +++ b/archive/edge/pt-edge/architecture/modules/minimal.md @@ -0,0 +1,119 @@ +--- +id: minimal +title: Mínimo +description: Explicação para o módulo Mínimo do Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## Visão geral {#overview} + +Como mencionado anteriormente, o Polygon Edge é um conjunto de diferentes módulos, todos ligados entre si.
+A **Blockchain** está ligada a **Estado** ou, por exemplo, a **Sincronização**, que canaliza novos blocos para a **Blockchain**. + +**Mínimo** é a pedra angular destes módulos interligados.
+Atua como hub central de todos os serviços executados no Polygon Edge. + +## Magia da inicialização {#startup-magic} + +Entre outras coisas, o Mínimo é responsável por: +* Configurar diretórios de dados +* Criar um keystore para comunicação do libp2p +* Criar espaço de armazenamento +* Configurar consenso +* Configurar o objeto da blockchain com GRPC, JSON RPC e Sincronização + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/pt-edge/architecture/modules/networking.md b/archive/edge/pt-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..880f471b11 --- /dev/null +++ b/archive/edge/pt-edge/architecture/modules/networking.md @@ -0,0 +1,80 @@ +--- +id: networking +title: Networking +description: Explicação para o módulo networking do Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## Visão geral {#overview} + +Um nó tem de comunicar com outros nós da rede para trocar informação útil.
+Para cumprir esta tarefa, o Polygon Edge aproveita o framework **libp2p**, já com provas dadas. + +A escolha do **libp2p** foca-se principalmente em: +* **Velocidade** - o libp2p tem um desempenho significativamente superior ao do devp2p (usado no GETH e outros clientes) +* **Extensibilidade** - é uma ótima base para outras funcionalidades do sistema +* **Modularidade** - o libp2p é modular por natureza, à semelhança do Polygon Edge. Isto dá maior flexibilidade, especialmente quando partes do Polygon Edge precisam de ser trocáveis + +## GRPC {#grpc} + +Além do **libp2p**, o Polygon Edge usa o protocolo **GRPC**.
+Tecnicamente, o Polygon Edge usa vários protocolos GRPC, que serão abordados mais tarde. + +A camada GRPC ajuda a abstrair todos os protocolos de solicitação/resposta e simplifica os protocolos de streaming necessários para o funcionamento do Polygon Edge. + +O GRPC conta com **Buffers de Protocolo** para definir *serviços* e *estruturas de mensagens*.
+Os serviços e estruturas são definidos em ficheiros *.proto*, que são compilados e são independentes da linguagem. + +Mencionámos anteriormente que o Polygon Edge aproveita vários protocolos GRPC.
+Fá-lo para impulsionar a UX global para o operador de nós, acabando muitas vezes por provocar um atraso com clientes como a GETH e a Parity. + +O operador de nós tem uma melhor visão geral do que se passa no sistema chamando o serviço GRPC, em vez de pesquisar logs para encontrar a informação que procura. + +### GRPC para operadores de nós {#grpc-for-node-operators} + +A secção seguinte pode parecer familiar, pois foi brevemente abordada na secção sobre [Comandos CLI](/docs/edge/get-started/cli-commands). + +O serviço GRPC concebido para ser utilizado pelos **operadores de nós** é definido assim: +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip + +Na verdade, os comandos CLI chamam as implementações destes métodos de serviço. + +Estes métodos são implementados em ***minimal/system_service.go***. + +::: + +### GRPC para outros nós {#grpc-for-other-nodes} + +O Polygon Edge também implementa diversos métodos de serviço que são usados por outros nós da rede.
+O serviço mencionado está descrito na secção **[Protocolo](docs/edge/architecture/modules/consensus)**. + +## 📜 Recursos {#resources} +* **[Buffers de protocolo](https://developers.google.com/protocol-buffers)** +* **[libp2p](https://libp2p.io/)** +* **[gRPC](https://grpc.io/)** diff --git a/archive/edge/pt-edge/architecture/modules/other-modules.md b/archive/edge/pt-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..616a481d3f --- /dev/null +++ b/archive/edge/pt-edge/architecture/modules/other-modules.md @@ -0,0 +1,36 @@ +--- +id: other-modules +title: Outros módulos +description: Explicação para alguns módulos do Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## Crypto {#crypto} + +O módulo **Crypto** contém funções de utilidade cripto. + +## Chain {#chain} + +O módulo **Chain** contém parâmetros da chain (forks ativos, motor de consenso, etc.) + +* **chains** - configurações da chain predefinidas (mainnet, goerli, ibft) + +## Helper {#helper} + +O módulo **Helper** contém pacotes auxiliares. + +* **dao** - utilitários Dao +* **enode** - função de codificação/descodificação de enodes +* **hex** - funções de codificação/descodificação hexadecimal +* **ipc** - funções de ligação IPC +* **keccak** - funções keccak +* **rlputil** - função de auxiliar de codificação/descodificação Rlp + +## Command {#command} + +O módulo **Command** contém interfaces para comandos CLI. \ No newline at end of file diff --git a/archive/edge/pt-edge/architecture/modules/sealer.md b/archive/edge/pt-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..b9ff4f1fb6 --- /dev/null +++ b/archive/edge/pt-edge/architecture/modules/sealer.md @@ -0,0 +1,73 @@ +--- +id: sealer +title: Selar +description: Explicação do módulo Sealer do Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## Visão geral {#overview} + +O **Sealer** é uma entidade que reúne as transações e cria um novo bloco.
+Em seguida, esse bloco é enviado para o módulo **Consenso** para ser selado. + +A lógica final do Sealer está localizada no módulo **Consenso**. + +## Método de execução {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution Trabalho em andamento + +Num futuro próximo, os módulos **Sealer** e **Consenso** serão combinados numa única entidade. + +O novo módulo irá incorporar uma lógica modular para diferentes tipos de mecanismos de consenso que exigem diferentes implantações de selagem: +* **PoS** (Proof of Stake) +* **PoA** (Proof of Authority) + +Atualmente, os módulos **Sealer** e **Consenso** trabalham com a PoW (Proof of Work). + +::: \ No newline at end of file diff --git a/archive/edge/pt-edge/architecture/modules/state.md b/archive/edge/pt-edge/architecture/modules/state.md new file mode 100644 index 0000000000..add91b0ea6 --- /dev/null +++ b/archive/edge/pt-edge/architecture/modules/state.md @@ -0,0 +1,248 @@ +--- +id: state +title: Estado +description: Explicação para o módulo Estado do Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +Para compreender verdadeiramente como funciona o módulo **Estado**, é necessário compreender alguns conceitos Ethereum básicos.
+ +Recomendamos vivamente a leitura do **[Guia do Estado no Ethereum](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)**. + +## Visão geral {#overview} + +Agora que nos familiarizamos com conceitos Ethereum básicos, deve ser fácil compreender a próxima visão geral. + +Mencionámos que a **World state trie** tem todas as contas Ethereum que existem.
+Estas contas são as folhas da árvore Merkle. Cada folha tem informação codificada sobre o **Estado da Conta**. + +Isto permite que o Polygon Edge obtenha uma árvore Merkle específica para um momento específico.
+Por exemplo, podemos obter o hash do estado no bloco 10. + +A árvore Merkle é denominada, em qualquer momento, ***Snapshot***. + +Podemos ter ***Snapshots*** para a **árvore de estado** ou para a **árvore de armazenamento** - elas são basicamente o mesmo.
+A única diferença reside no que as folhas representam: + +* No caso da árvore de armazenamento, as folhas contêm um estado arbitrário, que não podemos processar nem saber o que inclui +* No caso da árvore de estado, as folhas representam contas + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + +A interface **Snapshot** é definida como tal: + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +As informações que podem ser cometidas são definidas pelo *Object struct*: + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +A implementação da árvore Merkle encontra-se na pasta *state/immutable-trie*.
+*state/immutable-trie/state.go* implementa a interface **Estado**. + +*state/immutable-trie/trie.go* é o principal objeto da árvore Merkle. Representa uma versão otimizada da árvore Merkle, +que reutiliza a maior quantidade de memória possível. + +## Executor {#executor} + +*state/executor.go*inclui todas informações necessárias para que o Polygon Edge decida de que forma um bloco altera +o estado atual. A implementação do *ProcessBlock* está aqui localizada. + +O método *apply* faz a transição do estado real. O executor chama o EVM. + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## Runtime {#runtime} + +Quando uma transição de estado é executada, o módulo principal que executa a transição de estado é o EVM (localizado em +state/runtime/evm). + +A **dispatch table** efetua uma correspondência entre o **opcode** e a instrução. + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +A lógica principal que alimenta o EVM é o loop *Run*.
+ +Trata-se do principal ponto de entrada para o EVM. Faz um loop e verifica o opcode atual, obtém a instrução, verifica +se ela pode ser executada, consome gás e executa a instrução até que ela falhe ou pare. + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/pt-edge/architecture/modules/storage.md b/archive/edge/pt-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..36b800af8f --- /dev/null +++ b/archive/edge/pt-edge/architecture/modules/storage.md @@ -0,0 +1,118 @@ +--- +id: storage +title: Armazenamento +description: Explicação sobre o módulo Armazenamento do Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## Visão geral {#overview} + +Atualmente, o Polygon Edge utiliza o **LevelDB** para armazenamento de dados e também para armazenar dados **na memória**. + +Em todo o Polygon Edge, quando os módulos precisam interagir com o armazenamento de dados subjacente, +eles não precisam saber com que mecanismo ou serviço de base de dados estão a falar. + +A camada de base de dados é eliminada de um módulo chamado **Armazenamento**, que exporta as interfaces que os módulos consultam. + +Cada camada da base de dados, agora apenas **LevelDB**, implementa estes métodos separadamente, garantindo que eles se encaixem na implementação. + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### Prefixos {#prefixes} + +Para tornar a consulta ao armazenamento no LevelDB determinista e evitar conflitos de armazenamento de chaves, o Polygon Edge utiliza +prefixos e subprefixos ao armazenar dados + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## Planos futuros {#future-plans} + +Os planos para o futuro próximo incluem acrescentar algumas das soluções de base de dados mais populares, tais como: +* PostgreSQL +* MySQL + + +## 📜 Recursos {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/pt-edge/architecture/modules/syncer.md b/archive/edge/pt-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..fc01e5f1ed --- /dev/null +++ b/archive/edge/pt-edge/architecture/modules/syncer.md @@ -0,0 +1,65 @@ +--- +id: syncer +title: Syncer +description: Explicação para o módulo syncer do Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## Visão geral {#overview} + + Este módulo contém a lógica do protocolo de sincronização. Ele usado para sincronizar um nó novo com a rede em execução ou validar/inserir novos blocos para os nós que não participam do consenso (não são validadores). + +O Polygon Edge usa o **libp2p** como camada de rede e executa o **gRPC** sobre ele. + +Existem basicamente dois tipos de sincronização no Polygon Edge: +* Sincronização em massa: sincroniza uma grande variedade de blocos de uma só vez +* Sincronização de relógios: sincroniza por blocos + +### Sincronização em massa {#bulk-sync} + +Os passos para conseguir obter uma sincronização em massa são bastante simples: sincronize o máximo de blocos possível (disponíveis) do outro par para alcançá-lo o mais rápido possível. + +Este é o fluxo do processo de sincronização em massa: + +1. ** Determine se o nó precisa de sincronização em massa ** - Nesta etapa, o nó verifica o mapa de pares para ver se há alguém com um número de blocos maior do que o número que o nó possui localmente +2. ** Encontre o melhor par (usando o mapa de pares de sincronização) ** - Nesta etapa, o nó encontra o melhor par para sincronizar conforme os critérios mencionados no exemplo acima. +3. ** Abra um fluxo de sincronização em massa ** - Nesta etapa, o nó abre um fluxo de gRPC para o melhor par com o objetivo de obter blocos de sincronização em massa do número de blocos comum. +4. ** O melhor par fecha o fluxo após concluir o envio em massa ** - Nesta etapa, o melhor par com que o nó está a sincronizar vai fechar o fluxo assim que conclui o envio de todos os blocos disponíveis que ele possui +5. ** Ao concluir a sincronização em massa, verifique se o nó é um validador ** - Nesta etapa, o fluxo é fechado pelo melhor par, e o nó precisa verificar se é um validador após a sincronização em massa. + * Se for, ele sai do estado de sincronização e começa a participar do consenso + * Se não for, ele prossegue para uma ** Sincronização de relógios ** + +### Sincronização de relógios {#watch-sync} + +:::info +A etapa para a sincronização de relógios só é executada se o nó não for um validador, mas um nó comum não validador da rede, que apenas escuta os blocos recebidos. + +::: + +O comportamento da sincronização de relógios é bastante simples. O nó já está sincronizado com o resto da rede e só precisa analisar os novos blocos que estão a chegar. + +Este é o fluxo do processo de sincronização de relógios: + +1. ** Adicione um novo bloco quando o status de um par for atualizado ** - Nesta etapa, os nós escutam os eventos dos novos blocos. Quando chega um novo bloco, ele executa uma chamada de função de gRPC, recebe o bloco e atualiza o estado local. +2. ** Verifique se o nó é um validador após a sincronização do último bloco ** + * Se for, saia do estado de sincronização + * Se não for, continue a ouvir os eventos dos novos blocos + +## Relatório de desempenho {#perfomance-report} + +:::info +O desempenho foi medido numa máquina local sincronizando um ** milhão de blocos ** +::: + +| Nome | Resultado | +|----------------------|----------------| +| Sincronização de 1 milhão de blocos | ~ 25 minutos | +| Transferência de 1 milhão de blocos | ~ 1 minuto | +| Número de chamadas de GRPC | 2 | +| Cobertura de teste | ~ 93% | \ No newline at end of file diff --git a/archive/edge/pt-edge/architecture/modules/txpool.md b/archive/edge/pt-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..02c9fcf5dd --- /dev/null +++ b/archive/edge/pt-edge/architecture/modules/txpool.md @@ -0,0 +1,231 @@ +--- +id: txpool +title: TxPool +description: Explicação para o módulo TxPool do Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## Visão geral {#overview} + +O módulo TxPool representa a implementação da pool de transações, onde são adicionadas transações de diferentes partes do +sistema. O módulo também expõe várias funcionalidades úteis para operadores de nós, que são abordadas abaixo. + +## Comandos do operador {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +Os operadores de nós podem consultar estes endpoints GRPC, como descrito na secção **[Comandos CLI](/docs/edge/get-started/cli-commands#transaction-pool-commands)**. + +## Processamento de transações {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +O método ***addImpl*** é um componente vital do módulo **TxPool**. +É o ponto central para adição de transações ao sistema, sendo chamado a partir do serviço GRPC, os endpoints JSON RPC, +e sempre que o cliente receber uma transação através do protocolo **gossip**. + +É inserido como argumento **ctx**, que apenas denota o contexto a partir do qual as transações são adicionadas (GRPC, JSON RPC...).
+O outro parâmetro é a lista de transações a adicionar à pool. + +O essencial a verificar aqui é o campo **From** no seio da transação: +* Se o campo **From** estiver **vazio**, é considerado como uma transação não criptografada/não assinada. Estes tipos de transações só são +aceites no modo de desenvolvimento +* Se o campo **From** **não estiver vazio**, isso significa que é uma transação assinada, pelo que ocorrerá uma verificação da assinatura + +As transações são consideradas válidas depois de todas estas validações. + +## Estruturas de dados {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +Os campos do objeto TxPool que podem causar confusão são as listas **queue** e **sorted**. +* **queue** - implementação heap de uma lista ordenada de transações de contas (por nonce) +* **sorted** - lista ordenada para todas as transações promovidas atuais (todas as transações executáveis). Ordenada pelo preço do gás + +## Gestão do erro de limite de gás {#gas-limit-error-management} + +Sempre que enviar uma transação, há três maneiras pelas quais ela pode ser processada pela TxPool. + +1. Todas as transações pendentes podem caber num bloco +2. Uma ou mais transações pendentes não cabem num bloco +3. Uma ou mais transações pendentes nunca caberão num bloco + +Aqui, a palavra **_caber_** significa que a transação tem um limite de gás que é inferior ao gás restante do TxPool. + +O primeiro cenário não produz qualquer erro. + +### Segundo cenário {#second-scenario} + +- O gás restante da TxPool é definido de acordo com o limite de gás do último bloco, digamos **5000** +- Uma primeira transação é processada e consome **3000** gás da TxPool + - O gás restante da TxPool é agora **2000** +- Uma segunda transação, que é a mesma que a primeira - ambas consomem 3000 unidades de gás, é enviada +- Uma vez que o gás restante da TxPool é **inferior** ao gás da transação, não pode ser processada no atual +bloco + - É colocada numa fila de transações pendentes para que possa ser processada no bloco seguinte +- O primeiro bloco é escrito, chamemos-lhe **bloco #1** +- O gás restante da TxPool é definido de acordo com o limite de gás do bloco-pai - **bloco #1** +- A transação que foi colocada na fila de transações pendentes da TxPool é agora processada e escrita no bloco + - O gás restante da TxPool é agora **2000** +- O segundo bloco é escrito +- ... + +![Cenário de erro #1 da TxPool](/img/edge/txpool-error-1.png) + +### Terceiro cenário {#third-scenario} +- O gás restante da TxPool é definido de acordo com o limite de gás do último bloco, digamos **5000** +- Uma primeira transação é processada e consome **3000** gás da TxPool + - O gás restante da TxPool é agora **2000** +- É enviada uma segunda transação com um limite de gás definido para **6000** +- Uma vez que o limite de gás do bloco é **inferior** ao gás da transação, esta transação é descartada + - Nunca poderá caber num bloco +- O primeiro bloco é escrito +- ... + + +![Cenário de erro #2 da TxPool](/img/edge/txpool-error-2.png) + +> Isto acontece sempre que obtiver o seguinte erro: +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## Valor-alvo de gás do bloco {#block-gas-target} + +Há situações em que os nós pretendem manter o limite de gás do bloco abaixo ou num determinado valor na chain em curso. + +O operador de nós pode definir o valor-alvo do limite de gás num nó específico, o qual tentará aplicar este limite aos blocos recém-criados. +Se a maioria dos outros nós tiver definido um valor-alvo do limite de gás semelhante (ou igual), então o limite de gás do bloco rondará sempre +o valor-alvo desse bloco, progredindo lentamente no seu sentido (no máximo, `1/1024 * parent block gas limit`) à medida que são criados novos blocos. + +### Cenário de exemplo {#example-scenario} + +* O operador de nós define o limite de gás do bloco num só nó como `5000` +* Outros nós são igualmente configurados para `5000`, exceto um único nó, que é configurado para `7000` +* Quando os nós com o valor-alvo do gás definido para `5000` se tornarem proponentes, eles verificarão se o limite de gás já se encontra no valor-alvo +* Se o limite de gás não estiver no valor-alvo (é superior/inferior a este), o nó proponente irá definir o valor-alvo de gás do bloco no máximo (1/1024 * limite de gás do bloco pai) no sentido do alvo + 1. Ex: `parentGasLimit = 4500` e `blockGasTarget = 5000`, o proponente irá calcular o limite de gás para o novo bloco como `4504.39453125` (`4500/1024 + 4500`) + 2. Ex: `parentGasLimit = 5500` e `blockGasTarget = 5000`, o proponente irá calcular o limite de gás para o novo bloco como `5494.62890625` (`5500 - 5500/1024`) +* Isto garante que o limite de gás do bloco na chain se mantém no valor-alvo, porque o proponente individual que tem o alvo configurado para `7000` não pode avançar muito o limite e a maioria +dos nós que o tiverem definido como `5000` tentarão sempre mantê-lo nesse valor \ No newline at end of file diff --git a/archive/edge/pt-edge/architecture/modules/types.md b/archive/edge/pt-edge/architecture/modules/types.md new file mode 100644 index 0000000000..59c53ea44e --- /dev/null +++ b/archive/edge/pt-edge/architecture/modules/types.md @@ -0,0 +1,43 @@ +--- +id: types +title: Tipos +description: Explicação para o módulo Tipos do Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## Visão geral {#overview} + +O módulo **Tipos** implementa os tipos de objeto do núcleo, como: + +* **Endereço** +* **Hash** +* **Cabeçalho** +* muitas funções auxiliares + +## Codificação/Decodificação de RLP {#rlp-encoding-decoding} + +Diferente de clientes como GETH, o Polygon Edge não usa a reflexão para a codificação.
+A preferência não era usar a reflexão porque isso introduz novos problemas, como degradação de +desempenho e escalonamento mais difícil. + +O módulo **Tipos** fornece uma interface fácil de usar para empacotar e desempacotar RLP, usando o pacote FastRLP. + +O empacotamento é realizado através dos métodos *MarshalRLPWith* e *MarshalRLPWith*. Os métodos análogos existem para +desempacotamento. + +Ao definir manualmente estes métodos, o Polygon Edge não precisa usar a reflexão. Em *rlp_marshal.go*, é possível encontrar os +métodos para empacotamento: + +* **Corpos** +* **Blocos** +* **Cabeçalhos** +* **Recebimentos** +* **Registos** +* **Transações** \ No newline at end of file diff --git a/archive/edge/pt-edge/architecture/overview.md b/archive/edge/pt-edge/architecture/overview.md new file mode 100644 index 0000000000..e9e66de271 --- /dev/null +++ b/archive/edge/pt-edge/architecture/overview.md @@ -0,0 +1,61 @@ +--- +id: overview +title: Visão geral da arquitetura +sidebar_label: Overview +description: Introdução à arquitetura do Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +Partimos da ideia de criar um software que fosse *modular*. + +Essa característica está presente em quase todas as partes do Polygon Edge. Abaixo, temos uma breve visão geral da +arquitetura construída e das suas camadas. + +## Camadas do Polygon Edge {#polygon-edge-layering} + +![Arquitetura do Polygon Edge](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +Tudo começa na camada de rede de base, que utiliza o **libp2p**. Decidimos adotar esta tecnologia porque ela +se encaixa bem nas filosofias de design do Polygon Edge. Libp2p é: + +- Modular +- Extensível +- Rápida + +Mais importante, ela fornece uma ótima base para recursos mais avançados, que cobriremos posteriormente. + + +## Sincronização e Consenso {#synchronization-consensus} +A separação dos protocolos de sincronização e consenso permite a modularidade e implementação de mecanismos de sincronização e consenso **personalizados**, dependendo de como o cliente está a ser executado. + +O Polygon Edge foi projetado para oferecer algoritmos de consenso disponíveis e conectáveis. + +A lista atual de algoritmos de consenso aceitos: + +* IBFT PoA +* IBFT PoS + +## Blockchain {#blockchain} +A camada de blockchain é a camada central que coordena tudo no sistema do Polygon Edge. Ele é coberto em profundidade na seção *Módulos* correspondente. + +## Estado {#state} +A camada interna de Estado contém a lógica de transição do estado. Ela gerencia as mudanças de estado quando um novo bloco é incluído. Ele é coberto em profundidade na seção *Módulos* correspondente. + +## JSON RPC {#json-rpc} +A camada de RPC do JSON é uma camada dApp que os programadores do dApp usam para interagir com blockchains. Ele é coberto em profundidade na seção *Módulos* correspondente. + +## TxPool {#txpool} +A camada de TxPool representa o pool de transações e está intimamente ligada a outros módulos do sistema, pois as transações podem ser adicionadas a partir de múltiplos pontos de entrada. + +## GRPC {#grpc} +gRPC ou chamada de procedimento remoto do Google, é um framework RPC de código aberto robusto que o Google criou inicialmente para criar APIs escaláveis e rápidas. A camada de GRPC é vital para as interações do operador. Através dela, os operadores de nós podem interagir facilmente com o cliente e fornecer uma interface de utilizador agradável. diff --git a/archive/edge/pt-edge/community/propose-new-feature.md b/archive/edge/pt-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..84ef1e92f5 --- /dev/null +++ b/archive/edge/pt-edge/community/propose-new-feature.md @@ -0,0 +1,60 @@ +--- +id: propose-new-feature +title: Propor um recurso novo +description: "Modelo de PR e instruções para propor um recurso novo." +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## Visão geral {#overview} + +Se quiser incluir uma correção ou contribuir apenas para o código, recomendamos vivamente que primeiro entre em contacto com a equipa.
+O Polygon Edge usa um modelo de proposta de recurso relativamente básico, que é conciso e objetivo. + +## Modelo de PR {#pr-template} + +### Descrição {#description} + +Forneça uma descrição detalhada do que foi feito nesta PR + +### As alterações incluem {#changes-include} + +- [ ] Bugfix (alteração sem quebra de código que resolve um problema) +- [ ] Hotfix (alteração que resolve um problema urgente e requer uma atenção imediata) +- [ ] Recurso novo (alteração sem quebra de código que acrescenta funcionalidade) +- [ ] Alteração com quebra de código (alteração que não é retrocompatível e/ou altera a funcionalidade atual) + +### Alterações com quebra de código {#breaking-changes} + +Preencha esta secção se tiverem sido feitas alterações de quebra de código; caso contrário, exclua-a + +### Lista de verificação {#checklist} + +- [ ] Atribui este PR a mim mesmo +- [ ] Adicionei pelo menos 1 avaliador +- [ ] Adicionei as etiquetas relevantes +- [ ] Atualizei a documentação oficial +- [ ] Adicionei documentação suficiente ao código + +### Teste {#testing} + +- [ ] Testei este código com o pacote de teste oficial +- [ ] Testei este código manualmente + +## Testes manuais {#manual-tests} + +Preencha esta secção se tiver executado testes manuais para esta funcionalidade; caso contrário, exclua-a + +### Atualização da documentação {#documentation-update} + +Coloque nesta secção um link para o PR de atualização da documentação, se existir; caso contrário, exclua-a + +### Comentários adicionais {#additional-comments} + +Publique comentários adicionais nesta secção, se os tiver; caso contrário, exclua-a \ No newline at end of file diff --git a/archive/edge/pt-edge/community/report-bug.md b/archive/edge/pt-edge/community/report-bug.md new file mode 100644 index 0000000000..1b7b80939d --- /dev/null +++ b/archive/edge/pt-edge/community/report-bug.md @@ -0,0 +1,55 @@ +--- +id: report-bug +title: Comunicar um problema +description: Modelo e instruções para comunicar um problema do Polygon Edge. +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## Visão geral {#overview} + +Às vezes, as coisas dão errado.
+É sempre melhor informar a equipa sobre quaisquer problemas que possam estar a encontrar.
+Na página GitHub do Polygon Edge, pode registar um novo problema e começar a discutir com a equipa. + +## Modelo de problema {#issue-template} + +## [Assunto do problema] + +### Descrição {#description} + +Descreva o seu problema com o máximo de detalhes possível + +### Seu ambiente {#your-environment} + +* Sistema operativo e versão +* versão do Polygon Edge +* ramo que causa este problema + +### Passos para reproduzir {#steps-to-reproduce} + +* Conte-nos como reproduzir este problema
+* Onde o problema está, se souber
+* Quais comandos desencadearam o problema, se for o caso + +### Comportamento esperado {#expected-behaviour} + +Conte-nos o que deveria acontecer + +### Comportamento real {#actual-behaviour} + +Conte-nos o que acontece + +### Registos {#logs} + +Cole aqui todos os registos que demonstrem o problema, se existirem + +### Solução proposta {#proposed-solution} + +Se tiver alguma ideia de como corrigir este problema, explique aqui para que possamos começar a discutir \ No newline at end of file diff --git a/archive/edge/pt-edge/configuration/manage-private-keys.md b/archive/edge/pt-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..e51af0418d --- /dev/null +++ b/archive/edge/pt-edge/configuration/manage-private-keys.md @@ -0,0 +1,79 @@ +--- +id: manage-private-keys +title: Gerir chaves privadas +description: "Como gerir chaves privadas e que tipos de chaves existem." +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## Visão geral {#overview} + +O Polygon Edge tem dois tipos de chaves privadas que gere diretamente: + +* **Chave privada para o mecanismo de consenso** +* **Chave privada usada para networking por libp2p** +* **(Opcional) Chave privada BLS usada para o mecanismo de consenso para agregar as assinaturas dos validadores** + +Atualmente, o Polygon Edge não oferece suporte para a gestão direta de contas. + +Com base na estrutura do diretório descrita no [guia de Backup e Recuperação](/docs/edge/working-with-node/backup-restore), +o Polygon Edge armazena os ficheiros das chaves mencionados em dois diretórios distintos - **consensus** e **keystore**. + +## Formato das chaves {#key-format} + +As chaves privadas são armazenadas num **formato Base64** simples para que sejam legíveis e portáteis. + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info Tipo de chave + +Todos os ficheiros de chaves privadas gerados e usados dentro do Polygon Edge baseiam-se no ECDSA com a curva [secp256k1](https://en.bitcoin.it/wiki/Secp256k1). + +Como a curva não é padrão, não pode ser codificada e armazenada em qualquer formato PEM padronizado. +Não é suportada a importação de chaves que não estejam em conformidade com este tipo de chave. + +::: +## Chave privada de consenso {#consensus-private-key} + +O ficheiro de chave privada mencionado como *chave privada de consenso* é também designado **chave privada de validador**. +Esta chave privada é usada quando o nó age como validador na rede e precisa de assinar dados novos. + +O ficheiro de chave privada está localizado em `consensus/validator.key` e segue o [formato de chave](/docs/edge/configuration/manage-private-keys#key-format) mencionado. + +:::warning + +A chave privada de validador é exclusiva para cada nó de validador. A mesma chave não deve ser partilhada entre validadores, pois pode comprometer a segurança da sua chain. + +::: + +## Chave privada de networking {#networking-private-key} + +O ficheiro de chave privada mencionado para networking é usado pelo libp2p para gerar a PeerID correspondente e permitir que o nó participe na rede. + +Está localizado em `keystore/libp2p.key` e segue o [formato de chave](/docs/edge/configuration/manage-private-keys#key-format) mencionado. + +## Chave secreta BLS {#bls-secret-key} + +O ficheiro de chave secreta BLS é usado para agregar selos dedicados na camada de consenso. O tamanho dos selos dedicados agregados pela BLS é inferior às assinaturas ECDSA dedicadas serializadas. + +O recurso BLS é opcional e é possível escolher usá-lo ou não. Consulte [BLS](/docs/edge/consensus/bls) para mais detalhes. + +## Importar/Exportar {#import-export} + +Como os ficheiros de chave são armazenados no disco no formato Base64 simples, eles podem ser facilmente copiados ou importados. + +:::caution Alterar os ficheiros das chaves + +Qualquer tipo de alteração aos ficheiros de chave numa rede já configurada/em execução pode levar a uma perturbação grave da rede/do consenso, +dado que os mecanismos de consenso e de descoberta de pares armazenam os dados derivados destas chaves num armazenamento específico dos nós e dependem destes dados para +iniciar conexões e executar a lógica de consenso + +::: \ No newline at end of file diff --git a/archive/edge/pt-edge/configuration/prometheus-metrics.md b/archive/edge/pt-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..a1dab4e4d7 --- /dev/null +++ b/archive/edge/pt-edge/configuration/prometheus-metrics.md @@ -0,0 +1,35 @@ +--- +id: prometheus-metrics +title: Métricas Prometheus +description: "Como ativar as métricas Prometheus para o Polygon Edge." +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## Visão geral {#overview} + +O Polygon Edge pode relatar e servir as métricas Prometheus que, por sua vez, podem ser consumidas usando o(s) coletor(es) Prometheus. + +As métricas do Prometheus estão desativadas por padrão. Ele pode ser ativado especificando o endereço do ouvinte usando `--prometheus`[sinalizador](/docs/edge/get-started/cli-commands#prometheus) ou `Telemetry.prometheus`campo no ficheiro de configuração. As métricas serão servidas sob `/metrics` no endereço especificado. + +## Métricas disponíveis {#available-metrics} + +Estão disponíveis as seguintes métricas: + +| **Nome** | **Tipo** | **Descrição** | +|-------------------------------------------------|----------|---------------------------------------------| +| edge_txpool_pending_transactions | Gauge | Número de transações pendentes na TxPool | +| edge_consensus_validators | Gauge | Número de validadores | +| edge_consensus_rounds | Gauge | Número de rondas | +| edge_consensus_num_txs | Gauge | Número de transações no último bloco | +| edge_consensus_block_interval | Gauge | Tempo entre este bloco e o último, em segundos | +| edge_network_peers | Gauge | Número de pares conectados | +| edge_network_outbound_connections_count | Gauge | Número de conexões de saída | +| edge_network_inbound_connections_count | Gauge | Número de conexões de entrada | +| edge_network_pending_inbound_connections_count | Gauge | Número de conexões de saída pendentes | +| edge_network_pending_outbound_connections_count | Gauge | Número de conexões de entrada pendentes | +| edge_consensus_epoch_number | Gauge | Número de época atual | \ No newline at end of file diff --git a/archive/edge/pt-edge/configuration/sample-config.md b/archive/edge/pt-edge/configuration/sample-config.md new file mode 100644 index 0000000000..e11b550837 --- /dev/null +++ b/archive/edge/pt-edge/configuration/sample-config.md @@ -0,0 +1,151 @@ +--- +id: sample-config +title: Ficheiro Config do servidor +description: "Iniciar o servidor Polygon Edge utilizando um ficheiro de configuração." +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# Ficheiro de configuração do servidor {#server-configuration-file} +É possível iniciar o servidor com várias opções de configuração utilizando um ficheiro de configuração, em vez de usar apenas sinalizadores. +Comando usado para iniciar o servidor com um ficheiro config: `polygon-edge server --config ` + +## Exportar o ficheiro config com a configuração padrão {#export-config-file-with-default-configuration} +A configuração com definições padrão para o servidor Polygon Edge pode ser exportada para um ficheiro config tanto no formato de ficheiro `yaml` como `json`. +Este ficheiro pode ser usado como modelo para executar o servidor utilizando um ficheiro de configuração. + +### YAML {#yaml} +Para gerar o ficheiro config no formato `yaml`: +```bash +polygon-edge server export --type yaml +``` +ou apenas +```bash +polygon-edge server export +``` +o ficheiro config denominado `default-config.yaml` será criado no diretório a partir do qual este comando foi executado. + +Exemplo de ficheiro: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +Para gerar o ficheiro config no formato `json`: +```bash +polygon-edge server export --type json +``` +o ficheiro config denominado `default-config.json` será criado no diretório a partir do qual este comando foi executado. + +Exemplo de ficheiro: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +Consulte a secção [Comandos CLI](/docs/edge/get-started/cli-commands) para obter informações sobre como utilizar estes parâmetros. + +### Esquema Typescript {#typescript-schema} + +Segue-se o exemplo de um formato para o ficheiro de configuração. Está escrito em TypeScript para expressar os tipos de propriedades (`string`, `number`, `boolean`), a sua configuração pode ser derivada deles. Cabe destacar que o tipo `PartialDeep` de `type-fest` é usado para expressar que todas as propriedades são opcionais. + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/pt-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/pt-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..e1142b4c66 --- /dev/null +++ b/archive/edge/pt-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,139 @@ +--- +id: set-up-aws-ssm +title: Configure o SSM (Gestor de sistemas) da AWS +description: "Configure o SSM (Gestor de sistemas) da AWS para o Polygon Edge" +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## Visão geral {#overview} + +Atualmente, o Polygon Edge está preocupado em guardar 2 grandes segredos do tempo de execução: +* A **chave privada de validador** usada pelo nó, se este for um validador +* A **chave privada de rede** usada pelo libp2p, para participação e comunicação com outros pares + +Para informações adicionais, leia atentamente o [Guia Gerir Chaves Privadas](/docs/edge/configuration/manage-private-keys) + +Os módulos do Polygon Edge **não devem precisar de saber como guardar segredos**. Finalmente, um módulo não deve preocupar-se com +o facto de um segredo ser guardado num servidor longínquo ou localmente, no disco do nó. + +Tudo o que um módulo precisa de saber sobre como manter um segredo é **saber usar o segredo**, **saber que segredos obter +ou guardar**. Os detalhes de implementação mais finos destas operações são delegados no `SecretsManager`, que consiste numa abstração, claro. + +O operador de nós que está a iniciar o Polygon Edge pode agora especificar que gestor de segredos pretende usar e, assim que +o gestor de segredos correto é instanciado, os módulos lidam com os segredos através da interface mencionada - +sem se importar se tais segredos são armazenados num disco ou num servidor. + +Este artigo detalha os passos necessários para colocar o Polygon Edge em execução com +[AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html). + +:::info guias anteriores + +**Recomendamos vivamente** que, antes de seguir este artigo, leia os artigos sobre [**Configuração Local**](/docs/edge/get-started/set-up-ibft-locally) +e [**Configuração na Nuvem**](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +::: + + +## Pré-requisitos {#prerequisites} +### Política do IAM {#iam-policy} +O utilizador precisa criar uma Política do IAM que permita operações de leitura/gravação para o AWS Systems Manager Parameter Store. +Depois de criar com sucesso a Política do IAM, o utilizador precisa vinculá-la à instância do EC2 que está a executar o servidor da Polygon Edge. +A Política do IAM deve ser semelhante a algo como: +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +Mais informações sobre as funções de IAM do SSM da AWS podem ser encontradas nos [documentos da AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html). + +Informações necessárias antes de continuar: +* **Região** (a região na qual reside o Gestor de Sistemas e os nós) +* **Caminho do parâmetro** (caminho arbitrário no qual o segredo será colocado em, por exemplo`/polygon-edge/nodes`) + +## Etapa 1 - gere a configuração do gestor de segredos {#step-1-generate-the-secrets-manager-configuration} + +Para conseguir se comunicar perfeitamente com o SSM da AWS, o Polygon Edge tem de analisar um +ficheiro config já gerado, que contém todas as informações necessárias para o armazenamento de segredos no SSM da AWS. + +Para gerar a configuração, execute o seguinte comando: + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +Parâmetros presentes: +* `PATH`é o caminho para o qual o ficheiro de configuração deve ser exportado. `./secretsManagerConfig.json` padrão +* `NODE_NAME`é o nome do nó atual para o qual a configuração do SSM da AWS está a ser definida. Pode ser um valor arbitrário. `polygon-edge-node` padrão +* `REGION` é a região onde o SSM do AWS reside. Ela tem de ser a mesma região do nó que utiliza o SSM da AWS. +* `SSM_PARAM_PATH` é o nome do caminho onde o segredo será armazenado. Por exemplo, se `--name node1` e `ssm-parameter-path=/polygon-edge/nodes` +forem especificados, o segredo será armazenado como `/polygon-edge/nodes/node1/` + +:::caution Nomes dos nós + +Tenha cuidado ao especificar os nomes dos nós. + +O Polygon Edge usa o nome do nó especificado para acompanhar os segredos que gera e usa no SSM da AWS. +Especificar um nome do nó existente pode ter consequências de não gravar o segredo no SSM da AWS. + +Os segredos são armazenados no seguinte caminho base: `SSM_PARAM_PATH/NODE_NAME` + +::: + +## Etapa 2 - inicializar as chaves secretas usando a configuração {#step-2-initialize-secret-keys-using-the-configuration} + +Agora que o ficheiro de configuração está presente, podemos inicializar as chaves secretas necessárias com o ficheiro de configuração +definido na etapa 1, usando a `--config`: + +```bash +polygon-edge secrets init --config +``` + +O parâmetro `PATH` é a localização do parâmetro do gestor de segredos previamente gerado na etapa 1. + +:::info Política do IAM + +Esta etapa irá falhar se a Política do IAM que permite operações de leitura/gravação não estiver configurada corretamente e/ou não estiver vinculada à instância do EC2 que executa este comando. + +::: + +## Etapa 3 - gere o ficheiro de génese {#step-3-generate-the-genesis-file} + +O ficheiro de génese deve ser gerado de forma semelhante à dos guias [**Configuração Local**](/docs/edge/get-started/set-up-ibft-locally) +e [**Configuração na Nuvem**](/docs/edge/get-started/set-up-ibft-on-the-cloud), com ligeiras alterações. + +Uma vez que o SSM da AWS está a ser usado em vez do sistema de ficheiros local, os endereços de validador devem ser adicionados através do sinalizador `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Etapa 4 - inicie o cliente do Polygon Edge {#step-4-start-the-polygon-edge-client} + +Agora que as chaves estão configuradas e o ficheiro de génese foi gerado, a etapa final deste processo seria a iniciação do +Polygon Edge com o comando `server`. + +O comando `server` é usado da mesma forma que nos guias anteriormente mencionados, com uma adição ligeira - o flag `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +O parâmetro `PATH` é a localização do parâmetro do gestor de segredos previamente gerado na etapa 1. \ No newline at end of file diff --git a/archive/edge/pt-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/pt-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..0649647f37 --- /dev/null +++ b/archive/edge/pt-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,120 @@ +--- +id: set-up-gcp-secrets-manager +title: Configurar o gestor de segredos do GCP +description: "Configurar o gestor de segredos do GCP para o Polygon Edge." +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## Visão geral {#overview} + +Atualmente, o Polygon Edge está preocupado em guardar 2 grandes segredos do tempo de execução: +* A **chave privada de validador** usada pelo nó, se este for um validador +* A **chave privada de rede** usada pelo libp2p, para participação e comunicação com outros pares + +Para informações adicionais, leia atentamente o [Guia Gerir Chaves Privadas](/docs/edge/configuration/manage-private-keys) + +Os módulos do Polygon Edge **não devem precisar de saber como guardar segredos**. Finalmente, um módulo não deve preocupar-se com +o facto de um segredo ser guardado num servidor longínquo ou localmente, no disco do nó. + +Tudo o que um módulo precisa de saber sobre como manter um segredo é **saber usar o segredo**, **saber que segredos obter +ou guardar**. Os detalhes de implementação mais finos destas operações são delegados no `SecretsManager`, que consiste numa abstração, claro. + +O operador de nós que está a iniciar o Polygon Edge pode agora especificar que gestor de segredos pretende usar e, assim que +o gestor de segredos correto é instanciado, os módulos lidam com os segredos através da interface mencionada - +sem se importarem se os segredos são armazenados num disco ou num servidor. + +Este artigo detalha os passos necessários para colocar o Polygon Edge em execução com o [Gestor de Segredos do GCP](https://cloud.google.com/secret-manager). + +:::info guias anteriores + +**Recomendamos vivamente** que, antes de seguir este artigo, leia os artigos sobre [**Configuração Local**](/docs/edge/get-started/set-up-ibft-locally) +e [**Configuração na Nuvem**](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +::: + + +## Pré-requisitos {#prerequisites} +### Conta de faturação do GCP {#gcp-billing-account} +Para utilizar o Gestor de Segredos do GCP, o utilizador tem de ter a [Conta de faturação](https://console.cloud.google.com/) ativada no portal do GCP. +As contas novas do Google na plataforma do GCP são fornecidas com alguns fundos para começarem, como corolário da avaliação gratuita. +Mais informações em [GCP docs](https://cloud.google.com/free) + +### API do Gestor de Segredos {#secrets-manager-api} +O utilizador terá de ativar a API do Gestor de Segredos do GCP, antes de poder usá-la. +Isto pode ser feito através do [portal da API do Gestor de Segredos](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com). Mais informações: [Configurar o Gestor de Segredos](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + +### Credenciais do GCP {#gcp-credentials} +Por último, o utilizador precisa de gerar novas credenciais que serão usadas para autenticação. +Isto pode ser feito seguindo as instruções publicadas [aqui](https://cloud.google.com/secret-manager/docs/reference/libraries). +O ficheiro json gerado que contém as credenciais deve ser transferido para cada nó que necessitar de usar o Gestor de Segredos do GCP. + +Informações necessárias antes de continuar: +* **ID do projeto** (identificação do projeto definida na plataforma do GCP) +* **Localização do ficheiro das credenciais** (caminho para o ficheiro json que contém as credenciais) + +## Etapa 1 - gerar a configuração do gestor de segredos {#step-1-generate-the-secrets-manager-configuration} + +Para conseguir comunicar perfeitamente com o GCP SM, o Polygon Edge tem de analisar um +ficheiro config já gerado, que contém todas as informações necessárias para o armazenamento de segredos no GCP SM. + +Para gerar a configuração, execute o seguinte comando: + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +Parâmetros presentes: +* `PATH`é o caminho para o qual o ficheiro de configuração deve ser exportado. Predefinição `./secretsManagerConfig.json` +* `NODE_NAME`é o nome do nó atual para o qual a configuração do GCP SM está a ser configurada como tal. Pode ser um valor arbitrário. Predefinição `polygon-edge-node` +* `PROJECT_ID` é a identificação do projeto que o utilizador definiu na consola do GCP durante a configuração da conta e a ativação da API do Gestor de Segredos. +* `GCP_CREDS_FILE` é o caminho para o ficheiro json que contém as credenciais que permitirão o acesso de leitura/escrita do Gestor de Segredos. + +:::caution Nomes dos nós + +Tenha cuidado ao especificar os nomes dos nós. + +O Polygon Edge usa o nome do nó especificado para acompanhar os segredos que gera e usa no GCP SM. +A especificação de um nome de nó existente pode ter como consequência a falha na escrita do segredo no GCP SM. + +Os segredos são armazenados no seguinte caminho base: `projects/PROJECT_ID/NODE_NAME` + +::: + +## Etapa 2 - inicializar as chaves secretas usando a configuração {#step-2-initialize-secret-keys-using-the-configuration} + +Agora que o ficheiro de configuração está presente, podemos inicializar as chaves secretas necessárias com o ficheiro de configuração +definido na etapa 1, usando a `--config`: + +```bash +polygon-edge secrets init --config +``` + +O parâmetro `PATH` é a localização do parâmetro do gestor de segredos previamente gerado na etapa 1. + +## Etapa 3 - gerar o ficheiro de génese {#step-3-generate-the-genesis-file} + +O ficheiro de génese deve ser gerado de forma semelhante à dos guias [**Configuração Local**](/docs/edge/get-started/set-up-ibft-locally) +e [**Configuração da Nuvem**](/docs/edge/get-started/set-up-ibft-on-the-cloud), com ligeiras alterações. + +Uma vez que o GCP SM está a ser usado em vez do sistema de ficheiros local, os endereços de validador devem ser adicionados através do flag `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Etapa 4 - iniciar o cliente do Polygon Edge {#step-4-start-the-polygon-edge-client} + +Agora que as chaves estão configuradas e o ficheiro de génese foi gerado, a etapa final deste processo seria a iniciação do +Polygon Edge com o comando `server`. + +O comando `server` é usado da mesma forma que nos guias anteriormente mencionados, com uma adição ligeira - o flag `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +O parâmetro `PATH` é a localização do parâmetro do gestor de segredos previamente gerado na etapa 1. \ No newline at end of file diff --git a/archive/edge/pt-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/pt-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..bb139233ee --- /dev/null +++ b/archive/edge/pt-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,118 @@ +--- +id: set-up-hashicorp-vault +title: Configurar o Hashicorp Vault +description: "Configurar o Hashicorp Vault para o Polygon Edge." +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## Visão geral {#overview} + +Atualmente, o Polygon Edge está preocupado em guardar 2 grandes segredos do tempo de execução: +* A **chave privada de validador** usada pelo nó, se este for um validador +* A **chave privada de networking** usada pelo libp2p, para participar e comunicar com outros pares + +:::warning + +A chave privada de validador é exclusiva para cada nó de validador. A mesma chave não deve ser partilhada entre validadores, pois pode comprometer a segurança da sua chain. + +::: + +Para informações adicionais, leia atentamente o [Guia Gerir Chaves Privadas](/docs/edge/configuration/manage-private-keys) + +Os módulos do Polygon Edge **não devem precisar de saber como guardar segredos**. Finalmente, um módulo não deve preocupar-se com +o facto de um segredo ser guardado num servidor longínquo ou localmente, no disco do nó. + +Tudo o que um módulo precisa de saber sobre como manter um segredo é **saber usar o segredo**, **saber que segredos obter +ou guardar**. Os detalhes de implementação mais finos destas operações são delegados no `SecretsManager`, que consiste numa abstração, claro. + +O operador de nós que está a iniciar o Polygon Edge pode agora especificar que gestor de segredos pretende usar e, assim que +o gestor de segredos correto é instanciado, os módulos lidam com os segredos através da interface mencionada - +sem se importarem se os segredos são armazenados num disco ou num servidor. + +Este artigo detalha os passos necessários para colocar o Polygon Edge em execução com um servidor [Hashicorp Vault](https://www.vaultproject.io/). + +:::info guias anteriores + +**Recomendamos vivamente** que, antes de seguir este artigo, leia os artigos sobre [**Configuração Local**](/docs/edge/get-started/set-up-ibft-locally) +e [**Configuração na Nuvem**](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +::: + + +## Pré-requisitos {#prerequisites} + +Este artigo assume que uma instância funcional do servidor Hashicorp Vault **já foi configurada**. + +Além disso, é necessário que o servidor Hashicorp Vault que está a ser usado para o Polygon Edge tenha o **armazenamento de chave-valor ativado**. + +Informações necessárias antes de continuar: +* **O URL do servidor** (URL da API do servidor Hashicorp Vault) +* **Token** (token usado para acesso ao motor de armazenamento de chave-valor) + +## Etapa 1 - gerar a configuração do gestor de segredos {#step-1-generate-the-secrets-manager-configuration} + +Para conseguir comunicar perfeitamente com o servidor Vault, o Polygon Edge tem de analisar um +ficheiro config já gerado, que contém todas as informações necessárias para o armazenamento de segredos no Vault. + +Para gerar a configuração, execute o seguinte comando: + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +Parâmetros presentes: +* `PATH`é o caminho para o qual o ficheiro de configuração deve ser exportado. `./secretsManagerConfig.json` padrão +* `TOKEN` é o token de acesso mencionado anteriormente na [secção pré-requisitos](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `SERVER_URL`é o URL da API para o servidor Vault, também mencionado na [secção pré-requisitos](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `NODE_NAME`é o nome do nó atual para o qual a configuração do Vault está a ser configurada como tal. Pode ser um valor arbitrário. `polygon-edge-node` padrão + +:::caution Nomes dos nós + +Tenha cuidado ao especificar os nomes dos nós. + +O Polygon Edge usa o nome do nó especificado para acompanhar os segredos que gera e usa na instância do Vault. +A especificação de um nome de nó existente pode ter como consequência a substituição de dados no servidor do Vault. + +Os segredos são armazenados no seguinte caminho base: `secrets/node_name` + +::: + +## Etapa 2 - inicializar as chaves secretas usando a configuração {#step-2-initialize-secret-keys-using-the-configuration} + +Agora que o ficheiro de configuração está presente, podemos inicializar as chaves secretas necessárias com o ficheiro de configuração +definido na etapa 1, usando a `--config`: + +```bash +polygon-edge secrets init --config +``` + +O parâmetro `PATH` é a localização do parâmetro do gestor de segredos previamente gerado na etapa 1. + +## Etapa 3 - gerar o ficheiro de génese {#step-3-generate-the-genesis-file} + +O ficheiro de génese deve ser gerado de forma semelhante à dos guias [**Configuração Local**](/docs/edge/get-started/set-up-ibft-locally) +e [**Configuração na Nuvem**](/docs/edge/get-started/set-up-ibft-on-the-cloud), com ligeiras alterações. + +Uma vez que o Hashicorp Vault está a ser usado em vez do sistema de ficheiros local, os endereços de validador devem ser adicionados através do flag `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Etapa 4 - iniciar o cliente do Polygon Edge {#step-4-start-the-polygon-edge-client} + +Agora que as chaves estão configuradas e o ficheiro de génese foi gerado, a etapa final deste processo seria a iniciação do +Polygon Edge com o comando `server`. + +O comando `server` é usado da mesma forma que nos guias anteriormente mencionados, com uma adição ligeira - o flag `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +O parâmetro `PATH` é a localização do parâmetro do gestor de segredos previamente gerado na etapa 1. \ No newline at end of file diff --git a/archive/edge/pt-edge/consensus/bls.md b/archive/edge/pt-edge/consensus/bls.md new file mode 100644 index 0000000000..d348df73a5 --- /dev/null +++ b/archive/edge/pt-edge/consensus/bls.md @@ -0,0 +1,144 @@ +--- +id: bls +title: BLS +description: "Explicação e instruções sobre o modo BLS." +keywords: + - docs + - polygon + - edge + - bls +--- + +## Visão geral {#overview} + +BLS também conhecido como Boneh–Lynn–Shacham (BLS) é um esquema de assinatura criptográfica que permite que um usuário verifique se um signatário é autenticado. É um esquema de assinatura que pode agregar várias assinaturas. No Polygon Edge, o BLS é usado por defeito para fornecer melhor segurança no modo consenso do IBFT. BLS pode agregar assinaturas em um único array de byte único e reduzir o tamanho do cabeçalho de blocos. Cada chain pode escolher se quer usar o BLS ou não. A chave ECDSA é usada independentemente de o modo BLS estar habilitado ou não. + +## Apresentação de vídeo {#video-presentation} + +[![bls - vídeo](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## Como configurar uma chain nova usando o BLS {#how-to-setup-a-new-chain-using-bls} + +Consulte as seções [Configuração Local](/docs/edge/get-started/set-up-ibft-locally)/[Configuração na Nuvem](/docs/edge/get-started/set-up-ibft-on-the-cloud) para obter instruções de configuração detalhadas. + +## Como migrar de uma chain de PoA de ECDSA existente para chain de PoA de BLS {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +Esta seção descreve como usar o modo BLS em uma chain de PoA existente. +as seguintes etapas são necessárias para habilitar o BLS em uma chain de PoA. + +1. Pare todos os nós +2. Gere as chaves BLS para validadores +3. Adicione uma configuração de fork no genesis.json +4. Reinicie todos os nós + +### 1. Pare todos os nós {#1-stop-all-nodes} + +Encerre todos os processos dos validadores pressionando Ctrl + c (Control + c). Lembre-se da altura do último bloco (o maior número da sequência no registro de blocos comprometidos). + +### 2. Gere a chave BLS {#2-generate-the-bls-key} + +`secrets init` com o `--bls` gera uma chave do BLS. Para manter a chave de ECDSA e Rede, e adicionar uma nova chave de BLS, `--ecdsa` e `--network` precisam ser desabilitadas. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Adicione a configuração do fork {#3-add-fork-setting} + +O comando `ibft switch` adiciona uma configuração do fork, que permite o BLS na chain existente, em `genesis.json`. + +Para redes de PoA, os validadores precisam ser dados no comando. Como na forma do comando `genesis`, os sinalizadores `--ibft-validators-prefix-path` ou `--ibft-validator` podem ser usados para especificar o validador. + +Especifique a altura a partir da qual a chain começa a usar o BLS com o sinalizador `--from`. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. Reinicie todos os nós {#4-restart-all-nodes} + +Reinicie todos os nós pelo comando `server`. Depois que o bloco em `from` especificado na etapa anterior for criado, a chain habilita o BLS e mostra os registros como exibidos abaixo: + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +Os registros também mostram que modo de verificação é usado para gerar cada bloco após o bloco ser criado. + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## Como migrar de uma chain de PoS de ECDSA existente para um chain de PoS de BLS {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +Esta seção descreve como usar o modo BLS em uma chain de PoS existente. +As seguintes etapas são necessárias para habilitar o BLS na chain de PoS. + +1. Pare todos os nós +2. Gere as chaves BLS para validadores +3. Adicione uma configuração de fork no genesis.json +4. Chame o contrato de staking para registrar a chave pública do BLS +5. Reinicie todos os nós + +### 1. Pare todos os nós {#1-stop-all-nodes-1} + +Encerre todos os processos dos validadores pressionando Ctrl + c (Control + c). Lembre-se da altura do último bloco (o maior número da sequência no registro de blocos comprometidos). + +### 2. Gere a chave BLS {#2-generate-the-bls-key-1} + +`secrets init` com o `--bls`indicador gera a chave BLS. Para manter a chave ECDSA e Rede existentes, e adicionar uma nova chave BLS, `--ecdsa` e `--network` precisam ser desabilitadas. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Adicione a configuração do fork {#3-add-fork-setting-1} + +O comando `ibft switch` adiciona uma configuração do fork, que habilita o BLS a partir do meio da chain, para `genesis.json`. + +Especifique a altura a partir da qual a chain começa a usar o modo BLS com o indicador `from`, e a altura na qual o contrato é atualizado com o indicador `development`. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. Registre a chave pública do BLS no contrato de staking {#4-register-bls-public-key-in-staking-contract} + +Depois que o fork for adicionado e os validadores forem reiniciados, cada validador precisa chamar `registerBLSPublicKey` no contrato de staking para registrar a chave pública do BLS. Isso deve ser feito após a altura especificada em `--deployment` antes da altura especificada em `--from`. + +O roteiro para registrar a Chave Pública do BLS é definido no [repositório de Contrato Inteligente de Staking](https://github.com/0xPolygon/staking-contracts). + +Configure `BLS_PUBLIC_KEY` para ser registrado no ficheiro `.env`. Consulte o [pos-stake-unstake](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) para mais detalhes sobre outros parâmetros. + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +O seguinte comando registra a chave pública do BLS fornecida em `.env` para o contrato. + +```bash +npm run register-blskey +``` + +:::warning Os validadores precisam registrar a chave pública do BLS manualmente + +No modo BLS, os validadores devem ter o seu próprio endereço e a chave pública do BLS. A camada de consenso ignora os validadores que não registraram a chave pública do BLS no contrato quando o consenso obtém informações do validador do contrato. + +::: + +### 5. Reinicie todos os nós {#5-restart-all-nodes} + +Reinicie todos os nós pelo comando `server`. A chain habilita o BLS após o bloco em `from` especificado na etapa anterior ser criado. diff --git a/archive/edge/pt-edge/consensus/migration-to-pos.md b/archive/edge/pt-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..62d3e438e6 --- /dev/null +++ b/archive/edge/pt-edge/consensus/migration-to-pos.md @@ -0,0 +1,39 @@ +--- +id: migration-to-pos +title: Migração de PoA para PoS +description: "Como migrar o modo IBFT de PoA para PoS e vice-versa." +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## Visão geral {#overview} + +Esta secção orienta através da migração de modos de IBFT de PoA a PoS e vice-versa, para um cluster em execução, sem a necessidade de redefinir a blockchain. + +## Como migrar para PoS {#how-to-migrate-to-pos} + +Precisará parar todos os nós, adicionar a configuração de fork no genesis.json pelo comando `ibft switch` e reiniciar os nós. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution Mudar enquanto estiver a usar o ECDSA +Ao usar o ECDSA, o `--ibft-validator-type`sinalizador deve ser adicionado ao interruptor, mencionando que o ECDSA é usado. Se não for incluída, o Edge irá mudar automaticamente para BLS. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::Para mudar para PoS, terá de especificar 2 alturas de blocos: `deployment`e . `from`é `deployment`a altura para implantar o contrato de staking e é `from`a altura do início do PoS. O contrato de staking será implantado no endereço `0x0000000000000000000000000000000000001001` e `deployment`, como no caso de contrato pré-implantado. + +Verifique o [Proof of Stake](/docs/edge/consensus/pos-concepts) para mais detalhes sobre o contrato de staking. + +:::warning Os validadores precisam fazer staking manualmente +Cada validador precisa fazer staking após o contrato ser implantado em `deployment` e antes de `from`, para ser um validador no início do PoS. Cada validador atualizará o conjunto de validadores pelo conjunto no contrato de staking no início do PoS. + +Para saber mais sobre a classificação, visite a **[Configuração e uso da Proof of Stake](/docs/edge/consensus/pos-stake-unstake)**. +::: diff --git a/archive/edge/pt-edge/consensus/poa.md b/archive/edge/pt-edge/consensus/poa.md new file mode 100644 index 0000000000..149b8fa4d1 --- /dev/null +++ b/archive/edge/pt-edge/consensus/poa.md @@ -0,0 +1,110 @@ +--- +id: poa +title: Prova de Autoridade (PoA) +description: "Explicação e instruções sobre Prova de Autoridade." +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## Visão geral {#overview} + +A PoA do IBFT é o mecanismo de consenso padrão no Polygon Edge. Na PoA, os validadores são os responsáveis por criar os blocos e adicioná-los ao blockchain numa série. + +Todos os validadores formam um conjunto de validadores dinâmicos, em que os validadores podem ser adicionados ou removidos do conjunto empregando um mecanismo de voto. Isso significa que os validadores podem ser aceitos ou recusados no conjunto de validadores se a maioria (51%) dos nós validadores votar por adicionar/soltar um determinado validador ao conjunto. Desta forma, validadores mal-intencionados podem ser reconhecidos e removidos da rede, enquanto os novos validadores confiáveis podem ser adicionados. + +Todos os validadores se revezam em propor o próximo bloco (round-robin), e para o bloco ser validado/inserido no blockchain, uma supermaioria (mais de 2/3) dos validadores deve aprovar o bloco citado. + +Além dos validadores, existem não validadores que não participam da criação dos blocos, mas participam do processo de validação de blocos. + +## Como adicionar um validador ao conjunto de validadores {#adding-a-validator-to-the-validator-set} + +Este guia descreve como adicionar um nó de validador novo a uma rede IBFT ativa com 4 nós de validadores. +Se precisar de ajuda para configurar a rede, consulte as seções [Configuração Local/Configuração da](/edge/get-started/set-up-ibft-on-the-cloud.md)[](/edge/get-started/set-up-ibft-locally.md) Nuvem. + +### Etapa 1: Inicialize as pastas de dados para o IBFT e gere chaves de validador para o novo nó {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +Para se começar a executar com o IBFT no novo nó é necessário primeiro inicializar as pastas de dados e gerar as chaves: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +Este comando imprimirá a chave do validador (endereço) e a ID do nó. Precisará da chave do validador (endereço) para a etapa seguinte. + +### Etapa 2: Proponha um novo candidato a outros nós validadores. {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +Para um nó novo se tornar um validador, pelo menos 51% dos validadores precisam propô-lo. + +Exemplo de como propor um novo validador (`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`) do nó de validador existente no endereço grpc: 127.0.0.1:1000: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +A estrutura dos IBFT é coberta na secção [Comandos CLI](/docs/edge/get-started/cli-commands). + +:::info A chave pública do BLS + +A chave pública do BLS só é necessária se a rede estiver a ser executada com o BLS, pois a rede que não está a ser executada no `--bls` do modo BLS é desnecessária + +::: + +### Etapa 3: Execute o nó do cliente {#step-3-run-the-client-node} + +Como, neste exemplo, estamos a tentar executar a rede com todos os nós na mesma máquina, precisamos de cautela para evitar conflitos de portas. + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +Depois de buscar todos os blocos dentro do consola, notará que um novo nó está a participar da validação + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info Promover um não validador para um validador + +Naturalmente, um não validador pode se tornar um validador pelo processo de votação, mas para que ele seja incluído com sucesso no conjunto de validadores após o processo, o nó precisa ser reiniciado com o sinalizador `--seal`. + +::: + +## Como remover um validador do conjunto de validadores {#removing-a-validator-from-the-validator-set} + +Esta operação é bastante simples. Para remover um nó de validador do conjunto de validadores, este comando precisa de ser executado para a maioria dos nós de validador. + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info A chave pública do BLS + +A chave pública do BLS só é necessária se a rede estiver a ser executada com o BLS, pois a rede que não está a ser executada no `--bls` do modo BLS é desnecessária + +::: + +Depois que os comandos são executados, observe que o número de validadores caiu (neste exemplo de registo, de 4 para 3). + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/pt-edge/consensus/pos-concepts.md b/archive/edge/pt-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..1710f264f2 --- /dev/null +++ b/archive/edge/pt-edge/consensus/pos-concepts.md @@ -0,0 +1,120 @@ +--- +id: pos-concepts +title: Proof of Stake +description: "Explicação e instruções sobre Proof of Stake." +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## Visão geral {#overview} + +Esta seção visa dar uma melhor visão geral de alguns conceitos atualmente presentes na Proof of Stake (PoS) +implementação do Polygon Edge. + +A implementação da Proof of Stake (PoS) do Polygon Edge é uma alternativa para a implementação de IBFT de PoA, +fornecendo aos operadores de nó a capacidade de escolher facilmente entre os dois ao iniciar uma chain. + +## Recursos de PoS {#pos-features} + +A lógica principal por trás da implementação de Proof of Stake está situada no +o **[Contrato Inteligente de Estágio](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)**. + +Este contrato é pré-implantado sempre que o Polygon Edge do mecanismo de PoS é inicializado, e está disponível no endereço +`0x0000000000000000000000000000000000001001` do bloco `0`. + +### Epochs {#epochs} + +Epochs são um conceito introduzido com o acréscimo de PoS ao Polygon Edge. + +Os Epochs são considerados um período especial (em blocos) em que um determinado conjunto de validadores pode produzir blocos. +Seus comprimentos são modificáveis, o que significa que os operadores de nós podem configurar o comprimento de uma epoch durante a geração de génese. + +No final de cada época, um _bloco_ de época é criado e depois deste evento uma nova época começa. Para saber mais sobre +os blocos da epoch, consulte a seção [Blocos da Epoch](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Os conjuntos de validadores são atualizados no final de cada epoch. Os nós consultam o conjunto de validadores do Contrato Inteligente de Staking +durante a criação do bloco de epoch e salvam os dados obtidos para armazenamento local. Este ciclo de consulta e salvamento é +repetido no final de cada epoch. + +Essencialmente, isso garante que o Contrato Inteligente de Staking tenha total controle sobre os endereços no conjunto de validadores e +deixe apenas uma responsabilidade para os nós: consultar o contrato uma vez durante cada epoch para buscar informações +do último conjunto de validadores. Isso reduz a responsabilidade que cada nó tem ao cuidar dos conjuntos de validadores. + +### Staking {#staking} + +Os endereços podem ter fundos de staking no Contrato Inteligente de Staking chamando o método `stake` e especificando um valor para +o valor em staking na transação: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +Com fundos de staking no Contrato Inteligente de Staking, os endereços podem inserir o conjunto de validadores e, portanto, poder participar no +processo de produção de blocos. + +:::info Limite para staking +Atualmente, o limite mínimo para inserir o conjunto de validadores é `1 ETH`staking + +::: + +### Sem staking {#unstaking} + +Endereços que tenham fundos de staking podem apenas **cancelar todos os seus fundos de staking de uma só vez**. + +O cancelamento do staking pode ser chamado através do método `unstake` no Contrato Inteligente de Staking: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +Depois de cancelar o staking dos seus fundos, os endereços são removidos do conjunto de validadores no Contrato Inteligente de Staking e não são +considerados validadores durante a próxima epoch. + +## Blocos de Epoch {#epoch-blocks} + +**Os Blocos de Epoch** são um conceito introduzido na implementação de PoS do IBFT no Polygon Edge. + +Essencialmente, os blocos de epoch são blocos especiais que **não contêm transações** e ocorrem apenas no **final de uma epoch**. +Por exemplo, se o **tamanho da época** estiver definido como `50`blocos, os blocos da época seriam considerados como blocos `50`, `100``150`e assim por diante. + +Eles são usados para executar lógica adicional que não deve ocorrer durante a produção regular de blocos. + +Mais importante, eles são uma indicação para o nó de que **ele precisa para buscar as informações mais recentes do conjunto de validadores** +a partir do Contrato Inteligente de Staking. + +Depois de atualizar o conjunto de validadores no bloco de epoch, o conjunto de validadores (alterado ou inalterado) +é usado para os blocos `epochSize - 1` subsequentes, até que ele seja atualizado novamente obtendo as informações mais recentes do +Contrato Inteligente de Staking. + +Os comprimentos de epoch (em blocos) são modificáveis ao gerar o ficheiro de génese, usando um sinalizador especial `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +O tamanho padrão de uma epoch é blocos `100000` no Polygon Edge. + +## Pré-implantação de contrato {#contract-pre-deployment} + +O _Polygon Edge_ pré-implementa +o [Contrato Inteligente de Staking.](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol) +durante a **geração de génese** para o endereço `0x0000000000000000000000000000000000001001`. + +Ele faz isso sem um EVM em execução, modificando o estado do blockchain do Contrato Inteligente, usando os valores +de configuração transmitidos para o comando de génese. diff --git a/archive/edge/pt-edge/consensus/pos-stake-unstake.md b/archive/edge/pt-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..2f18c455cd --- /dev/null +++ b/archive/edge/pt-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,174 @@ +--- +id: pos-stake-unstake +title: Configure e use Proof of Stake (PoS) +description: "Stake, unstake e outras instruções relacionadas a staking." +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## Visão geral {#overview} + +Este guia detalha como configurar a rede Proof of Stake com o Polygon Edge e como fazer staking de fundos para nós +para se tornarem validadores e como cancelar o staking de fundos. + +É **altamente encorajado** a ler e passar por [Configuração Local](/docs/edge/get-started/set-up-ibft-locally) / [Configurações de Nuvem](/docs/edge/get-started/set-up-ibft-on-the-cloud), antes de seguir o caminho +com este guia de PoS. Essas seções descrevem as etapas necessárias para iniciar um cluster de Prova de Autoridade (PoA) com o +Polygon Edge. + +Atualmente, não há limite no número de validadores que podem fazer staking de fundos no Contrato Inteligente de Staking. + +## Contrato Inteligente de Staking {#staking-smart-contract} + +O repositório para o Contrato Inteligente de Staking está localizado [aqui](https://github.com/0xPolygon/staking-contracts). + +Ele mantém os scripts de teste necessários, os arquivos ABI e, principalmente, o próprio Contrato Inteligente de Staking. + +## Como configurar um cluster de nó N {#setting-up-an-n-node-cluster} + +Como configurar uma rede com Polygon Edge está coberto nas seções +[Configuração Local](/docs/edge/get-started/set-up-ibft-locally) / [Configurações de Nuvem](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +A **única diferença** entre configurar um cluster de PoS e PoA é a geração de génese. + +**Ao gerar o ficheiro de génese para um cluster de PoS, é necessário um sinalizador adicional`--pos`**: + +```bash +polygon-edge genesis --pos ... +``` + +## Como definir o comprimento de uma epoch {#setting-the-length-of-an-epoch} + +As epochs são cobertas em detalhes na seção [Blocos de Epoch](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Para definir o tamanho de uma epoch para um cluster (em blocos), ao gerar o ficheiro de génese, um sinalizador adicional +é especificado `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +Este valor especificou no ficheiro de génese que o tamanho da epoch deve ser de `50` blocos. + +O valor padrão para o tamanho de uma epoch (em blocos) é `100000`. + +:::info Redução do comprimento da epoch + +Como descrito na seção [Blocos da epoch](/docs/edge/consensus/pos-concepts#epoch-blocks), +os blocos da epoch são usados para atualizar os conjuntos de validadores para nós. + +O comprimento de epoch padrão nos blocos (`100000`) pode ser um tempo longo para as atualizações de conjunto de validadores. Considerando que os novos +blocos são adicionados a cada 2 segundos aproximadamente, seriam necessárias ~55,5 horas para que o conjunto de validadores possa mudar. + +A configuração de um valor mais baixo para o comprimento da epoch garante que o conjunto de validadores seja atualizado com mais frequência. + +::: + +## Como usar os scripts do Contrato Inteligente de Staking {#using-the-staking-smart-contract-scripts} + +### Pré-requisitos {#prerequisites} + +Os repositórios de Contrato Inteligente de Staking são um projeto Hardhat, que requer NPM. + +Para inicializá-lo corretamente, no principal diretório, execute: + +```bash +npm install +```` + +### Configuração dos scripts de ajuda fornecidos {#setting-up-the-provided-helper-scripts} + +Os scripts para interagir com o Contrato Inteligente de Staking implantado estão localizados no +repositório do [Contrato Inteligente de Staking](https://github.com/0xPolygon/staking-contracts). + +Crie um ficheiro `.env` com os seguintes parâmetros na localização do repositório do Contrato Inteligente: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +Onde os parâmetros estão: + +* **JSONRPC_URL** - o endpoint JSON-RPC para o nó em execução +* **PRIVATE_KEYS** - chaves privadas do endereço de staking. +* **STAKING_CONTRACT_ADDRESS** - endereço do contrato inteligente de staking ( +padrão `0x0000000000000000000000000000000000001001`) +* **BLS_PUBLIC_KEY** - chave pública de BLS do staker. Só é necessária se a rede estiver a ser executada com BLS + +### Fundos de staking {#staking-funds} + +:::info Endereço de staking + +O Contrato Inteligente de Staking é pré-implantado no +endereço `0x0000000000000000000000000000000000001001`. + +Qualquer tipo de interação com o mecanismo de staking é feito através de Contrato Inteligente de Staking no endereço especificado. + +Para saber mais sobre o Contrato Inteligente de Staking, visite +o **[Contrato Inteligente de Estaca](/docs/edge/consensus/pos-concepts#contract-pre-deployment)** . + +::: + +Para ser parte do conjunto de validadores, o endereço precisa fazer staking de um determinado valor de fundos acima de um limiar. + +Atualmente, o limiar padrão para se tornar parte do conjunto de validadores é `1 ETH`. + +O staking pode ser iniciado chamando o `stake` método do Contrato Inteligente de Staking, e especificando um valor `>= 1 ETH`. + +Depois do ficheiro `.env` mencionado na +a [seção anterior](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) foi configurada e uma +cadeia foi iniciada no modo PoS, o staking pode ser feito com o seguinte comando no repositório de Contrato Inteligente de Staking: + +```bash +npm run stake +``` + +O script do `stake` Hardhat faz staking de um valor padrão de `1 ETH`, que pode ser alterado modificando-se o ficheiro `scripts/stake.ts` +. + +Se os fundos de staking forem `>= 1 ETH`, o conjunto de validadores no Contrato Inteligente de Staking é atualizado, e o endereço +será parte do conjunto de validadores a partir da próxima epoch. + +:::info Registro de chaves de BLS +Se a rede estiver a ser executada no modo BLS, para que os nós se tornem validadores, eles precisam registrar suas chaves públicas de BLS após o staking + +Isso pode ser realizado com o seguinte comando: + +```bash +npm run register-blskey +``` +::: + +### Fundos de cancelamento de staking {#unstaking-funds} + +Os endereços que têm um staking só ** podem cancelar os stakings de todos os seus fundos** uma única vez. + +Depois do ficheiro `.env` mencionado na +[seção anterior](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) +ter sido configurado e um chain ter sido iniciado no modo PoS, o cancelamento de staking pode ser feito com o seguinte comando no +repositório de Contrato Inteligente de Staking: + +```bash +npm run unstake +``` + +### Como obter a lista de stakers {#fetching-the-list-of-stakers} + +Todos os endereços que fazem staking de fundos são salvos no Contrato Inteligente de Staking. + +Depois do ficheiro `.env` mencionado na +[seção anterior](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) +ter sido configurado e a chain ter iniciado no modo PoS, a a lista de validadores pode ser obtida com o +seguinte comando no repositório do Contrato Inteligente de Staking: + +```bash +npm run info +``` diff --git a/archive/edge/pt-edge/faq/Contracts.md b/archive/edge/pt-edge/faq/Contracts.md new file mode 100644 index 0000000000..e5aeb5ee6f --- /dev/null +++ b/archive/edge/pt-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: Perguntas frequentes de Contratos Inteligentes +description: "Perguntas frequentes para Contratos Inteligentes do Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## O Polygon Edge oferece suporte a Contratos Inteligentes? {#does-polygon-edge-support-smart-contracts} + +Sim. As redes Polygon Edge são blockchains compatíveis com Ethereum, portanto os Contratos Inteligentes também são implantáveis em chains do Polygon Edge. + +## É possível atualizar a lógica de contrato de staking para PoS após a implantação? {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +Por enquanto, depois de ter iniciado a rede de PoS, não é possível alterar a lógica do contrato de staking, pois ele é parte do ficheiro de génese. Assim, não é possível, por exemplo, alterar o número mínimo/máximo de validadores. No entanto, é possível fazer ou cancelar o staking, para adicionar ou remover validadores. + + + diff --git a/archive/edge/pt-edge/faq/Gas.md b/archive/edge/pt-edge/faq/Gas.md new file mode 100644 index 0000000000..b8477044d8 --- /dev/null +++ b/archive/edge/pt-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: Perguntas frequentes de gás +description: "Perguntas frequentes de gás para o Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Como fazer valer um preço de gás mínimo? {#how-to-enforce-a-minimum-gas-price} +Pode usar o sinalizador `--price-limit` fornecido no comando do servidor. Isso irá fazer valer o seu nó para aceitar apenas transações que tenham gás maior ou igual ao limiar de preço que definiu. Para garantir que ele seja aplicado na rede inteira, é preciso ter certeza de que todos os nós tenham o mesmo limiar de preços. + + +## Pode ter transações com taxas de gás de 0? {#can-you-have-transactions-with-0-gas-fees} +Sim, pode. O limiar de preços padrão que os nós impõem é `0`, o que significa que os nós aceitarão transações que tenham preço de gás definido em `0`. + +## Como definir o fornecimento total de token de gás (nativo)? {#how-to-set-the-gas-native-token-total-supply} + +Pode definir um saldo pré-minerado para as contas (endereços) usando o `--premine flag`. Observe que esta é uma configuração do ficheiro de génese, e não pode ser alterada posteriormente. + +Exemplo de como usar o `--premine flag`: + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +Isso define um saldo pré-minerado de 1000 ETH para 0x3956E90e632AebBF34DEB49b71c28A83Bc029862 (o valor do argumento está em Wei). + +O valor pré-minerado do token de gás será o fornecimento total. Nenhum outro valor da moeda nativa (token de gás) pode ser cunhado posteriormente. + +## A borda oferece suporte a ERC-20 como token de gás? {#does-edge-support-erc-20-as-a-gas-token} + +A borda não oferece suporte ao token de ERC-20 como token de gás. Apenas a moeda Edge nativa é compatível com gás. + +## Como aumentar o limite de gás? {#how-to-increase-the-gas-limit} + +Existem duas opções para aumentar o limite de gás no Polygon Edge: +1. Limpar a chain e aumentar `block-gas-limit`para valor máximo do uint64 no ficheiro da génese +2. Use o `--block-gas-target`sinalizador com um alto valor para aumentar o limite de gás de todos os nós. Isto requer reinicialização do nó. Explicação detalhada [aqui](/docs/edge/architecture/modules/txpool/#block-gas-target). \ No newline at end of file diff --git a/archive/edge/pt-edge/faq/Tokens.md b/archive/edge/pt-edge/faq/Tokens.md new file mode 100644 index 0000000000..ec793e2354 --- /dev/null +++ b/archive/edge/pt-edge/faq/Tokens.md @@ -0,0 +1,23 @@ +--- +id: tokens +title: Perguntas frequentes sobre tokens +description: "Perguntas frequentes sobre os tokens do Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## O Polygon Edge é compatível com o EIP-1559? {#does-polygon-edge-support-eip-1559} +No momento, o Polygon Edge não é compatível com o EIP-1559. + +## Como definir o símbolo de moeda (token)? {#how-to-set-the-currency-token-symbol} + +O símbolo de token é apenas para uso na interface, por isso não pode ser configurado ou codificado em outra parte da rede. +Mas é possível alterá-lo quando adicionar a rede a uma carteira como MetaMask, por exemplo. + +## O que acontece com transações quando uma chain é interrompida? {#what-happens-to-transactions-when-a-chain-halts} + +Todas as transações que não foram processadas estão dentro do TxPool (fila enfileirada ou promovida). Se a chain for interrompida (todas as paradas de produção de blocos), estas transações nunca serão inseridas em blocos.
Este não é apenas o caso quando a chain é interrompida. Se os nós forem interrompidos ou reiniciados, todas as transações que não foram executadas e ainda estiverem no TxPool, serão removidas silenciosamente.
A mesma coisa acontecerá com transações quando uma alteração de quebra for introduzida, pois é necessário que os nós sejam reiniciados. diff --git a/archive/edge/pt-edge/faq/Validators.md b/archive/edge/pt-edge/faq/Validators.md new file mode 100644 index 0000000000..fd88d61ed0 --- /dev/null +++ b/archive/edge/pt-edge/faq/Validators.md @@ -0,0 +1,85 @@ +--- +id: validators +title: Perguntas frequentes sobre validadores +description: "Perguntas frequentes sobre os validadores do Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Como adicionar/remover um validador? {#how-to-add-remove-a-validator} + +### PoA {#poa} +A adição/remoção de validadores é feita por votação. Pode encontrar [aqui](/docs/edge/consensus/poa) um guia completo sobre este assunto. + +### PoS {#pos} +Pode encontrar [aqui](/docs/edge/consensus/pos-stake-unstake) um guia sobre como fazer o stake de fundos, para que um nó possa tornar-se validador, e o unstake (remover o validador). + +Note que: +- Pode usar o flag génese `--max-validator-count` para definir um número máximo de stakers que podem juntar-se ao conjunto de validadores. +- Pode usar o flag génese `--min-validator-count ` para definir o número mínimo de stakers necessários para aderir ao conjunto de validadores (`1` por defeito). +- Quando se atinge o número máximo de validadores, deixa de ser possível adicionar outro validador até remover um existente do conjunto (independentemente de o montante da participação do novo validador ser superior). Se remover um validador, o número de validadores restantes não pode ser inferior a `--min-validator-count`. +- Existe um limite padrão de `1` unidade de moeda de rede (gás) nativa para se tornar validador. + + + +## Qual é o espaço em disco recomendado para um validador? {#how-much-disk-space-is-recommended-for-a-validator} + +Recomendamos que comece com 100 G como base estimada de forma conservadora, garantindo que é possível ampliar o espaço em disco posteriormente. + + +## Existe um limite para o número de validadores? {#is-there-a-limit-to-the-number-of-validators} + +Se estamos a falar de limitações técnicas, o Polygon Edge não tem explicitamente um limite para o número de nós que pode ter em rede. Pode definir os limites de ligação (número de ligações de entrada/saída) numa base "por nó". + +Se estamos a falar de limitações práticas, verá um pior desempenho com um cluster de 100 nós do que com um cluster de 10 nós. Ao aumentar o número de nós no cluster, aumenta a complexidade da comunicação e apenas os custos de rede em geral. Tudo depende do tipo de rede que está a usar e do tipo de topologia de rede que tem. + +## Como mudar de PoA para PoS? {#how-to-switch-from-poa-to-pos} + +O PoA é o mecanismo de consenso padrão. Para um novo cluster, mudar para PoS implica adicionar o flag `--pos` ao gerar o ficheiro de génese. Se tem um cluster em execução, encontra [aqui](/docs/edge/consensus/migration-to-pos) informação sobre como efetuar a mudança. Todas as informações de que precisa sobre os nossos mecanismos de consenso e configuração podem ser encontradas na nossa [secção sobre consenso](/docs/edge/consensus/poa). + +## Como atualizo os meus nós quando houver uma quebra de código? {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +Pode encontrar um guia detalhado sobre este procedimento [aqui](/docs/edge/validator-hosting#update). + +## A quantidade mínima de staking é configurável para o PoS Edge? {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +A quantidade mínima de staking é, por defeito, `1 ETH` e não é configurável. + +## Por que razão os comandos JSON RPC `eth_getBlockByNumber` e `eth_getBlockByHash` não devolvem o endereço do minerador? {#not-return-the-miner-s-address} + +O consenso atualmente utilizado no Polygon Edge é o IBFT 2.0, que, por sua vez, se baseia no mecanismo de votação explicado em Clique PoA: [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225). + +Analisando o EIP-225 (Clique PoA), esta é a parte relevante que explica para que é usado o `miner`(também conhecido como `beneficiary`): + +
+Adaptamos os campos de cabeçalho ethash da seguinte forma: +
    +
  • beneficiário/minerador: endereço utilizado para propor a alteração da lista de assinantes autorizados.
  • +
      +
    • Normalmente, deve ser preenchido com zeros, sendo modificado apenas durante a votação.
    • +
    • Contudo, são permitidos valores arbitrários (mesmo os que não fazem sentido, como a votação de não assinantes) para evitar uma complexidade extra nas implementações em torno da mecânica de votação.
    • +
    • Deve ser preenchido com zeros nos blocos de checkpoint (isto é, transição de época).
    • +
    + +
+ +
+ +Assim, o campo `miner` é usado para propor um voto a favor de um determinado endereço, e não para mostrar o proponente do bloco. + +As informações sobre o proponente do bloco podem ser encontradas recuperando a pubkey no campo Seal do campo de dados extra Instanbul codificado por RLP nos cabeçalhos do bloco. + +## Que partes e valores do Genesis podem ser modificados com segurança? {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +Certifique-se de criar uma cópia manual do arquivo genesis.json existente antes de tentar editá-lo. Além disso, toda a chain tem de ser interrompida antes de editar o arquivo genesis.json. Assim que o arquivo de gênese for modificado, a versão mais recente dele tem de ser distribuída em todos os nós não validadores e valdiator + +::: + +**Somente a seção de bootnodes do arquivo de gênese pode ser modificada com segurança**, onde pode adicionar ou remover bootnodes da lista. \ No newline at end of file diff --git a/archive/edge/pt-edge/get-started/cli-commands.md b/archive/edge/pt-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..59d0c5b53c --- /dev/null +++ b/archive/edge/pt-edge/get-started/cli-commands.md @@ -0,0 +1,2220 @@ +--- +id: cli-commands +title: Comandos do CLI +description: "Lista de comandos do CLI e sinalizadores de comando para o Polygon Edge." +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +Esta seção detalha os comandos presentes, os sinalizadores de comando no Polygon Edge e como eles são usados. + +:::tip Suporte de saída de JSON + +O sinalizador `--json` é suportado em alguns comandos. Este sinalizador instrui o comando para imprimir o resultado no formato JSON + +::: + +## Comandos de inicialização {#startup-commands} + +| **Comando** | **Descrição** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| servidor | O comando padrão que inicia o cliente blockchain, executando o bootstrapping em todos os módulos juntos | +| génese | Gera um ficheiro *genesis.json*, que é usado para definir um estado chain predefinido antes de iniciar o cliente. A estrutura do ficheiro génese está descrita abaixo | +| pré-implantação da gênese | Predeploys um Contrato Inteligente para redes novas | + +### sinalizadores do servidor {#server-flags} + + +| **Todas as sinalizações do servidor** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [prometheus](/docs/edge/get-started/cli-commands#prometheus) | [block-gas-target](/docs/edge/get-started/cli-commands#block-gas-target) | +| [max-peers](/docs/edge/get-started/cli-commands#max-peers) | [max-inbound-peers](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [max-outbound-peers](/docs/edge/get-started/cli-commands#max-outbound-peers) | [max-enqueued](/docs/edge/get-started/cli-commands#max-enqueued) | +| [log-level](/docs/edge/get-started/cli-commands#log-level) | [log-to](/docs/edge/get-started/cli-commands#log-to) | +| [chain](/docs/edge/get-started/cli-commands#chain) | [join](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [limite de preço](/docs/edge/get-started/cli-commands#price-limit) | [max-slots](/docs/edge/get-started/cli-commands#max-slots) | +| [config](/docs/edge/get-started/cli-commands#config) | [secrets-config](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-interval](/docs/edge/get-started/cli-commands#dev-interval) | +| [no-discover](/docs/edge/get-started/cli-commands#no-discover) | [recuperação](/docs/edge/get-started/cli-commands#restore) | +| [block-time](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +Usado para especificar o diretório de dados usado para armazenar dados de cliente do Polygon Edge. Padrão: `./test-chain`. + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +Define endereço e porta do serviço JSON-RPC `address:port`. +Se apenas a porta estiver definida `:10001`, ele irá se conectar a todas as interfaces `0.0.0.0:10001`. +Se omitir, o serviço irá se conectar ao padrão `address:port`. +Endereço padrão: `0.0.0.0:8545`. + +--- + +####

json-rpc-block-range-limit + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +Define o intervalo de blocos máximo a ser considerado na execução de solicitações json-rpc que incluam valores de deBlock/toBlock (por exemplo, eth_getLogs). Este limite pode ser completamente desativado configurando o valor para `0`. Padrão:`1000`. + +--- + +####

json-rpc-batch-request-limit + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +Define o comprimento máximo a ser considerado ao lidar com solicitações de lote json-rpc. Este limite pode ser completamente desativado configurando o valor para `0`. Padrão: `20`. + +--- + +####

grpc + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +Define endereço e porta do serviço gRPC `address:port`. Endereço padrão: `127.0.0.1:9632`. + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +Define o endereço e a porta do serviço libp2p `address:port`. Endereço padrão: `127.0.0.1:1478`. + +--- + +####

prometheus + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +Define o endereço e a porta do servidor prometheus `address:port` . +Se apenas a porta estiver definida `:5001`, o serviço irá se conectar a todas as interfaces `0.0.0.0:5001`. +Se omitido, o serviço não será iniciado. + +--- + +####

block-gas-target + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +Define o limite de gás de blocos de meta para a chain. Padrão (não imposto): `0`. + +Uma explicação mais detalhada sobre a meta de gás de blocos pode ser encontrada na [seção TxPool](/docs/edge/architecture/modules/txpool#block-gas-target). + +--- + +####

max-peers + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +Define a contagem máxima de pares do cliente. Padrão: `40`. + +O limite de pares deve ser especificado usando o sinalizador `max-peers` ou `max-inbound/outbound-peers`. + +--- + +####

max-inbound-peers + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +Define a contagem máxima de pares de entrada do cliente. Se `max-peers` estiver definido, o limite max-inbound-peer é calculado usando as seguintes fórmulas. + +`max-inbound-peer = InboundRatio * max-peers`, onde `InboundRatio` é `0.8`. + +--- + +####

max-outbound-peers + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +Define a contagem máxima de pares de saída do cliente. Se `max-peers` estiver definido, a contagem max-outbound-peer é calculada usando as seguintes fórmulas. + +`max-outbound-peer = OutboundRatio * max-peers`, onde `OutboundRatio` é `0.2`. + +--- + +####

max-enqueued + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +Define o número máximo de transações em fila por conta. Padrão:`128`. + +--- + +####

log-level + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +Define o nível do registro para a saída da consola. Padrão: `INFO`. + +--- + +####

log-to + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +Define o nome do ficheiro de registo que irá manter toda a saída do registo do comando do servidor. +Por padrão, todos os registos do servidor serão colocados na consola (stdout), +mas se o sinalizador estiver definido, não haverá saída para a consola ao executar o comando do servidor. + +--- + +####

chain + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +Especifica o ficheiro de génese usado para iniciar a chain. Padrão: `./genesis.json`. + +--- + +####

join + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Especifica o endereço do par que deve ser associado. + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +Define o endereço IP externo sem a porta, pois pode ser visto por pares. + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +Define o endereço DNS do host. Ele pode ser usado para anunciar um DNS externo. Suporta `dns`,`dns4`,`dns6`. + +--- + +####

limite de preço + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +Define o limite mínimo para preço de gás para fazer cumprir a aceitação no pool. Padrão: `1`. + +--- + +####

max-slots + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +Define o máximo de slots no pool. Padrão: `4096`. + +--- + +####

Config + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +Especifica o caminho para config. CLI. Suporta `.json`. + +--- + +####

secrets-config + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +Define o caminho para o ficheiro config. SecretsManager. Usado para Hashicorp Vault, AWS SSM e GCP Secrets Manager. Se omitido, o gestor de segredos FS local é usado. + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +Define o cliente para modo dev. Padrão: `false`. No modo dev, a descoberta de pares é desabilitada por padrão. + +--- + +####

dev-interval + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +Define o intervalo de notificação dev do cliente em segundos. Padrão: `0`. + +--- + +####

no-discover + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +Impede o cliente de descobrir outros pares. Padrão: `false`. + +--- + +####

recuperação + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +Restaure blocos de ficheiro do arquivo especificado + +--- + +####

block-time + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +Define o tempo de produção de blocos em segundos. Padrão: `2` + +--- + +####

access-control-allow-origins + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +Define os domínios autorizados para poder compartilhar respostas de solicitações JSON-RPC. +Adiciona múltiplos sinalizadores `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"` para autorizar múltiplos domínios. +Se omitido, o cabeçalho Access-Control-Allow-Origins será definido para `*` e todos os domínios serão autorizados. + +--- + +### sinalizadores de génese {#genesis-flags} +| **Todas as sinalizações da gênese** | +|---------------------------------------|---------------------------------------------| +| [dir](/docs/edge/get-started/cli-commands#dir) | [Nome](/docs/edge/get-started/cli-commands#name) | +| [pos](/docs/edge/get-started/cli-commands#pos) | [epoch-size](/docs/edge/get-started/cli-commands#epoch-size) | +| [premine](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [ibft-validator-type](/docs/edge/get-started/cli-commands#ibft-validator-type) | [ibft-validators-prefix-path](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [ibft-validator](/docs/edge/get-started/cli-commands#ibft-validator) | [block-gas-limit](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [consensus](/docs/edge/get-started/cli-commands#consensus) | [bootnode](/docs/edge/get-started/cli-commands#bootnode) | +| [max-validator-count](/docs/edge/get-started/cli-commands#max-validator-count) | [min-validator-count](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

dir + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +Define o diretório para os dados de génese do Polygon Edge. Padrão: `./genesis.json`. + +--- + +####

Nome + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +Define o nome para a chain. Padrão: `polygon-edge`. + +--- + +####

pos + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +Define o sinalizador que indica que o cliente deve usar IBFT Proof of Stake. +O padrão é Proof o Authority se o sinalizador não for fornecido ou `false`. + +--- + +####

epoch-size + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +Define o tamanho da epoch para chain. Padrão `100000`. + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +Define as contas e os saldos pré-minerados no `address:amount`formato. +O valor pode ser decimal ou hex. +Saldo pré-minerado por padrão: `0xD3C21BCECCEDA1000000`(1 milhão de tokens de moeda nativa). + +--- + +####

chainid + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +Define a identificação da chain. Padrão: `100`. + +--- + +####

ibft-validator-type + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +Especifica o modo de validação dos cabeçalhos de blocos. Valores possíveis: `[ecdsa, bls]`. Padrão: `bls`. + +--- + +####

ibft-validators-prefix-path + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +Caminho de prefixos para o diretório de pastas de validadores. Precisa estar presente se o sinalizador `ibft-validator` for omitido. + +--- + +####

ibft-validator + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Define os endereços transmitidos como validadores IBFT. Precisa estar presente se o sinalizador `ibft-validators-prefix-path` for omitido. +1. Se a rede estiver a ser executada com ECDSA, o formato é `--ibft-validator [ADDRESS]`. +2. Se a rede estiver a ser executada com BLS, o formato é `--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]`. + +--- + +####

block-gas-limit + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +Refere-se ao valor máximo de gás usado por todas as operações em um bloco. Padrão: `5242880`. + +--- + +####

consensus + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +Define o protocolo de consenso. Padrão: `pow`. + +--- + +####

bootnode + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +URL Multiaddr para p2p discovery bootstrap. Este sinalizador pode ser usado várias vezes. +Em vez de um endereço IP, o endereço DNS do bootnode pode ser fornecido. + +--- + +####

max-validator-count + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +O número máximo de stakers capazes de aderir ao conjunto de validadores em um consenso de PoS. +Este número não pode exceder o valor de MAX_SAFE_INTEGER (2^53 - 2). + +--- + +####

min-validator-count + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +O número mínimo de stakers necessários para ingressar no conjunto de validadores em um consenso de PoS. +Este número não pode exceder o valor do max-validator-count. +O padrão é 1. + +--- + +### sinalizadores de pré-implantação da gênese {#genesis-predeploy-flags} + +

artifacts-path

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +Define o caminho para os artefatos do contrato JSON que contém `abi`os `bytecode`e .`deployedBytecode` + +--- + +

chain

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +Define o caminho para o `genesis.json`ficheiro que deve ser atualizado. Padrão `./genesis.json`. + +--- + +

constructor-args

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +Define os argumentos do construtor de contratos inteligentes, se houver. Para obter um guia detalhado sobre como estes argumentos devem parecer, consulte [o artigo](/docs/edge/additional-features/predeployment) da pré-implantação. + +--- + +

predeploy-address

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +Define o endereço para o pré-implantação. Padrão `0x0000000000000000000000000000000000001100`. + +--- + + +## Comandos do operador {#operator-commands} + +### Comandos de pares {#peer-commands} + +| **Comando** | **Descrição** | +|------------------------|-------------------------------------------------------------------------------------| +| peers add | Adiciona um novo par usando o endereço libp2p | +| peer list | Lista todos os pares para o cliente que está conectado através do libp2p | +| peers status | Retorna o status de um par específico da lista de pares usando o endereço libp2p | + +

peers add flags

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Endereço libp2p do par no formato multiaddr. + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +Endereço do API de gRPC. Padrão: `127.0.0.1:9632`. + +

peers list flags

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +Endereço do API de gRPC. Padrão: `127.0.0.1:9632`. + +

peers status flags

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Identificação de nó Libp2p de um par específico na rede p2p. + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +Endereço do API de gRPC. Padrão: `127.0.0.1:9632`. + +### Comandos do IBFT {#ibft-commands} + +| **Comando** | **Descrição** | +|------------------------|-------------------------------------------------------------------------------------| +| ibft snapshot | Retorna o snapshot do IBFT | +| ibft candidates | Consulta o conjunto atual de candidatos propostos, bem como os candidatos que ainda não foram incluídos | +| ibft propose | Propõe um novo candidato a ser adicionado/removido do conjunto de validadores | +| ibft status | Retorna o status geral do cliente IBFT | +| ibft switch | Adiciona configurações do fork no ficheiro genesis.json para alternar o tipo de IBFT | +| ibft quorum | Especifica o número de blocos após o qual o método de tamanho de quórum ideal será usado para obter consenso | + + +

ibft snapshot flags

+ +

number

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +A altura do bloco (número) do snapshot. + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +Endereço do API de gRPC. Padrão: `127.0.0.1:9632`. + +

ibft candidates flags

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Endereço do API de gRPC. Padrão: `127.0.0.1:9632`. + +

ibft propose flags

+ +

vote

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +Propõe alteração no conjunto de validadores. Valores possíveis: `[auth, drop]`. + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +Endereço da conta a ser votada. + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +Chave pública de BLS da conta a ser votada, necessária apenas no modo BLS. + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Endereço do API de gRPC. Padrão: `127.0.0.1:9632`. + +

ibft status flags

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +Endereço do API de gRPC. Padrão: `127.0.0.1:9632`. + +

ibft switch flags

+ +

chain

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +Especifica o ficheiro de génese a atualizar. Padrão: `./genesis.json`. + +--- + +

Tipo

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +Especifica o tipo de IBFT para alternar. Valores possíveis: `[PoA, PoS]`. + +--- + +

deployment

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +Especifica a altura da implantação do contrato. Disponível apenas com PoS. + +--- + +

from

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +Especifica o modo de validação dos cabeçalhos de blocos. Valores possíveis: `[ecdsa, bls]`. Padrão: `bls`. + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +Caminho de prefixo para os diretórios de novos validadores. Precisa estar presente se o sinalizador `ibft-validator` for omitido. Disponível apenas quando o modo IBFT é PoA (sinalizador `--pos` é omitido). + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Define os endereços transmitidos como validadores do IBFT usados após o fork. Precisa estar presente se o sinalizador `ibft-validators-prefix-path` for omitido. Disponível apenas no modo PoA. +1. Se a rede estiver a ser executada com ECDSA, o formato é `--ibft-validator [ADDRESS]`. +2. Se a rede estiver a ser executada com BLS, o formato é `--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]`. + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +O número máximo de stakers capazes de aderir ao conjunto de validadores em um consenso de PoS. +Este número não pode exceder o valor de MAX_SAFE_INTEGER (2^53 - 2). + +--- + +

min-validator-count

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +O número mínimo de stakers necessários para ingressar no conjunto de validadores em um consenso de PoS. +Este número não pode exceder o valor do max-validator-count. +O padrão é 1. + +Especifica a altura do início do fork. + +--- + +

ibft quorum flags

+ +

from

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +A altura para mudar o cálculo do quórum para QuorumOptimal, que usa a fórmula `(2/3 * N)`, com `N` sendo o número de nós de validadores. Observe que isso é para compatibilidade reversa ou seja, apenas para chains que usaram um cálculo herdado de Quórum até uma determinada altura de blocos. + +--- + +

chain

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +Especifica o ficheiro de génese a atualizar. Padrão: `./genesis.json`. + +### Comandos de pool de transações {#transaction-pool-commands} + +| **Comando** | **Descrição** | +|------------------------|--------------------------------------------------------------------------------------| +| txpool status | Retorna o número de transações no pool | +| txpool subscribe | Assina eventos no pool de transações | + +

txpool status flags

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +Endereço do API de gRPC. Padrão: `127.0.0.1:9632`. + +

txpool subscribe flags

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +Endereço do API de gRPC. Padrão: `127.0.0.1:9632`. + +--- + +

promoted

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +Subescreve eventos tx promovidos no TxPool. + +--- + +

dropped

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +Subscreve eventos tx descartados no TxPool. + +--- + +

demoted

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +Subscreve eventos tx rebaixados no TxPool. + +--- + +

added

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +Subscreve eventos tx adicionados ao TxPool. + +--- + +

enqueued

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +Subscreve eventos tx com fila nas filas de contas. + +--- + +### Comandos de blockchain {#blockchain-commands} + +| **Comando** | **Descrição** | +|------------------------|-------------------------------------------------------------------------------------| +| status | Retorna o status do cliente. A resposta detalhada pode ser encontrada abaixo | +| monitor | Subscreve a um fluxo de eventos de blockchain. A resposta detalhada pode ser encontrada abaixo | +| versão | Retorna a versão atual do cliente | + +

sinalizadores de status

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +Endereço do API de gRPC. Padrão: `127.0.0.1:9632`. + +

monitor flags

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +Endereço do API de gRPC. Padrão: `127.0.0.1:9632`. + +--- +

comando da versão

+ + + + + + version + + + + +Exibe a versão de lançamento, git branch, commit hash e tempo de compilação. + +## Comandos de segredos {#secrets-commands} + +| **Comando** | **Descrição** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| secrets init | Inicializa as chaves privadas para o gestor de segredos correspondentes | +| secrets generate | Gera um ficheiro de configuração do gestor de segredos que pode ser analisado pelo Polygon Edge | +| Saída de segredos | Imprime o endereço de chave pública BLS, o endereço de chave pública de validador e o ID de nó para referência | + +### secrets init flags {#secrets-init-flags} + +

Config

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +Define o caminho para o ficheiro config. SecretsManager. Usado para Hashicorp Vault. Se omitido, o gestor de segredos FS local é usado. + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +Define o diretório para os dados do Polygon Edge se o FS local for usado. + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +Define o sinalizador que indica se deve gerar uma chave ECDSA. Padrão: `true`. + +--- + +

network

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +Define o sinalizador que indica se deve gerar uma chave de rede Libp2p. Padrão: `true`. + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +Define o sinalizador que indica se deve gerar uma chave BLS. Padrão: `true`. + +### secrets generate flags {#secrets-generate-flags} + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +Define o diretório do ficheiro de configurações de gestor de segredos Padrão: `./secretsManagerConfig.json` + +--- + +

Tipo

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +Especifica o tipo de gestor de segredos [`hashicorp-vault`]. Padrão: `hashicorp-vault` + +--- + +

token

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +Especifica o token de acesso ao serviço + +--- + +

server-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +Especifica o URL do servidor do serviço + +--- + +

Nome

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +Especifica o nome do nó de manutenção de registros no serviço. Padrão: `polygon-edge-node` + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Especifica o espaço de nomes usado para o gestor de segredos do Vault Hashicorp. Padrão: `admin` + +### sinalizadores de saída de segredos {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +Define o sinalizador indicando se deve apenas emitir a chave pública BLS. Padrão: `true` + +--- + +

Config

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +Define o caminho para o ficheiro config. SecretsManager. Se omitido, o gestor de segredos FS local é usado. + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +Define o diretório para os dados do Polygon Edge se o FS local for usado. + +--- + +

node-id

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +Define o sinalizador indicando se deve apenas emitir o ID do nó da rede. Padrão: `true` + +--- + +

Validador

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +Define o sinalizador indicando se deve apenas emitir o endereço do validador. Padrão: `true` + +--- + +## Respostas {#responses} + +### Resposta de status {#status-response} + +O objeto de resposta é definido usando Buffers de Protocolo. +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### Resposta do monitor {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## Utilitários {#utilities} + +### whitelist commands {#whitelist-commands} + +| **Comando** | **Descrição** | +|------------------------|-------------------------------------------------------------------------------------| +| whitelist show | Exibe informações de lista de permissões | +| whitelist deployment | Atualiza a lista de permissões de implantação de contrato inteligente | + +

whitelist show

+ + + + + whitelist show + + + + +Exibe informações da lista de permissões. + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +Especifica o ficheiro de génese a atualizar. Padrão: `./genesis.json`. + +--- + +

whitelist deployment

+ +

chain

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +Especifica o ficheiro de génese a atualizar. Padrão: `./genesis.json`. + +--- + +

add

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Adiciona um endereço novo à lista de permissões de implantação de contratos. Apenas os endereços na lista de permissões de implantação de contratos que podem implantar contratos. Se ela estiver vazia, qualquer endereço pode executar a implantação de contratos + +--- + +

remove

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Remove um endereço da lista de permissões de implantação de contratos. Apenas os endereços na lista de permissões de implantação de contratos que podem implantar contratos. Se ela estiver vazia, qualquer endereço pode executar a implantação de contratos + +--- + +### backup flags {#backup-flags} + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +Endereço do API de gRPC. Padrão: `127.0.0.1:9632`. + +--- + +

out

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +Caminho de ficheiro de arquivo a salvar. + +--- + +

from

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +A altura do início de blocos no arquivo. Padrão: 0. + +--- + +

to

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +A altura do fim de blocos no arquivo. + +--- + +## Modelo de génese {#genesis-template} +O ficheiro de génese deve ser usado para definir o estado inicial do blockchain (ex. se algumas contas devem ter um saldo inicial). + +O ficheiro *./genesis.json* a seguir é gerado: +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### Diretório de dados {#data-directory} + +Ao executar o sinalizador *data-dir*, uma pasta de **test-chain** é gerada. +A estrutura de pastas consiste nas seguintes subpastas: +* **blockchain** - armazena o LevelDB para objetos de blockchain +* **trie** - armazena LevelDB para as tentativas de Merkle +* **keystore** - armazena chaves privadas para o cliente. Isto inclui a chave privada libp2p e a chave privada de selagem/validador +* **consensus** - armazena qualquer informação de consenso que o cliente possa necessitar durante o trabalho + +## Recursos {#resources} +* **[Buffers de protocolo](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/pt-edge/get-started/installation.md b/archive/edge/pt-edge/get-started/installation.md new file mode 100644 index 0000000000..7d2ca5e33e --- /dev/null +++ b/archive/edge/pt-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: Instalação +description: "Como instalar o Polygon Edge." +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +Consulte o método de instalação que melhor se aplica a si. + +Recomendamos que use os lançamentos pré-construídos e verifique os checksums fornecidos. + +## Lançamentos pré-construídos {#pre-built-releases} + +Consulte a página [Lançamentos do GitHub](https://github.com/0xPolygon/polygon-edge/releases) para uma lista de lançamentos. + +O Polygon Edge é fornecido com binários AMD64/ARM64 de compilação cruzada para Darwin e Linux. + +--- + +## Imagem do Docker {#docker-image} + +As imagens oficiais do Docker estão hospedadas no [hub.docker.com registry](https://hub.docker.com/r/0xpolygon/polygon-edge). + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## Construir a partir da fonte {#building-from-source} + +Antes de usar `go install`, certifique-se de que tem o Go `>=1.18` instalado e devidamente configurado. + +O ramo estável é o ramo da versão mais recente. + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## Utilizar `go install` + +Antes de usar `go install`, certifique-se de que tem o Go `>=1.17` instalado e devidamente configurado. + +`go install github.com/0xPolygon/polygon-edge@release/` + +O binário estará disponível na variável de `GOBIN`ambiente e incluirá as alterações da versão mais recente. Pode verificar as [Liberações do GitHub](https://github.com/0xPolygon/polygon-edge/releases) para saber qual é o mais tardar. diff --git a/archive/edge/pt-edge/get-started/set-up-ibft-locally.md b/archive/edge/pt-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..21c71d6e1a --- /dev/null +++ b/archive/edge/pt-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,367 @@ +--- +id: set-up-ibft-locally +title: Configuração local +description: "Guia de configuração local passo a passo." +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution Este guia é apenas para fins de teste + +O guia abaixo irá instruí-lo em como configurar uma rede Polygon Edge na sua máquina local para finalidades de testes +e desenvolvimento. + +O procedimento difere muito da maneira que você gostaria de configurar a rede Polygon Edge para um cenário num +um provedor de nuvem: **[Configuração da nuvem](/docs/edge/get-started/set-up-ibft-on-the-cloud)** + +::: + + +## Requisitos {#requirements} + +Consultar [Instalação](/docs/edge/get-started/installation) para instalar o Polygon Edge. + +## Visão geral {#overview} + +![Configuração local](/img/edge/ibft-setup/local.svg) + +Neste guia, o nosso objetivo é estabelecer uma rede blockchain `polygon-edge` funcional trabalhando com o [protocolo de consenso IBFT](https://github.com/ethereum/EIPs/issues/650). +A rede blockchain consistirá em 4 nós, todos eles nós de validador e, como tal, elegíveis para propor blocos e validar blocos provenientes de outros proponentes. +Todos os 4 nós serão executados na mesma máquina, pois a ideia deste guia é fornecer um cluster de IBFT totalmente funcional no menor tempo possível. + +Para o conseguir, iremos guiá-lo ao longo de 4 etapas fáceis: + +1. A inicialização de diretórios de dados irá gerar as chaves de validador para cada um dos 4 nós e inicializar os diretórios de dados de blockchain vazios. As chaves de validador são importantes, pois precisamos fazer o bootstrap do bloco de génese com o conjunto inicial de validadores usando essas chaves. +2. A preparação da string de conexão para o bootnode trará informações vitais para cada nó que vamos executar em relação a que nó se conectar ao iniciar. +3. Para gerar o ficheiro `genesis.json`, será preciso inserir as chaves de validador geradas na **etapa 1** e usadas para definir os validadores iniciais da rede no bloco de génese e a string de conexão de bootnode na **etapa 2**. +4. Executar todos os nós é o principal objetivo deste guia e será a a última etapa a ser executada. Vamos instruir os nós sobre que diretório de dados usar e onde encontrar `genesis.json`, o que executa o bootstrap do estado inicial da rede. + +Como todos os quatro nós serão executados no localhost, durante o processo de configuração, é esperado que todos os diretórios de dados +para cada um dos nós estejam no mesmo diretório principal. + +:::info Número de validadores + +Não há um número mínimo de nós por cluster, o que significa que são possíveis clusters com apenas 1 nó de validador. +Lembre-se de que com um cluster de um _único_ nó **não existe tolerância às falhas** nem **garantia de BFT**. + +O número mínimo recomendado de nós para obter a garantia de BFT é 4 - já que num cluster de 4 nós pode ser tolerada +a falha de 1 nó, com os restantes 3 a funcionarem normalmente. + +::: + +## Etapa 1: inicialize as pastas de dados para o IBFT e gere chaves de validador {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +Para operar com o IBFT, é necessário inicializar as pastas de dados, +uma para cada nó: + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +Cada um destes comandos imprimirá a chave de validador, a chave pública BLS e a [ID do nó](https://docs.libp2p.io/concepts/peer-id/). Irá precisar da identificação do primeiro nó para a etapa seguinte. + +### Segredos de execução {#outputting-secrets} +A saída de segredos pode ser recuperada novamente, se necessário. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## Etapa 2: preparar o string de conexão multiaddr para o bootnode {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Para estabelecer com sucesso a conectividade, um nó deve saber a que servido `bootnode` se conectar para obter +informações sobre todos os nós restantes da rede. O `bootnode` é, por vezes, conhecido como servidor `rendezvous` no jargão p2p. + +`bootnode` não é uma instância especial do nó do polygon-edge. Cada nó do polygon-edge pode atuar como um `bootnode`, mas +cada nó do polygon-edge precisa ter um conjunto de bootnodes especificado, que será contatado para informações sobre como se conectar com +todos os restantes nós da rede. + +Para criar um string de conexão para especificar o bootnode, temos de seguir +o [formato multiaddr](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +Neste guia trataremos o primeiro e segundo nós como bootnodes para todos os outros nós. O que acontece neste cenário +é que os nós que se conectam ao `node 1` ou `node 2` irão obter informações sobre como se conectar entre si através de um +bootnode mutuamente contactado. + +:::info É necessário especificar pelo menos um bootnode para iniciar um nó + +É necessário pelo menos **um** bootnode para que outros nós da rede possam encontrar-se. São recomendados mais bootnodes, pois +eles oferecem resiliência à rede em caso de interrupção. +Neste guia listaremos dois nós, mas isto pode ser alterado rapidamente, sem qualquer impacto na validade do ficheiro `genesis.json`. + +::: + +Como estamos a executar no localhost, é seguro assumir que o `` é `127.0.0.1`. + +Para o , ``vamos usar `10001`já que configuraremos o servidor libp2p para `node 1`para ouvir nesta porta posteriormente. + +Por fim, precisamos da ``, que podemos obter da saída do comando `polygon-edge secrets init --data-dir test-chain-1` previamente executado (que foi usado para gerar chaves e diretórios de dados para o `node1`) + +Depois da compilação, o string de conexão multiaddr para o `node 1` que usaremos como bootnode terá o seguinte aspeto (só a ``, que se encontra no final, deverá ser diferente): +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Da mesma forma, construímos o multiaddr para o segundo bootnode como abaixo +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info Hostnames DNS em vez de ips + +O Polygon Edge suporta o uso de hostnames DNS para a configuração dos nós. Este é um recurso muito útil para implantações baseadas na nuvem, já que o ip do nó pode mudar por vários motivos. + +O formato multiaddr para o string de conexão ao usar os hostnames DNS é o seguinte: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## Etapa 3: gerar o ficheiro de génese com os 4 nós como validadores {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +O que faz este comando: + +* O `--ibft-validators-prefix-path` define o caminho da pasta do prefixo para o caminho especificado que o IBF no Polygon Edge pode +usar. Este diretório é usado para abrigar a pasta `consensus/`, onde a chave privada do validador é mantida. A +chave pública do validador é necessária para construir o ficheiro de génese - a lista inicial de nós de bootstrap. +Este sinalizador faz sentido apenas ao configurar a rede no localhost, já que num cenário do mundo real não podemos esperar +que todos os diretórios de dados de nós estejam no mesmo sistema de arquivos de onde podemos ler facilmente suas chaves públicas. +* O `--bootnode` define o endereço do bootnode que irá permitir que os nós se encontrem. +Usaremos a string multiaddr do `node 1`, como mencionado na **etapa 2**. + +O resultado deste comando é o ficheiro `genesis.json`, que contém o bloco de génese do nosso blockchain novo, com o conjunto de validador predefinido e a configuração para que nó para entrar em contato primeiro para estabelecer a conectividade. + +:::info Mudar para ECDSA + +BLS é o modo de validação padrão dos cabeçalhos de blocos. Se desejar que a sua chain seja executada no modo ECDSA, pode usar o `—ibft-validator-type`sinalizador , com o argumento `ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info Pré-mineração de saldos de conta + +Provavelmente quererá configurar a sua rede blockchain com alguns endereços que têm saldos "pré-minerados". + +Para o conseguir, passe tantos flags `--premine` quantos quiser por endereço que pretende que seja inicializado com um determinado saldo +na blockchain. + +Por exemplo, se quisermos pré-minerar 1000 ETH para o endereço `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` do nosso bloco de génese, então precisaremos de fornecer o seguinte argumento: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Note que o valor pré-minerado está em WEI, não ETH.** + +::: + +:::info Defina o limite de gás do bloco + +O limite de gás predefinido para cada bloco é `5242880`. Este valor é escrito no ficheiro génese, mas poderá querer +aumentá-lo/diminui-lo. + +Para o fazer, pode usar o flag `--block-gas-limit`, seguido do valor pretendido, como se mostra abaixo: + +```shell +--block-gas-limit 1000000000 +``` +::: + +:::info Defina o limite do descritor do ficheiro de sistema + +O limite de descritores de ficheiros padrão (número máximo de ficheiros abertos) pode ser baixo e, no Linux, tudo é um ficheiro. Se os nós forem esperados ter alta taxa de transferência, poderá considerar aumentar este limite. Verifique os documentos oficiais da sua distribuição do linux para mais detalhes. + +#### Verifique os limites atuais do sistema operativo (ficheiros abertos) {#check-current-os-limits-open-files} +```shell title="ulimit -n" +1024 # Ubuntu default +``` + +#### Aumente o limite de ficheiros abertos {#increase-open-files-limit} +- Executar `polygon-edge`em primeiro plano (shell) + ```shell title="Set FD limit for the current session" + ulimit -n 65535 # affects only current session, limit won't persist after logging out + ``` + + ```shell title="Edit /etc/security/limits.conf" + # add the following lines to the end of the file to modify FD limits + * soft nofile 65535 # sets FD soft limit for all users + * hard nofile 65535 # sets FD hard limit for all users + + # End of file + ``` +Salve o ficheiro e reinicie o sistema. + +- Executar `polygon-edge`em segundo plano como serviço + +Se for `polygon-edge`executado como serviço de sistema, usando a ferramenta como , limites do descritor de `systemd`arquivos deve ser gerenciado usando `systemd`. + ```shell title="Edit /etc/systemd/system/polygon-edge.service" + [Service] + ... + LimitNOFILE=65535 + ``` + +### Solução de problemas {#troubleshooting} +```shell title="Watch FD limits of polygon edge running process" +watch -n 1 "ls /proc/$(pidof polygon-edge)/fd | wc -l" +``` + +```shell title="Check max FD limits for polygon-edge running process" +cat /proc/$(pidof polygon-edge)/limits +``` +::: + + +## Etapa 4: executar todos os clientes {#step-4-run-all-the-clients} + +Como estamos a tentar executar uma rede Polygon Edge consistindo em 4 nós, todos na mesma máquina, precisamos +evitar conflitos de portas. É por isso que usaremos a seguinte lógica para determinar as portas de escuta de cada servidor de um nó: + +- `10000` para o servidor de gRPC de `node 1`, `20000` para o servidor de GRPC de `node 2`, etc. +- `10001` para o servidor de libp2p de `node 1`, `20001` para o servidor de libp2p de `node 2`, etc. +- `10002` para o servidor JSON-RPC de `node 1`, `20002` para o servidor JSON-RPC de `node 2`, etc. + +Para executar o **primeiro** cliente (observe a porta `10001` desde que ela foi usada como parte do libp2p multiaddr na **etapa 2** junto com a ID de Nó de 1s do nó): + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +Para executar o **segundo** cliente: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +Para executar o **terceiro** cliente: + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +Para executar o **quarto** cliente: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +Para rever brevemente o que foi feito até agora: + +* O diretório para dados de cliente foi especificado para ser **./test-chain-\*** +* Os servidores GRPC foram iniciados nas portas **10000**, **20000**, **30000** e **40000**, para cada nó respetivamente +* Os servidores de libp2p foram iniciados nas portas **10001**, **20001**, **30001** e **40001**, para cada nó respetivamente +* Os servidores JSON-RPC foram iniciados nas portas **10002**, **20002**, **30002** e **40002**, para cada nó respetivamente +* O sinalizador *de vedação* significa que o nó que está a ser iniciado irá participar na selagem do bloco +* O sinalizador *chain* especifica que ficheiro de génese deve ser usado para a configuração de chain + +A estrutura do ficheiro de génese é abordada na secção [Comandos CLI](/docs/edge/get-started/cli-commands). + +Depois de executar os comandos anteriores, configurou uma rede Polygon Edge de 4 nós capaz de selar blocos e recuperar +da falha de um nó. + +:::info Inicie o cliente usando o ficheiro config + +Em vez de especificar todos os parâmetros de configuração como argumentos CLI, o cliente também pode ser iniciado usando um ficheiro config através da execução do seguinte comando: + +````bash +polygon-edge server --config +```` +Exemplo: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Atualmente, suportamos e com `json`base em ficheiros de configuração, os ficheiros de configuração `yaml`de amostra podem ser encontrados **[aqui](/docs/edge/configuration/sample-config)** + +::: + +:::info Etapas para executar um nó não-validador + +Um não-validador irá sempre sincronizar os últimos blocos recebidos do nó de validador; pode iniciar um nó não-validador executando o seguinte comando. + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +Por exemplo, pode adicionar o **quinto** cliente não-validador executando o seguinte comando: + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info Especifique o limite de preço + +Um nó Polygon Edge pode ser iniciado com um **limite de preço** definido para as transações de entrada. + +A unidade para o limite de preço é `wei`. + +A definição de um limite de preço significa que qualquer transação processada pelo nó atual terá de ter um preço do gás **superior** +ao limite de preço definido; caso contrário, não será incluído num bloco. + +O facto de obrigar a maioria dos nós a respeitar um determinado limite de preço impõe a regra de que as transações na rede +não podem estar abaixo de um determinado preço limite. + +O valor predefinido para o limite de preço é `0`, o que significa que não é de todo imposto por predefinição. + +Exemplo de uso do flag `--price-limit`: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Vale a pena notar que os limites de preço **são aplicados apenas em transações não locais**, ou seja, +que o limite de preço não se aplica a transações adicionadas localmente ao nó. + +::: + +:::info URL WebSocket + +Por predefinição, quando se executa o Polygon Edge, este gera um URL WebSocket baseado na localização da chain. +O esquema do URL `wss://` é usado para links HTTPS e o `ws://` para HTTP. + +URL Localhost WebSocket: +````bash +ws://localhost:10002/ws +```` +Note que o número da porta depende da porta JSON-RPC escolhida para o nó. + +URL de WebSocket Edgenet: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## Etapa 5: interaja com a rede polygon-edge {#step-5-interact-with-the-polygon-edge-network} + +Agora que configurou pelo menos um cliente em execução, pode interagir com o blockchain usando a conta que pré-minerou acima +e especificando o URL JSON-RPC para qualquer um dos 4 nós: +- Nó 1: `http://localhost:10002` +- Nó 2: `http://localhost:20002` +- Nó 3: `http://localhost:30002` +- Nó 4: `http://localhost:40002` + +Siga este guia para emitir comandos do operador para o cluster recém-construído: [como consultar informações do operador](/docs/edge/working-with-node/query-operator-info) (as portas GRPC para o cluster que construímos são `10000`/`20000`/`30000`/ `40000`para cada nó respetivamente) diff --git a/archive/edge/pt-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/pt-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..2bd2892283 --- /dev/null +++ b/archive/edge/pt-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,387 @@ +--- +id: set-up-ibft-on-the-cloud +title: Configuração da nuvem +description: "Guia passo-a-passo de configuração da nuvem." +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info Este guia destina-se a configurações mainnet ou testnet + +O guia abaixo indicará como configurar uma rede Polygon Edge num fornecedor de serviços na nuvem para a configuração de produção da sua testnet ou mainnet. + +Se pretende configurar uma rede Polygon Edge localmente para testar rapidamente o `polygon-edge` antes de fazer uma configuração tipo produção, consulte a página +**[Configuração Local](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## Requisitos {#requirements} + +Consultar [Instalação](/docs/edge/get-started/installation) para instalar o Polygon Edge. + +### Configurar a conectividade da VM {#setting-up-the-vm-connectivity} + +Dependendo do fornecedor de serviços na nuvem que escolher, pode configurar a conectividade e as regras entre VMs usando uma firewall, +grupos de segurança ou listas de controlo de acesso. + +Como a única parte do `polygon-edge` que precisa de ser exposta a outras VMs é o servidor libp2p, basta permitir +todas as comunicações entre VMs na porta `1478` padrão do libp2p. + +## Visão geral {#overview} + +![Configuração da nuvem](/img/edge/ibft-setup/cloud.svg) + +Neste guia, o nosso objetivo é estabelecer uma rede blockchain `polygon-edge` funcional trabalhando com o [protocolo de consenso IBFT](https://github.com/ethereum/EIPs/issues/650). +A rede blockchain consistirá em 4 nós, todos eles nós de validador e, como tal, elegíveis para propor blocos e validar blocos provenientes de outros proponentes. +Cada um dos 4 nós correrá sobre a sua própria VM, já que a ideia deste guia é dar-lhe uma rede Polygon Edge totalmente funcional, mantendo as chaves privadas de validador para garantir uma configuração de rede sem confiança. + +Para o conseguir, iremos guiá-lo ao longo de 4 etapas fáceis: + +0. Consulte a lista de **Requisitos** mais acima +1. Gere as chaves privadas para cada um dos validadores e inicialize o diretório de dados +2. Prepare o string de conexão para que o bootnode seja colocado no `genesis.json` partilhado +3. Crie o `genesis.json` na sua máquina local e envie-o/transfira-o para cada um dos nós +4. Inicie todos os nós + +:::info Número de validadores + +Não há um número mínimo de nós por cluster, o que significa que são possíveis clusters com apenas 1 nó de validador. +Lembre-se de que com um cluster de um _único_ nó **não existe tolerância às falhas** nem **garantia de BFT**. + +O número mínimo recomendado de nós para obter a garantia de BFT é 4 - já que num cluster de 4 nós pode ser tolerada +a falha de 1 nó, com os restantes 3 a funcionarem normalmente. + +::: + +## Etapa 1: inicializar as pastas de dados e gerar as chaves de validador {#step-1-initialize-data-folders-and-generate-validator-keys} + +Para colocar o Polygon Edge a funcionar, é necessário inicializar as pastas de dados, em cada nó: + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +Cada um destes comandos imprimirá a chave de validador, a chave pública BLS e a [ID do nó](https://docs.libp2p.io/concepts/peer-id/). Irá precisar da identificação do primeiro nó para a etapa seguinte. + +### Segredos de execução {#outputting-secrets} +A saída de segredos pode ser recuperada novamente, se necessário. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning Não divulgue o seu diretório de dados! + +Os diretórios de dados gerados acima, além de inicializarem os diretórios para reter o estado da blockchain, também geram as suas chaves privadas de validador. +**Esta chave deve ser mantida em segredo, já que o respetivo roubo poderia conceder a alguém a capacidade de se fazer passar por si como validador na rede!** + +::: + +## Etapa 2: preparar o string de conexão multiaddr para o bootnode {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Para estabelecer com sucesso a conectividade, um nó deve saber a que servidor `bootnode` se ligar para obter +informações sobre todos os nós restantes da rede. O `bootnode` é por vezes conhecido como servidor `rendezvous` na gíria p2p. + +O `bootnode` não é uma instância especial de um nó do Polygon Edge. Cada nó do Polygon Edge pode servir de `bootnode` e +cada nó do Polygon Edge precisa de ter um conjunto de bootnodes especificados, que serão contactados para fornecerem informações sobre como se conectar +com todos os restantes nós da rede. + +Para criar um string de conexão para especificar o bootnode, temos de seguir +o [formato multiaddr](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +Neste guia trataremos o primeiro e segundo nós como bootnodes para todos os outros nós. O que acontece neste cenário +é que os nós que se conectam ao `node 1` ou `node 2` irão obter informações sobre como se conectar entre si através de um +bootnode mutuamente contactado. + +:::info É necessário especificar pelo menos um bootnode para iniciar um nó + +É necessário pelo menos **um** bootnode para que outros nós da rede possam encontrar-se. São recomendados mais bootnodes, pois +eles oferecem resiliência à rede em caso de interrupção. +Neste guia listaremos dois nós, mas isto pode ser alterado rapidamente, sem qualquer impacto na validade do ficheiro `genesis.json`. + +::: + +Como a primeira parte do string de conexão multiaddr é o ``, aqui terá de inserir o endereço IP conforme acessível por outros nós; dependendo da sua configuração, este poderá ser um endereço IP privado ou público, não `127.0.0.1`. + +Para a `` usaremos `1478`, já que é a porta predefinida do libp2p. + +Por fim, precisamos da ``, que podemos obter da saída do comando `polygon-edge secrets init --data-dir data-dir` previamente executado (que foi usado para gerar chaves e diretórios de dados para o `node 1`) + +Depois da compilação, o string de conexão multiaddr para o `node 1` que usaremos como bootnode terá o seguinte aspeto (só a ``, que se encontra no final, deverá ser diferente): +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Da mesma forma, construímos o multiaddr para o segundo bootnode como abaixo +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info Hostnames DNS em vez de ips + +O Polygon Edge suporta o uso de hostnames DNS para a configuração dos nós. Este é um recurso muito útil para implantações baseadas na nuvem, já que o ip do nó pode mudar por vários motivos. + +O formato multiaddr para o string de conexão ao usar os hostnames DNS é o seguinte: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## Etapa 3: gerar o ficheiro de génese com os 4 nós como validadores {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +Esta etapa pode ser executada na sua máquina local, mas precisará das chaves públicas de validador para cada um dos 4 validadores. + +Os validadores podem partilhar com segurança o `Public key (address)`, como mostrado abaixo, na saída dos seus comandos `secrets init`, para que +possa gerar com segurança o genesis.json com esses validadores no conjunto inicial de validadores, identificados através das chaves públicas: + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +Dado que recebeu as 4 chaves públicas dos validadores, pode executar o seguinte comando para gerar o `genesis.json` + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +O que faz este comando: + +* O `--ibft-validator` define a chave pública do validador que deve ser incluído no conjunto inicial de validadores do bloco de génese. Podem existir muitos validadores iniciais. +* O `--bootnode` define o endereço do bootnode que irá permitir que os nós se encontrem. +Usaremos o string multiaddr do `node 1`, como mencionado na **etapa 2**, embora possa adicionar o número de bootnodes que quiser, como mostrado acima. + +:::info Mudar para ECDSA + +BLS é o modo de validação padrão dos cabeçalhos de blocos. Se desejar que a sua chain seja executada no modo ECDSA, pode usar o `—ibft-validator-type`sinalizador , com o argumento `ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info Pré-mineração de saldos de conta + +Provavelmente quererá configurar a sua rede blockchain com alguns endereços que têm saldos "pré-minerados". + +Para o conseguir, passe tantos flags `--premine` quantos quiser por endereço que pretende que seja inicializado com um determinado saldo +na blockchain. + +Por exemplo, se quisermos pré-minerar 1000 ETH para o endereço `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` do nosso bloco de génese, então precisaremos de fornecer o seguinte argumento: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Note que o valor pré-minerado está em WEI, não ETH.** + +::: + +:::info Defina o limite de gás do bloco + +O limite de gás predefinido para cada bloco é `5242880`. Este valor é escrito no ficheiro génese, mas poderá querer +aumentá-lo/diminui-lo. + +Para o fazer, pode usar o flag `--block-gas-limit`, seguido do valor pretendido, como se mostra abaixo: + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Defina o limite do descritor do ficheiro de sistema + +O limite de descritores de ficheiros padrão (número máximo de ficheiros abertos) pode ser baixo e, no Linux, tudo é um ficheiro. Se os nós forem esperados ter alta taxa de transferência, poderá considerar aumentar este limite. Verifique os documentos oficiais da sua distribuição do linux para mais detalhes. + +#### Verifique os limites atuais do sistema operativo (ficheiros abertos) {#check-current-os-limits-open-files} +```shell title="ulimit -n" +1024 # Ubuntu default +``` + +#### Aumente o limite de ficheiros abertos {#increase-open-files-limit} +- Executar `polygon-edge`em primeiro plano (shell) + ```shell title="Set FD limit for the current session" + ulimit -n 65535 # affects only current session, limit won't persist after logging out + ``` + + ```shell title="Edit /etc/security/limits.conf" + # add the following lines to the end of the file to modify FD limits + * soft nofile 65535 # sets FD soft limit for all users + * hard nofile 65535 # sets FD hard limit for all users + + # End of file + ``` +Salve o ficheiro e reinicie o sistema. + +- Executar `polygon-edge`em segundo plano como serviço + +Se for `polygon-edge`executado como serviço de sistema, usando a ferramenta como , limites do descritor de `systemd`arquivos deve ser gerenciado usando `systemd`. + ```shell title="Edit /etc/systemd/system/polygon-edge.service" + [Service] + ... + LimitNOFILE=65535 + ``` + +### Solução de problemas {#troubleshooting} +```shell title="Watch FD limits of polygon edge running process" +watch -n 1 "ls /proc/$(pidof polygon-edge)/fd | wc -l" +``` + +```shell title="Check max FD limits for polygon-edge running process" +cat /proc/$(pidof polygon-edge)/limits +``` +::: + +Depois de especificar: +1. As chaves públicas dos validadores a serem incluídas no bloco de génese como conjunto de validadores +2. Os strings de conexão multiaddr do bootnode +3. As contas e saldos pré-minerados a serem incluídos no bloco de génese + +e de gerar o `genesis.json`, deve copiá-lo para todas as VMs da rede. Dependendo da sua configuração, pode +copiá-lo/colá-lo, enviá-lo para o operador de nós ou simplesmente colocá-lo no SCP/FTP. + +A estrutura do ficheiro de génese é abordada na secção [Comandos CLI](/docs/edge/get-started/cli-commands). + +## Etapa 4: executar todos os clientes {#step-4-run-all-the-clients} + +:::note Networking nos fornecedores de serviços na nuvem + +A maioria dos fornecedores de serviços na nuvem não expõe os endereços IP (especialmente, os de domínio público) como interface de rede direta na sua VM, mas configuram um proxy NAT invisível. + + +Para permitir que os nós se conectem entre si, neste caso, precisaria de ouvir o endereço IP `0.0.0.0` para se ligar a todas as interfaces; ainda assim, precisaria de especificar o endereço IP ou endereço DNS que os outros nós podem usar para se conectarem à sua instância. Isto é conseguido usando o argumento `--nat` ou `--dns`, onde pode especificar o seu endereço IP ou DNS externo, respetivamente. + +#### Exemplo {#example} + +O endereço IP associado que pretende escutar é `192.0.2.1`, mas não está diretamente ligado a nenhuma das interfaces da sua rede. + +Para permitir que os nós se conectem, teria de passar os seguintes parâmetros: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +Ou, se pretende especificar um endereço DNS `dns/example.io`, passe os seguintes parâmetros: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +Isto faria com que o seu nó escutasse todas as interfaces, mas também se apercebesse de que os clientes se ligam a ele através do endereço `--nat` ou `--dns` especificado. + +::: + +Para executar o **primeiro** cliente: + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Para executar o **segundo** cliente: + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Para executar o **terceiro** cliente: + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Para executar o **quarto** cliente: + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Depois de executar os comandos anteriores, configurou uma rede Polygon Edge de 4 nós capaz de selar blocos e recuperar +da falha de um nó. + +:::info Inicie o cliente usando o ficheiro config + +Em vez de especificar todos os parâmetros de configuração como argumentos CLI, o cliente também pode ser iniciado usando um ficheiro config através da execução do seguinte comando: + +````bash +polygon-edge server --config +```` +Exemplo: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Atualmente, apenas oferecemos suporte ao arquivo de configuração com `json`base, o ficheiro de configuração de amostra pode ser encontrado **[aqui](/docs/edge/configuration/sample-config)** + +::: + +:::info Etapas para executar um nó não-validador + +Um não-validador irá sempre sincronizar os últimos blocos recebidos do nó de validador; pode iniciar um nó não-validador executando o seguinte comando. + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +Por exemplo, pode adicionar o **quinto** cliente não-validador executando o seguinte comando: + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info Especifique o limite de preço + +Um nó Polygon Edge pode ser iniciado com um **limite de preço** definido para as transações de entrada. + +A unidade para o limite de preço é `wei`. + +A definição de um limite de preço significa que qualquer transação processada pelo nó atual terá de ter um preço do gás **superior** +ao limite de preço definido; caso contrário, não será incluído num bloco. + +O facto de obrigar a maioria dos nós a respeitar um determinado limite de preço impõe a regra de que as transações na rede +não podem estar abaixo de um determinado preço limite. + +O valor predefinido para o limite de preço é `0`, o que significa que não é de todo imposto por predefinição. + +Exemplo de uso do flag `--price-limit`: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Vale a pena notar que os limites de preço **são aplicados apenas em transações não locais**, ou seja, +que o limite de preço não se aplica a transações adicionadas localmente ao nó. + +::: + +:::info URL WebSocket + +Por predefinição, quando se executa o Polygon Edge, este gera um URL WebSocket baseado na localização da chain. +O esquema do URL `wss://` é usado para links HTTPS e o `ws://` para HTTP. + +URL Localhost WebSocket: +````bash +ws://localhost:10002/ws +```` +Note que o número da porta depende da porta JSON-RPC escolhida para o nó. + +URL Edgenet WebSocket: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/pt-edge/get-started/terraform-aws-deployment.md b/archive/edge/pt-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..890196908c --- /dev/null +++ b/archive/edge/pt-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,177 @@ +--- +id: terraform-aws-deployment +title: Implantação do Terraform na AWS +description: "Implante a rede Polygon Edge no fornecedor de serviços na nuvem AWS utilizando o Terraform" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info Guia de implantação de produção + +Este é o guia de implantação na AWS oficial, pronto para produção e totalmente automatizado. + +A implantação manual na ***[Nuvem](set-up-ibft-on-the-cloud)*** ou ***[Local](set-up-ibft-locally)*** +é recomendada para testes e/ou se o seu fornecedor de serviços na nuvem não for a AWS. + +::: + +:::info + +Esta implantação destina-se apenas a PoA. +Se necessitar do mecanismo PoS, basta seguir este ***[guia](/docs/edge/consensus/migration-to-pos)*** para mudar de PoA para PoS. + +::: + +Este guia descreverá, em detalhe, o processo de implantação de uma rede blockchain Polygon Edge no fornecedor de serviços na nuvem AWS, +que está pronto para produção, uma vez que os nós de validadores estão espalhados por múltiplas zonas de disponibilidade. + +## Pré-requisitos {#prerequisites} + +### Ferramentas do sistema {#system-tools} +* [terraform](https://www.terraform.io/) +* [cli aws](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [ID da chave de acesso e chave de acesso secreto aws](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Variáveis Terraform {#terraform-variables} +Duas variáveis que devem ser fornecidas, antes de executar a implantação: + +* `alb_ssl_certificate` - ARN do certificado do AWS Certificate Manager a ser usado pelo ALB para o protocolo https. + O certificado deve ser gerado antes de iniciar a implantação e tem de estar no estado **Issued** +* `premine` - conta que receberá a moeda nativa previamente minerada. +O valor deve seguir a especificação oficial do flag [CLI](/docs/edge/get-started/cli-commands#genesis-flags) + +## informações sobre implantação {#deployment-information} +### Recursos implantados {#deployed-resources} +Visão geral de alto nível dos recursos que serão implantados: + +* VPC dedicado +* 4 nós de validadores (que também são bootnodes) +* 4 gateways NAT para permitir o tráfego da internet de saída dos nós +* função Lambda usada para gerar o primeiro bloco (génese) e iniciar a chain +* Grupos de segurança dedicados e funções IAM +* Bucket S3 usado para armazenar o ficheiro genesis.json +* Application Load Balancer usado para expor o endpoint JSON-RPC + +### Tolerância à falha {#fault-tolerance} + +Para esta implantação são necessárias apenas regiões que tenham 4 zonas de disponibilidade. Cada nó é implantado numa única AZ. + +Ao colocar cada nó numa única AZ, todo o cluster da blockchain se torna tolerante a falhas de um único nó (AZ), uma vez que o Polygon Edge implementa o +consenso IBFT, que permite que um único nó falhe num cluster de 4 nós de validador. + +### Acesso às linhas de comandos {#command-line-access} + +Os nós de validador não são expostos de forma alguma à internet pública (o JSON-PRC é acedido apenas via ALB) +e nem sequer têm endereços IP públicos ligados a si. +O acesso às linhas de comandos dos nós só é possível através do [Gestor do Sistema AWS - Gestor de Sessões](https://aws.amazon.com/systems-manager/features/). + +### Atualização do AMI base {#base-ami-upgrade} + +Esta implantação usa o `ubuntu-focal-20.04-amd64-server` AWS AMI. **Não** desencadeará o *redeployment* do EC2 se o AWS AMI for atualizado. + +Se, por algum motivo, o AMI base tiver de ser atualizado, +o mesmo pode ser alcançado executando o comando `terraform taint` para cada instância, antes de `terraform apply`. +As instâncias podem ser "tainted" executando o comando +`terraform taint module.instances[].aws_instance.polygon_edge_instance` + +Exemplo: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info + +Num ambiente de produção, `terraform taint` deve ser executado um a um para manter a rede blockchain funcional. + +::: + +## Procedimento de implantação {#deployment-procedure} + +### Passos pré-implantação {#pre-deployment-steps} +* leia na íntegra o readme do registo terraform [polygon-technology-edge](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) +* adicione o módulo `polygon-technology-edge` ao seu ficheiro `main.tf` usando as *provision instructions* da página readme dos módulos +* execute o comando `terraform init` para instalar todas as dependências Terraform necessárias +* forneça um novo certificado no [AWS Certificate Manager](https://aws.amazon.com/certificate-manager/) +* certifique-se de que o certificado fornecido está no estado **Issued** e anote o **ARN** do certificado +* configure a sua declaração de saída para obter a saída dos módulos na cli + +#### `main.tf` exemplo {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### `terraform.tfvars` exemplo {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### Etapas de implantação {#deployment-steps} +* crie o ficheiro `terraform.tfvars` +* defina as variáveis terraform necessárias neste ficheiro (como explicado acima). +:::info + +Existem outras variáveis não obrigatórias que podem personalizar totalmente esta implantação. +Pode substituir os valores padrão adicionando os seus próprios ao ficheiro `terraform.tfvars`. + + A especificação de todas as variáveis disponíveis pode ser encontrada no ***[registo](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)** Terraform dos módulos* + +::: +* certifique-se de que configurou corretamente uma autenticação de cli aws executando `aws s3 ls` - não devem ocorrer erros +* implante a infraestrutura `terraform apply` + +### Passos pós-implantação {#post-deployment-steps} +* assim que a implantação estiver concluída, observe o valor da variável `json_rpc_dns_name` impresso na cli +* crie um registo dns cname público apontando o nome do seu domínio para o valor `json_rpc_dns_name` fornecido. Por exemplo: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* assim que o registo cname se propagar, verifique se a chain está a funcionar corretamente chamando o seu endpoint JSON-PRC. + Do exemplo acima: + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## Procedimento de destruição {#destroy-procedure} +:::warning + +O procedimento seguinte eliminará permanentemente toda a infraestrutura implantada com estes scripts terraform. +Certifique-se de que tem [backups dos dados da blockchain](docs/edge/working-with-node/backup-restore) adequados e/ou está a trabalhar com um ambiente de teste. + +::: + +Se precisar de remover toda a infraestrutura, execute o seguinte comando `terraform destroy`. +Além disso, precisará de remover manualmente os segredos armazenados na AWS [Parameter Store](https://aws.amazon.com/systems-manager/features/) +para a região onde decorreu a implantação. diff --git a/archive/edge/pt-edge/overview.md b/archive/edge/pt-edge/overview.md new file mode 100644 index 0000000000..9325acef28 --- /dev/null +++ b/archive/edge/pt-edge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Polygon Edge +sidebar_label: What is Edge +description: "Uma introdução ao Polygon Edge." +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +O Polygon Edge é uma estrutura modular e extensível para construir redes blockchain compatíveis com a Ethereum, sidechains e soluções de escalonamento geral. + +A sua principal utilização é a de alavancar uma nova rede blockchain ao mesmo tempo que oferece a compatibilidade total com os contratos inteligentes e transações da Ethereum. Utiliza o mecanismo de consenso IBFT (Istanbul Byzantine Fault Tolerant), suportado por dois "sabores" como [PoA (proof of authority)](/docs/edge/consensus/poa) e [PoS (proof of stake)](/docs/edge/consensus/pos-stake-unstake). + +O Polygon Edge também suporta a comunicação com múltiplas redes blockchain, permitindo transferências de tokens [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) e [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) através da utilização da [solução de bridge centralizada](/docs/edge/additional-features/chainbridge/overview). + +As carteiras padrão da indústria podem ser usadas para interagir com o Polygon Edge através dos endpoints [JSON-RPC](/docs/edge/working-with-node/query-json-rpc) e os operadores de nós podem realizar várias ações nos nós através do protocolo [gRPC](/docs/edge/working-with-node/query-operator-info). + +Para saber mais sobre o Polygon, visite o [website oficial](https://polygon.technology). + +**[Repositório GitHub](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +Trata-se de um trabalho em curso, pelo que se podem verificar mudanças arquitetónicas no futuro. O código ainda não foi auditado, +pelo que deve contactar a equipa do Polygon se pretende usá-lo para produção. + +::: + + + +Para começar com a execução de uma rede `polygon-edge` localmente, leia: [Instalação](/docs/edge/get-started/installation) e [Configuração Local](/docs/edge/get-started/set-up-ibft-locally). diff --git a/archive/edge/pt-edge/performance-reports/overview.md b/archive/edge/pt-edge/performance-reports/overview.md new file mode 100644 index 0000000000..f06292bc9b --- /dev/null +++ b/archive/edge/pt-edge/performance-reports/overview.md @@ -0,0 +1,32 @@ +--- +id: overview +title: Visão geral +description: "Introdução aos testes com o Polygon Edge." +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +Observe que o nosso , `loadbot`que foi usado para realizar estes testes, está agora desvalorizado. +::: + +| Tipo | Valor | Link para o teste | +| ---- | ----- | ------------ | +| Transferências regulares | 1428 tps | [4 de julho de 2022](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| Transferências ERC-20 | 1111 tps | [4 de julho de 2022](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| Minerar NFT | 714 tps | [4 de julho de 2022](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +O nosso objetivo é fazer um software de cliente blockchain de alto desempenho, rico em recursos e fácil de configurar e manter. +Todos os testes foram feitos usando o Polygon Edge Loadbot. +Cada relatório de desempenho que encontrará nesta secção está devidamente datado, o ambiente está claramente descrito e o método de teste claramente explicado. + +O objetivo destes testes de desempenho consiste em mostrar o desempenho prático real da rede blockchain Polygon Edge. +Qualquer pessoa deve ser capaz de obter os mesmos resultados que foram publicados aqui, no mesmo ambiente, usando o nosso loadbot. + +Todos os testes de desempenho foram realizados na plataforma AWS, numa chain que consiste em nós de instância EC2. \ No newline at end of file diff --git a/archive/edge/pt-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/pt-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..2833a5c8c9 --- /dev/null +++ b/archive/edge/pt-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,132 @@ +--- +id: test-2022-01-21 +title: 21 de janeiro de 2022 +description: "Teste de desempenho a partir de 21 de janeiro." +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## 21 de janeiro de 2022 {#january-21st-2022} + +### Resumo {#summary} + +:::caution +Observe que o nosso , `loadbot`que foi usado para realizar estes testes, está agora desvalorizado. +::: + +Este teste foi realizado após a refatorização do TxPool que melhorou consideravelmente o desempenho (lançado em [v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0)). + +O objetivo era configurar uma rede grande que consiste em 30 validadores que participam ativamente para realizar devidamente o teste de estresse do +consenso e de transações de TxPool visto que todas as transações foram enviadas para o JSON-RPC de nó único. + +Nosso objetivo não era tentar atingir o maior TPS possível, pois o tamanho da rede afeta negativamente o desempenho, +e como o limiar do gás dos blocos e do tempo dos blocos são definidos em valores razoáveis que não consomem muitos recursos do sistema e permitiriam que ele executasse em hardware de fácil acesso. + +### Resultados {#results} + +| Métrica | Valor | +| ------ | ----- | +| Transações por segundo | 344 | +| Falha nas transações | 0 | +| Transações bem-sucedidas | 10000 | +| Tempo de execução total | 30 s | + +### Ambiente {#environment} + +
+ Configuração do host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornecedor de serviços na nuvemAWS
Tamanho da instânciat2.xlarge
Networkingsubnet privada
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Limite do descritor do ficheiro65535
Máx. de processos do utilizador65535
+
+
+
+
+ +
+ Configuração da blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Versão do Polygon EdgeCommit de 8377162281d1a2e4342ae27cd4e5367c4364aee2 no branch de desenvolvimento
Nós validadores30
Nós não validadores0
ConsensoIBFT PoA
Tempo do bloco2000 ms
Limite de gás do bloco5242880
+
+
+
+
+ +
+ Configuração do Loadbot +
+
+ + + + + + + + + + + + + +
Total de transações10000
Transações enviadas por segundo400
Tipo de transaçõesTransferências de EOA para EOA
+
+
+
+
diff --git a/archive/edge/pt-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/pt-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..1e65f13570 --- /dev/null +++ b/archive/edge/pt-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,390 @@ +--- +id: test-2022-03-02 +title: 2 de março de 2022 +description: "Teste de desempenho de 2 de março." +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### Resumo {#summary} + +:::caution +Observe que o nosso , `loadbot`que foi usado para realizar estes testes, está agora desvalorizado. +::: + +Este teste foi realizado para medir as transferências de tokens ERC-20 de SC e funcionalidade de cunhagem de token ERC721 SC com cargas pesadas e velocidade das transações. + +O objetivo era verificar se tudo estava a funcionar conforme esperado durante cargas pesadas. Essa foi também a razão pela qual introduzimos as métricas de gás na saída do loadbot, que nos mostram se os blocos são devidamente preenchidos com transações. + +Todas as transações foram enviadas para o único nó via API GRPC e os recibos foram recebidos por meio da API JSON-RPC. Depois de terem sido efetuadas todas as transações, as informações de cada bloco sobre gás foram lidas recorrendo ao método JSON-RPC eth_getBlockByNumber. + +Nosso objetivo não era se alcançar um TPS máximo possível, +uma vez que o limiar do gás dos blocos e do tempo dos blocos são definidos em valores razoáveis que não consomem muitos recursos do sistema e permitiriam que ele executasse em hardware de fácil acesso. + +### Resultados ERC-20 {#results-erc20} + +| Métrica | Valor | +| ------ | ----- | +| Tipo de transação | ERC-20 | +| Transações por segundo | 65 | +| Falha nas transações | 0 | +| Transações bem-sucedidas | 5000 | +| Tempo de execução das transações ERC-20 | 76.681690s | +| Tempo de implantação SC | 4.048250s | + +### Resultados ERC-721 {#results-erc721} + +| Métrica | Valor | +| ------ | ----- | +| Tipo de transação | ERC-721 | +| Transações por segundo | 20 | +| Falha nas transações | 0 | +| Transações bem-sucedidas | 2000 | +| Tempo de execução das transações ERC-721 | 97.239920s | +| Tempo de implantação SC | 3.048970s | + +### Ambiente ERC-20 {#environment-erc20} + +
+ Configuração do host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornecedor de serviços na nuvemAWS
Tamanho da instânciat2.micro
Networkingsubnet privada
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Limite do descritor do ficheiro65535
Máx. de processos do utilizador65535
+
+
+
+
+ +
+ Configuração da blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versão do Polygon EdgeCommit 8a033aa1afb191abdac04636d318f83f32511f3c no branch de desenvolvimento
Nós validadores6
Nós não-validadores0
ConsensoIBFT PoA
Tempo do bloco2s
Limite de gás do bloco5242880
Utilização média do bloco95%
+
+
+
+
+ +
+ Configuração do Loadbot +
+
+ + + + + + + + + + + + + +
Total de transações5000
Transações enviadas por segundo200
Tipo de transaçõesTransferências ERC-20 para ERC-20
+
+
+
+
+ +
+ Log do Loadbot + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### Ambiente ERC-721 {#environment-erc721} + +
+ Configuração do host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornecedor de serviços na nuvemAWS
Tamanho da instânciat2.micro
Networkingsubnet privada
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Limite do descritor do ficheiro65535
Máx. de processos do utilizador65535
+
+
+
+
+ +
+ Configuração da blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versão do Polygon EdgeCommit 8a033aa1afb191abdac04636d318f83f32511f3c no branch de desenvolvimento
Nós validadores6
Nós não-validadores0
ConsensoIBFT PoA
Tempo do bloco2s
Limite de gás do bloco5242880
Utilização média do bloco94%
+
+
+
+
+ +
+ Configuração do Loadbot +
+
+ + + + + + + + + + + + + +
Total de transações2000
Transações enviadas por segundo200
Tipo de transaçõesCunhagem de tokens ERC-721
+
+
+
+
+ +
+ Log do Loadbot + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/pt-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/pt-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..0c2232e71b --- /dev/null +++ b/archive/edge/pt-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,960 @@ +--- +id: test-2022-03-23 +title: 23 de março de 2022 +description: "Teste de desempenho de 23 de março." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### Resumo {#summary} + +:::caution +Observe que o nosso , `loadbot`que foi usado para realizar estes testes, está agora desvalorizado. +::: + +Este teste foi realizado para medir as transferências de tokens SC ERC-20, a mineração de tokens SC ERC-721 e a funcionalidade de transações EOA para EOA com cargas pesadas e velocidade das transações nos nós com recursos de hardware superiores. + +O objetivo era verificar se tudo está a funcionar conforme esperado durante cargas pesadas. Essa foi também a razão pela qual introduzimos as métricas de gás na saída do loadbot, que nos mostram se os blocos são devidamente preenchidos com transações. + +Todas as transações foram enviadas para o único nó via API GRPC e os recibos foram recebidos por meio da API JSON-RPC. Depois de terem sido efetuadas todas as transações, as informações de cada bloco sobre gás foram lidas recorrendo ao método JSON-RPC eth_getBlockByNumber. + +O nosso objetivo era conseguir alcançar um TPS máximo possível nos recursos de hardware disponíveis. +Para o conseguir, modificámos o limite de gás do bloco e os parâmetros de tempo do bloco, para nos dar os melhores resultados tps possíveis e manter a integridade e estabilidade do sistema. + +:::info Limite de gás de bloco + +O limite de gás de bloco pode ser aumentado para um número relativamente maior se as transações estiverem usando muito gás para executar. +No exemplo abaixo, a mineração de token ERC-721 funcionou muito mais rapidamente com limite de gás de bloco definido para 80 000 000 (em vez de 20 milhões), mas com transferências de token ERC20 com limite de gás de bloco de 80 milhões, o servidor apresentou falha. + +::: + +:::info Ambientes de produção + +Ao configurar um ambiente de produção, é necessário ter cuidado se estiver a tentar alcançar o elevado desempenho da chain. +Se o parâmetro do limite de gás do bloco estiver definido como 1s e houver uma elevada carga de transações num único nó, este irá consumir muita RAM (se não toda a que estiver disponível) e pode crashar o servidor. +Use o loadbot para testar tudo ao pormenor, monitorizar a utilização de recursos do sistema e definir devidamente os seus parâmetros de configuração. + +::: + +:::info Erros de memória esgotada + +Alguns distros do Linux vão automaticamente destruir o processo que tem um uso de RAM muito elevado (erro de OOM), para preservar a estabilidade do sistema. +A saída de registo deste erro de esgotamento de memória parece com o exibido abaixo. +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### Resultados das transferências EOA para EOA {#results-of-eoa-to-eoa-transfers} +| Métrica | Valor | +| ------ | ----- | +| Tipo de transação | EOA para EOA | +| Transações por segundo | 689 | +| Falha nas transações | 0 | +| Transações bem-sucedidas | 20000 | +| Total de blocos usados | 25 | +| Tempo de execução total | 29.921110s | + +### Resultados das transferências de tokens ERC-20 {#results-of-erc20-token-transfers} + +| Métrica | Valor | +| ------ | ----- | +| Tipo de transação | ERC-20 | +| Transações por segundo | 500 | +| Falha nas transações | 0 | +| Transações bem-sucedidas | 20000 | +| Total de blocos usados | 33 | +| Tempo de execução das transações ERC-20 | 40.402900s | +| Tempo de implantação SC | 2.004140s | + +### Resultados da mineração de tokens ERC-721 {#results-of-erc721-token-minting} + +| Métrica | Valor | +| ------ | ----- | +| Tipo de transação | ERC-721 | +| Transações por segundo | 157 | +| Falha nas transações | 0 | +| Transações bem-sucedidas | 20000 | +| Total de blocos usados | 124 | +| Tempo de execução das transações ERC-721 | 127.537340s | +| Tempo de implantação SC | 2.004420s | + + +### Resultados da cunhagem do token ERC-721 com um limite de gás de bloco muito elevado (80 milhões) {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| Métrica | Valor | +| ------ | ----- | +| Tipo de transação | ERC-721 | +| Transações por segundo | 487 | +| Falha nas transações | 0 | +| Transações bem-sucedidas | 20000 | +| Total de blocos usados | 34 | +| Tempo de execução das transações ERC-721 | 41.098410s | +| Tempo de implantação SC | 2.004300s | + + +### Ambiente EOA para EOA {#environment-eoa-to-eoa} +
+ Configuração do host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornecedor de serviços na nuvemAWS
Tamanho da instânciac5.2xlarge
Networkingsubnet privada
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite do descritor do ficheiro65535
Máx. de processos do utilizador65535
+
+
+
+
+ +
+ Configuração da blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versão do Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 no branch de desenvolvimento
Nós validadores4
Nós não-validadores0
ConsensoIBFT PoA
Tempo do bloco1s
Limite de gás do bloco20000000
Máx. de slots1000000
Utilização média do bloco84,00%
+
+
+
+
+ +
+ Configuração do Loadbot +
+
+ + + + + + + + + + + + + +
Total de transações20000
Transações enviadas por segundo689
Tipo de transaçõesTransferências EOA para EOA
+
+
+
+
+ +
+ Log do Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### Ambiente ERC-20 {#environment-erc20} +
+ Configuração do host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornecedor de serviços na nuvemAWS
Tamanho da instânciac5.2xlarge
Networkingsubnet privada
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite do descritor do ficheiro65535
Máx. de processos do utilizador65535
+
+
+
+
+ +
+ Configuração da blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versão do Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 no branch de desenvolvimento
Nós validadores4
Nós não-validadores0
ConsensoIBFT PoA
Tempo do bloco1s
Limite de gás do bloco20000000
Máx. de slots1000000
Utilização média do bloco88,38%
+
+
+
+
+ +
+ Configuração do Loadbot +
+
+ + + + + + + + + + + + + +
Total de transações20000
Transações enviadas por segundo500
Tipo de transaçõesTransferências ERC-20 para ERC-20
+
+
+
+
+ +
+ Log do Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### Ambiente ERC-721 {#environment-erc721} +
+ Configuração do host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornecedor de serviços na nuvemAWS
Tamanho da instânciac5.2xlarge
Networkingsubnet privada
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite do descritor do ficheiro65535
Máx. de processos do utilizador65535
+
+
+
+
+ +
+ Configuração da blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versão do Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 no branch de desenvolvimento
Nós validadores4
Nós não-validadores0
ConsensoIBFT PoA
Tempo do bloco1s
Limite de gás do bloco20000000
Máx. de slots1000000
Utilização média do bloco92,90%
+
+
+
+
+ +
+ Configuração do Loadbot +
+
+ + + + + + + + + + + + + +
Total de transações20000
Transações enviadas por segundo157
Tipo de transaçõesCunhagem de tokens ERC-721
+
+
+
+
+ +
+ Log do Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### ERC-20 do ambiente - limite de gás de bloco muito elevado {#environment-erc20-very-high-block-gas-limit} +
+ Configuração do host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornecedor de serviços na nuvemAWS
Tamanho da instânciac5.2xlarge
Networkingsubnet privada
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite do descritor do ficheiro65535
Máx. de processos do utilizador65535
+
+
+
+
+ +
+ Configuração da blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versão do Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 no branch de desenvolvimento
Nós validadores4
Nós não-validadores0
ConsensoIBFT PoA
Tempo do bloco1s
Limite de gás do bloco80000000
Máx. de slots1000000
Utilização média do bloco---
+
+
+
+
+ +
+ Configuração do Loadbot +
+
+ + + + + + + + + + + + + +
Total de transações20000
Transações enviadas por segundo---
Tipo de transaçõesTransferências ERC-20 para ERC-20
+
+
+
+
+ +
+ Registo de erros de esgotamento de memória + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### ERC-721 do ambiente - limite de gás de bloco muito elevado {#environment-erc721-very-high-block-gas-limit} +
+ Configuração do host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornecedor de serviços na nuvemAWS
Tamanho da instânciac5.2xlarge
Networkingsubnet privada
Sistema operativoAmazon Linux 2 AMI (HVM) - Kernel 5.10
Limite do descritor do ficheiro65535
Máx. de processos do utilizador65535
+
+
+
+
+ +
+ Configuração da blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versão do Polygon EdgeCommit 06e11eac8da98c79c938fc53dda2da3318cfbe04 no branch de desenvolvimento
Nós validadores4
Nós não-validadores0
ConsensoIBFT PoA
Tempo do bloco1s
Limite de gás do bloco80000000
Máx. de slots1000000
Utilização média do bloco84,68%
+
+
+
+
+ +
+ Configuração do Loadbot +
+
+ + + + + + + + + + + + + +
Total de transações20000
Transações enviadas por segundo487
Tipo de transaçõesCunhagem de tokens ERC-721
+
+
+
+
+ +
+ Log do Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/pt-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/pt-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..c4d167d5cb --- /dev/null +++ b/archive/edge/pt-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,568 @@ +--- +id: test-2022-07-04 +title: 4 de julho de 2022 +description: "Teste de desempenho de 4 de julho." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### Resumo {#summary} + +:::caution +Observe que o nosso , `loadbot`que foi usado para realizar estes testes, está agora desvalorizado. +::: + +Este teste foi realizado para medir as transferências de tokens SC ERC-20, a mineração de tokens SC ERC-721 e a funcionalidade de transações EOA para EOA com cargas pesadas e velocidade das transações nos nós com recursos de hardware superiores. + +O objetivo era verificar se tudo está a funcionar conforme esperado durante cargas pesadas. Essa foi também a razão pela qual introduzimos as métricas de gás na saída do loadbot, que nos mostram se os blocos são devidamente preenchidos com transações. + +Todas as transações foram enviadas para o único nó via API GRPC e os recibos foram recebidos por meio da API JSON-RPC. Depois de terem sido efetuadas todas as transações, as informações de cada bloco sobre gás foram lidas recorrendo ao método JSON-RPC eth_getBlockByNumber. + +O nosso objetivo era conseguir alcançar um TPS máximo possível nos recursos de hardware disponíveis. +Para o conseguir, modificámos o limite de gás do bloco e os parâmetros de tempo do bloco, para nos dar os melhores resultados tps possíveis e manter a integridade e estabilidade do sistema. + + +:::info Ambientes de produção + +Ao configurar um ambiente de produção, é necessário ter cuidado se estiver a tentar alcançar o elevado desempenho da chain. +Se o parâmetro do limite de gás do bloco estiver definido como 1s e houver uma elevada carga de transações num único nó, este irá consumir muita RAM (se não toda a que estiver disponível) e pode crashar o servidor. +Use o loadbot para testar tudo ao pormenor, monitorizar a utilização de recursos do sistema e definir devidamente os seus parâmetros de configuração. + +::: + + + +### Resultados das transferências EOA para EOA {#results-of-eoa-to-eoa-transfers} +| Métrica | Valor | +| ------ | ----- | +| Tipo de transação | EOA para EOA | +| Transações por segundo | 1428 | +| Transações falhadas | 0 | +| Transações bem-sucedidas | 30000 | +| Total de blocos usados | 15 | +| Tempo de execução total | 21,374620s | + +### Resultados das transferências de tokens ERC-20 {#results-of-erc20-token-transfers} + +| Métrica | Valor | +| ------ | ----- | +| Tipo de transação | ERC-20 | +| Transações por segundo | 1111 | +| Transações falhadas | 0 | +| Transações bem-sucedidas | 50000 | +| Total de blocos usados | 38 | +| Tempo de execução das transações ERC-20 | 45,906450s | +| Tempo de implantação SC | 2,006580s | + +### Resultados da mineração de tokens ERC-721 {#results-of-erc721-token-minting} + +| Métrica | Valor | +| ------ | ----- | +| Tipo de transação | ERC-721 | +| Transações por segundo | 714 | +| Transações falhadas | 0 | +| Transações bem-sucedidas | 30000 | +| Total de blocos usados | 39 | +| Tempo de execução das transações ERC-721 | 42,864140s | +| Tempo de implantação SC | 2,005500s | + + + + +### Ambiente EOA para EOA {#environment-eoa-to-eoa} +
+ Configuração do host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornecedor de serviços na nuvemAWS EC2
Tamanho da instânciac6a.48xlarge
Networkingsubnet privada
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Limite do descritor do ficheiro65535
Máx. de processos do utilizador65535
+
+
+
+
+ +
+ Configuração da blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versão do Polygon EdgeLançamento v0.4.1
Nós validadores4
Nós não-validadores0
ConsensoIBFT PoA
Tempo do bloco1s
Limite de gás do bloco70778880
Máx. de slots276480
Utilização média do bloco59,34%
+
+
+
+
+ +
+ Configuração do Loadbot +
+
+ + + + + + + + + + + + + +
Total de transações30000
Transações enviadas por segundo1428
Tipo de transaçõesTransferências EOA para EOA
+
+
+
+
+ +
+ Log do Loadbot + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### Ambiente ERC-20 {#environment-erc20} +
+ Configuração do host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornecedor de serviços na nuvemAWS EC2
Tamanho da instânciac6a.48xlarge
Networkingsubnet privada
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Limite do descritor do ficheiro65535
Máx. de processos do utilizador65535
+
+
+
+
+ +
+ Configuração da blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versão do Polygon EdgeLançamento v0.4.1
Nós validadores4
Nós não-validadores0
ConsensoIBFT PoA
Tempo do bloco1s
Limite de gás do bloco47185920
Máx. de slots184320
Utilização média do bloco81,29%
+
+
+
+
+ +
+ Configuração do Loadbot +
+
+ + + + + + + + + + + + + +
Total de transações50000
Transações enviadas por segundo1111
Tipo de transaçõesTransferências ERC-20 para ERC-20
+
+
+
+
+ +
+ Log do Loadbot + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### Ambiente ERC-721 {#environment-erc721} +
+ Configuração do host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Fornecedor de serviços na nuvemAWS EC2
Tamanho da instânciac6a.48xlarge
Networkingsubnet privada
Sistema operativoLinux Ubuntu 20.04 LTS - Focal Fossa
Limite do descritor do ficheiro65535
Máx. de processos do utilizador65535
+
+
+
+
+ +
+ Configuração da blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Versão do Polygon EdgeLançamento v0.4.1
Nós validadores4
Nós não-validadores0
ConsensoIBFT PoA
Tempo do bloco1s
Limite de gás do bloco94371840
Máx. de slots1000000
Utilização média do bloco93,88%
+
+
+
+
+ +
+ Configuração do Loadbot +
+
+ + + + + + + + + + + + + +
Total de transações30000
Transações enviadas por segundo714
Tipo de transaçõesCunhagem de tokens ERC-721
+
+
+
+
+ +
+ Log do Loadbot + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/pt-edge/troubleshooting.md b/archive/edge/pt-edge/troubleshooting.md new file mode 100644 index 0000000000..85cd20700f --- /dev/null +++ b/archive/edge/pt-edge/troubleshooting.md @@ -0,0 +1,71 @@ +--- +id: troubleshooting +title: Solução de problemas +description: "Seção de solução de problemas para o Polygon Edge" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# Solução de problemas {#troubleshooting} + +## Erro de `method=eth_call err="invalid signature"` {#error} + +Quando estiver a usar uma carteira para fazer uma transação com o Polygon Edge, certifique-se de que a configuração da rede local da sua carteira: + +1. O `chainID`é o correto. O `chainID` padrão para borda é `100`, mas pode ser personalizado usando o sinalizador de génese `--chain-id`. + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. Certifique-se de que, no campo “URL do RPC”, use a porta do RPC JSON do nó ao qual está conectando. + + +## Como obter um URL de WebSocket {#how-to-get-a-websocket-url} + +Por predefinição, quando se executa o Polygon Edge, ele gera um endpoint de WebSocket baseado na localização da chain. +O esquema do URL `wss://` é usado para links HTTPS e o `ws://` para HTTP. + +URL Localhost WebSocket: +````bash +ws://:/ws +```` +Note que o número da porta depende da porta JSON-RPC escolhida para o nó. + +URL de WebSocket Edgenet: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## `insufficient funds`Erro ao tentar implantar um contrato {#error-when-trying-to-deploy-a-contract} + +Se receber este erro, certifique-se de que tem fundos suficientes no endereço desejado e que o endereço usado seja o correto
. +Para definir o saldo pré-minerado, pode usar o sinalizador de génese `genesis [--premine ADDRESS:VALUE]` ao gerar o ficheiro de génese. +Exemplo de usar este sinalizador: +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +Isso faz pré-mineração de 1000000000000000000000 WEI para 0x3956E90e632AebBF34DEB49b71c28A83Bc029862. + + +## Tokens ERC-20 não liberados enquanto estiver a usar o Chainbridge {#erc20-tokens-not-released-while-using-chainbridge} + +Se tentar transferir os tokens ERC-20 entre o PoS do Polygon e uma rede de borda local, seus tokens ERC-20 forem depositados, e a proposta for executada no relayer, mas os tokens não forem liberados na sua rede de borda, certifique-se de que o handler ERC-20 na chain do Polygon Edge tenha tokens suficientes para liberação.
+O contrato de handler na chain de destino deve ter tokens suficientes para liberação para o modo de bloqueio-liberação. Se não tiver tokens ERC-20 no Handler ERC-20 da sua rede de borda local, cunhe novos tokens e os transfira para o handler ERC-20. + +## Erro `Incorrect fee supplied` ao usar o Chainbridge {#error-when-using-chainbridge} + +Pode receber este erro ao tentar transferir tokens ERC-20 entre chain de PoS de Polygon de Mumbai e uma configuração do Polygon Edge local. Este erro aparece quando define a taxa na implantação usando o sinalizador `--fee`, mas não defina o mesmo valor na transação de depósito. +Pode usar o comando abaixo para alterar a taxa: +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +Pode encontrar mais informações sobre este sinalizador [aqui](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md). + + + + + diff --git a/archive/edge/pt-edge/validator-hosting.md b/archive/edge/pt-edge/validator-hosting.md new file mode 100644 index 0000000000..77978d63e9 --- /dev/null +++ b/archive/edge/pt-edge/validator-hosting.md @@ -0,0 +1,265 @@ +--- +id: validator-hosting +title: Hosting de validadores +description: "Requisitos de hosting para o Polygon Edge" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +Seguem-se sugestões para a hospedagem correta de um nó de validador numa rede Polygon Edge. Preste muita atenção a todos os itens listados abaixo para garantir +que o seu validador está devidamente configurado para ser seguro, estável e apresentar um elevado desempenho. + +## Base de conhecimento {#knowledge-base} + +Leia este documento com atenção antes de tentar executar o nó de validador. +Documentos adicionais que podem ser úteis: + +- [Instalação](get-started/installation) +- [Configuração da nuvem](get-started/set-up-ibft-on-the-cloud) +- [Comandos CLI](get-started/cli-commands) +- [Ficheiro config do servidor](configuration/sample-config) +- [Chaves privadas](configuration/manage-private-keys) +- [Métricas Prometheus](configuration/prometheus-metrics) +- [Gestores de segredos](/docs/category/secret-managers) +- [Backup/Recuperação](working-with-node/backup-restore) + +## Requisitos de sistema mínimos {#minimum-system-requirements} + +| Tipo | Valor | Influenciado por | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 2 núcleos |
  • Número de consultas JSON-RPC
  • Tamanho do estado da blockchain
  • Limite de gás do bloco
  • Tempo do bloco
| +| RAM | 2 GB |
  • Número de consultas JSON-RPC
  • Tamanho do estado da blockchain
  • Limite de gás do bloco
| +| Disco |
  • 10 GB de partição da raiz
  • 30 GB de partição da raiz com LVM para extensão do disco
|
  • Tamanho do estado da blockchain
| + + +## Configuração do serviço {#service-configuration} + +O binário `polygon-edge` tem de ser executado como serviço de sistema automaticamente depois de se estabelecer a conectividade de rede e de ter as funcionalidades start / stop / restart. + Recomendamos que seja usado um gestor de serviço como `systemd.` + +Exemplo de ficheiro de configuração do sistema `systemd`: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### Binário {#binary} + +Nas cargas de trabalho de produção, o binário `polygon-edge` só deve ser implantado a partir de binários de lançamento do GitHub pré-construídos - não por compilação manual. +:::info + +Ao compilar manualmente o ramo Github `develop`, pode introduzir alterações de quebra de código no seu ambiente. +Por este motivo, é recomendável implantar o binário Polygon Edge exclusivamente a partir das novas versões, pois ele +contém informações sobre alterações de quebra de código e como superá-las. + +::: + +Consulte a [Instalação](/docs/edge/get-started/installation) para uma visão geral completa do método de instalação. + +### Armazenamento de dados {#data-storage} + +A pasta `data/` com todo o estado da blockchain deve ser montada num disco/volume dedicado, permitindo +backups automáticos do disco, a extensão do volume e, opcionalmente, a montagem do disco/volume noutra instância, em caso de falha. + + +### Ficheiros log {#log-files} + +Os ficheiros log têm de ser rodados diariamente (com uma ferramenta como `logrotate`). +:::warning + +Se configurados sem rotação de log, os ficheiros log podem usar todo o espaço em disco disponível, o que pode interromper o tempo de atividade do validador. + +::: + +Exemplo de configuração do `logrotate`: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +Consulte a seção [Logging](#logging) abaixo para obter recomendações sobre o armazenamento do log. + +### Dependências adicionais {#additional-dependencies} + +`polygon-edge` é compilado estaticamente, não necessitando de dependências adicionais do sistema operativo host. + +## Manutenção {#maintenance} + +Seguem abaixo as melhores práticas para manter o nó de validador da rede Polygon Edge em execução + +### Backup {#backup} + +Existem dois tipos de procedimentos de backup recomendados para nós Polygon Edge. + +A sugestão é usar ambos, sempre que possível, sendo o backup do Polygon Edge uma opção sempre disponível. + +* ***Backup do volume***: + Backup diário incremental do volume `data/` do nó Polygon Edge ou da VM completa, se possível. + + +* ***Backup do Polygon Edge***: + É recomendado o trabalho diário do CRON, que faz backups regulares do Polygon Edge e move os ficheiros `.dat` para um local externo ou para um armazenamento seguro de objetos na nuvem. + +Idealmente, o backup do Polygon Edge não se deve sobrepor ao backup do volume descrito acima. + +Consulte a [Instância de backup/recuperação de nós](working-with-node/backup-restore) para obter instruções sobre como executar backups do Polygon Edge. + +### Logging {#logging} + +Os logs produzidos pelos nós Polygon Edge devem: +- ser enviados para um armazenamento de dados externo com capacidade de indexação e pesquisa +- ter um período de retenção de log de 30 dias + +Se é a primeira vez que configura um validador Polygon Edge, recomendamos que inicie o nó +com a opção `--log-level=DEBUG` para poder depurar rapidamente quaisquer problemas que possa enfrentar. + +:::info + +O `--log-level=DEBUG` fará com que a saída do log do nó seja a mais prolixa possível. +Os logs de depuração irão aumentar drasticamente o tamanho do ficheiro log, algo que deve ser considerado ao configurar +a solução de rotação do log. + +::: +### Patches de segurança do sistema operativo {#os-security-patches} + +Os administradores precisam de garantir que o SO da instância do validador é atualizada regularmente com os patches mais recentes, pelo menos uma vez por mês. + +## Métricas {#metrics} + +### Métricas do sistema {#system-metrics} + +Os administradores precisam de configurar algum tipo de monitor das métricas do sistema (por exemplo: Telegraf + InfluxDB + Grafana ou um SaaS de terceiros). + +Métricas que precisam de ser monitorizadas e que precisam de notificações de alarme configuradas: + +| Nome da métrica | Limite do alarme | +|-----------------------|-------------------------------| +| Uso da CPU (%) | > 90% durante mais de 5 minutos | +| Utilização da RAM (%) | > 90% durante mais de 5 minutos | +| Utilização do disco raiz | > 90% | +| Utilização do disco de dados | > 90% | + +### Métricas do validador {#validator-metrics} + +Os administradores precisam de configurar a recolha de métricas da API Prometheus do Polygon Edge para poderem +monitorizar o desempenho da blockchain. + +Consulte as [métricas Prometheus](configuration/prometheus-metrics) para entender que métricas estão a ser expostas e como configurar a recolha de métricas Prometheus. + + +É necessário ter uma atenção extra às seguintes métricas: +- ***Tempo de produção do bloco*** - se o tempo de produção do bloco é superior ao normal, isso significa que existe um potencial problema na rede +- ***Número de rondas de consenso*** - se existe mais do que 1 ronda, isso significa que existe um potencial problema com o conjunto de validadores da rede +- ***Número de pares*** - se o número de pares cair, isso significa que existe um problema de conectividade na rede + +## Segurança {#security} + +Seguem abaixo as melhores práticas para garantir o funcionamento do nó de validador da rede Polygon Edge. + +### Serviços API {#api-services} + +- ***JSON-RPC*** - +Único serviço API que tem de ser exposto ao público (através do load balancer ou diretamente). +Esta API deve ser executada em todas as interfaces ou num endereço IP específico (exemplo: `--json-rpc 0.0.0.0:8545` ou `--json-prc 192.168.1.1:8545` ). +:::info + +Como esta é uma API voltada para o público, é recomendável que o load balancer/proxy reverso na sua frente ofereça segurança e limite da taxa. + +::: + + +- ***LibP2P*** - +Esta é a API de networking usada por nós para comunicação por pares. Tem de ser executada em todas as interfaces ou num endereço IP específico +( `--libp2p 0.0.0.0:1478` ou `--libp2p 192.168.1.1:1478` ). Esta API não deve ser publicamente exposta, +mas antes acessível a todos os outros nós. +:::info + +Se executada num localhost ( `--libp2p 127.0.0.1:1478` ), os outros nós não conseguirão conectar-se. + +::: + + +- ***GRPC*** - +Esta API é usada apenas para executar comandos do operador, nada mais. Como tal, deve ser executada exclusivamente no localhost ( `--grpc-address 127.0.0.1:9632` ). + +### Segredos do Polygon Edge {#polygon-edge-secrets} + +Os segredos do Polygon Edge (chaves `ibft` e `libp2p`) não devem ser armazenados num sistema de ficheiros local. +Em vez disso, deve usar um [Gestor de Segredos](configuration/secret-managers/set-up-aws-ssm) suportado. +O armazenamento de segredos num sistema de ficheiros local só deve ser usado em ambientes de não produção. + +## Atualização {#update} + +Segue-se o procedimento de atualização pretendido para nós de validador, descrito como instruções passo-a-passo. + +### Procedimento de atualização {#update-procedure} + +- Descarregue o binário Polygon Edge mais recente a partir das [releases](https://github.com/0xPolygon/polygon-edge/releases) oficiais do GitHub +- Pare o serviço Polygon Edge (exemplo: `sudo systemctl stop polygon-edge.service` ) +- Substitua o binário `polygon-edge` existente pelo que descarregou (exemplo: `sudo mv polygon-edge /usr/local/bin/` ) +- Verifique se foi instalada a versão `polygon-edge` correta executando `polygon-edge version` - deve corresponder à versão de lançamento +- Consulte a documentação de lançamento para ver se existe algum passo de retrocompatibilidade que tem de seguir antes de iniciar o serviço `polygon-edge` +- Inicie o serviço `polygon-edge` (exemplo: `sudo systemctl start polygon-edge.service` ) +- Por fim, verifique a saída do log `polygon-edge` e certifique-se de que está a correr sem quaisquer logs de `[ERROR]` + +:::warning + +Quando existe uma versão de quebra de código, este procedimento de atualização deve ser executado em todos os nós, +pois o binário atualmente em execução não é compatível com o novo lançamento. + +Isto significa que a chain tem de ser interrompida por um período de tempo curto (até os binários `polygon-edge` serem substituídos e o serviço reiniciado), +logo planeie tudo corretamente. + +Pode usar ferramentas como **[Ansible](https://www.ansible.com/)** ou um script personalizado para executar a atualização de forma eficiente +e minimizar o tempo de inatividade da chain. + +::: + +## Procedimento de inicialização {#startup-procedure} + +Segue-se o fluxo pretendido para o procedimento de inicialização do validador Polygon Edge + +- Leia atentamente os documentos listados na secção [Base de Conhecimento](#knowledge-base) +- Aplique os patches mais recentes do sistema operativo no nó de validador +- Descarregue o binário `polygon-edge` mais recente dos [lançamentos](https://github.com/0xPolygon/polygon-edge/releases) oficiais do GitHub e coloque-o na instância local `PATH` +- Inicialize um dos [gestores de segredos](/docs/category/secret-managers) suportados usando o comando CLI `polygon-edge secrets generate` +- Gere e armazene segredos usando o `polygon-edge secrets init` [comando CLI](/docs/edge/get-started/cli-commands#secrets-init-flags) +- Anote os valores `NodeID` e `Public key (address)` +- Gere o ficheiro `genesis.json` conforme descrito na [configuração da nuvem](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators) usando o `polygon-edge genesis` [comando CLI](/docs/edge/get-started/cli-commands#genesis-flags) +- Gere o ficheiro config predefinido usando o `polygon-edge server export` [comando CLI](/docs/edge/configuration/sample-config) +- Edite o ficheiro `default-config.yaml` para acomodar o ambiente de nó de validador local (caminhos dos ficheiros, etc.) +- Crie um serviço Polygon Edge ( `systemd` ou semelhante) onde o binário `polygon-edge` executará o servidor a partir de um ficheiro `default-config.yaml` +- Inicie o servidor Polygon Edge iniciando o serviço (exemplo: `systemctl start polygon-edge` ) +- Verifique a saída do log `polygon-edge` e certifique-se de que os blocos estão a ser gerados e que não existem logs de `[ERROR]` +- Verifique a funcionalidade da chain chamando um método JSON-RPC como [`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid) diff --git a/archive/edge/pt-edge/working-with-node/backup-restore.md b/archive/edge/pt-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..0a10da3670 --- /dev/null +++ b/archive/edge/pt-edge/working-with-node/backup-restore.md @@ -0,0 +1,93 @@ +--- +id: backup-restore +title: Backup/Recuperação de instância de nó +description: "Como fazer backup e recuperar uma instância de nó Polygon Edge." +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## Visão geral {#overview} + +Este guia explica a detalhe como fazer backup e recuperar uma instância de nó Polygon Edge. +Cobre as pastas base e o que estas contêm, bem como os ficheiros que são críticos para a realização de um backup e recuperação bem-sucedidos. + +## Pastas base {#base-folders} + +O Polygon Edge usa o LevelDB como motor de armazenamento. +Ao iniciar um nó Polygon Edge, as seguintes subpastas são criadas no diretório de trabalho especificado: +* **blockchain** - armazena os dados da blockchain +* **trie** - armazena as árvores Merkle (dados de estado do mundo) +* **keystore** - armazena chaves privadas para o cliente. Isto inclui a chave privada libp2p e a chave privada de selagem/validador +* **consensus** - armazena qualquer informação de consenso que o cliente possa necessitar durante o trabalho. Por enquanto, armazena a *chave de validador privada* do nó + +É essencial que estas pastas sejam preservadas para que a instância Polygon Edge seja executada sem problemas. + +## Criar o backup de um nó em execução e recuperá-lo para um novo nó {#create-backup-from-a-running-node-and-restore-for-new-node} + +Esta secção orienta-o ao longo da criação de dados de arquivo da blockchain num nó em execução e da recuperação para outra instância. + +### Backup {#backup} + +O comando `backup` obtém blocos de um nó em execução por gRPC e gera um ficheiro de arquivo. Se `--from` e `--to` não forem indicados no comando, este comando irá buscar blocos da génese até ao mais recente. + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### Recuperação {#restore} + +Um servidor importa blocos de um arquivo no início quando começa com um flag `--restore`. Certifique-se de que existe uma chave para o novo nó. Para saber mais sobre a importação ou geração de chaves, visite a secção [Gestores de Segredos](/docs/edge/configuration/secret-managers/set-up-aws-ssm). + +```bash +$ polygon-edge server --restore archive.dat +``` + +## Backup/Recuperação de dados inteiros {#back-up-restore-whole-data} + +Esta secção orienta-o ao longo do backup de dados, incluindo dados de estado e chave, e da recuperação para a nova instância. + +### Etapa 1: parar o cliente em execução {#step-1-stop-the-running-client} + +Como o Polygon Edge usa o **LevelDB** para armazenamento de dados, o nó tem de ser interrompido durante o período de backup, +pois o **LevelDB** não permite o acesso simultâneo aos ficheiros da sua base de dados. + +Além disso, o Polygon Edge também faz a descarga de dados. + +A etapa inicial envolve a interrupção do cliente em execução (seja por meio de um gestor de serviços ou de outro mecanismo que envia um sinal SIGINT para o processo), +para que possa desencadear 2 eventos, enquanto é encerrado graciosamente: +* Descarga de dados em execução para o disco +* Ativação do bloqueio de ficheiros DB pelo LevelDB + +### Etapa 2: backup do diretório {#step-2-backup-the-directory} + +Agora que cliente não está a funcionar, o diretório de dados já pode ser copiado para outro meio. +Lembre-se que os ficheiros com extensão `.key` contêm dados da chave privada que podem ser usados para representar o nó atual, +e jamais deverão ser partilhados com terceiros/desconhecidos. + +:::info + +Faça backup e recupere o ficheiro `genesis` gerado manualmente, para que o nó recuperado fique totalmente operacional. + +::: + +## Recuperação {#restore-1} + +### Etapa 1: parar o cliente em execução {#step-1-stop-the-running-client-1} + +Se qualquer instância do Polygon Edge estiver a ser executada, ela precisa de ser interrompida para que a etapa 2 seja bem-sucedida. + +### Etapa 2: copiar o diretório de dados de backup para a pasta pretendida {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +O diretório de dados cujo backup foi feito anteriormente pode ser copiado para a pasta pretendida assim que o cliente deixar de estar a funcionar. +Além disso, recupere o ficheiro `genesis` previamente copiado. + +### Etapa 3: execute o cliente Polygon Edge enquanto especifica o diretório de dados correto {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +Para que o Polygon Edge possa usar o diretório de dados recuperados, no lançamento, o utilizador tem de especificar o caminho para o +diretório de dados. Consulte o flag [Comandos CLI](/docs/edge/get-started/cli-commands) para informações sobre o flag `data-dir`. diff --git a/archive/edge/pt-edge/working-with-node/query-json-rpc.md b/archive/edge/pt-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..90917b2291 --- /dev/null +++ b/archive/edge/pt-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,93 @@ +--- +id: query-json-rpc +title: Endpoints de JSON RPC de consulta +description: "Faça uma consulta de dados e inicie a chain com uma conta pré-minerada." +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## Visão geral {#overview} + +A camada JSON-RPC do Polygon Edge fornece aos programadores a funcionalidade de interagir facilmente com o blockchain, +através de solicitações HTTP. + +Este exemplo cobre o uso de ferramentas como **curl** para informações de consulta, bem como a inicialização da chain com uma conta pré-minerada, +e envio de uma transação. + +## Etapa 1: crie um ficheiro de génese com uma conta pré-minerada {#step-1-create-a-genesis-file-with-a-premined-account} + +Para gerar um ficheiro de génese, execute o comando a seguir: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +O sinalizador de **pré-mineração** define o endereço que deve ser incluído com um saldo inicial no ficheiro de **génese**.
+Neste caso, o endereço `0x1010101010101010101010101010101010101010` terá um **saldo padrão** inicial de +`0xD3C21BCECCEDA1000000`(1 milhão de tokens de moeda nativa). + +Se quiséssemos especificar saldo, poderíamos separar o saldo e o endereço com um `:`, como este: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +O saldo pode ser um valor `hex` ou `uint256`. + +:::warning Apenas contas pré-mineração para as quais tem chave privada! + +Se tiver pré-mineração de contas e não tiver uma chave privada para acessá-las, o saldo pré-minerado não será utilizável + +::: + +## Etapa 2: inicie o Polygon Edge no modo dev {#step-2-start-the-polygon-edge-in-dev-mode} + +Para iniciar o Polygon Edge no modo de programação, que é explicado na seção [Comandos de CLI](/docs/edge/get-started/cli-commands), +execute o seguinte: +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## Etapa 3: consulte o saldo da conta {#step-3-query-the-account-balance} + +Agora que o cliente está pronto e em execução no modo dev, usando o ficheiro de génese gerado na **etapa 1**, podemos usar uma ferramenta como +**curl** para consultar o saldo da conta: +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +O comando deve retornar o seguinte resultado: +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## Etapa 4: Envie uma transação de transferência {#step-4-send-a-transfer-transaction} + +Agora que confirmamos que a conta que configuramos como pré-minerada tem o saldo correto, podemos transferir alguma quantidade de Ether: + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/pt-edge/working-with-node/query-operator-info.md b/archive/edge/pt-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..64cbf6ec3d --- /dev/null +++ b/archive/edge/pt-edge/working-with-node/query-operator-info.md @@ -0,0 +1,85 @@ +--- +id: query-operator-info +title: Consulta de informações sobre o operador +description: "Como consultar informações sobre o operador." +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## Pré-requisitos {#prerequisites} + +Este guia assume que seguiu a [Configuração Local](/docs/edge/get-started/set-up-ibft-locally) ou o [guia sobre como configurar um cluster IBFT na nuvem](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +É necessário um nó em funcionamento para consulta de qualquer tipo de informações sobre o operador. + +Com o Polygon Edge, os operadores de nós têm tudo sob controlo e sabem o que está a fazer o nó que eles operam.
+Em qualquer momento, eles podem usar a camada de informações sobre os nós no gRPC e obter informações significativas - sem necessitar de filtrar os logs. + +:::note + +Se o seu nó não estiver a ser executado em `127.0.0.1:8545`, deve adicionar um flag `--grpc-address ` aos comandos listados neste documento. + +::: + +## informações sobre os pares {#peer-information} + +### Lista de pares {#peers-list} + +Para obter uma lista completa de pares conectados (incluindo o próprio nó em execução), execute o seguinte comando: +````bash +polygon-edge peers list +```` + +Este retornará uma lista de endereços libp2p que são atualmente pares do cliente em execução. + +### Estado dos pares {#peer-status} + +Para o estado de um par específico, execute: +````bash +polygon-edge peers status --peer-id
+```` +Sendo que o parâmetro *address* é o endereço libp2p do par. + +## Informações sobre o IBFT {#ibft-info} + +Muitas vezes, um operador pode querer conhecer o estado do nó em funcionamento no consenso IBFT. + +Felizmente, o Polygon Edge oferece uma maneira fácil de encontrar esta informação. + +### Snapshots {#snapshots} + +A execução do comando a seguir retorna o snapshot mais recente. +````bash +polygon-edge ibft snapshot +```` +Para consultar o snapshot a uma altura específica (número do bloco), o operador pode executar: +````bash +polygon-edge ibft snapshot --num +```` + +### Candidatos {#candidates} + +Para obter as informações mais recentes sobre candidatos, o operador pode executar: +````bash +polygon-edge ibft candidates +```` +Este comando consulta o conjunto atual de candidatos propostos, bem como os candidatos que ainda não foram incluídos + +### Estado {#status} + +O comando que se segue retorna a chave de validador atual do cliente IBFT em execução: +````bash +polygon-edge ibft status +```` + +## Pool de transações {#transaction-pool} + +Para encontrar o número atual de transações na pool de transações, o operador pode executar: +````bash +polygon-edge txpool status +```` diff --git a/archive/edge/ru-edge/additional-features/blockscout.md b/archive/edge/ru-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..689bc166d7 --- /dev/null +++ b/archive/edge/ru-edge/additional-features/blockscout.md @@ -0,0 +1,415 @@ +--- +id: blockscout +title: Blockscout +description: Настройка экземпляра Blockscout для работы с Polygon Edge. +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## Обзор {#overview} +В этом руководстве подробно рассказывается о компиляции и развертывании экземпляров Blockscout для работы с Polygon-Edge. +Blockscout использует собственную [документацию](https://docs.blockscout.com/for-developers/manual-deployment), однако в настоящем руководстве содержатся простые, но подробные пошаговые инструкции по настройке экземпляра Blockscout. + +## Среда {#environment} +* Операционная система: [ссылка для загрузки](https://releases.ubuntu.com/20.04/) Ubuntu Server 20.04 LTS с разрешениями sudo +* Аппаратное обеспечение сервера: 8 процессоров / ОЗУ 16 ГБ / жесткий диск 50 ГБ (LVM) +* Сервер базы данных: выделенный сервер с 2 процессорами / ОЗУ 4 ГБ / SSD-накопитель 100 ГБ / PostgreSQL 13.4 + +### Сервер БД {#db-server} +Для настоящего руководства требуется подготовить сервер базы данных и настроить базу данных и пользователя БД. +В настоящем руководстве не будет подробно описываться процесс развертывания и настройки сервера PostgreSQL. +Этому посвящено множество других руководств, например [Руководство DigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart) + +:::info ОТКАЗ ОТ ОТВЕТСТВЕННОСТИ + +Настоящее руководство предназначено только для запуска Blockscout на одном экземпляре, что не является идеальной моделью работы. +В производственной среде может потребоваться добавление в архитектуру обратного прокси, балансировщика нагрузки, опций масштабируемости и т. д. + +::: + +# Процедура развертывания Blockscout {#blockscout-deployment-procedure} + +## Часть 1 — установка зависимостей {#part-1-install-dependencies} +Прежде чем начинать, нам нужно убедиться, что мы установили все двоичные файлы, от которых зависит blockscout. + +### Обновление и модернизация системы {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### Добавление репозиториев erlang {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### Добавление репозитория NodeJS {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### Установка Rust {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### Установите требуемую версию Erlang {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### Установите требуемую версию Elixir {#install-required-version-of-elixir} +Требуется версия Elixir `1.13`. Если мы попробуем установить эту версию из официального репозитория, +`erlang` произведет обновление до `Erlang/OTP 25`, а нам этого не нужно. +В связи с этим мы установим конкретную предварительно скомпилированную версию `elixir`со страницы релизов на GitHub. + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +Теперь нам нужно будет правильно настроить двоичные файлы системы `exlixir`. +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +Проверьте правильность установки `elixir`и ,`erlang` запустив .`elixir -v` +Вывод должен выглядеть следующим образом: +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning + +`Erlang/OTP` версии `24` и `Elixir` версии `1.13.*` обязательны. +Если использовать другие версии, вы столкнетесь с проблемами при компиляции и запуске Blockscout. + +::: +:::info + +Ознакомьтесь с официальной ***[страницей требований Blockscout](https://docs.blockscout.com/for-developers/information-and-settings/requirements)*** + +::: + +### Установите NodeJS {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### Установите Cargo {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### Установите другие зависимости {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### Также вы можете установить клиент postgresql для проверки подключения к базе данных {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## Часть 2 — установка переменных среды {#part-2-set-environment-variables} +Прежде чем начать компиляцию Blockscout, необходимо установить переменные среды. +В этом руководстве мы установим только базовый минимум для начала работы. +Полный список переменных, которые можно настроить, находится [здесь](https://docs.blockscout.com/for-developers/information-and-settings/env-variables) + +### Задайте подключение к базе данных как переменную среды {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +Протестируйте подключение к базе данных, используя указанные параметры. +Поскольку вы задали переменные среды PG, вы сможете подключиться к базе данных только следующим образом: +```bash +psql +``` + +Если база данных настроена правильно, вы должны увидеть строку psql: +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +Иначе вы увидите ошибку следующего вида: +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +В этом случае вам будут полезны [эти документы](https://ubuntu.com/server/docs/databases-postgresql). + +:::info Подключение к базе данных + +Перед переходом к следующей части убедитесь, что вы решили все проблемы с подключением к базе данных. Вам нужно будет предоставить привилегии superuser пользователю blockscout. + +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## Часть 3 — клонирование и компиляция Blockscout {#part-3-clone-and-compile-blockscout} +Теперь мы готовы начать установку Blockscout. + +### Клонируйте репозиторий Blockscout {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### Сгенерируйте секретный ключ для защиты рабочей сборки {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +В последней строке вы должны увидеть длинную строку случайных символов. +Ее необходимо задать как переменную среды `SECRET_KEY_BASE`, прежде чем переходить к следующему шагу. +Например: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### Задайте производственный режим {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### Выполните компиляцию {#compile} +Перейдите в каталог клонирования и начните компиляцию + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info + +Если вы уже выполнили развертывание, удалите статичные активы из предыдущей сборки ***mix phx.digest.clean***. + +::: + +### Перенесите базы данных {#migrate-databases} +:::info + +Этот этап не будет успешно выполнен, если вы не настроили подключение к БД надлежащим образом, не указали +или задали неправильные параметры переменой среды DATABASE_URL. +Пользователь базы данных должен иметь привилегии superuser. + +::: +```bash +mix do ecto.create, ecto.migrate +``` + +Если вам требуется сначала отключить базу данных, запустите +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### Установите зависимости npm и скомпилируйте активы клиентской части {#install-npm-dependencies-and-compile-frontend-assets} +Вам нужно будет перейти в каталог, содержащий активы клиентской части. + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info Имейте терпение + +Компиляция этих активов может занять несколько минут, и при этом не будет отображаться никакой вывод. +Может показаться, что процесс завис, но нужно просто подождать. Когда процесс компиляции будет завершен, вывод должен выглядеть примерно так: `webpack 5.69.1 compiled with 3 warnings in 104942 ms` + +::: + +### Создайте статичные активы {#build-static-assets} +Для этого шага нужно будет вернуться на корневой уровень папки клонирования Blockscout. +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### Сгенерируйте самостоятельно подписанные сертификаты {#generate-self-signed-certificates} +:::info + +Вы можете пропустить этот шаг, если не будете использовать `https`. + +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## Часть 4 — создание и запуск сервиса Blockscout {#part-4-create-and-run-blockscout-service} +В этой части нам требуется настроить системный сервис, поскольку мы хотим, чтобы Blockscout запускался и работал в фоновом режиме даже после перезагрузки системы. + +### Создайте файл сервиса {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### Отредактируйте файл сервиса {#edit-service-file} +Используйте предпочитаемый текстовый редактор Linux, чтобы отредактировать этот файл и настроить сервис. +```bash +sudo vi /etc/systemd/system/explorer.service +``` +Содержимое файла explorer.service должно выглядеть следующим образом: +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### Включите запуск сервиса при загрузке системы {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### Переместите папку клонирования Blockscout в общесистемную область {#move-your-blockscout-clone-folder-to-system-wide-location} +Сервису Blockscout потребуется доступ к папке, которую вы клонировали из репозитория Blockscout и где вы скомпилировали все активы. +```bash +sudo mv ~/blockscout /usr/local +``` + +### Создайте файл переменных среды, который будет использоваться сервисом Blockscout {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info + +Используйте `SECRET_KEY_BASE`, сгенерированный в части 3. + +::: +Сохраните файл и выйдите из редактора. + +### Запустите сервис Blockscout {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## Часть 5 — тестирование функционала экземпляра Blockscout {#part-5-test-out-the-functionality-of-your-blockscout-instance} +Теперь осталось только проверить, работает ли сервис Blockscout. +Проверьте статус сервиса: +```bash +sudo systemctl status explorer.service +``` + +Для проверки статуса сервиса: +```bash +sudo journalctl -u explorer.service -f +``` + +Вы можете проверить, есть ли новые порты для прослушивания: +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +Вам нужно будет получить список портов прослушивания, и в этом списке должно быть примерно следующее: +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +Веб-сервис Blockscout запускает порт и протокол, определенные в файле env. В этом примере используется `4000`(http). +Если все хорошо, у вас должен быть доступ к веб-порталу Blockscout с помощью `http://:4000`. + +## Важные соображения {#considerations} +Для наилучшей производительности рекомендуется использовать выделенный/локальный полный нод `polygon-edge`как архивный нод, не являющийся валидатором. Он будет использоваться только для запросов Blockscout. +К API `json-rpc`этого нода не требуется открытый доступ, поскольку Blockscout выполняет все запросы на серверном уровне. + + +## Заключительные соображения {#final-thoughts} +Мы только что развернули один экземпляр Blockscout, который работает нормально, однако для рабочих целей следует разместить этот экземпляр за обратным прокси, например Nginx. +Также следует подумать о масштабируемости базы данных и экземпляра в зависимости от требований вашего сценария работы. + +Обязательно ознакомьтесь с официальной [документацией по Blockscout](https://docs.blockscout.com/), где вы найдете множество вариантов настройки. \ No newline at end of file diff --git a/archive/edge/ru-edge/additional-features/chainbridge/definitions.md b/archive/edge/ru-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..bbdd487635 --- /dev/null +++ b/archive/edge/ru-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,215 @@ +--- +id: definitions +title: Общие определения +description: Общие определения терминов, используемых в chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## Ретранслятор {#relayer} +Chainbridge — это мост ретрансляторного типа. Роль ретранслятора заключается в голосовании за исполнение заявки (например, сколько токенов сжечь/выпустить). Он отслеживает события из каждой цепочки и при получении `Deposit`события из цепочки и голосует за предложение в контракте Bridge конечной цепочки. Ретранслятор вызывает метод в контракте Bridge для исполнения предложения после отправки требуемого количества голосов. Мост делегирует исполнение контракту Handler. + + +## Типы контрактов {#types-of-contracts} +В ChainBridge существует три типа контрактов в каждой цепочке, они называются Bridge/Handler/Target. + +| **Тип** | **Описание** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Контракт Bridge | Контракт Bridge, который управляет запросами, голосами, исполнениями, должен быть развернут в каждой цепочке. Пользователи вызывают `deposit`в Bridge, чтобы запустить трансфер, и Bridge делегирует процесс контракту Handler, соответствующему контракту Target. Как только контракт Handler успешно вызовет контракт Target, контракт Bridge эмитирует событие `Deposit` для уведомления ретрансляторов. | +| Контракт Handler | Контракт взаимодействует с контрактом Target для выполнения депозита или предложения. Он проверяет запрос пользователя, вызывает контракт Target и помогает с некоторыми настройками контракта Target. Существуют определенные контракты Handler для вызова каждого контракта Target, который имеет другой интерфейс. Косвенные вызовы, которые производит контракт Handler, позволяют мосту осуществлять передачу любых активов. В настоящее время в рамках ChainBridge реализовано три типа контрактов Handler: ERC20Handler, ERC721Handler и GenericHandler. | +| Контракт Target | Контракт, который управляет активами, подлежащими обмену, или сообщениями, передающимися между цепочками. Взаимодействие с этим контрактом будет осуществляться с каждой стороны моста. | + +
+ +![Архитектура ChainBridge](/img/edge/chainbridge/architecture.svg) *Архитектура ChainBridge* + +
+ +
+ +![Рабочий процесс трансфера токенов ERC20](/img/edge/chainbridge/erc20-workflow.svg) *ex. Рабочий процесс трансфера токенов ERC20* + +
+ +## Типы аккаунтов {#types-of-accounts} + +Перед началом работы убедитесь, что на аккаунтах достаточно нативных токенов для создания транзакций. В Polygon Edge вы можете назначить предварительно созданные балансы на аккаунты при создании генезисного блока. + +| **Тип** | **Описание** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Администратор | По умолчанию данному аккаунту будет присвоена роль администратора. | +| Пользователь | Аккаунт отправителя/получателя, который отправляет/получает активы. Аккаунт отправителя оплачивает комиссию за газ при утверждении трансфера токенов и вызове депозита в контракте Bridge для начала трансфера. | + +:::info Роль администратора +Некоторые действия может выполнить только аккаунт администратора. Тот, кто развертывает контракт Bridge, имеет по умолчанию роль администратора. Ниже вы найдете инструкции, как предоставить роль администратора другому аккаунту и удалить эту роль. + +### Добавление роли администратора {#add-admin-role} + +Добавление администратора + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### Удаление роли администратора {#revoke-admin-role} + +Удаление администратора + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## Операции, которые разрешено осуществлять в рамках аккаунта `admin`, приведены ниже. {#account-are-as-below} + +### Настройка ресурса {#set-resource} + +Регистрация идентификатора ресурса с адресом контракта для обработчика. + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Настройка контракта с возможностью произвольного сжигания/минтинга {#make-contract-burnable-mintable} + +Настройка контракта на токены с возможностью произвольного минтинга/сжигания в обработчике. + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Отмена предложения {#cancel-proposal} + +Отмена предложения по исполнению. + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### Пауза / снятие паузы {#pause-unpause} + +Постановка на временную паузу депозитов, создания предложений, голосования и исполнения депозитов. + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### Изменение комиссии {#change-fee} + +Изменение комиссии, которая будет выплачена в адрес контракта Bridgeю + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### Добавление/удаление ретранслятора {#add-remove-a-relayer} + +Добавление аккаунта в качестве нового ретранслятора или удаление аккаунта из ретрансляторов. + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### Изменение порога ретранслятора {#change-relayer-threshold} + +Изменение количества голосов, требуемых для исполнение предложения. + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## Идентификатор цепочки {#chain-id} + +Chainbridge `chainId`— это произвольное значение, которое используется в мосте для дифференциации между сетями блокчейн, и оно должно находиться в диапазоне uint8. Чтобы избежать путаницы с идентификатором цепочки, эти значения не совпадают. Данное значение должно быть уникальным, но оно не должно совпадать с идентификатором сети. + +В этом примере мы задали `99`в `chainId`, потому что идентификатор цепочки тестовой сети Mumbai testnet составляет `80001`, который не может быть представлен при помощи uint8. + +## Идентификатор ресурса {#resource-id} + +Идентификатор ресурса — это уникальное 32-байтое значение в межсетевой среде, связанное с определенным активом (ресурсом), который передается между сетями. + +Идентификатор ресурса — это произвольное число, но, как правило, последний байт содержит идентификатор цепочки исходной цепочки (сети, из которой был получен актив). + +## JSON-RPC URL для Polygon PoS {#json-rpc-url-for-polygon-pos} + +В данном руководстве мы будем использовать https://rpc-mumbai.matic.today, публичный URL-адрес JSON-RPC , предоставленный Polygon, который может иметь ограничения по трафику или скорости. Он будет использоваться только для подключения к тестовой сети Polygon Mumbai. Рекомендуем получить URL-адрес JSON-RPC с помощью внешнего сервиса, например Infura, поскольку развертывание контрактов требует отправления множества запросов/заявок в адрес JSON-RPC. + +## Способы обработки трансфера токенов {#ways-of-processing-the-transfer-of-tokens} +При осуществлении трансфера токенов ERC20 между цепочками они могут обрабатываться в двух различных режимах: + +### Режим блокировки/освобождения {#lock-release-mode} +Исходная цепочка: токены, которые вы отправляете, будут заблокированы в контракте Handler.
Конечная цепочка: то же количество токенов, которые вы отправили в исходной цепочке, будет разблокировано и передано из контракта Handler на аккаунт получателя в конечной цепочке. + +### Режим сжигания/минтинга {#burn-mint-mode} +Исходная цепочка: токены, которые вы отправляете, будут токенами для
сжигания. Конечная цепочка: то же количество токенов, которые вы отправили и сожгли в исходной цепочке, будет подвержено минтингу в конечной цепочке и отправлено на аккаунт получателя. + +Вы можете использовать различные режимы в каждой цепочке. Это означает, что вы можете заблокировать токен в основной цепочке в то время, пока осуществляется минтинг токена в подцепочке для осуществления трансфера. Например, блокировка/освобождение токенов может иметь смысл, если контролируется общий объем или график минтинга. Токены будут подвергаться минтингу/сжиганию, если контракт в подцепочке должен следовать за поставкой в основой цепочке. + +Режим по умолчанию — это режим блокировки/освобождения. Если вы хотите сделать токены с возможностью минтинга/сжигания, вам нужно вызвать метод `adminSetBurnable`. Если вы хотите осуществлять минтинг токенов при исполнении, вам нужно будет предоставить роль `minter` контракту Handler ERC20. + + diff --git a/archive/edge/ru-edge/additional-features/chainbridge/overview.md b/archive/edge/ru-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..c7be5a9dc7 --- /dev/null +++ b/archive/edge/ru-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Обзор +description: Обзор ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Что такое ChainBridge? {#what-is-chainbridge} + +ChainBridge — это модульный многоцелевой блокчейн-мост с поддержкой EVM и совместимых с Substrate цепочек, созданный ChainSafe. Он позволяет пользователям осуществлять трансфер всех видов активов или сообщений между двумя различными цепочками. + +Чтобы узнать больше о ChainBridge, просим вас ознакомиться с [официальной документацией](https://chainbridge.chainsafe.io/), которая предоставлена разработчиками. + +Данное руководство должно оказать вам помощь при интеграции Chainbridge в Polygon Edge. В нем рассматривается настройка моста между работающим Polygon PoS (тестовая сеть Mumbai testnet) и локальной сетью Polygon PoS. + +## Требования {#requirements} + +В этом руководстве вы запустите ноды Polygon Edge, ретранслятор ChainBridge (подробнее об этом [здесь](/docs/edge/additional-features/chainbridge/definitions)) и инструмент cb-sol-cli, который является инструментом CLI для локального развертывания контрактов, регистрации ресурса и изменения настроек для моста (см. [здесь](https://chainbridge.chainsafe.io/cli-options/#cli-options)). Перед началом настройки требуется создать следующие условия: + +* Go: >= 1.17 +* Node.js >= 16.13.0 +* Git + + +Кроме того, вам нужно будет клонировать следующие репозитории с версиями для запуска некоторых предложений. + +* [Polygon Edge](https://github.com/0xPolygon/polygon-edge): на ветке `develop` +* [ChainBridge](https://github.com/ChainSafe/ChainBridge): v1.1.5 +* [Инструменты развертывания ChainBridge](https://github.com/ChainSafe/chainbridge-deploy): `f2aa093`на `main` ветке + + +Прежде чем перейти к следующему разделу, необходимо настроить сеть Polygon Edge. Более подробную информацию можно найти в разделах [Локальная настройка](/docs/edge/get-started/set-up-ibft-locally) или [Облачная настройка](/docs/edge/get-started/set-up-ibft-on-the-cloud). \ No newline at end of file diff --git a/archive/edge/ru-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/ru-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..8e583c37f7 --- /dev/null +++ b/archive/edge/ru-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,142 @@ +--- +id: setup-erc20-transfer +title: Трансфер токенов ERC20 +description: Как настроить трансфер токенов ERC-20 в chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +На данный момент мы настроили мост для обмена активами/данными между Polygon PoS и цепочкой Polygon Edge. Этот раздел поможет вам настроить мост ERC20 и отправлять токены между различными блокчейнами. + +## Шаг 1: зарегистрируйте идентификатор ресурса {#step-1-register-resource-id} + +Сначала зарегистрируйте идентификатор ресурса, используемый для ассоциации с ресурсами в среде из нескольких цепочек. Идентификатор ресурса — это 32-байтое значение, которое должно быть уникально для ресурса, который мы передаем между этими блокчейнами. Идентификаторы ресурса являются произвольными значениями, но они могут иметь идентификатор цепочки домашней цепочки в последнем байте в качестве соглашения (домашняя цепочка относится к сети, из которой эти ресурсы были получены). + +Чтобы зарегистрировать идентификатор ресурса, можно использовать команду `cb-sol-cli bridge register-resource`. Вам нужно будет дать приватный ключ для аккаунта `admin`. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (Необязательно) Сделайте контракты с возможностью произвольного минтинга/сжигания {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## Шаг 2: осуществите трансфер токенов ERC20 {#step-2-transfer-erc20-token} + +Мы отправим токены ERC20 из цепочки Polygon PoS в цепочку Polygon Edge. + +Сначала вы получите токены посредством минтинга. Аккаунт с ролью `minter` может генерировать новые токены при помощи минтинга. Аккаунт, в котором был развернут контракт ERC20, имеет по умолчанию роль `minter`. Чтобы указать другие аккаунты в качестве участников роли `minter`, нужно запустить команду `cb-sol-cli erc20 add-minter`. + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +Чтобы проверить текущий остаток, можно использовать команду `cb-sol-cli erc20 balance`. + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +Затем нужно подтвердить трансфер токенов ERC20 с аккаунта при помощи ERC20 Handler + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +Чтобы осуществить трансфер токенов в цепочках Polygon Edge, нужно вызвать `deposit`. + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +После успешного выполнения транзакции депозита ретранслятор получит событие и проголосует за предложение. Он выполняет транзакцию отправки токенов на аккаунт получателя в цепочке Polygon Edge после отправки требуемого количества голосов. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +После успешного выполнения транзакции вы получите токены в цепочке Polygon Edge. + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/ru-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/ru-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..0993ef60cc --- /dev/null +++ b/archive/edge/ru-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,134 @@ +--- +id: setup-erc721-transfer +title: Трансфер NFT ERC721 +description: Как настроить трансфер токенов ERC721 в chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Этот раздел поможет вам настроить мост ERC721 и осуществлять отправку NFT между сетями блокчейн. + +## Шаг 1: зарегистрируйте идентификатор ресурса {#step-1-register-resource-id} + +Сначала вам необходимо зарегистрировать идентификатор ресурса для токенов ERC721 в контрактах Bridge в обеих цепочках. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (Необязательно): сделайте контракты с возможностью произвольного минтинга/сжигания {#optional-make-contracts-mintable-burnable} + +Чтобы сделать токены с возможностью произвольного минтинга/сжигания, вам нужно будет вызвать следующие команды: + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## Шаг 2: осуществите трансфер NFT {#step-2-transfer-nft} + +Сначала получите NFT при помощи минтинга, если вам требуется NFT. + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Чтобы проверить владельца NFT, вы можете использовать `cb-sol-cli erc721 owner` + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Затем необходимо подтвердить трансфер NFT при помощи ERC721 Handler + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Наконец, вы можете запустить процедуру трансфера + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +Ретранслятор получит событие и проголосует за предложение. Он выполняет транзакцию по отправке NFT на аккаунт получателя в цепочке Polygon Edge после отправки требуемого количества голосов. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Вы можете проверить владельца NFT в сети Polygon Edge после того, как исполнение будет завершено. + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/ru-edge/additional-features/chainbridge/setup.md b/archive/edge/ru-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..928e9cf27e --- /dev/null +++ b/archive/edge/ru-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,198 @@ +--- +id: setup +title: Настройка +description: Как настроить chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Развертывание контрактов {#contracts-deployment} + +В этом разделе вы выполните развертывание требуемых контрактов для Polygon PoS и цепочки Polygon Edge с помощью `cb-sol-cli`. + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +Вначале мы выполним развертывание контрактов в цепочке Polygon PoS с помощью команды `cb-sol-cli deploy`. Флаг `--all` указывает команде выполнить развертывание всех контрактов, включая Bridge, ERC20 Handler, ERC721 Handler, Generic Handler, ERC20 и ERC721. Кроме того, он задает адрес аккаунта ретранслятора по умолчанию и предельное значение + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +Подробнее о chainID и JSON-RPC URL см. [здесь](/docs/edge/additional-features/chainbridge/definitions) + +:::caution + +Цена на газ по умолчанию в `cb-sol-cli` составляет `20000000` (`0.02 Gwei`). Чтобы задать правильную цену на газ в транзакции, задавайте значение с помощью аргумента `--gasPrice`. + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +Для развертывания контракта Bridge требуется приблизительно 0x3f97b8 (4167608) газа. Убедитесь, что в генерируемых блоках имеется достаточный лимит газа для транзакции создания контракта. Чтобы узнать больше об изменении лимита газа в блоке Polygon Edge, см. +раздел [Локальная настройка](/docs/edge/get-started/set-up-ibft-locally) + +::: + +После развертывания контрактов вы получите следующий результат: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +Теперь мы можем развернуть контракты в цепочке Polygon Edge. + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Сохраните выводы терминала с развернутыми адресами смарт-контрактов, поскольку они понадобятся нам для следующего шага. + +## Настройка ретранслятора {#relayer-setup} + +В этом разделе вы запустите ретранслятор для обмена данными между 2 цепочками. + +Вначале нам потребуется клонировать и построить репозиторий ChainBridge. + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +Затем вам потребуется создать `config.json` и настроить URL JSON-RPC, адрес ретранслятора и адрес контракта для каждой цепочки. + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +Чтобы запустить ретранслятор, вам нужно будет импортировать приватный ключ, соответствующий адресу аккаунта ретранслятора. Когда вы будете импортировать приватный ключ, вам нужно будет ввести пароль. После успешного импорта ключ будет сохранен в `keys/
.key`. + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +Затем вы сможете запустить ретранслятор. Вам нужно будет ввести тот же пароль, который вы выбрали вначале при сохранении ключа. + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +После запуска ретранслятора он начнет следить за новыми блоками в каждой цепочке. diff --git a/archive/edge/ru-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/ru-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..1c4a239fb4 --- /dev/null +++ b/archive/edge/ru-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,255 @@ +--- +id: use-case-erc20-bridge +title: Сценарий использования — мост ERC20 +description: Пример контракта с мостом ERC20 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +В этом разделе описывается процесс настройки моста ERC20 для практического сценария использования. + +В этом руководстве вы будете использовать тестовую сеть Mumbai Polygon PoS и локальную цепочку Polygon Edge. Убедитесь, что у вас имеется конечная точка JSON-RPC для Mumbai и что вы настроили Polygon Edge в локальной среде. Подробнее см. в разделах [Локальная настройка](/docs/edge/get-started/set-up-ibft-locally) или [Облачная настройка](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +## Сценарий {#scenario} + +Данный сценарий заключается в настройке моста для токена ERC20, развернутого в публичной цепочке (Polygon PoS), для недорогого трансфера в приватную цепочку (Polygon Edge) для пользователей в обычной ситуации. В этом случае общее количество токенов определено в публичной цепочке, а в приватной цепочке должно существовать только то количество токенов, которое передано из публичной цепочки в приватную цепочку. Поэтому вам потребуется использовать режим блокировки/освобождения в публичной цепочке и режим сжигания/минтинга в приватной цепочке. + +При отправке токенов из публичной цепочки в приватную цепочку токен блокируется в контракте ERC20 Handler публичной цепочки, и выполняется минтинг того же количества токенов в приватной цепочке. При трансфере из приватной цепочке в публичную цепочку токен в приватной цепочке сжигается и такое же количество токенов освобождается контрактом ERC20 Handler в публичной цепочке. + +## Контракты {#contracts} + +Разъясним это на примере простого контракта ERC20, а не контракта ChainBridge. Для режима сжигания/минтинга контракт ERC20 должен иметь методы `mint` и `burnFrom` в дополнение к методам ERC20: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +Все коды и скрипты находятся в репозитории Github [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Шаг 1: развертывание контрактов Bridge и ERC20 Handler {#step1-deploy-bridge-and-erc20-handler-contracts} + +Вначале вы развернете контракты Bridge и ERC20Handler с помощью `cb-sol-cli` в обеих цепочках. + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Вы получите адреса контрактов Bridge и ERC20Handler следующим образом: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Шаг 2: развертывание контракта ERC20 {#step2-deploy-your-erc20-contract} + +Вы выполните развертывание вашего контракта ERC20. Этот пример поможет вам с проектом hardhat [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Создайте файл `.env` и задайте следующие значения. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Теперь вы развернете контракт ERC20 в обеих цепочках. + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +После успешного развертывания вы получите адрес контракта, который будет выглядеть вот так: + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## Шаг 3: регистрация идентификатора ресурса в Bridge {#step3-register-resource-id-in-bridge} + +Вы зарегистрируете идентификатор ресурса, используемый для ассоциации с ресурсом в среде нескольких цепочек. Необходимо задать один и тот же идентификатор ресурса в обеих цепочках. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## Шаг 4: настройка режима минтинга/сжигания для моста ERC20 в Edge {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +Ожидается, что мост (контракт Bridge) будет работать как режим сжигания/минтинга в Polygon Edge. Вы зададите режим сжигания/минтинга с помощью .`cb-sol-cli` + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +Также вам нужно будет предоставить роли minter и burner контракту ERC20 Handler. + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Шаг 5: минтинг токена {#step5-mint-token} + +Вы будете производить минтинг новых токенов ERC20 в цепочке Mumbai. + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +После успешного выполнения транзакции в аккунте появится выпущенный токен. + +## Шаг 6: запуск трансфера ERC20 {#step6-start-erc20-transfer} + +Прежде чем приступать к этому шагу, необходимо убедиться, что ретранслятор запущен. Подробнее см. в разделе [Настройка](/docs/edge/additional-features/chainbridge/setup). + +При трансфере токенов из Mumbai в Edge контракт ERC20 Handler в Mumbai выводит токены с вашего аккаунта. До трансфера следует вызвать одобрение. + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +Наконец, вы начнете трансфер токенов из Mumbai в Edge, используя `cb-sol-cli`. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +После успешного выполнения транзакции депозита ретранслятор получит событие и проголосует за предложение. Он выполняет транзакцию отправки токенов в аккаунт получателя в цепочке Polygon Edge после отправки требуемого количества голосов. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +После успешного выполнения транзакции вы получите токены в цепочке Polygon Edge. diff --git a/archive/edge/ru-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/ru-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..c2bcb7eb73 --- /dev/null +++ b/archive/edge/ru-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,307 @@ +--- +id: use-case-erc721-bridge +title: Сценарий использования — ERC721 Bridge +description: Пример для контракта Bridge ERC721 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +В этом разделе описывается процесс настройки Bridge ERC721 для практического сценария использования. + +В этом руководстве вы будете использовать тестовую сеть Mumbai Polygon PoS и локальную цепочку Polygon Edge. Убедитесь, что у вас имеется конечная точка JSON-RPC для Mumbai и что вы настроили Polygon Edge в локальной среде. Подробнее см. в разделах [Локальная настройка](/docs/edge/get-started/set-up-ibft-locally) или [Облачная настройка](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +## Сценарий {#scenario} + +Этот сценарий заключается в создании Bridge для NFT ERC721, который уже развернут в публичной цепочке (Polygon PoS), чтобы обеспечить недорогой трансфер в публичной цепочке (Polygon Edge) для пользователей в обычном случае. В таком случае оригинальные метаданные были определены в публичной цепочке, а в частной цепочке могут существовать только те NFT, которые были переданы из публичной цепочки. Поэтому вам потребуется использовать режим блокировки/освобождения в публичной цепочке и режим сжигания/минтинга в приватной цепочке. + +При отправке токенов NFT из публичной цепочки в приватную цепочку NFT токен блокируется в контракте ERC721 Handler публичной цепочки и выполняется минтинг того же количества токенов NFT в приватной цепочке. При трансфере из приватной цепочки в публичную цепочку NFT токен в приватной цепочке сжигается и такое же количество токенов NFT освобождается контрактом ERC721 Handler в публичной цепочке. + +## Контракты {#contracts} + +Разъясним это на примере простого контракта ERC721, а не контракта ChainBridge. Для режима сжигания/минтинга контракт ERC721 должен иметь методы `mint`и `burn` в дополнение к методам, определенным в ERC721 следующим образом: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +Все коды и скрипты находятся в репозитории Github [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Шаг 1: разверните контракты Bridge и ERC721 Handler {#step1-deploy-bridge-and-erc721-handler-contracts} + +Вначале следует развернуть контракты Bridge и ERC721 Handler с помощью `cb-sol-cli` в обеих цепочках. + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Вы получите адреса контрактов Bridge и ERC721 Handler следующим образом: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Шаг 2: разверните ваш контракт ERC721 {#step2-deploy-your-erc721-contract} + +Вам следует развернуть контракт RC721. Этот пример поможет вам с проектом hardhat [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Создайте файл `.env` и задайте следующие значения. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Затем следует развернуть контракт ERC721 в обеих цепочках. + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +После успешного развертывания вы получите адрес контракта, который будет выглядеть вот так: + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## Шаг 3: регистрация идентификатора ресурса в Bridge {#step3-register-resource-id-in-bridge} + +Вам следует зарегистрировать идентификатор ресурса, используемый для ассоциации с ресурсами в среде из нескольких цепочек. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## Шаг 4: настройте режим минтинга/сжигания для моста ERC721 в Edge {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +Мост должен работать в качестве режима сжигания/минтинга в Edge. Вам следует установить режим сжигания/минтинга. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +А также вам следует предоставить роль того, кто осуществляет минтинг и сжигание, контракту ERC721 Handler. + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Шаг 5: осуществите минтинг NFT {#step5-mint-nft} + +Вам следует осуществить минтинг новых ERC721 NFT в цепочке Mumbai. + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +После успешного выполнения транзакции на аккунте появится выпущенный токен NFT. + +## Шаг 6: запустите трансфер ERC721 {#step6-start-erc721-transfer} + +Прежде чем осуществить этот шаг, убедитесь, что вы запустили ретранслятор. Подробнее см. в разделе [Настройка](/docs/edge/additional-features/chainbridge/setup). + +При трансфере NFT из Mumbai в Edge контракт ERC721 Handler выводит NFT с вашего аккаунта. До трансфера следует вызвать одобрение. + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +Наконец, запустите трансфер NFT из Mumbai в адрес Edge. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +После успешного выполнения транзакции депозита ретранслятор получит событие и проголосует за предложение. Он выполняет транзакцию по отправке NFT в адрес аккаунта получателя в цепочке Polygon Edge после подачи необходимого количества голосов. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +После успешного выполнения транзакции вы получите NFT в цепочке Polygon Edge. diff --git a/archive/edge/ru-edge/additional-features/permission-contract-deployment.md b/archive/edge/ru-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..3d1e9ce69b --- /dev/null +++ b/archive/edge/ru-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,85 @@ +--- +id: permission-contract-deployment +title: Разрешение на развертывание смарт-контрактов +description: Как добавить разрешение на развертывание смарт-контрактов. +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## Обзор {#overview} + +Руководство подробно описывает, как составить белый список адресов, на которых можно развернуть смарт-контракты. Операторы сети иногда хотят предотвратить развертывание пользователями смарт-контрактов, не имеющих отношения к целям сети. Операторы сети могут сделать следующее: + +1. Составить белый список адресов для развертывания смарт-контрактов +2. Удалить адреса из белого списка для развертывания смарт-контрактов + +## Видеопрезентация {#video-presentation} + +[![Развертывание контракта с разрешением - видео](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## Как это использовать? {#how-to-use-it} + + +Вы можете найти все команды cli, связанные с белым списком для развертывания на странице [Команды CLI](/docs/edge/get-started/cli-commands#whitelist-commands). + +* `whitelist show`: отображает информацию о белом списке +* `whitelist deployment --add`: добавляет новый адрес к белому списку для развертывания контрактов +* `whitelist deployment --remove`: удаляет новый адрес из белого списка для развертывания контрактов + +#### Отобразить все адреса из белого списка для развертывания {#show-all-addresses-in-the-deployment-whitelist} + +Существует 2 способа найти адреса из белого списка для развертывания. +1. Посмотреть `genesis.json`, где сохраняются белые списки +2. Выполнить `whitelist show`, что распечатывает информацию для всех белых списков, которые поддерживаются Polygon Edge + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### Добавить адрес в белый список для развертывания {#add-an-address-to-the-deployment-whitelist} + +Чтобы добавить новый адрес в белый список для развертывания, необходимо выполнить `whitelist deployment --add [ADDRESS]`команду CLI. Количество адресов, которые присутствуют в белом списке, не ограничено. Только те адреса, которые присутствуют в белом списке для развертывания, могут развертывать контракты. Если белый список пуст, то любой адрес может выполнять развертывание. + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### Удалить адрес из белого списка для развертывания. {#remove-an-address-from-the-deployment-whitelist} + +Чтобы удалить адрес из белого списка для развертывания, выполните `whitelist deployment --remove [ADDRESS]` команду CLI. Только те адреса, которые присутствуют в белом списке для развертывания, могут развертывать контракты. Если белый список пуст, то любой адрес может выполнять развертывание. + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/ru-edge/architecture/modules/blockchain.md b/archive/edge/ru-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..326920881c --- /dev/null +++ b/archive/edge/ru-edge/architecture/modules/blockchain.md @@ -0,0 +1,160 @@ +--- +id: blockchain +title: Блокчейн +description: Разъяснение по модулям блокчейна и состояния Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## Обзор {#overview} + +Одними из основных модулей Polygon Edge являются модули блокчейна и состояния — **Blockchain** и **State**.
+ +**Blockchain** — это мощный модуль, занимающийся реорганизацией блоков. Он отвечает за всю логику, выполняемую при добавлении нового блока в блокчейн. + +**State** — модуль, отражающий *изменения состояния* объекта. Он обеспечивает изменения состояния при добавлении нового блока.
Помимо прочего, модуль **State** отвечает за следующее: +* Выполнение транзакций +* Выполнение EVM +* Изменение попыток Merkle +* Также он выполняет многие другие задачи, которые описаны в соответствующем разделе **State** 🙂 + +Важно помнить, что эти 2 части тесно связаны и взаимодействуют друг с другом для обеспечения работы клиента.
Например, когда уровень **Blockchain** получает новый блок (без реорганизации), он вызывает **State** для изменения состояния. + +**Blockchain** также отвечает за некоторые задачи, относящиеся к консенсусу (например, *проверяет правильность ethHash*, *правильность PoW*).
Его можно кратко описать **как основное логическое ядро, посредством которого добавляются все блоки**. + +## *WriteBlocks* + +Один из наиболее важных элементов, связанных с уровнем **Blockchain**, — это метод *WriteBlocks*: + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +Метод *WriteBlocks* представляет собой точку входа для записи блоков в блокчейн. Как параметр он принимает диапазон блоков.
+Вначале производится валидация блоков. После этого производится их запись в цепочку. + +Фактическое *изменение состояния* выполняется посредством вызова метода *processBlock* в составе *WriteBlocks*. + +Стоит отметить, что этот метод используют и другие модули (например, **Sealer**), поскольку он является точкой входа для записи блоков в блокчейн. + +## Подписка на блокчейн {#blockchain-subscriptions} + +Обычно необходимо иметь способ отслеживания изменений, связанных с блокчейном.
+Именно здесь вступает в дело модуль подписок **Subscriptions**. + +Подписки — это способ подключиться к потокам событий блокчейна и сразу же получить значимые данные. + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +События блокчейна **Blockchain Events** содержат информацию о любых изменениях, вносимых в цепочку. В их число входят реорганизация и добавление новых блоков: + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip Повторение пройденного + +Помните, как мы рассказывали о команде ***monitor*** в составе [команд CLI](/docs/edge/get-started/cli-commands)? + +События блокчейна (Blockchain Events) — это изначальные события, которые происходят в Polygon Edge, а затем отражаются в формате сообщений Protocol Buffers для удобства передачи. + +::: \ No newline at end of file diff --git a/archive/edge/ru-edge/architecture/modules/consensus.md b/archive/edge/ru-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..efe2dd0f83 --- /dev/null +++ b/archive/edge/ru-edge/architecture/modules/consensus.md @@ -0,0 +1,508 @@ +--- +id: consensus +title: Консенсус +description: Объяснение к модулю консенсуса в Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## Обзор {#overview} + +Модуль **Консенсус** предоставляет интерфейс для механизмов консенсуса. + +В настоящее время доступны следующие механизмы консенсуса: +* **IBFT PoA** +* **IBFT PoS** + +Polygon Edge хочет поддерживать состояние модульности и подключаемости.
+Базовая логика консенсуса абстрагирована, что позволяет строить поверх нее новые механизмы консенсуса без +снижения полезности и удобства использования. + +## Интерфейс консенсуса {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + +Интерфейс ***Консенсуса*** лежит в основе вышеописанного абстрагирования.
+* Метод **VerifyHeader** представляет функцию помощника, которую уровень консенсуса открывает для уровня **блокчейна** +Он отвечает за проверку заголовков +* Метод **Start** просто запускает процесс консенсуса и все, что с ним связано, в том числе синхронизацию, +запечатывание и другие необходимые задачи +* Метод **Close** закрывает соединение консенсуса + +## Конфигурация консенсуса {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +Иногда бывает необходимо передать пользовательское местоположение для хранения данных протоколом консенсуса или пользовательскую карту ключ-значение для использования в механизме консенсуса. Для этого служит структура ***Config***, +которая считывается при создании нового экземпляра консенсуса. + +## IBFT {#ibft} + +### ExtraData {#extradata} + +Объект заголовка блокчейна имеет много полей, в том числе и поле **ExtraData**. + +IBFT использует это дополнительное поле для хранения операционной информации о блоке, позволяющей ответить на такие вопросы, как: +* «Кто подписал этот блок?» +* «Кто отвечает за валидацию этого блока?» + +Эти дополнительные поля для IBFT определяются следующим образом: +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### Подписание данных {#signing-data} + +Чтобы нод мог подписать информацию в IBFT, он использует метод *signHash*: +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +Также стоит отметить метод *VerifyCommittedFields*, подтверждающий, что поставленные печати поступили от корректных валидаторов: +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### Снимки {#snapshots} + +Snapshots создают *снимки* или отпечатки *состояния* системы при любой высоте блока (число). + +Снимки содержат набор нодов, которые являются валидаторами, а также информацию о голосовании (валидаторы могут голосовать за других валидаторов). +Валидаторы включают информацию о голосовании в поле заголовка **Miner** и меняют значение **nonce**: +* Nonce состоит из **всех единиц**, если нод хочет удалить валидатор +* Nonce состоит из **всех нулей**, если нод хочет добавить валидатор + +Расчет Snapshots производится с использованием метода ***processHeaders***: + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +Этот метод обычно вызывается с 1 заголовком, но при этом используется тот же процесс, что и при наличии нескольких заголовков.
+Для каждого переданного заголовка IBFT необходимо подтвердить, что автор предложения заголовка является валидатором. Для этого можно легко +использовать самый актуальный снимок и проверить, включен ли нод в набор валидаторов. + +После этого выполняется проверка nonce. Голос включается и учитывается, а при наличии достаточного количества голосов нод добавляется/удаляется из набора валидаторов, после чего сохраняется новый снимок. + +#### Хранилище снимков {#snapshot-store} + +Сервис снимков управляет хранилищем **snapshotStore**, которое хранит список всех доступных снимков, и обновляет его. +Используя его, сервис может быстро определить, какой снимок связан с какой высотой блока. +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### Запуск IBFT {#ibft-startup} + +Для запуска IBFT Polygon Edge требуется предварительно настроить транспорт IBFT: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +При этом создается новая тема с прототипом IBFT с новым сообщением поддержки прототипа.
+Сообщения предназначены для использвоания валидаторами. Затем Polygon Edge подписывается на тему и обрабатывает сообщения соответствующим образом. + +#### MessageReq {#messagereq} + +Валидаторы обмениваются сообщениями: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +Поле **View** в **MessageReq** показывает текущую позицию нода внутри цепочки. +У него имеются атрибуты *round* и *sequence*. +* **round** представляет раунд автора предложения для высоты +* **sequence** представляет высоту блокчейна + +Очередь *msgQueue* в реализации IBFT предназначена для хранения запросов сообщений. Она упорядочивает сообщения по параметру *View* (вначале используя критерий sequence, а затем критерий round). Реализация IBFT имеет разные очереди для разных состояний системы. + +### Состояния IBFT {#ibft-states} + +После запуска механизма консенсуса с помощью метода **Start** он входит в бесконечный цикл, моделирующий машину состояния: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### SyncState {#syncstate} + +Все ноды первоначально запускаются в состоянии **Sync**. + +Это связано с необходимостью доставки из блокчейна свежих данных. Клиенту нужно определить, является ли он валидатором, +найти актуальный снимок. Это состояние обрабатывает все блоки в состоянии ожидания. + +После завершения синхронизации, когда клиент определяет, что является валидатором, ему необходимо перейти в состояние **AcceptState**. +Если клиент **не** является валидатором, он продолжит синхронизацию и останется в состоянии **SyncState** + +#### AcceptState {#acceptstate} + +Состояние **Accept** проверяет снимки и набор валидаторов. Если текущий нод не входит в набор валидаторов, +он возвращается в состояние **Sync**. + +Если же нод **является** валидатором, он рассчитывает автора предложения. Если оказывается, что текущий нод является автором предложения, он строит блок и отправляет сообщения предварительной подготовки и подготовки. + +* Сообщения предварительной подготовки отправляются авторами предложений валидаторам, чтобы сообщить им о предложении +* Сообщения подготовки — это сообщения, в которых валидаторы соглашаются с предложением. Все ноды получают все сообщения подготовки +* Сообщения записи (Commit) содержат информацию о реализации предложения + +Если текущий нод **не является** валидатором, он использует метод *getNextMessage* для чтения сообщения из ранее показанной очереди.
+Он ожидает сообщения предварительной подготовки. Когда нод подтвердит, что все правильно, он переходит в состояние **Validate**. + +#### ValidateState {#validatestate} + +Состояние **Validate** довольно простое: в этом состоянии ноды просто читают сообщения и добавляют их в состояние локального снимка. diff --git a/archive/edge/ru-edge/architecture/modules/json-rpc.md b/archive/edge/ru-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..0d8b93db42 --- /dev/null +++ b/archive/edge/ru-edge/architecture/modules/json-rpc.md @@ -0,0 +1,180 @@ +--- +id: json-rpc +title: JSON RPC +description: Объяснение к модулю JSON RPC в Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## Обзор {#overview} + +Модуль **JSON RPC** реализует **уровень JSON RPC API**, который разработчики децентрализованных приложений используют для взаимодействия с +блокчейном. + +Он включает поддержку стандартных **[конечных точек json-rpc](https://eth.wiki/json-rpc/API)** и +конечных точек websocket. + +## Интерфейс блокчейна {#blockchain-interface} + +Polygon Edge использует ***интерфейс блокчейна*** для определения всех методов, которые требуются модулю JSON RPC для +доставки его конечных точек. + +Интерфейс блокчейна реализуется сервером **[Minimal](/docs/edge/architecture/modules/minimal)**. Это базовая реализация, которая передается на уровень JSON RPC. + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## Конечные точки ETH {#eth-endpoints} + +Все стандартные конечные точки JSON RPC реализованы в сервисе: + +````bash +jsonrpc/eth_endpoint.go +```` + +## Диспетчер фильтров {#filter-manager} + +Сервис диспетчера фильтров **Filter Manager** работает вместе с сервером JSON RPC. + +Он обеспечивает поддержку фильтрации блоков в блокчейне.
+В частности, он включает фильтры уровня **журнала** и уровня **блоков**. + +Диспетчер фильтров активно использует события подписки, описанные в +разделе [Блокчейн](blockchain#blockchain-subscriptions) + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +Для обработки событий Диспетчера фильтров используется метод *Run*: + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## 📜 Ресурсы {#resources} +* **[Ethereum JSON-RPC](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/ru-edge/architecture/modules/minimal.md b/archive/edge/ru-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..1eaea8a852 --- /dev/null +++ b/archive/edge/ru-edge/architecture/modules/minimal.md @@ -0,0 +1,117 @@ +--- +id: minimal +title: Модуль минимальный +description: Объяснение к минимальному модулю Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## Обзор {#overview} + +Как было указано ранее, Polygon Edge это набор различных модулей, которые связаны между собой.
**Блокчейн** подключается к **Состоянию**, или, например, к **Синхронизации**, что осуществляет подключение новых блоков в **Блокчейн**. + +**Минимальный** — это краеугольный камень для этих соединенных модулей.
Он действует в качестве центрального хаба для всех сервисов, которые работают на Polygon Edge. + +## Волшебство запуска {#startup-magic} + +Помимо всего прочего, модуль минимальный отвечает за следующее: +* Настройка каталогов данных +* Создание хранилища ключей для взаимодействия с libp2p +* Создание хранилища +* Настройка консенсуса +* Настройка объекта блокчейна с помощью GRPC, JSON RPC и синхронизации + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/ru-edge/architecture/modules/networking.md b/archive/edge/ru-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..44c29f5f80 --- /dev/null +++ b/archive/edge/ru-edge/architecture/modules/networking.md @@ -0,0 +1,73 @@ +--- +id: networking +title: Сетевое взаимодействие +description: Объяснение к модулю сетевого взаимодействия Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## Обзор {#overview} + +Нод должен общаться с другими нодами в сети, чтобы обмениваться полезной информацией.
Чтобы выполнить эту задачу, Polygon Edge использует проверенную инфраструктуру **libp2p**. + +Выбор в пользу **libp2p** в первую очередь обусловлен: +* **Скоростью** — libp2p имеет значительное улучшение производительности по сравнению с devp2p (используется в GETH и у других клиентов) +* **Расширяемостью** — этот фрейм служит отличной основой для других возможностей системы +* **Модульностью** — libp2p имеет модульную природу, так же как и Polygon Edge. Это обеспечивает большую гибкость, особенно когда части Polygon Edge должны быть сменными + +## GRPC {#grpc} + +Помимо **libp2p** Polygon Edge использует протокол **GRPC**.
Технически Polygon Edge использует несколько протоколов GRPC, о которых более подробно будет изложено далее. + +Уровень GRPC помогает абстрагироваться от всех протоколов запроса/ответа и упрощает потоковые протоколы, которые необходимы для функционирования Polygon Edge. + +GRPC полагается на **буферы протоколов** для определения *сервисов* и *структур сообщения*.
Сервисы и структуры определены в файлах *.proto*, которые скомпилированы и не зависят от языка. + +Ранее мы упоминали, что Polygon Edge использует несколько протоколов GRPC.
Это было сделано для увеличения общего UX для оператора нодов, который часто отстает от таких клиентов, как GETH и Parity. + +Оператор нодов получает более полное представление о том, что происходит с системой, обращаясь сервису GRPC, вместо того чтобы пролистывать журналы в поисках нужной информации. + +### GRPC для операторов нодов {#grpc-for-node-operators} + +Данный раздел может показаться знакомым, поскольку он был кратко освещен в разделе [Команды CLI](/docs/edge/get-started/cli-commands). + +Сервис GRPC, который предназначен для использования **операторами нодов**, определяется следующим образом: +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip +Команды CLI фактически вызывают применение этих сервисных методов. + +Эти методы реализованы в ***minimal/system_service.go***. +::: + +### GRPC для других нодов {#grpc-for-other-nodes} + +Polygon Edge также реализует несколько сервисных методов, которые используются другими нодами в сети.
Указанный сервис описан в разделе **[Протокол](docs/edge/architecture/modules/consensus)**. + +## 📜 Ресурсы {#resources} +* **[Буферы протоколов](https://developers.google.com/protocol-buffers)** +* **[libp2p](https://libp2p.io/)** +* **[GRPC](https://grpc.io/)** diff --git a/archive/edge/ru-edge/architecture/modules/other-modules.md b/archive/edge/ru-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..94f9eda1cf --- /dev/null +++ b/archive/edge/ru-edge/architecture/modules/other-modules.md @@ -0,0 +1,36 @@ +--- +id: other-modules +title: Другие модули +description: Объяснение к некоторым модулям Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## Крипто {#crypto} + +Модуль **Крипто** содержит функции криптоутилиты. + +## Цепочка {#chain} + +Модуль **Цепочка** содержит параметры цепочки (активные параллельные ответвления, механизм консенсуса и т. д.) + +* **цепочки** — предопределенные конфигурации цепочек (mainnet, goerli, ibft) + +## Помощник {#helper} + +Модуль **Помощник** содержит пакеты с помощниками. + +* **dao** — утилиты Dao +* **enode** — функция кодирования/декодирования Enode +* **hex** — функции кодирования/декодирования Hex +* **ipc** — функции подключения IPC +* **keccak** — функции Keccak +* **rlputil** — функция помощников кодирования/декодирования Rlp + +## Команда {#command} + +Модуль **Команда** содержит интерфейсы для команд CLI. \ No newline at end of file diff --git a/archive/edge/ru-edge/architecture/modules/sealer.md b/archive/edge/ru-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..977cc01d2a --- /dev/null +++ b/archive/edge/ru-edge/architecture/modules/sealer.md @@ -0,0 +1,73 @@ +--- +id: sealer +title: Sealer +description: Объяснение к модулю Sealer в Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## Обзор {#overview} + +Модуль **Sealer** — это сущность, которая собирает транзакции и создает новый блок.
+Затем этот блок отправляется в **Consensus** для запечатывания. + +Заключительная логика запечатывания находится в модуле **Consensus**. + +## Запустить метод {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution Выполняется работа + +Модули **Sealer** и **Consensus** в будущем будут объединены в единую сущность. + +Новый модуль будет содержать модульную логику для разных механизмов консенсуса, требующих разные варианты реализации запечатывания: +* **PoS** (доказательство стейка) +* **PoA** (доказательство полномочий) + +В настоящее время модули **Sealer** и **Consensus** работают с PoW (доказательство работы). + +::: \ No newline at end of file diff --git a/archive/edge/ru-edge/architecture/modules/state.md b/archive/edge/ru-edge/architecture/modules/state.md new file mode 100644 index 0000000000..9d05b41426 --- /dev/null +++ b/archive/edge/ru-edge/architecture/modules/state.md @@ -0,0 +1,240 @@ +--- +id: state +title: Состояние +description: Объяснение к модулю состояния Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +Чтобы действительно понять, как работает **Состояние**, вам нужно понять базовые концепции Ethereum.
+ +Мы настоятельно рекомендуем прочитать раздел **[Состояние в руководстве по Ethereum](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)**. + +## Обзор {#overview} + +Теперь, когда мы ознакомились с базовыми концепциями Ethereum, вы легко должны понять следующий обзор. + +Мы упомянули, что в **Мировом дереве Меркла для системы состояний** находятся все существующие аккаунты Ethereum.
Эти аккаунты являются листьями дерева Меркла. Каждый лист имеет закодированную информацию **о состоянии аккаунта**. + +Это позволяет Polygon Edge получить определенное дерево Меркла для определенного момента времени.
Например, мы можем получить хеш состояния на блоке 10. + +Дерево Меркла в любой момент времени называется ***Снимок***. + +Мы можем иметь ***снимки*** для **дерева состояний** или для **дерева хранения** — они в основном одинаковы.
Единственное отличие заключается в том, что представляют собой листья: + +* У дерева хранения листья содержат произвольное состояние, которое мы не можем обработать или узнать, что там находится. +* У дерева состояний листья представляют собой аккаунты + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + +Интерфейс **Снимка** определяется следующим образом: + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +Информация, которая может быть зафиксирована, определяется *Структурой объекта*: + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +Реализация для дерева Меркла находится в папке *state/immutable-trie*.
*state/immutable-trie/state.go* реализует Интерфейс **состояния**. + +*state/immutable-trie/trie.go* — основной объект дерева Меркла. Он представляет собой оптимизированную версию дерева Меркла, которая повторно использует как можно больше памяти. + +## Исполнитель {#executor} + +*state/executor.go* включает всю информацию, необходимую Polygon Edge для решения того, как блок меняет текущее состояние. Реализация *ProcessBlock* находится здесь. + +Метод *apply* выполняет фактический переход состояний. Исполнитель вызывает EVM. + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## Время выполнения {#runtime} + +При выполнении перехода состояний основной модуль, выполняющий переход состояний, — это EVM (он расположен в state/runtime/evm). + +**Таблица диспетчеризации** выполняет проверку соответствия между **opcode** и инструкцией. + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +Основу логики, которая обеспечивает работу EVM, составляет цикл *Run*.
+ +Это основной пункт входа для EVM. Он выполняет цикл и проверяет текущий opcode, извлекает инструкцию, проверяет, может ли она быть выполнена, потребляет газ и выполняет инструкцию до тех пор, пока не произойдет сбой или остановка. + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/ru-edge/architecture/modules/storage.md b/archive/edge/ru-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..7a672e784d --- /dev/null +++ b/archive/edge/ru-edge/architecture/modules/storage.md @@ -0,0 +1,117 @@ +--- +id: storage +title: Хранение +description: Объяснение к модулю хранения Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## Обзор {#overview} + +Для хранения данных Polygon Edge использует **LevelDB**, а также систему хранения данных **в оперативной памяти**. + +Когда модулям Polygon Edge требуется взаимодействовать с внутренним хранилищем данных, им не нужно знать, с какой СУБД или каким сервисом они взаимодействуют. + +Уровень БД полностью абстрагирован через модуль хранения **Storage**, который экспортирует запрашиваемые модулями интерфейсы. + +Этим методы реализованы отдельно для каждого уровня БД (сейчас только **LevelDB**), что обеспечивает их полную совместимость с реализацией. + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### Префиксы {#prefixes} + +Для поддержки детерминистских запросов хранения LevelDB и предотвращения конфликтов ключевых систем хранения Polygon Edge использует +префиксы и субпрефиксы при сохранении данных + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## Планы на будущее {#future-plans} + +В ближайшем будущем планируется добавить поддержку некоторых из самых популярных решений БД, в том числе: +* PostgreSQL +* MySQL + + +## 📜 Ресурсы {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/ru-edge/architecture/modules/syncer.md b/archive/edge/ru-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..7b1f1752d9 --- /dev/null +++ b/archive/edge/ru-edge/architecture/modules/syncer.md @@ -0,0 +1,68 @@ +--- +id: syncer +title: Syncer +description: Объяснение к модулю Syncer в Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## Обзор {#overview} + +Это модуль содержит логику для протокола синхронизации. Он используется для синхронизации нового нода с работающей сетью или для валидации и вставки новых блоков для нодов, которые не участвуют в консенсусе (не валидаторы). + +Polygon Edge использует **libp2p** как сетевой уровень, а поверх него используется **gRPC**. + +В Polygon Edge есть 2 типа синхронизации: +* Bulk Sync — синхронизация большого количества блоков за раз +* Watch Sync — синхронизация по отдельным блокам + +### Bulk Sync {#bulk-sync} + +Шаги процедуры Bulk Sync простые и предназначены для достижения цели процедуры Bulk Sync — синхронизировать как можно больше блоков (доступных) от других узлов для максимального быстрой актуализации. + +Выполнение процесса Bulk Sync выглядит так: + +1. ** Определить, требуется ли ноду синхронизация Bulk Sync **: на этом шаге нод проверяет карту узлов, чтобы определить, существуют ли другие ноды с большим количеством блоков, чем у этого нода (локально) +2. ** Найти лучший нод (используя карту синхронизации узлов) **: на этом шаге нод находит лучший узел для синхронизации, основываясь на критериях, указанных в примере выше. +3. ** Открыть поток массовой синхронизации **: на этом шаге нод открывает поток gRPC для лучшего узла для пакетной синхронизации блоков с общим количеством блоков +4. ** Лучший узел закрывает поток после завершения массовой отправки**: на этом шаге лучший узел, с которым нод выполняет синхронизацию, закрывает поток после отправки всех доступных на нем блоков +5. ** После завершения пакетной синхронизации следует проверить, является ли нод валидатором **: на этом шаге лучший узел закрывает поток, и нод проверяет, является ли он валидатором после пакетной синхронизации. + * Если нод становится валидатором, он выходит из состояния синхронизации и начинает участвовать в консенсусе + * Если нет, они продолжают участвовать в синхронизации ** Watch Sync ** + +### Watch Sync {#watch-sync} + +:::info + +Шаг синхронизации Watch Sync выполняется, только если нод не является валидатором, а является обычным нодом сети, который прослушивает поступающие блоки. + +::: + +Процедура Watch Sync допольно простая, поскольку нод уже синхронизирован с остальной сетью и ему нужно только обрабатывать новые поступающие блоки. + +Это шаги, из которых состоит процесс Watch Sync: + +1. ** Добавьте новый блок при обновлении статуса узла **: на этом шаге ноды прослушивают новые события блоков, а при поступлении нового блока он вызывает функцию gRPC, получает блок и обновляет локальное состояние. +2. ** После синхронизации последнего блока проверьте, является ли нод валидатором ** + * Если да, он выводится из состояния синхронизации + * Если нет, он продолжает прослушивать новые события блока + +## Отчет о производительности {#perfomance-report} + +:::info + +Измерение производительности производилось на локальном компьютере посредством синхронизации ** миллиона блоков ** + +::: + +| Название | Результат | +|----------------------|----------------| +| Синхронизация 1 млн блоков | ~ 25 мин | +| Передача 1 млн блоков | ~ 1 мин | +| Количество вызовов GRPC | 2 | +| Охват теста | ~ 93% | \ No newline at end of file diff --git a/archive/edge/ru-edge/architecture/modules/txpool.md b/archive/edge/ru-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..74750d3cff --- /dev/null +++ b/archive/edge/ru-edge/architecture/modules/txpool.md @@ -0,0 +1,222 @@ +--- +id: txpool +title: TxPool +description: Объяснение к модулю TxPool в Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## Обзор {#overview} + +Модуль TxPool представляет собой реализацию пула транзакций, в который транзакции добавляются из различных частей системы. Модуль также предоставляет несколько полезных функций для операторов нодов, которые описаны ниже. + +## Команды оператора {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +Операторы нодов могут запрашивать эти конечные точки GRPC, как описано в разделе **[Команды CLI](/docs/edge/get-started/cli-commands#transaction-pool-commands)**. + +## Обработка транзакций {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +Метод ***addImpl*** — это то, с чем работает модуль **TxPool**. Это то место, где в систему добавляются транзакции, которые вызываются из сервиса GRPC, конечных точек JSON RPC, каждый раз, когда клиент получает транзакцию через протокол **gossip**. + +Он принимает в качестве аргумента **ctx**, который просто обозначает контекст, из которого добавляются транзакции (GRPC, JSON RPC...)
. Другим параметром является список транзакций, которые должны быть добавлены в пул. + +Главное, на что следует обратить внимание, — это проверка поля **От** в транзакции: +* Если поле **От** **пустое**, транзакция считается незашифрованной/неподписанной. Эти виды транзакций можно принимать лишь в рамках режима разработки +* Если поле **От** **не пусто**, это означает, что это подписанная транзакция, и поэтому осуществляется верификация подписи + +После проведения всех проверок транзакции считаются действительными. + +## Структуры данных {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +Поля в объекте TxPool, которые могут вызвать путаницу, — это **очередь** и **отсортированные** списки. +* **очередь** — это массовая реализация отсортированного списка транзакций аккаунта (по случайному одноразовому числу) +* **отсортированный** — отсортированный список для всех текущих продвигаемых транзакций (всех исполняемых транзакций). Отсортированный по цене на газ + +## Управление ошибками предельного уровня газа {#gas-limit-error-management} + +Когда вы отправляете транзакцию, существует три способа ее обработки в TxPool. + +1. Все отложенные транзакции могут вписываться в блок +2. Одна или несколько отложенных транзакций не могут вписываться в блок +3. Одна или несколько отложенных транзакций никогда не вписываются в блок + +Здесь слово **_вписываться_** означает, что транзакция имеет лимит газа, который ниже, чем уровень газа, который остается в TxPool. + +Первый сценарий не приводит к возникновению ошибки. + +### Второй сценарий {#second-scenario} + +- Уровень оставшегося газа в TxPool устанавливается в качестве предельного уровня газа в последнем блоке, допустим **5000** +- Первая транзакция обрабатывается и потребляет **3000** газа из TxPool + - Оставшийся уровень газа в TxPool составляет сейчас **2000** +- Затем подается вторая транзакция, которая является такой же, как и первая: они обе потребляют 3000 газа +- Поскольку уровень оставшегося газа в TxPool сейчас **ниже**, чем газ в транзакциях, ее невозможно обработать в текущем блоке + - Она возвращается в очередь транзакций для того, чтобы ее можно было обработать в следующем блоке +- Первый блок написан, назовем его **блок №1** +- Уровень оставшегося газа в TxPool устанавливается в качестве предельного уровня газа родительского блока, а именно **блока №1** +- Транзакция, которая была возвращена в очередь отложенных транзакций в TxPool, теперь обрабатывается и записывается в блок + - Оставшийся уровень газа в TxPool составляет сейчас **2000** +- Второй блок написан +- ... + +![Сценарий ошибки TxPool №1](/img/edge/txpool-error-1.png) + +### Третий сценарий {#third-scenario} +- Уровень оставшегося газа в TxPool устанавливается в качестве предельного уровня газа в последнем блоке, допустим **5000** +- Первая транзакция обрабатывается и потребляет **3000** газа из TxPool + - Оставшийся уровень газа в TxPool составляет сейчас **2000** +- Подается вторая транзакция с уровнем газа в размере **6000** +- Поскольку лимит газа **ниже**, чем газ в транзакции, эта транзакция отбрасывается + - Она никогда не сможет вписаться в блок +- Первый блок написан +- ... + + +![Сценарий ошибки TxPool №2](/img/edge/txpool-error-2.png) + +> Этот сценарий происходит, когда вы получаете следующую ошибку: +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## Целевой показатель газа для блоков {#block-gas-target} + +Существуют ситуации, когда ноды хотят держать лимит газа ниже или на определенном целевом показателе в работающей цепочке. + +Оператор нода может установить целевой показатель предельного уровня газа на определенный нод, который попытается применить этот предельный уровень к вновь созданным блокам. Если большинство других нодов также имеют аналогичный (или такой же) целевой показатель предельного уровня газа, то лимит газа для блоков будет всегда находиться около этого целевого показателя газа для блоков, медленно продвигаясь к нему (по максимуму `1/1024 * parent block gas limit`) по мере создания новых блоков. + +### Пример сценария {#example-scenario} + +* Оператор нода устанавливает лимит газа для одиночного нода на уровне `5000` +* Другие ноды также настроены на уровне `5000`, кроме одиночного нода, который настроен на уровне `7000` +* Когда ноды, для которых настроен целевой показатель уровня газа в размере `5000`, станут авторами предложения, они будут проверять, не достигнут ли уже целевой показатель предельного уровня газа +* Если лимит газа не достиг целевого показателя (он выше или ниже), предлагающий нод установит целевой показатель газа для блоков на наивысший уровень (1/1024 *родительский лимит газа) в направлении целевого показателя + 1. Например: `parentGasLimit = 4500`и `blockGasTarget = 5000`, автор предложения рассчитает лимит газа для нового блока на уровне `4504.39453125` (`4500/1024 + 4500`) + 2. Например: `parentGasLimit = 5500`и `blockGasTarget = 5000`, автор предложения рассчитает лимит газа для нового блока на уровне `5494.62890625` (`5500 - 5500/1024`) +* Это обеспечивает сохранение лимита газа для блоков в цепочке на целевом уровне, поскольку единичный автор предложения, у которого целевой показатель установлен на `7000`, не может сильно продвинуть предельный уровень, а большинство нодов, у которых он установлен на уровне `5000`, всегда будут пытаться сохранить его на том значении \ No newline at end of file diff --git a/archive/edge/ru-edge/architecture/modules/types.md b/archive/edge/ru-edge/architecture/modules/types.md new file mode 100644 index 0000000000..94d406c56a --- /dev/null +++ b/archive/edge/ru-edge/architecture/modules/types.md @@ -0,0 +1,41 @@ +--- +id: types +title: Типы +description: Объяснение к модулю типов в Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## Обзор {#overview} + +Модуль **Типы** реализует основные типы объектов, в том числе: + +* **Адрес** +* **Hash** +* **Header** +* множество функций помощника + +## Кодирование/декодирование RLP {#rlp-encoding-decoding} + +В отличие от таких клиентов, как GETH, Polygon Edge не использует отражение для шифрования.
+Отказ от использования отражения вызван тем, что оно создает новые проблемы, такие как снижение производительности и затруднение масштабирования. + +Модуль **Типы** предоставляет удобный интерфейс для маршализации и демаршализации RLP с использованием пакета FastRLP. + +Маршализация выполняется с помощью методов *MarshalRLPWith* и *MarshalRLPTo*. Аналогичные методы существуют и для демаршализации. + +Благодаря определению этих методов вручную Polygon Edge не требуется использовать отражения. В *rlp_marshal.go* можно найти +методы маршализации: + +* **Bodies** +* **Blocks** +* **Headers** +* **Receipts** +* **Logs** +* **Transactions** \ No newline at end of file diff --git a/archive/edge/ru-edge/architecture/overview.md b/archive/edge/ru-edge/architecture/overview.md new file mode 100644 index 0000000000..fc4bf03771 --- /dev/null +++ b/archive/edge/ru-edge/architecture/overview.md @@ -0,0 +1,59 @@ +--- +id: overview +title: Обзор архитектуры +sidebar_label: Overview +description: Введение в архитектуру Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +Мы начали с идеи создания программного обеспечения, которое будет *модульным*. + +Эта концепция присутствует практически во всех частях Polygon Edge. Ниже вы найдете краткий обзор построенной архитектуры и ее уровней. + +## Уровни Polygon Edge {#polygon-edge-layering} + +![Архитектура Polygon Edge](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +Все начинается с базового уровня сети, который использует **libp2p**. Мы выбрали эту технологию, потому что она вписывается в философию дизайна Polygon Edge. Libp2p имеет следующие преимущества: + +- Модульная +- Расширяемая +- Быстрая + +Более того, она дает отличный фундамент для более сложных функций, о которых мы расскажем позднее. + + +## Синхронизация и консенсус {#synchronization-consensus} +Разделение протоколов синхронизации и консенсуса обеспечивает модульность и возможность реализации **пользовательских** механизмов синхронизации и консенсуса в зависимости от того, как запускается клиент. + +Polygon Edge предназначается для предоставления подключаемых алгоритмов консенсуса. + +Текущий список поддерживаемых алгоритмов консенсуса: + +* IBFT PoA +* IBFT PoS + +## Блокчейн {#blockchain} +Уровень блокчейна — это центральный уровень, координирующий все, что происходит в системе Polygon Edge. Он подробно описывается в соответствующем разделе *Модули*. + +## Состояние {#state} +Внутренний уровень состояния содержит логику изменения состояния. Он обеспечивает изменения состояния при добавлении нового блока. Он подробно описывается в соответствующем разделе *Модули*. + +## JSON RPC {#json-rpc} +Уровень JSON RPC — это уровень API, используемый разработчиками децентрализованных приложений для взаимодействия с блокчейном. Он подробно описывается в соответствующем разделе *Модули*. + +## TxPool {#txpool} +Уровень TxPool представляет пул транзакций и тесно связан с другими модулями в системе, поскольку транзакции могут добавляться из нескольких точек входа. + +## grpc {#grpc} +gRPC, или вызов удаленного режима Google — это надежный RPC с открытым исходным кодом, который Google изначально создал для создания масштабируемых и быстрых API. Уровень GRPC жизненно необходим для взаимодействия с оператором. Благодаря ему операторы нодов могут легко взаимодействовать с клиентом, что обеспечивает удобство UX. diff --git a/archive/edge/ru-edge/community/propose-new-feature.md b/archive/edge/ru-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..132b6d63c3 --- /dev/null +++ b/archive/edge/ru-edge/community/propose-new-feature.md @@ -0,0 +1,59 @@ +--- +id: propose-new-feature +title: Предложение новой функции +description: "Шаблон PR и инструкции по предложению новой функции." +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## Обзор {#overview} + +Если вы хотите включить исправление или просто внести добавление в код, мы настоятельно вам рекомендуем сначала связаться с командой.
Polygon Edge использует относительно простой шаблон для предложения функций, лаконичный и понятный. + +## Шаблон PR {#pr-template} + +### Описание {#description} + +Просим вас представить подробное описание того, что было сделано в этом PR + +### Изменения включают {#changes-include} + +- [ ]Bugfix (изменение, которое не ломает структуру, но при этом решает проблему) +- [ ]Hotfix (изменение, которое решает срочную проблему и требует немедленного внимания) +- [ ]Новая функция (изменение, которое не ломает структуру, но при этом добавляет функциональность) +- [ ]Серьезное изменение (изменение, которое не является обратно-совместимым и/или изменяет текущую функциональность) + +### Серьезные изменения {#breaking-changes} + +Заполните этот раздел, если были сделаны серьезные изменения, в противном случае удалите его + +### Контрольный список {#checklist} + +- [ ]Я поручил этот PR себе +- [ ]Я добавил не менее 1 рецензента +- [ ]Я добавил соответствующие ярлыки +- [ ]Я обновил официальную документацию +- [ ]Я добавил достаточную документацию в код + +### Тестирование {#testing} + +- [ ]Я протестировал этот код с помощью официального пакета тестов +- [ ]Я проверил этот код вручную + +## Тесты вручную {#manual-tests} + +Заполните этот раздел, если вы выполнили тесты для этой функциональности вручную, в противном случае удалите его + +### Обновление документации {#documentation-update} + +Просим вас разместить ссылку на PR обновления документации в этом разделе, если такая ссылка существует, в противном случае удалите этот раздел. + +### Дополнительные комментарии {#additional-comments} + +Просим вас оставить дополнительные комментарии в этом разделе, если они у вас есть, в противном случае удалите этот раздел \ No newline at end of file diff --git a/archive/edge/ru-edge/community/report-bug.md b/archive/edge/ru-edge/community/report-bug.md new file mode 100644 index 0000000000..0726f9b5e0 --- /dev/null +++ b/archive/edge/ru-edge/community/report-bug.md @@ -0,0 +1,55 @@ +--- +id: report-bug +title: Как сообщить о проблеме +description: Шаблон и инструкции по сообщениям о проблемах с Polygon Edge. +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## Обзор {#overview} + +Иногда вещи ломаются.
+Всегда лучше рассказать команде о проблемах, с которыми вы сталкиваетесь.
+На странице Polygon Edge на GitHub вы можете зарегистрировать новую проблему и начать ее обсуждение с командой. + +## Шаблон проблемы {#issue-template} + +## [Тема проблемы] + +### Описание {#description} + +Опишите свою проблему как можно подробнее здесь + +### Ваша среда {#your-environment} + +* ОС и версия +* версия Polygon Edge +* ответвление, вызывающее проблему + +### Шаги для воспроизведения {#steps-to-reproduce} + +* Расскажите нам, как воспроизвести эту проблему
+* Где наблюдается проблема, если вы это знаете
+* Какие команды вызывают проблему, если ее вызывают команды + +### Ожидаемое поведение {#expected-behaviour} + +Расскажите, что должно проиcходить + +### Фактическое поведение {#actual-behaviour} + +Расскажите, что произошло на самом деле + +### Журналы {#logs} + +Вставьте сюда любые журналы, показывающие проблему, если у вас они есть + +### Предлагаемое решение {#proposed-solution} + +Если у вас есть идея относительно исправления проблемы, напишите ее здесь, чтобы мы могли начать ее обсуждение \ No newline at end of file diff --git a/archive/edge/ru-edge/configuration/manage-private-keys.md b/archive/edge/ru-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..66319c196e --- /dev/null +++ b/archive/edge/ru-edge/configuration/manage-private-keys.md @@ -0,0 +1,68 @@ +--- +id: manage-private-keys +title: Управление приватными ключами +description: "Как управлять приватными ключами, и какие типы ключей существуют." +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## Обзор {#overview} + +В Polygon Edge существуют два типа приватных ключей, которыми он непосредственно управляет: + +* **Приватный ключ для механизма консенсуса** +* **Приватный ключ для сетевого взаимодействия в рамках libp2p** +* **(Необязательно) Приватный ключ BLS для механизма консенсуса, чтобы объединить подписи валидаторов** + +В настоящее время Polygon Edge не предлагает поддержку прямого управления аккаунтом. + +Основываясь на структуре директории, описанной в [Руководстве по резервному копированию и восстановлению](/docs/edge/working-with-node/backup-restore), Polygon Edge хранит эти упомянутые ключевые файлы в двух разных директориях — **консенсусе** и **хранилище ключей**. + +## Формат ключа {#key-format} + +Приватные ключи хранятся в простом **формате Base64**, поэтому они могут быть доступными для человеческого понимания и переносимыми. + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info Тип ключа +Все файлы с приватными ключами генерируются и используются в Polygon Edge полагаются на ECDSA с кривой [secp256k1](https://en.bitcoin.it/wiki/Secp256k1). + +Поскольку кривая нестандартна, ее нельзя закодировать и хранить в любом стандартизированном формате PEM. Импорт ключей, не соответствующих этому типу ключей, не поддерживается. +::: +## Приватный ключ консенсуса {#consensus-private-key} + +Файл с приватным ключом, известный как *приватный ключ консенсуса*, также называется **приватным ключом валидатора**. Приватный ключ используется в тех случаях, когда нод действует в качестве валидатора в сети и должен подписывать новые данные. + +Файл с приватным ключом находится в `consensus/validator.key` и придерживается упомянутого [формата ключей](/docs/edge/configuration/manage-private-keys#key-format). + +:::warning +Приватный ключ валидатора уникален для каждого узла проверки. Один и тот же ключ не должен использоваться всеми валидаторами, поскольку это может поставить под угрозу безопасность вашей цепочки. +::: + +## Приватный ключ для сетевого взаимодействия {#networking-private-key} + +Файл приватного ключа, необходимый для сетевого взаимодействия, используется libp2p для генерации соответствующего PeerID и позволяет ноду участвовать в сети. + +Он расположен в `keystore/libp2p.key` и придерживается упомянутого [формата ключа](/docs/edge/configuration/manage-private-keys#key-format). + +## Ключ секретного типа BLS {#bls-secret-key} + +Файл секретного ключа BLS используется для объединения зафиксированных печатей на уровне консенсуса. Размер агрегированных совершенных печатей BLS меньше, чем выдаваемых подписей ECDSA. + +Функция BLS является необязательной, и можно выбирать, использовать BLS или нет. Более подробную информацию смотрите в [BLS](/docs/edge/consensus/bls). + +## Импорт/экспорт {#import-export} + +Поскольку файлы с ключами хранятся в простой базе Base64 на диске, их можно легко резервировать или импортировать. + +:::caution Изменение файлов с ключами +Любые изменения, внесенные в файлы с ключами в уже созданной/работающей сети, могут привести к серьезным сбоям в работе сети/консенсуса, поскольку механизмы консенсуса и обнаружения пиров хранят данные, полученные из этих ключей, в специальных хранилищах нодов и полагаются на эти данные для установления соединений и выполнения логики консенсуса +::: \ No newline at end of file diff --git a/archive/edge/ru-edge/configuration/prometheus-metrics.md b/archive/edge/ru-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..c7d22a6222 --- /dev/null +++ b/archive/edge/ru-edge/configuration/prometheus-metrics.md @@ -0,0 +1,34 @@ +--- +id: prometheus-metrics +title: Метрика Prometheus +description: "Как включить метрику Prometheus для Polygon Edge." +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## Обзор {#overview} + +Polygon Edge может сообщать и обслуживать метрику Prometheus, которая в свою очередь может быть использована с помощью коллекторов Prometheus. + +Метрика Prometheus отключена по умолчанию. Она может быть включена путем указания адреса слушателя с помощью флага `--prometheus` или поля `Telemetry.prometheus` в файле конфигурации. Метрика будет обслуживаться в соответствии с `/metrics` на указанный адрес. + +## Доступная метрика {#available-metrics} + +Доступна следующая метрика: + +| **Название** | **Тип** | **Описание** | +|-----------------------------------------------|---------------|-------------------------------------------------| +| txpool_pending_transactions | Gauge | Количество отложенных транзакций в TxPool | +| consensus_validators | Gauge | Количество валидаторов | +| consensus_rounds | Gauge | Количество раундов | +| consensus_num_txs | Gauge | Количество транзакций в последнем блоке | +| consensus_block_interval | Gauge | Время между этим и последним блоком в секундах | +| network_peers | Gauge | Количество подключаемых одноранговых узлов | +| network_outbound_connections_count | Gauge | Количество исходящих соединений | +| network_inbound_connections_count | Gauge | Количество входящих соединений | +| network_pending_outbound_connections_count | Gauge | Количество отложенных исходящих соединений | +| network_pending_inbound_connections_count | Gauge | Количество отложенных входящих соединений | \ No newline at end of file diff --git a/archive/edge/ru-edge/configuration/sample-config.md b/archive/edge/ru-edge/configuration/sample-config.md new file mode 100644 index 0000000000..89e29dfbd6 --- /dev/null +++ b/archive/edge/ru-edge/configuration/sample-config.md @@ -0,0 +1,149 @@ +--- +id: sample-config +title: Файл конфигурации сервера +description: "Запустите сервер Polygon Edge с помощью файла конфигурации." +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# Файл конфигурации сервера {#server-configuration-file} +Запуск сервера с различными вариантами конфигурации можно сделать с помощью файла конфигурации вместо использования только флагов. Команда, которая используется для запуска сервера с помощью файла конфигурации: `polygon-edge server --config ` + +## Экспорт файла конфигурации с конфигурацией по умолчанию {#export-config-file-with-default-configuration} +Конфигурация по умолчанию для сервера Polygon Edge может быть экспортирована в файл конфигурации в любом из следующих форматов: `yaml`или `json`. Этот файл можно использовать в качестве шаблона для запуска сервера с помощью файла конфигурации. + +### YAML {#yaml} +Для создания файла конфигурации в формате `yaml`: +```bash +polygon-edge server export --type yaml +``` +или просто +```bash +polygon-edge server export +``` +файл конфигурации с названием `default-config.yaml` будет создан в той же директории, из которой была запущена эта команда. + +Пример файла: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +Для создания файла конфигурации в формате `json`: +```bash +polygon-edge server export --type json +``` +файл конфигурации с названием `default-config.json` будет создан в той же директории, из которой была запущена эта команда. + +Пример файла: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +Ознакомьтесь с разделом [Команды CLI](/docs/edge/get-started/cli-commands), чтобы узнать, как использовать эти параметры. + +### Схема Typescript {#typescript-schema} + +Ниже приводится формат образца для файла конфигурации. Он написан в TypeScript для выражения типов свойств (`string`, `number`, `boolean`), из которых вы можете вывести свою конфигурацию. Стоит отметить, что тип `PartialDeep` от `type-fest` используется для выражения того, что все свойства необязательны. + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/ru-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/ru-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..19a8d36e54 --- /dev/null +++ b/archive/edge/ru-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,124 @@ +--- +id: set-up-aws-ssm +title: Настройка AWS SSM (диспетчера систем) +description: "Настройка AWS SSM (диспетчера систем) для Polygon Edge." +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## Обзор {#overview} + +В настоящее время Polygon Edge работает над тем, чтобы сохранять два основных секрета времени выполнения: +* **Приватный ключ валидатора**, который использует нод, при условии что нод является валидатором +* **Приватный ключ для сетевого взаимодействия**, который использует libp2p, для участия и общения с другими одноранговыми узлами + +Подробнее см. [Руководство по управлению приватными ключами](/docs/edge/configuration/manage-private-keys) + +Модули Polygon Edge **не должны уметь хранить секреты**. В конечном итоге модуль не должен заботиться о том, хранится ли секрет на отдаленном сервере или локально на диске нода. + +Все, что должен знать модуль о хранении секрета, — **это то, как использовать этот секрет**, **какие секреты получать или сохранять**. Более тонкие детали реализации этих операций делегируются `SecretsManager`, что, конечно же, является абстракцией. + +Оператор нода, который запускает Polygon Edge, может теперь указывать, какой диспетчер секретов они хотят использовать, и, как только создается правильный диспетчер секретов, модули работают с секретами через указанный интерфейс, не заботясь о том, где хранятся секреты: на диске или на сервере. + +В этой статье подробно описываются необходимые шаги для того, чтобы запустить Polygon Edge вместе с [хранилищем параметров диспетчера систем AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html). + +:::info предыдущие руководства +**Настоятельно рекомендуется** перед тем, как перейти к этой статье, ознакомиться со статьями о [**локальной настройке**](/docs/edge/get-started/set-up-ibft-locally) и [**облачной настройке**](/docs/edge/get-started/set-up-ibft-on-the-cloud). +::: + + +## Предварительные условия {#prerequisites} +### Политика IAM {#iam-policy} +Пользователю нужно создать политику IAM, позволяющую выполнять операции чтения-записи для хранилища параметров диспетчера систем AWS Systems Manager. +После успешного создания политики IAM пользователю необходимо прикрепить ее к экземпляру EC2, на котором работает сервер Polygon Edge. +Политика IAM должна выглядеть примерно так: +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +Подробнее о ролях AWS SSM IAM см. в [документации по AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html). + +Прежде чем продолжить, ознакомьтесь со следующей информацией: +* **Region** (регион, в котором находятся диспетчер систем и ноды) +* **Parameter Path** (произвольный путь для сохранения секрета, например `/polygon-edge/nodes`) + +## Шаг 1 — создание конфигурации диспетчера секретов {#step-1-generate-the-secrets-manager-configuration} + +Чтобы Polygon Edge мог беспрепятственно взаимодействовать с AWS SSM, ему необходимо проанализировать уже созданный файл конфигурации, который содержит всю необходимую информацию для хранения секретов в AWS SSM. + +Запустите следующую команду, чтобы создать конфигурацию: + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +Присутствующие параметры: +* `PATH`— это путь, по которому должен экспортироваться файл конфигурации. По умолчанию `./secretsManagerConfig.json` +* `NODE_NAME` — имя текущего нода, для которого настраивается конфигурация AWS SSM. Это может быть произвольное значение. По умолчанию `polygon-edge-node` +* `REGION` — регион, где находится AWS SSM. Это должен быть тот же регион, что и у нода, использующего AWS SSM. +* `SSM_PARAM_PATH` — имя пути, где будет храниться секрет. Например, если задать `--name node1` и `ssm-parameter-path=/polygon-edge/nodes`, +секрет будет храниться как `/polygon-edge/nodes/node1/` + +:::caution Название нодов +Будьте внимательны, когда даете названия нодам. + +Polygon Edge использует указанное название нода для отслеживания тех секретов, которые он генерирует и использует в AWS SSM. Если указать имя существующего нода, возможна ошибка записи секрета в AWS SSM. + +Секреты хранятся на следующем базовом пути: `SSM_PARAM_PATH/NODE_NAME` +::: + +## Шаг 2 — инициирование секретных ключей с помощью конфигурации {#step-2-initialize-secret-keys-using-the-configuration} + +Теперь, когда файл конфигурации уже присутствует, мы можем инициализировать необходимые секретные ключи с помощью файла конфигурации, созданного в шаге 1, используя `--config`: + +```bash +polygon-edge secrets init --config +``` + +`PATH`Param — это местоположение ранее созданного диспетчера секретов param из шага 1. + +:::info Политика IAM + +На этом шаге произойдет ошибка, если политика IAM с разрешением операций чтения-записи настроена неправильно и/или не прикреплена к экземпляру EC2, который запускает эту команду. + +::: + +## Шаг 3 — создание генезис-файла {#step-3-generate-the-genesis-file} + +Генезис-файл должен быть создан аналогично руководствам по [**локальной настройке**](/docs/edge/get-started/set-up-ibft-locally) и [**облачной настройке**](/docs/edge/get-started/set-up-ibft-on-the-cloud) с незначительными изменениями. + +Поскольку AWS SSM используется вместо локальной файловой системы, адреса валидаторов должны быть добавлены через флаг `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Шаг 4 — запуск клиента Polygon Edge {#step-4-start-the-polygon-edge-client} + +Теперь, когда ключи созданы и генезис-файл генерируется, последний шаг для запуска всего процесса — это запуск Polygon Edge с помощью команды `server`. + +Команда `server` используется так же, как и в вышеупомянутых руководствах, с незначительным дополнением — флаг `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +`PATH`Param — это местоположение ранее созданного диспетчера секретов param из шага 1. \ No newline at end of file diff --git a/archive/edge/ru-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/ru-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..a2de892c54 --- /dev/null +++ b/archive/edge/ru-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,101 @@ +--- +id: set-up-gcp-secrets-manager +title: Настройка диспетчера секретов GCP +description: "Настройте диспетчер секретов GCP для Polygon Edge." +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## Обзор {#overview} + +В настоящее время Polygon Edge работает над тем, чтобы сохранять два основных секрета времени выполнения: +* **Приватный ключ валидатора**, который использует нод, при условии что нод является валидатором +* **Приватный ключ для сетевого взаимодействия**, который использует libp2p, для участия и общения с другими одноранговыми узлами + +Подробнее см. [Руководство по управлению приватными ключами](/docs/edge/configuration/manage-private-keys) + +Модули Polygon Edge **не должны уметь хранить секреты**. В конечном итоге модуль не должен заботиться о том, хранится ли секрет на отдаленном сервере или локально на диске нода. + +Все, что должен знать модуль о хранении секрета, — **это то, как использовать этот секрет**, **какие секреты получать или сохранять**. Более тонкие детали реализации этих операций делегируются `SecretsManager`, что, конечно же, является абстракцией. + +Оператор нода, который запускает Polygon Edge, может теперь указывать, какой диспетчер секретов они хотят использовать, и, как только создается правильный диспетчер секретов, модули работают с секретами через указанный интерфейс, не заботясь о том, где хранятся секреты: на диске или на сервере. + +В этой статье подробно описываются необходимые шаги для того, чтобы запустить Polygon Edge вместе с [диспетчером секретов GCP](https://cloud.google.com/secret-manager). + +:::info предыдущие руководства +**Настоятельно рекомендуется** перед тем, как перейти к этой статье, ознакомиться со статьями о [**локальной настройке**](/docs/edge/get-started/set-up-ibft-locally) и [**облачной настройке**](/docs/edge/get-started/set-up-ibft-on-the-cloud). +::: + + +## Предварительные условия {#prerequisites} +### Аккаунт для биллинга GCP {#gcp-billing-account} +Чтобы использовать диспетчер секретов GCP, пользователь должен включить [аккаунт для биллинга](https://console.cloud.google.com/) на портале GCP. Новым аккаунтам на платформе GCP предоставляется средства для начала работы в качестве бесплатной пробной версии. Подробнее о [документации GCP](https://cloud.google.com/free) + +### API диспетчера секретов {#secrets-manager-api} +Пользователю необходимо включить API диспетчера секретов GCP, перед тем как его использовать. Это можно сделать через [портал диспетчера секретов API](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com). Подробнее: [настройка диспетчера секретов](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + +### Учетные данные GCP {#gcp-credentials} +Наконец, пользователь должен создать новые учетные данные, которые будут использоваться для аутентификации. Это можно сделать путем выполнения инструкций, размещенных [здесь](https://cloud.google.com/secret-manager/docs/reference/libraries). Сгенерированный файл json, содержащий учетные данные, должен быть передан каждому ноду, которому требуется использовать диспетчер секретов GCP. + +Прежде чем продолжить, ознакомьтесь со следующей информацией: +* **Идентификатор проекта** (идентификатор проекта, определенный на платформе GCP) +* **Расположение файла с учетными данными** (путь к файлу json, в котором содержатся учетные данные) + +## Шаг 1 — создание конфигурации диспетчера секретов {#step-1-generate-the-secrets-manager-configuration} + +Чтобы Polygon Edge мог беспрепятственно взаимодействовать с GCP SM, ему необходимо проанализировать уже созданный файл конфигурации, который содержит всю необходимую информацию для хранения секретов на GCP SM. + +Запустите следующую команду, чтобы создать конфигурацию: + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +Присутствующие параметры: +* `PATH`— это путь, по которому должен экспортироваться файл конфигурации. По умолчанию `./secretsManagerConfig.json` +* `NODE_NAME` — это название текущего нода, для которого создается конфигурация GCP SM. Это может быть произвольное значение. По умолчанию `polygon-edge-node` +* `PROJECT_ID`— идентификатор проекта, который пользователь определил в консоли GCP во время настройки аккаунта и активации API диспетчера секретов. +* `GCP_CREDS_FILE` — это путь к файлу json, содержащий учетные данные, который позволит читать/записывать доступ к диспетчеру секретов. + +:::caution Название нодов +Будьте внимательны, когда даете названия нодам. + +Polygon Edge использует указанное название нодов для отслеживания тех секретов, которые он генерирует и использует на GCP SM. Указание названия существующего нода может вызвать невозможность записи секрета на GCP SM. + +Секреты хранятся на следующем базовом пути: `projects/PROJECT_ID/NODE_NAME` +::: + +## Шаг 2 — инициирование секретных ключей с помощью конфигурации {#step-2-initialize-secret-keys-using-the-configuration} + +Теперь, когда файл конфигурации уже присутствует, мы можем инициализировать необходимые секретные ключи с помощью файла конфигурации, созданного в шаге 1, используя `--config`: + +```bash +polygon-edge secrets init --config +``` + +`PATH`Param — это местоположение ранее созданного диспетчера секретов param из шага 1. + +## Шаг 3 — создание генезис-файла {#step-3-generate-the-genesis-file} + +Генезис-файл должен быть создан аналогично руководствам по [**локальной настройке**](/docs/edge/get-started/set-up-ibft-locally) и [**облачной настройке**](/docs/edge/get-started/set-up-ibft-on-the-cloud) с незначительными изменениями. + +Поскольку GCP SM используется вместо локальной файловой системы, адреса валидаторов должны быть добавлены через флаг `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Шаг 4 — запуск клиента Polygon Edge {#step-4-start-the-polygon-edge-client} + +Теперь, когда ключи созданы и генезис-файл генерируется, последний шаг для запуска всего процесса — это запуск Polygon Edge с помощью команды `server`. + +Команда `server` используется так же, как и в вышеупомянутых руководствах, с незначительным дополнением — флаг `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +`PATH`Param — это местоположение ранее созданного диспетчера секретов param из шага 1. \ No newline at end of file diff --git a/archive/edge/ru-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/ru-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..96e61fd7d5 --- /dev/null +++ b/archive/edge/ru-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,102 @@ +--- +id: set-up-hashicorp-vault +title: Настройка хранилища Hashicorp Vault +description: "Настройте хранилище Hashicorp Vaul для Polygon Edge." +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## Обзор {#overview} + +В настоящее время Polygon Edge работает над тем, чтобы сохранять два основных секрета времени выполнения: +* **Приватный ключ валидатора**, который использует нод, при условии что нод является валидатором +* **Приватный ключ для сетевого взаимодействия**, который использует libp2p, для участия и общения с другими одноранговыми узлами + +:::warning +Приватный ключ валидатора уникален для каждого узла валидатора. Один и тот же ключ не должен использоваться всеми валидаторами, поскольку это может поставить под угрозу безопасность вашей цепочки. +::: + +Для получения более подробной информации просим вас ознакомиться с [Руководством по управлению приватными ключами](/docs/edge/configuration/manage-private-keys) + +Модули Polygon Edge **не должны уметь хранить секреты**. В конечном итоге модуль не должен заботиться о том, хранится ли секрет на отдаленном сервере или локально на диске нода. + +Все, что должен знать модуль о хранении секрета, — **это то, как использовать этот секрет**, **какие секреты получать или сохранять**. Более тонкие детали реализации этих операций делегируются `SecretsManager`, что, конечно же, является абстракцией. + +Оператор нода, который запускает Polygon Edge, может теперь указывать, какой диспетчер секретов они хотят использовать, и, как только создается правильный диспетчер секретов, модули работают с секретами через указанный интерфейс, не заботясь о том, где хранятся секреты: на диске или на сервере. + +В этой статье подробно описываются необходимые шаги для того, чтобы запустить Polygon Edge вместе с сервером хранилища [Hashicorp Vault](https://www.vaultproject.io/). + +:::info предыдущие руководства +**Настоятельно рекомендуется** перед тем, как перейти к этой статье, ознакомиться со статьями о [**локальной настройке**](/docs/edge/get-started/set-up-ibft-locally) и [**облачной настройке**](/docs/edge/get-started/set-up-ibft-on-the-cloud). +::: + + +## Предварительные условия {#prerequisites} + +В этой статье предполагается, что функционирующий экземпляр сервера хранилища Hashicorp Vault **уже настроен**. + +Кроме того, необходимо, чтобы на сервере хранилища Hashicorp Vault, который используется для Polygon Edge, было **включено хранилище KV**. + +Прежде чем продолжить, ознакомьтесь со следующей информацией: +* **URL-адрес сервера** (URL API сервера хранилища Hashicorp Vault) +* **Токен** (токен доступа, используемый для доступа к двигателю хранилища KV) + +## Шаг 1 — создание конфигурации диспетчера секретов {#step-1-generate-the-secrets-manager-configuration} + +Чтобы Polygon Edge мог беспрепятственно взаимодействовать с сервером Vault, ему необходимо проанализировать уже созданный файл конфигурации, который содержит всю необходимую информацию для хранения секретов на Vault. + +Запустите следующую команду, чтобы создать конфигурацию: + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +Присутствующие параметры: +* `PATH`— это путь, по которому должен экспортироваться файл конфигурации. По умолчанию `./secretsManagerConfig.json` +* `TOKEN`— токен доступа, который ранее упоминается в [разделе о предварительных условиях](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `SERVER_URL`— это URL API для сервера Vault, который также упоминается в [разделе о предварительных условиях](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `NODE_NAME`— название текущего нода для которого создается конфигурация Vault. Это может быть произвольное значение. По умолчанию `polygon-edge-node` + +:::caution Название нод +Будьте внимательны, когда даете названия нодам. + +Polygon Edge использует указанное название нод для отслеживания тех секретов, которые он генерирует и использует на экземпляре Vault. Указание названия существующего нода может привести к перезаписи данных на сервере Vault. + +Секреты хранятся на следующем базовом пути: `secrets/node_name` +::: + +## Шаг 2 — инициирование секретных ключей с помощью конфигурации {#step-2-initialize-secret-keys-using-the-configuration} + +Теперь, когда файл конфигурации уже присутствует, мы можем инициализировать необходимые секретные ключи с помощью файла конфигурации, созданного в шаге 1, используя `--config`: + +```bash +polygon-edge secrets init --config +``` + +`PATH`Param — это местоположение ранее созданного диспетчера секретов param из шага 1. + +## Шаг 3 — создание генезис-файла {#step-3-generate-the-genesis-file} + +Генезис-файл должен быть создан аналогично руководствам по [**локальной настройке**](/docs/edge/get-started/set-up-ibft-locally) и [**облачной настройке**](/docs/edge/get-started/set-up-ibft-on-the-cloud) с незначительными изменениями. + +Поскольку Hashicorp Vault используется вместо локальной файловой системы, адреса валидаторов должны быть добавлены через флаг `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Шаг 4 — запуск клиента Polygon Edge {#step-4-start-the-polygon-edge-client} + +Теперь, когда ключи созданы и генезис-файл генерируется, последний шаг для запуска всего процесса — это запуск Polygon Edge с помощью команды `server`. + +Команда `server` используется так же, как и в вышеупомянутых руководствах, с незначительным дополнением — флаг `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +`PATH`Param — это местоположение ранее созданного диспетчера секретов param из шага 1. \ No newline at end of file diff --git a/archive/edge/ru-edge/consensus/bls.md b/archive/edge/ru-edge/consensus/bls.md new file mode 100644 index 0000000000..8f1da105de --- /dev/null +++ b/archive/edge/ru-edge/consensus/bls.md @@ -0,0 +1,144 @@ +--- +id: bls +title: BLS +description: "Объяснение и инструкции для режима BLS." +keywords: + - docs + - polygon + - edge + - bls +--- + +## Обзор {#overview} + +BLS, также известный как Boneh–Lynn–Shacham (BLS) — это криптографическая схема подписи, которая позволяет пользователю удостовериться в том, что подписант является подлинным. Это схема подписи, которая может объединить несколько подписей. BLS используется в Polygon Edge по умолчанию для повышения безопасности в режиме консенсуса IBFT. BLS может агрегировать подписи в однобайтый массив и уменьшать размер заголовка блока. Каждая цепочка может выбрать, следует ли использовать BLS. Ключ ECDSA используется вне зависимости от того, включен ли режим BLS. + +## Видеопрезентация {#video-presentation} + +[![bls - видео](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## Настройка новой цепочки с помощью BLS {#how-to-setup-a-new-chain-using-bls} + +Подробные инструкции по настройке можно найти в разделах [Локальная настройка](/docs/edge/get-started/set-up-ibft-locally) / [Облачная настройка](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +## Как выполнить миграцию из существующей цепочки ECDSA PoA в цепочку BLS PoA {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +В этом разделе описывается использование режима BLS в существующей цепочке PoA. +Для включения BLS в цепочке PoA требуются следующие шаги. + +1. Остановите все ноды +2. Сгенерируйте ключи BLS для валидаторов +3. Добавьте настройку форка в genesis.json +4. Перезапустите все ноды + +### 1. Остановка всех нодов {#1-stop-all-nodes} + +Завершите все процессы валидаторов, нажав Ctrl + c (Control + c). Запомните высоту последнего блока (самый большой порядковый номер в журнале записанных блоков). + +### 2. Генерирование ключа BLS {#2-generate-the-bls-key} + +`secrets init` с `--bls` генерирует ключ BLS. Чтобы сохранить ECDSA и сетевой ключ и добавить новый ключ BLS, необходимо отключить `--ecdsa` и `--network`. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Добавление настройки форка {#3-add-fork-setting} + +Команда `ibft switch` добавляет настройку форка, включающую BLS в существующей цепочке, в `genesis.json`. + +В сетях PoA в команде необходимо указать валидаторы. Как и в случае с командой `genesis`, для указания валидатора можно использовать флаги `--ibft-validators-prefix-path` или `--ibft-validator`. + +Укажите высоту, с которой начинается цепочка, используя BLS с флагом `--from`. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. Перезапуск всех нодов {#4-restart-all-nodes} + +Перезапустите все ноды с помощью команды `server`. После создания блока на позиции `from`, как указано в предыдущем шаге, цепочка включает BLS и показывает журналы следующим образом: + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +Журналы также показывают, какой режим проверки используется для генерирования каждого блока после создания блока. + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## Как выполнить миграцию из существующей цепочки ECDSA PoA в цепочку BLS PoS {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +В этом разделе описывается использование режима BLS в существующей цепочке PoS. +Для включения BLS в цепочке PoS требуются следующие шаги. + +1. Остановите все ноды +2. Сгенерируйте ключи BLS для валидаторов +3. Добавьте настройку форка в genesis.json +4. Вызовите контракт стейкинга для регистрации публичного ключа BLS +5. Перезапустите все ноды + +### 1. Остановка всех нодов {#1-stop-all-nodes-1} + +Завершите все процессы валидаторов, нажав Ctrl + c (Control + c). Запомните высоту последнего блока (самый большой порядковый номер в журнале записанных блоков). + +### 2. Генерирование ключа BLS {#2-generate-the-bls-key-1} + +`secrets init` с флагом `--bls` генерирует ключ BLS. Чтобы сохранить ECDSA и сетевой ключ и добавить новый ключ BLS, необходимо отключить `--ecdsa` и `--network`. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Добавление настройки форка {#3-add-fork-setting-1} + +Команда `ibft switch` добавляет настройку форка, включающую BLS из середины цепочки, в `genesis.json`. + +Укажите высоту начала цепочки, используя режим BLS с флагом `from`, а также высоту обновления контракта с флагом `development`. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. Регистрация публичного ключа BLS в контракте стейкинга {#4-register-bls-public-key-in-staking-contract} + +После добавления форка и перезапуска валидаторов каждый валидатор должен вызвать `registerBLSPublicKey` в контракте стейкинга для регистрации публичного ключа BLS. Это необходимо сделать после указания высоты в `--deployment`, прежде чем высота будет указана в `--from`. + +Скрипт регистрации публичного ключа BLS определен в [репозитории Staking Smart Contract](https://github.com/0xPolygon/staking-contracts). + +Установите `BLS_PUBLIC_KEY` для регистрации в файл `.env`. Используйте [pos-stake-unstake](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) для получения более подробной информации о других параметрах. + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +Следующая команда регистрирует в контракте публичный ключ BLS, заданный в `.env`. + +```bash +npm run register-blskey +``` + +:::warning Валидаторы должны регистрировать публичный ключ BLS вручную + +В режиме BLS валидаторы должны иметь собственный адрес и публичный ключ BLS. Уровень консенсуса игнорирует валидаторов, которые не зарегистрировали публичный ключ BLS в контракте, когда консенсус доставляет информацию валидатора из контракта. + +::: + +### 5. Перезапуск всех нодов {#5-restart-all-nodes} + +Перезапустите все ноды с помощью команды `server`. Цепочка включает BLS после создания блока в `from`, как указано на предыдущем шаге. diff --git a/archive/edge/ru-edge/consensus/migration-to-pos.md b/archive/edge/ru-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..eb975ae939 --- /dev/null +++ b/archive/edge/ru-edge/consensus/migration-to-pos.md @@ -0,0 +1,40 @@ +--- +id: migration-to-pos +title: Миграция из PoA в PoS +description: "Как выполнить миграцию из режима PoA в режим PoS IBFT и наоборот." +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## Обзор {#overview} + +В этом разделе описывается миграция между режимами PoA и PoS IBFT в работающем кластере без необходимости перезагрузки блокчейна. + +## Как выполнить миграцию в PoS {#how-to-migrate-to-pos} + +Необходимо остановить все ноды, добавить конфигурацию форка в genesis.json с помощью команды `ibft switch` и перезапустить ноды. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution Переключение при использовании ECDSA +При использовании ECDSA должен быть добавлен `--ibft-validator-type`флажок, который упоминает что используется ECDSA. Если не включено, Edge автоматически переключится на BLS. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::Чтобы перейти в PoS, вам нужно будет указать 2 высоты блока: `deployment`и . `from``deployment`это высота для развертывания контракта стейкинга и `from`является высотой начала PoS. Контракт стейкинга будет развернут по адресу `0x0000000000000000000000000000000000001001` в `deployment`, как и в случае с предварительно развернутым контрактом. + +См. раздел [Доказательство доли владения (Proof of Stake)](/docs/edge/consensus/pos-concepts) для получения дополнительной информации о контракте стейкинга. + +:::warning Валидаторы делают стейки вручную + +Чтобы стать валидатором в начале PoS, каждый валидатор должен сделать стейк после развертывания контракта в `deployment` и до `from`. Каждый валидатор будет обновлять собственный набор валидаторов через контракт стейкинга в начале PoS. + +Чтобы узнать больше о стейкинге посетите раздел **[Настройка и используйте Proof](/docs/edge/consensus/pos-stake-unstake)** of Stake. +::: diff --git a/archive/edge/ru-edge/consensus/poa.md b/archive/edge/ru-edge/consensus/poa.md new file mode 100644 index 0000000000..89fc1b4ef3 --- /dev/null +++ b/archive/edge/ru-edge/consensus/poa.md @@ -0,0 +1,108 @@ +--- +id: poa +title: Доказательство полномочий (PoA) +description: "Разъяснения и инструкции относительно доказательства полномочий." +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## Обзор {#overview} + +IBFT PoA используется в Polygon Edge как механизм консенсуса по умолчанию. В PoA валидаторы отвечают за создание блоков и их последовательное добавление в блокчейн. + +Все валидаторы составляют динамический набор валидаторов, поддерживающий добавление и удаление валидаторов с помощью механизма голосования. Это означает, что валидатора можно добавить в набор или удалить из набора, если большинство (51%) нодов валидаторов проголосуют за добавление или удаление данного валидатора. Это позволяет распознавать и удалять из сети злоумышленников и добавлять в сеть новых валидаторов, которым можно доверять. + +Все валидаторы по очереди предлагают следующий блок (круговая очередь), и для валидации блока и его вставки в блокчейн требуется одобрение данного блока квалифицированным большинством (более 2/3) валидаторов. + +Помимо валидаторов, имеются и другие ноды, которые не участвуют в создании блоков, но участвуют в процессе валидации. + +## Добавление валидатора в набор валидаторов {#adding-a-validator-to-the-validator-set} + +В этом руководстве описывается добавление нового нода валидатора в активную сеть IBFT с 4 нодами валидаторов. +Если вам нужна помощь в настройке сети, обратитесь в секции [Local Setup](/edge/get-started/set-up-ibft-locally.md) / [Cloud Setup](/edge/get-started/set-up-ibft-on-the-cloud.md). + +### Шаг 1. Инициализируйте папки данных для IBFT и сгенерируйте ключи валидаторов для нового нода {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +Чтобы запустить IBFT на новом ноде, необходимо предварительно инициализировать папки данных и сгенерировать ключи: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +Эта команда распечатает ключ валидатора (адрес) и идентификатор нода. Для следующего шага вам потребуется ключ валидатора (адрес). + +### Шаг 2. Предложите нового кандидата из числа других нодов валидатора {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +Чтобы новый нод стал валидатором, его должны предложить не менее 51% валидаторов. + +Примеры предложения нового валидатора (`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`) из существующего нода валидатора на адресе grpc: 127.0.0.1:10000: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +Структура команд IBFT описывается в разделе [Команды CLI](/docs/edge/get-started/cli-commands). + +:::info Публичный ключ BLS + +Публичный ключ BLS необходим, только если сеть работает с BLS. Если сеть не работает в режиме BLS `--bls`, это не требуется +::: + +### Шаг 3. Запустите нод клиента {#step-3-run-the-client-node} + +Поскольку в этом примере мы пытаемся запустить сеть, где все ноды находятся на одном компьютере, нам нужно следить за тем, чтобы избежать конфликтов портов. + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +После доставки всех блоков на консоли можно заметить, что в валидации участвует новый нод + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info Повышение статуса нода до валидатора + +Нод может стать валидатором в результате голосования, однако для успешного добавления в набор валидаторов после окончания голосования нод необходимо перезапустить с флагом `--seal`. + +::: + +## Удаление валидатора из набора валидаторов {#removing-a-validator-from-the-validator-set} + +Это довольно простая операция. Чтобы удалить нод валидатора из набора валидаторов, эту команду необходимо выполнить на большинстве нодов валидатора. + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info Публичный ключ BLS + +Публичный ключ BLS необходим, только если сеть работает с BLS. Если сеть не работает в режиме BLS `--bls`, это не требуется +::: + +После выполнения команд необходимо убедиться, что количество валидаторов уменьшилось (в данном примере журнала — с 4 до 3). + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/ru-edge/consensus/pos-concepts.md b/archive/edge/ru-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..ae3f7b5bd6 --- /dev/null +++ b/archive/edge/ru-edge/consensus/pos-concepts.md @@ -0,0 +1,117 @@ +--- +id: pos-concepts +title: Доказательство доли владения (Proof of Stake) +description: "Разъяснения и инструкции относительно PoS (доказательства доли владения)." +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## Обзор {#overview} + +В этом разделе дается более детальный обзор некоторых концепций, присутствующих в реализации доказательства доли владения (PoS) +в Polygon Edge. + +Реализация Polygon Edge PoS призвана служить альтернативой существующей реализации PoA IBFT, +чтобы дать операторам нодов возможность выбрать предпочтительный вариант при запуске цепочки. + +## Характеристики PoS {#pos-features} + +Логика ядра реализации PoS находится в +**[смарт-контракт стейкинга](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)**. + +Этот контракт развертывается при инициализации механизма PoS цепочки Polygon Edge и доступен по адресу +`0x0000000000000000000000000000000000001001` из блока `0`. + +### Эпохи {#epochs} + +Эпохи — это концепция, введенная с добавлением PoS в Polygon Edge. + +Эпохи — это специальные временные промежутки (в блоках), в которых определенный набор валидаторов может производить блоки. +Их длину можно изменять, т. е. операторы нодов могут настроить длину эпохи при генерировании генезиса. + +В конце каждой эпохи создается _блок эпохи_, и после этого события начинается новая эпоха. Подробнее о блоках эпохи см. в разделе [Блоки эпохи](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Наборы валидаторов обновляются в конце каждой эпохи. Ноды запрашивают набор валидаторов из смарт-контракта стейкинга +при создании блока эпохи и сохраняют полученные данные в локальное хранилище. Этот цикл запроса и сохранения +повторяется в конце каждой эпохи. + +Благодаря ему смарт-контракт стейкинга имеет полный контроль над адресами в наборе валидаторов, оставляя нодам только одну обязанность — один раз отправлять запрос к контракту во время эпохи для доставки информации о последнем +наборе валидаторов. Это избавляет отдельные ноды от необходимости обслуживать наборы валидаторов. + +### Стейкинг {#staking} + +Адреса могут вносить средства в качестве стейка для смарт-контракта стейкинга, вызывая метод `stake` и указывая значение +суммы стейка в транзакции: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +Используя для стейкинга средства в смарт-контракте стейкинга, адреса помогут попадать в набор валидаторов и получать возможность участвовать в процессе создания блоков. + +:::info Пороговое значение стейкинга + +В настоящее время минимальное пороговое значение для входа в набор валидаторов предусматривает стейкинг `1 ETH` + +::: + +### Отзыв стейкинга {#unstaking} + +Адреса, выделившие средства на стейкинг, могут **отозвать только все эти средства целиком**. + +Отзыв стейкинга запускается посредством вызова метода `unstake` для смарт-контракта стейкинга: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +После отзыва средств для стейкинга адреса удаляются из набора валидаторов в смарт-контракте стейкинга и перестают считаться валидаторами в следующую эпоху. + +## Блоки эпохи {#epoch-blocks} + +**Блоки эпохи** — это понятие, введенное в реализации PoS IBFT в Polygon Edge. + +Блоки эпохи — это специальные блоки, которые **не содержат транзакций** и появляются только **в конце эпохи**. +Например, если **размер эпохи** устанавливается в блоки, блоки эпохи будут считаться `50`блоками `50`, `100``150`и так далее. + +Они используются для выполнения дополнительной логики, которая не должна использоваться при обычном создании блоков. + +Более того, они показывают ноду, что ему **необходимо доставить информацию о последнем наборе валидаторов** +из смарт-контракта стейкинга. + +После обновления набора валидаторов в блоке эпохи набор валидаторов (измененный или неизмененный) +используется для последующих `epochSize - 1` блоков, пока снова не обновляется посредством извлечения актуальной информации из +смарт-контракта стейкинга Staking Smart Contract. + +Длина эпохи (в блоках) настраивается при генерировании файла генезиса с помощью специального параметра `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +По умолчанию размер эпохи в Polygon Edge составляет `100000` блоков. + +## Предварительное развертывание контракта {#contract-pre-deployment} + +Polygon Edge _предварительно развертывает_ +[Смарт-контракт стейкинга](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol) +во время **генерирования генезиса** на адрес `0x0000000000000000000000000000000000001001`. + +Это делается без запуска EVM посредством изменения состояния блокчейна смарт-контракта напрямую с использованием +значений конфигурации, переданных команде генезиса. diff --git a/archive/edge/ru-edge/consensus/pos-stake-unstake.md b/archive/edge/ru-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..9e4ddb1e36 --- /dev/null +++ b/archive/edge/ru-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,163 @@ +--- +id: pos-stake-unstake +title: Настройка и использование доказательства доли владения (PoS) +description: "Стейк, снятие стейка и другие инструкции, связанные со стейками." +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## Обзор {#overview} + +В этом руководстве подробно рассказывается, как настроить сеть PoS в Polygon Edge и как делать стейки на ноды, +чтобы делать их валидаторами, и как отзывать средства из стейков. + +Он **настоятельно рекомендуется** читать и пройти через [Локальная настройка](/docs/edge/get-started/set-up-ibft-locally) / [Облачная настройка](/docs/edge/get-started/set-up-ibft-on-the-cloud), прежде чем продолжать использовать это руководство по PoS. В этих разделах описываются шаги, необходимые для запуска кластера доказательства полномочий (PoA) в +Polygon Edge. + +В настоящее время отсутствует какой-либо лимит по количеству валидаторов, которые могут использовать средства для стейков смарт-контракта стейкинга. + +## Смарт-контракт стейкинга {#staking-smart-contract} + +Репозиторий смарт-контракта стейкинга находится [здесь](https://github.com/0xPolygon/staking-contracts). + +В нем хранятся необходимые скрипты для тестирования, файлы ABI и сам смарт-контракт стейкинга. + +## Настройка кластера нода N {#setting-up-an-n-node-cluster} + +Настройка сети с помощью Polygon Edge описана в разделах + [Локальная настройка](/docs/edge/get-started/set-up-ibft-locally) / [Облачная настройка](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +**Единственное отличие** между настройкой кластеров PoS и PoA заключается в генерировании генезиса. + +**При генерировании файла генезиса для кластера PoS требуется дополнительный флаг `--pos`**: + +```bash +polygon-edge genesis --pos ... +``` + +## Настройка длительности эпохи {#setting-the-length-of-an-epoch} + +Эпохи подробно описываются в разделе [блоки эпохи](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Чтобы настроить размер эпохи для кластера (в блоках) при генерировании файла генезиса указывается дополнительный флаг + `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +Это значение в файле генезиса указывает, что размер эпохи должен составлять `50` блоков. + +Значение размера эпохи по умолчанию (в блоках) составляет `100000`. + +:::info Уменьшение длительности эпохи + +Как описано в разделе [Блоки эпохи](/docs/edge/consensus/pos-concepts#epoch-blocks), +блоки эпохи используются для обновления наборов валидаторов для нодов. + +Длина эпохи в блоках по умолчанию (`100000`) может быть слишком большой для обновления набора валидатора. Учитывая, что новые блоки добавляются примерно каждые 2 секунды, для возможного изменения набора валидаторов потребуется примерно 55,5 часа. + +Если установить меньшее значение длины эпохи, набор валидаторов будет обновляться чаще. + +::: + +## Использование скриптов смарт-контракта стейкинга {#using-the-staking-smart-contract-scripts} + +### Предварительные условия {#prerequisites} + +Репозиторий смарт-контракта стейкинга — это проект Hardhat, требующий NPM. + +Для правильной инициализации следует запустить в основном каталоге команду: + +```bash +npm install +```` + +### Настройка предоставленных скриптов помощников {#setting-up-the-provided-helper-scripts} + +Скрипты для взаимодействия с развернутым смарт-контрактом стейкинга находятся в [репозитории Staking Smart Contract](https://github.com/0xPolygon/staking-contracts). + +Создайте файл `.env` со следующими параметрами в каталоге репозитория смарт-контрактов: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +Назначение параметров: + +* **JSONRPC_URL** — конечная точка JSON-RPC для запуска нода +* **PRIVATE_KEYS** — приватные ключи адреса стейкера. +* **STAKING_CONTRACT_ADDRESS** — адрес смарт-контракта стейкинга ( +по умолчанию `0x0000000000000000000000000000000000001001`) +* **BLS_PUBLIC_KEY** — публичный ключ BLS стейкера. Требуется, только если в сети используется BLS + +### Средства для стейкинга {#staking-funds} + +:::info Адрес стейкинга +Смарт-контракт стейкинга предварительно развернут по адресу `0x0000000000000000000000000000000000001001`. + +Любое взаимодействие с механизмом стейкинга выполняется через смарт-контракт стейкинга по указанному адресу. + +Больше о смарт-контракте стейкинга можно узнать в разделе +**[смарт-контракт](/docs/edge/consensus/pos-concepts#contract-pre-deployment)** . +::: + +Чтобы стать частью набора валидаторов, адрес должен внести в качестве стейка определенную сумму средств сверх порогового значения. + +В настоящее время пороговое значение по умолчанию для вхождения в набор валидаторов составляет `1 ETH`. + +Стейкинг можно инициировать посредством вызова метода `stake` смарт-контракта стейкинга со значением `>= 1 ETH`. + +После настройки файла `.env`, указанного в [предыдущем разделе](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts), и запуска цепочки в режиме PoS стейкинг можно выполнить с помощью следующей команды в репозитории смарт-контракта стейкинга: + +```bash +npm run stake +``` + +Скрипт `stake` Hardhat использует для стейка количество по умолчанию `1 ETH`, которое можно изменить посредством изменения файла `scripts/stake.ts` +. + +Если используемые для стейка средства `>= 1 ETH`, набор валидаторов в смарт-контракте стейкинга обновляется и адрес +становится частью набора валидаторов начиная со следующей эпохи. + +:::info Регистрация ключей BLS + +Если сеть работает в режиме BLS, для получения статуса валидаторов ноды должны зарегистрировать публичные ключи BLS после стейкинга + +Это можно сделать с помощью следующей команды: + +```bash +npm run register-blskey +``` +::: + +### Отзыв средств из стейкинга {#unstaking-funds} + +Адреса, у которых есть стейк, могут **отозвать из стейка только все средства** сразу. + +После настройки файла `.env`, указанного в [предыдущем разделе](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts), +и запуска цепочки в режиме PoS отзыв стейка можно выполнить с помощью следующей команды в репозитории Staking Smart Contract: + +```bash +npm run unstake +``` + +### Доставка списка стейкеров {#fetching-the-list-of-stakers} + +Все адреса, выделившие средства на стейк, сохраняются в смарт-контракте стейкинга. + +После настройки файла `.env`, указанного в [предыдущем разделе](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts), +и запуска цепочки в режиме PoS доставку режима валидаторов можно выполнить с помощью следующей команды в репозитории Staking Smart Contract: + +```bash +npm run info +``` diff --git a/archive/edge/ru-edge/faq/Contracts.md b/archive/edge/ru-edge/faq/Contracts.md new file mode 100644 index 0000000000..4677f1825e --- /dev/null +++ b/archive/edge/ru-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: Часто задаваемые вопросы по смарт-контрактам +description: "Часто задаваемые вопросы по смарт-контрактам Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## Поддерживает ли Polygon Edge смарт-контракты? {#does-polygon-edge-support-smart-contracts} + +Да. Сети Polygon Edge представляют собой Ethereum-совместимые блокчейны, и поэтому смарт-контракты, которые можно развернуть в Ethereum, также можно развернуть в цепочках Polygon Edge. + +## Можно ли обновить логику контракта стейкинга для PoS после развертывания? {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +После запуска сети PoS логику контракта стейкинга изменять нельзя, потому что она становится частью файла генезиса. Поэтому, например, нельзя изменить минимальное или максимальное количество валидаторов. Вы можете добавлять или удалять стейки для добавления или удаления валидаторов. + + + diff --git a/archive/edge/ru-edge/faq/Gas.md b/archive/edge/ru-edge/faq/Gas.md new file mode 100644 index 0000000000..2771998f12 --- /dev/null +++ b/archive/edge/ru-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: Часто задаваемые вопросы о газе +description: "Часто задаваемые вопросы о газе для Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Как принудительно установить минимальную цену на газ? {#how-to-enforce-a-minimum-gas-price} +Вы можете использовать параметр `--price-limit` команды сервера. После этого ваш нод будет принимать только транзакции с ценой газа выше или равной заданному лимиту. Чтобы обеспечить применение лимита во всей сети, необходимо убедиться, что один и тот же лимит цены установлен для всех нодов. + + +## Возможны ли транзакции, где комиссия за газ равняется 0? {#can-you-have-transactions-with-0-gas-fees} +Да. По умолчанию для нодов установлен лимит цены `0`, т. е. ноды принимают транзакции, для которых установлена цена на газ `0`. + +## Как установить общие поставки токенов для газа (нативные)? {#how-to-set-the-gas-native-token-total-supply} + +Для аккаунтов (адресов) можно задать остаток предварительного баланса, используя `--premine flag`. Следует отметить, что это конфигурация из файла генезиса, ее нельзя будет изменить позднее. + +Пример использования `--premine flag`: + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +Эта команда устанавливает предварительно пополненный баланс 1000 ETH для 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862 (количество в аргументе указано в wei). + +Предварительно пополненное количество токенов газа будет представлять все доступные поставки. Позднее будет невозможен минтинг другого количества нативной валюты (токенов газа). + +## Поддержикает ли Edge токен газа ERC-20? {#does-edge-support-erc-20-as-a-gas-token} + +Edge не поддерживает использование токенов ERC-20 как токенов газа. Только нативная валюта Edge может использоваться для оплаты комиссии за газ. + +## Как увеличить лимит газа? {#how-to-increase-the-gas-limit} + +В Polygon Edge есть два варианта увеличения газа: +1. Вывод цепочки и увеличение `block-gas-limit`до максимального значения uint64 в файле генеза +2. Используйте `--block-gas-target`флаг с высоким значением, чтобы увеличить лимит газа всех нодов. Это требует перезагрузки нода. [Подробное объяснение здесь](/docs/edge/architecture/modules/txpool/#block-gas-target). \ No newline at end of file diff --git a/archive/edge/ru-edge/faq/Tokens.md b/archive/edge/ru-edge/faq/Tokens.md new file mode 100644 index 0000000000..5bff47cb9b --- /dev/null +++ b/archive/edge/ru-edge/faq/Tokens.md @@ -0,0 +1,23 @@ +--- +id: tokens +title: Часто задаваемые вопросы о токенах +description: "Часто задаваемые вопросы о токенах Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## Поддерживает ли Polygon Edge EIP-1559? {#does-polygon-edge-support-eip-1559} +В настоящее время Polygon Edge не поддерживает EIP-1559. + +## Как установить символ валюты (токена)? {#how-to-set-the-currency-token-symbol} + +Символ токена — это элемент пользовательского интерфейса, так что его нельзя настроить или запрограммировать в сети. +Однако вы можете изменить его при добавлении сети в кошелек, например Metamask. + +## Что происходит с транзакциями, когда цепочка останавливается? {#what-happens-to-transactions-when-a-chain-halts} + +Все транзакции, которые не были обработаны, находятся в the очереди или в очередь, продвигаемой очереди). Если цепочка halts(all блокирует производство), эти транзакции никогда не будут выходить в блоки.
Это не только случай, когда цепочка останавливается. Если узлы остановлены или перезапускаются, все транзакции, которые не были выполнены и все еще находятся в TxPool, будут молча удалены.
То же самое произойдет и в транзакциях, когда будет введено изменение разрыва, поскольку требуется перезапустить ноды. diff --git a/archive/edge/ru-edge/faq/Validators.md b/archive/edge/ru-edge/faq/Validators.md new file mode 100644 index 0000000000..c551456267 --- /dev/null +++ b/archive/edge/ru-edge/faq/Validators.md @@ -0,0 +1,83 @@ +--- +id: validators +title: Часто задаваемые вопросы о валидаторах +description: "Часто задаваемые вопросы о валидаторах Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Как добавить/удалить валидатор? {#how-to-add-remove-a-validator} + +### PoA {#poa} +Добавление/удаление валидаторов осуществляется путем голосования. Вы можете найти руководство по этому поводу [здесь](/docs/edge/consensus/poa). + +### PoS {#pos} +Вы можете найти руководство о том, как поставить средства [здесь](/docs/edge/consensus/pos-stake-unstake), чтобы нод мог стать валидатором, и как отказаться от стейка (удалить валидатор). + +Просим обратить ваше внимание на следующее: +- Вы можете использовать генезис-флаг `--max-validator-count`, чтобы установить максимальное количество стейкеров, которые могут присоединиться к набору валидаторов. +- Вы можете использовать генезис-флаг `--min-validator-count `, чтобы установить минимальное количество стейкеров, необходимых для присоединения к набору валидаторов (по умолчанию `1`). +- Когда максимальное количество валидаторов достигнуто, вы больше не можете добавлять валидаторы до тех пор, пока не удалите уже существующий валидатор из набора (не имеет значения, если размер стейка выше у нового валидатора). Если вы удалите валидатор, количество оставшихся валидаторов не может быть ниже `--min-validator-count`. +- Для получения статуса валидатора по умолчанию установлен порог равный `1`единиц валюты нативной сети (газа). + + + +## Сколько пространства на диске рекомендуется для валидатора? {#how-much-disk-space-is-recommended-for-a-validator} + +Мы рекомендуем начать с 100G в качестве консервативно оцененной дорожки и убедиться, что впоследствии можно будет масштабировать диск. + + +## Существует ли лимит на количество валидаторов? {#is-there-a-limit-to-the-number-of-validators} + +Если говорить о технических ограничениях, то в Polygon Edge отсутствует явное ограничение на количество нодов, которые вы можете иметь в сети. Вы можете установить лимиты соединений (количество входящих/исходящих соединений) для каждого нода. + +Если говорить о практических ограничениях, то производительность кластера из 100 нодов будет более низкой, чем у кластера из 10 нодов. Увеличивая количество нодов в кластере, вы увеличиваете сложность взаимодействия и накладные расходы на сеть в целом. Все зависит от того, на какой сети вы работаете и какая у вас топология сети. + +## Как переключиться с PoA на PoS? {#how-to-switch-from-poa-to-pos} + +PoA — это механизм консенсуса по умолчанию. Для нового кластера, чтобы переключиться на PoS, необходимо добавить флаг `--pos` при генерации генезис-файла. Если у вас есть запущенный кластер, то инструкции, как переключиться, можно найти [здесь](/docs/edge/consensus/migration-to-pos). В [разделе о консенсусе](/docs/edge/consensus/poa) можно найти всю информацию о нашем механизме консенсуса и настройке. + +## Как обновить ноды при внесении серьезных изменений? {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +Подробное руководство можно найти [здесь](/docs/edge/validator-hosting#update). + +## Можно ли настроить минимальный размер стейка для PoS Edge? {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +Минимальный размер стейка по умолчанию составляет `1 ETH`, и его нельзя настраивать. + +## Почему такие команды JSON RPC, как `eth_getBlockByNumber`и `eth_getBlockByHash`, не возвращают адрес майнера? {#not-return-the-miner-s-address} + +В настоящее время в Polygon Edge используется консенсус IBFT 2.0, который, в свою очередь, основан на механизме голосования, описанном в Clique PoA: [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225). + +Если посмотреть на EIP-225 (Clique PoA), это соответствующая часть, которая объясняет, для чего используется `miner`( `beneficiary`): + +
Мы перепрофилируем поля заголовка ethash следующим образом:
    +
  • бенефициар/майнер: адрес для предложений о внесении изменений в список авторизованных подписчиков.
  • +
      +
    • Обычно заполняется нулями, изменяется только во время голосования.
    • +
    • Тем не менее, произвольные значения разрешаются (даже бессмысленные, такие как голосование против тех, кто не подписался), чтобы избежать дополнительных сложностей в реализации механики голосования.
    • +
    • Необходимо заполнить нулями в блоках контрольной точки (т. е. перехода эпохи).
    • +
    + +
+ +
+ +Таким образом, поле `miner` используется для предложения голосования за определенный адрес, а не для того, чтобы показать автора предложения блока. + +Информацию об авторе предложения блока можно найти путем восстановления pubkey из Seal, поля дополнительных данных Istanbul в заголовках блоков, закодированных RLP. + +## Какие части и значения Genesis можно смело изменить? {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +Перед попыткой его редактировать, пожалуйста, убедитесь, что вручную создать файл genesis.json. Кроме того, вся цепочка должна быть остановлена, прежде чем редактировать файл genesis.json. После изменения файла генеза его необходимо распространить на все ноды не валидатора и валидатора. + +::: + +**Только раздел загрузки файла genesis может быть безопасно изменен**, где можно добавить или удалить bootnodes из списка. \ No newline at end of file diff --git a/archive/edge/ru-edge/get-started/cli-commands.md b/archive/edge/ru-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..60954f2db6 --- /dev/null +++ b/archive/edge/ru-edge/get-started/cli-commands.md @@ -0,0 +1,2219 @@ +--- +id: cli-commands +title: Команды CLI +description: "Перечень команд интерфейса командной строки (CLI) и параметров команд для Polygon Edge." +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +В этом разделе описываются команды и параметры команд Polygon Edge, а также их использование. + +:::tip Поддержка вывода JSON + +Некоторые команды поддерживают параметр `--json`. Этот флаг предписывает команде распечатать вывод в формате JSON + +::: + +## Команды пуска {#startup-commands} + +| **Команда** | **Описание** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| server | Команда по умолчанию, запускающая клиент блокчейна и выполняющая загрузку всех модулей | +| genesis | Генерирует файл *genesis.json*, который используется для установки заданного состояния цепочки до запуска клиента. Структура файла генезиса описана ниже | +| genesis predeploy | Предварительно развертывает смарт-контракт для свежих сетей | + +### параметры команды server {#server-flags} + + +| **Все флаги сервера** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [prometheus](/docs/edge/get-started/cli-commands#prometheus) | [block-gas-target](/docs/edge/get-started/cli-commands#block-gas-target) | +| [max-peers](/docs/edge/get-started/cli-commands#max-peers) | [max-inbound-peers](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [max-outbound-peers](/docs/edge/get-started/cli-commands#max-outbound-peers) | [max-enqueued](/docs/edge/get-started/cli-commands#max-enqueued) | +| [log-level](/docs/edge/get-started/cli-commands#log-level) | [log-to](/docs/edge/get-started/cli-commands#log-to) | +| [chain](/docs/edge/get-started/cli-commands#chain) | [join](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [price-limit](/docs/edge/get-started/cli-commands#price-limit) | [max-slots](/docs/edge/get-started/cli-commands#max-slots) | +| [config](/docs/edge/get-started/cli-commands#config) | [secrets-config](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-interval](/docs/edge/get-started/cli-commands#dev-interval) | +| [no-discover](/docs/edge/get-started/cli-commands#no-discover) | [restore](/docs/edge/get-started/cli-commands#restore) | +| [block-time](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +Используется, чтобы указать директорию данных для хранения данных клиента Polygon Edge. По умолчанию: `./test-chain`. + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +Устанавливает адрес и порт для сервиса JSON-RPC `address:port`. +Если определен только порт, `:10001` он привязывается ко всем интерфейсам `0.0.0.0:10001`. +Если параметр пропущен, сервис выполняет привязку по умолчанию `address:port`. +Адрес по умолчанию: `0.0.0.0:8545`. + +--- + +####

json-rpc-block-range-limit + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +Устанавливает максимальный диапазон блоков, рассматриваемых при выполнении запросов json-rpc и включающих значения fromBlock/toBlock (например, eth_getLogs). Значение по умолчанию:`1000`. + +--- + +####

json-rpc-batch-request-limit + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +Устанавливает максимальную длину, рассматриваемую при обработке пакетных запросов json-rpc. По умолчанию: `20`. + +--- + +####

grpc + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +Устанавливает адрес и порт для сервиса gRPC `address:port`. Адрес по умолчанию: `127.0.0.1:9632`. + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +Устанавливает адрес и порт для сервиса libp2p `address:port`. Адрес по умолчанию: `127.0.0.1:1478`. + +--- + +####

prometheus + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +Устанавливает адрес и порт для сервера prometheus `address:port`. +Если определен только порт, `:5001` сервис будет привязан ко всем интерфейсам `0.0.0.0:5001`. +Если параметр пропущен, сервис не запускается. + +--- + +####

block-gas-target + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +Устанавливает целевой лимит газа на блок для цепочки. По умолчанию (не устанавливается принудительно): `0`. + +Более подробное разъяснение целевого предела газа на блок находится в [разделе TxPool](/docs/edge/architecture/modules/txpool#block-gas-target). + +--- + +####

max-peers + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +Устанавливает максимальное количество пиров для клиента. По умолчанию: `40`. + +Лимит пиров задается с помощью параметра `max-peers` или `max-inbound/outbound-peers`. + +--- + +####

max-inbound-peers + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +Задает максимальное количество входящих пиров клиента. Если установлено значение `max-peers`, лимит max-inbound-peer рассчитывается по следующей формуле. + +`max-inbound-peer = InboundRatio * max-peers`, где `InboundRatio` равняется `0.8`. + +--- + +####

max-outbound-peers + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +Устанавливает максимальное количество исходящих пиров клиента. Если установлено значение `max-peers`, количество max-outbound-peer рассчитывается по следующей формуле. + +`max-outbound-peer = OutboundRatio * max-peers`, где `OutboundRatio` равняется `0.2`. + +--- + +####

max-enqueued + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +Устанавливает максимальное количество транзакций в очереди на аккаунт. Значение по умолчанию:`128`. + +--- + +####

log-level + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +Устанавливает уровень журнала для вывода консоли. По умолчанию: `INFO`. + +--- + +####

log-to + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +Определяет имя файла журнала, которое будет держать весь вывод журнала для команды server. +По умолчанию все журналы команды server выводятся на консоль (stdout), +но если этот параметр включен, вывода на консоль при запуске команды server не будет. + +--- + +####

chain + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +Указывает файл генезиса, используемый для запуска цепочки. По умолчанию: `./genesis.json`. + +--- + +####

join + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Указывает адрес пира, который требуется присоединить. + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +Устанавливает внешний IP-адрес без порта так, как его видят пиры. + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +Задает DNS-адрес хоста. Можно использовать, чтобы рекламировать внешний DNS. Поддерживает `dns`,`dns4`,`dns6`. + +--- + +####

price-limit + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +Устанавливает минимальный лимит цены на газ для принятия в пул. По умолчанию: `1`. + +--- + +####

max-slots + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +Устанавливает максимальное количество слотов в пуле. По умолчанию: `4096`. + +--- + +####

Конфигурация + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +Указывает путь к конфигурации интерфейса командной строки. Поддерживает `.json`. + +--- + +####

secrets-config + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +Задает путь к файлу конфигурации SecretsManager. Используется для Hashicorp Vault, AWS SSM и GCP Secrets Manager. Если пропущен, используется локальный диспетчер секретов FS. + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +Устанавливает клиент в режим разработчика. По умолчанию: `false`. В режиме dev открытие сверстника отключено по умолчанию. + +--- + +####

dev-interval + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +Устанавливает интервал уведомления разработчика клиента в секундах. По умолчанию: `0`. + +--- + +####

no-discover + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +Запрещает клиенту находить других пиров. По умолчанию: `false`. + +--- + +####

restore + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +Восстанавливает блоки из указанного файла архива + +--- + +####

block-time + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +Задает время производства блока в секундах. По умолчанию: `2` + +--- + +####

access-control-allow-origins + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +Задает авторизованные домены для общего доступа к ответам из запросов JSON-RPC. +Несколько параметров `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"` можно использовать для включения авторизации нескольких доменов. +Если параметр пропущен, заголовок Access-Control-Allow-Origins устанавливается как `*` и все домены авторизуются. + +--- + +### параметры команды genesis {#genesis-flags} +| **Все флаги генеза** | +|---------------------------------------|---------------------------------------------| +| [dir](/docs/edge/get-started/cli-commands#dir) | [name](/docs/edge/get-started/cli-commands#name) | +| [pos](/docs/edge/get-started/cli-commands#pos) | [epoch-size](/docs/edge/get-started/cli-commands#epoch-size) | +| [premine](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [ibft-validator-type](/docs/edge/get-started/cli-commands#ibft-validator-type) | [ibft-validators-prefix-path](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [ibft-validator](/docs/edge/get-started/cli-commands#ibft-validator) | [block-gas-limit](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [consensus](/docs/edge/get-started/cli-commands#consensus) | [bootnode](/docs/edge/get-started/cli-commands#bootnode) | +| [max-validator-count](/docs/edge/get-started/cli-commands#max-validator-count) | [min-validator-count](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

dir + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +Устанавливает каталог для данных генезиса Polygon Edge. По умолчанию: `./genesis.json`. + +--- + +####

Название + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +Задает имя цепочки. По умолчанию: `polygon-edge`. + +--- + +####

pos + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +Устанавливает флаг, указывающий, что клиент должен использовать PoS IBFT. PoA используется по умолчанию, если флаг не установлен или `false`. + +--- + +####

epoch-size + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +Задает размер эпохи для цепочки. По умолчанию `100000`. + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +Задает предварительно пополненные счета и их остатки на балансе в формате `address:amount`. +Количество можно вводить в десятичном или шестнадцатеричном формате. +По умолчанию предопределен баланс: `0xD3C21BCECCEDA1000000`(1 миллион токенов нативной валюты). + +--- + +####

chainid + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +Задает идентификатор цепочки. По умолчанию: `100`. + +--- + +####

ibft-validator-type + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +Указывает режим валидации заголовков блоков. Возможные значения: `[ecdsa, bls]`. По умолчанию: `bls`. + +--- + +####

ibft-validators-prefix-path + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +Путь префикса для каталога папки валидатора. Должен присутствовать, если отсутствует параметр `ibft-validator`. + +--- + +####

ibft-validator + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Задает передаваемые адреса как валидаторы IBFT. Должен присутствовать, если отсутствует параметр `ibft-validators-prefix-path`. +1. Если сеть работает с ECDSA, используется формат `--ibft-validator [ADDRESS]`. +2. Если сеть работает с BLS, используется формат `--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]`. + +--- + +####

block-gas-limit + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +Указывает максимальное количество газа, используемое всеми операциями в блоке. По умолчанию: `5242880`. + +--- + +####

consensus + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +Задает протокол консенсуса. По умолчанию: `pow`. + +--- + +####

bootnode + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Multiaddr URL для загрузочной строки обнаружения p2p. Этот параметр можно использовать несколько раз. +Вместо IP-адреса можно указать DNS-адрес загрузочного узла. + +--- + +####

max-validator-count + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +Максимальное количество стейкеров, которые могут присоединиься к набору валидаторов в консенсусе PoS. +Это количество не может превышать значение MAX_SAFE_INTEGER (2^53 - 2). + +--- + +####

min-validator-count + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +Минимальное количество стейкеров, которые должны присоединиться к набору валидаторов в консенсусе PoS. +Это количество не может превышать значение max-validator-count. +Значение по умолчанию равняется 1. + +--- + +### flags predeploy {#genesis-predeploy-flags} + +

artifacts-path

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +Устанавливает путь к контрактному артефактам `abi`JSON, который содержит , `bytecode`и .`deployedBytecode` + +--- + +

chain

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +Устанавливает путь к `genesis.json`файлу, который должен быть обновлен. По умолчанию `./genesis.json`. + +--- + +

constructor-args

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +Устанавливает аргументы конструктора смарт-контракта, если таковые имеются. Подробное руководство по тому, как должны выглядеть эти аргументы, пожалуйста, обратитесь в [статью предварительного развертывания](/docs/edge/additional-features/predeployment). + +--- + +

predeploy-address

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +Устанавливает адрес для предварительного развертывания. По умолчанию `0x0000000000000000000000000000000000001100`. + +--- + + +## Команды оператора {#operator-commands} + +### Команды пиров {#peer-commands} + +| **Команда** | **Описание** | +|------------------------|-------------------------------------------------------------------------------------| +| peers add | Добавляет нового пира, используя адрес libp2p | +| peers list | Выводит список все пиров, к которым клиент подключен через libp2p | +| peers status | Выводит статус определенного пира из списка пиров, используя адрес libp2p | + +

Параметры команды peers add

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Адрес пира libp2p в формате multiaddr. + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +Адрес gRPC API. По умолчанию: `127.0.0.1:9632`. + +

Параметры комнады peers list

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +Адрес gRPC API. По умолчанию: `127.0.0.1:9632`. + +

Параметры команды peers status

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Идентификатор нода Libp2p определенного пира в сети p2p. + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +Адрес gRPC API. По умолчанию: `127.0.0.1:9632`. + +### Команды IBFT {#ibft-commands} + +| **Команда** | **Описание** | +|------------------------|-------------------------------------------------------------------------------------| +| ibft snapshot | Возвращает снимок IBFT | +| ibft candidates | Запрашивает текущий набор предложенных кандидатов, а также кандидатов, которые еще не были включены | +| ibft propose | Предлагает нового кандидата для добавления/удаления из набора валидаторов | +| ibft status | Возвращает общий статус клиента IBFT | +| ibft switch | Добавляет конфигурации форка в файл genesis.json для переключения типа IBFT | +| ibft quorum | Указывает номер блока, после которого для достижения консенсуса будет использоваться метод оптимального размера кворума | + + +

Параметры команды ibft snapshot

+ +

number

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +Высота блока (число) для снимка. + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +Адрес gRPC API. По умолчанию: `127.0.0.1:9632`. + +

Параметры команды ibft candidates

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Адрес gRPC API. По умолчанию: `127.0.0.1:9632`. + +

Параметры команды ibft propose

+ +

vote

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +Предлагает изменения набора валидаторов. Возможные значения: `[auth, drop]`. + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +Адрес аккаунта, за который требуется проголосовать. + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +Публичный ключ BLS аккаунта, за который требуется проголосовать, нужен только в режиме BLS. + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Адрес gRPC API. По умолчанию: `127.0.0.1:9632`. + +

Параметры команды ibft status

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +Адрес gRPC API. По умолчанию: `127.0.0.1:9632`. + +

Параметры команды ibft switch

+ +

chain

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +Указывает файл генезиса для обновления. По умолчанию: `./genesis.json`. + +--- + +

Тип

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +Указывает тип IBFT для переключения. Возможные значения: `[PoA, PoS]`. + +--- + +

deployment

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +Указывает высоту развертывания контракта. Параметр доступен только для PoS. + +--- + +

from

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +Указывает режим валидации заголовков блоков. Возможные значения: `[ecdsa, bls]`. По умолчанию: `bls`. + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +Путь префикса для каталогов новых валидаторов. Должен присутствовать, если отсутствует параметр `ibft-validator`. Доступен только при использовании IBFT в режиме PoA (параметр `--pos` отсутствует). + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Задает переданные адреса, использованные валидаторами IBFT после форка. Должен присутствовать, если отсутствует параметр `ibft-validators-prefix-path`. Доступен только в режиме PoA. +1. Если сеть работает с ECDSA, используется формат `--ibft-validator [ADDRESS]`. +2. Если сеть работает с BLS, используется формат `--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]`. + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +Максимальное количество стейкеров, которые могут присоединиься к набору валидаторов в консенсусе PoS. +Это количество не может превышать значение MAX_SAFE_INTEGER (2^53 - 2). + +--- + +

min-validator-count

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +Минимальное количество стейкеров, которые должны присоединиться к набору валидаторов в консенсусе PoS. +Это количество не может превышать значение max-validator-count. +Значение по умолчанию равняется 1. + +Задает начальную высоту форка. + +--- + +

Параметры команды ibft quorum

+ +

from

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +Высота переключения расчета кворума на QuorumOptimal, который использует формулу `(2/3 * N)`, где `N` — количество нодов валидатора. Обратите внимание, что это требуется только для обратной совместимости, т. е. только для цепочек, использовавших старые расчеты кворума до определенной высоты блока. + +--- + +

chain

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +Указывает файл генезиса для обновления. По умолчанию: `./genesis.json`. + +### Команды пула транзакций {#transaction-pool-commands} + +| **Команда** | **Описание** | +|------------------------|--------------------------------------------------------------------------------------| +| txpool status | Возвращает количество транзакций в пуле | +| txpool subscribe | Подписывается на события в пуле транзакций | + +

Параметры команды txpool status

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +Адрес gRPC API. По умолчанию: `127.0.0.1:9632`. + +

Параметры команды txpool subscribe

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +Адрес gRPC API. По умолчанию: `127.0.0.1:9632`. + +--- + +

promoted

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +Подписывается на продвигаемые события транзакций в пуле TxPool. + +--- + +

dropped

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +Подписывается на отброшенные события транзакций в пуле TxPool. + +--- + +

demoted

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +Подписывается на пониженные события транзакций в пуле TxPool. + +--- + +

added

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +Подписывается на добавленные события транзакций в пуле TxPool. + +--- + +

enqueued

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +Подписывается на поставленные в очередь события транзакций в очередях аккаунта. + +--- + +### Команды блокчейна {#blockchain-commands} + +| **Команда** | **Описание** | +|------------------------|-------------------------------------------------------------------------------------| +| status | Возвращает статус клиента. Подробный отклик приведен ниже | +| monitor | Подписывается на поток событий блокчейна. Подробный отклик приведен ниже | +| version | Возвращает текущую версию клиента | + +

Параметры команды status

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +Адрес gRPC API. По умолчанию: `127.0.0.1:9632`. + +

Параметры команды monitor

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +Адрес gRPC API. По умолчанию: `127.0.0.1:9632`. + +--- +

Команда

+ + + + + + version + + + + +Отображает версию релиза, ветку git, хэш и время сборки. + +## Команды секретов {#secrets-commands} + +| **Команда** | **Описание** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| secrets init | Инициализирует приватные ключи для соответствующего диспетчера секретов | +| secrets generate | Генерирует файл конфигурации диспетчера секретов, который может обрабатываться Polygon Edge | +| вывод секретов | Отображает адрес открытого ключа BLS, адрес открытого ключа валидатора и идентификатор нода для ссылки | + +### Параметры команды secrets init {#secrets-init-flags} + +

Конфигурация

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +Задает путь к файлу конфигурации SecretsManager. Используется для Hashicorp Vault. Если пропущен, используется локальный диспетчер секретов FS. + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +Задает директорию данных Polygon Edge, если используется локальная файловая система. + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +Устанавливает флаг необходимости сгенерировать ключ ECDSA. По умолчанию: `true`. + +--- + +

network

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +Устанавливает флаг необходимости сгенерировать ключ сети Libp2p. По умолчанию: `true`. + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +Устанавливает флаг необходимости сгенерировать ключ BLS. По умолчанию: `true`. + +### Параметры команды secrets generate {#secrets-generate-flags} + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +Задает каталог файла конфигурации диспетчера секретов по умолчанию: `./secretsManagerConfig.json` + +--- + +

Тип

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +Указывает тип диспетчера секретов [`hashicorp-vault`]. По умолчанию: `hashicorp-vault` + +--- + +

token

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +Указывает токен доступа к сервису + +--- + +

server-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +Указывает URL-адрес сервера для сервиса + +--- + +

Название

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +Указывает имя нода для учета записей в сервисе. По умолчанию: `polygon-edge-node` + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Задает пространство имен, используемое для диспетчера секретов Hashicorp Vault. По умолчанию: `admin` + +### Флаги вывода {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +Устанавливает флаг, указывающий, выводить ли только открытый ключ BLS. По умолчанию: `true` + +--- + +

Конфигурация

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +Задает путь к файлу конфигурации SecretsManager. Если пропущен, используется локальный диспетчер секретов FS. + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +Задает директорию данных Polygon Edge, если используется локальная файловая система. + +--- + +

node-id

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +Устанавливает флаг, указывающий, следует ли выводить только идентификатор сетевой ноды. По умолчанию: `true` + +--- + +

Валидатор

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +Устанавливает флаг, указывающий, следует ли выводить только адрес валидатора. По умолчанию: `true` + +--- + +## Отклики {#responses} + +### Отклик состояния {#status-response} + +Объект отклика определяется с использованием буферов протокола. +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### Отклик монитора {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## Утилиты {#utilities} + +### Команды белого списка {#whitelist-commands} + +| **Команда** | **Описание** | +|------------------------|-------------------------------------------------------------------------------------| +| whitelist show | Выводит информацию белого списка | +| whitelist deployment | Обновляет белый список развертывания смарт-контракта | + +

whitelist show

+ + + + + whitelist show + + + + +Отображает информацию белого списка. + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +Указывает файл генезиса для обновления. По умолчанию: `./genesis.json`. + +--- + +

whitelist deployment

+ +

chain

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +Указывает файл генезиса для обновления. По умолчанию: `./genesis.json`. + +--- + +

add

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Добавляет новый адрес к белому списку для развертывания контрактов. Выполнять развертывание контрактов могут только адреса из белого списка развертывания контрактов. Если белый список пуст, любой адрес может развернуть контракт + +--- + +

remove

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Удаляет адрес из белого списка развертывания контракта. Выполнять развертывание контрактов могут только адреса из белого списка развертывания контрактов. Если белый список пуст, любой адрес может развернуть контракт + +--- + +### параметры backup {#backup-flags} + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +Адрес gRPC API. По умолчанию: `127.0.0.1:9632`. + +--- + +

out

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +Путь к файлу архива для сохранения. + +--- + +

from

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +Начальная высота блоков в архиве. По умолчанию: 0. + +--- + +

to

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +Конечная высота блоков в архиве. + +--- + +## Шаблон генезиса {#genesis-template} +Файл генезиса следует использовать для установки начального состояния блокчейна (например, если какие-то аккаунты должны иметь начальный баланс). + +Генерируется следующий файл *./genesis.json*: +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### Директория данных {#data-directory} + +При выполнении команды с параметром *data-dir* создается папка **test-chain**. +Структура этой папки состоит из следующих вложенных папок: +* **blockchain** — хранит БД LevelDB для объектов блокчейна +* **trie** — хранит БД LevelDB для попыток Merkle +* **хранилище ключей** — хранит приватные ключи для клиента. Это включает приватный ключ libp2p и приватный ключ запечатывания/валидатора +* **consensus** — хранит любую информацию о консенсусе, которая может потребоваться клиенту во время работы + +## Информационные ресурсы {#resources} +* **[Буферы протоколов](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/ru-edge/get-started/installation.md b/archive/edge/ru-edge/get-started/installation.md new file mode 100644 index 0000000000..7a4f7c9b1e --- /dev/null +++ b/archive/edge/ru-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: Установка +description: "Как установить Polygon Edge." +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +Вы можете применить тот способ установки, который наиболее вам удобен. + +Мы рекомендуем использовать предварительно построенные релизы и проверять предоставленные контрольные суммы. + +## Предварительно построенные релизы {#pre-built-releases} + +Вы можете увидеть список всех релизов на странице [Релизы GitHub](https://github.com/0xPolygon/polygon-edge/releases). + +Polygon Edge поставляется с кросс-компилированными двоичными файлами AMD64/ARM64 для Darwin и Linux. + +--- + +## Изображение Docker {#docker-image} + +Официальные изображения Docker размещаются в [реестре hub.docker.com](https://hub.docker.com/r/0xpolygon/polygon-edge). + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## Построение из источника {#building-from-source} + +Перед тем как использовать `go install`, убедитесь, что вы установили и правильно настроили Go `>=1.18`. + +Стабильный филиал — это ветка последнего релиза. + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## Использование `go install` + +Перед тем как использовать `go install`, убедитесь, что вы установили и правильно настроили Go `>=1.17`. + +`go install github.com/0xPolygon/polygon-edge@release/` + +Бинарный будет доступен в переменной `GOBIN`окружения, и будет включать изменения из последнего релиза. Вы можете оформить заказ на [GitHub Releases](https://github.com/0xPolygon/polygon-edge/releases), чтобы узнать, кто из них является последним. diff --git a/archive/edge/ru-edge/get-started/set-up-ibft-locally.md b/archive/edge/ru-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..6484ad9ccc --- /dev/null +++ b/archive/edge/ru-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,415 @@ +--- +id: set-up-ibft-locally +title: Локальная настройка +description: "Пошаговое руководство по локальной настройке." +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution Настоящее руководство предназначено исключительно для целей тестирования + +Данное руководство содержит инструкции по настройке сети Polygon Edge на локальном компьютере для целей тестирования и разработки . + +Данная процедура сильно отличается от процедуры настройки сети Polygon Edge в реальном сценарии на системе Облачный провайдер: **[Cloud Setup](/docs/edge/get-started/set-up-ibft-on-the-cloud)** + +::: + + +## Требования {#requirements} + +В разделе [Установка](/docs/edge/get-started/installation) описывается установка Polygon Edge. + +## Обзор {#overview} + +![Локальная настройка](/img/edge/ibft-setup/local.svg) + +Цель этого руководства — развернуть рабочую `polygon-edge` сеть блокчейна, использующую [протокол консенсуса IBFT](https://github.com/ethereum/EIPs/issues/650). +Сеть блокчейна будет состоять из 4 нодов, все из которых будут являться валидаторами и соответственно будут иметь полномочия предлагать блоки и подтвердждать блоки, поступившие от других авторов предложений. +Все 4 нода будут работать на одном компьютере, поскольку настоящее руководство призвано помочь вам развернуть полностью функциональный кластер IBFT за минимальное время. + +Для этого мы выполним 4 простых шага. + +1. При инициализации каталогов данных будут сгенерированы ключи валидатора для каждого из 4 нодов и будут инициализированы пустые каталоги данных блокчейна. Ключи валидатора играют важную роль, поскольку с их помощью мы добавим в загрузку блок генезиса с начальным набором валидаторов. +2. Подготовка строки подключения для загрузочного нода даст необходимую информацию для каждого нода, который мы будем запускать, в том числе о том, к какому ноду подключаться при первом запуске. +3. При генерировании файла `genesis.json` в качестве исходных данных потребуются ключи валидатора, сгенерированные на **шаге 1**, для настройки начальных валидаторов сети в блоке генезиса и строка подключения загрузочного нода из **шага 2**. +4. Последним шагом и главной целью этого руководства будет запуск всех нодов. При этом мы сообщим нодам, какую директорию данных им нужно будет использовать и где найти `genesis.json` для полной загрузки начального состояния сети. + +Поскольку все четыре нода будут работать на локальной системе localhost, при настройке предполагается, что все каталоги данных каждого из нодов находятся в одном и том же родительском каталоге. + +:::info Количество валидаторов + +Минимального ограничения количества нодов в кластере нет, т. е. можно создавать кластеры только с одним нодом валидатора. +Необходимо помнить, что кластер с _единственным_ нодом не имеет **отказоустойчивости** и **гарантии BFT**. + +Для достижения гарантии BFT рекомендуется использовать кластер, содержащий не менее 4 нодов, потому что такой кластер выдерживает выход из строя 1 нода при нормальной работе остальных 3 нодов. + +::: + +## Шаг 1: инициализация папок данных для IBFT и генерирование ключей валидатора {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +Для начала работы с IBFT необходимо инициализировать папки данных, +по одной для каждого нода: + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +Каждая из этих команд выводит на печать ключ валидатора, публичный ключ BLS и [идентификатор нода](https://docs.libp2p.io/concepts/peer-id/). Для следующего шага вам потребуется идентификатор первого нода. + +### Секреты {#outputting-secrets} +Вывод секретов может быть возвращен снова, если это необходимо. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## Шаг 2: подготовка мультиадресной строки подключения для загрузочного нода {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Для успешного подключения нода необходимо знать, к какому серверу `bootnode` этот нод должен подключиться для получения информации обо всех остальных нодах в сети. На жаргоне p2p `bootnode` иногда также называют сервером `rendezvous`. + +`bootnode` не является особенным экземпляром нода Polygon Edge. Каждый нод Polygon Edge может выступать в качестве `bootnode`, но +для каждого нода Polygon Edge требуется указать набор загрузочных нодов, у которых будет запрашиваться информация о способе подключения ко всем остальным нодам в сети. + +Чтобы создать строку подключения для указания загрузочного нода, необходимо соблюдать мультиадресный формат [multiaddr](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +В этом руководстве мы будем рассматривать первый и второй ноды как загрузочные ноды для всех остальных нодов. В этом сценарии ноды, подключающиеся к `node 1` или `node 2`, получат информацию о подключении друг к другу через общий загрузочный нод, с которым они контактируют. + +:::info Для запуска нода необходимо указать хотя бы один загрузочный нод + +Чтобы ноды в сети могли находить друг друга, требуется хотя бы **один** загрузочный нод. Рекомендуется использовать больше загрузочных нодов, поскольку они обеспечивают устойчивость сети в случае неполадок. +В этом руководстве мы укажем два нода, но это можно изменить в любое время, что не повлияет на действительность файла `genesis.json`. + +::: + +Поскольку мы работаем в локальной системе localhost, можно предположить, что `` является `127.0.0.1`. + +Для `` мы будем использовать `10001`, поскольку мы собираемся настроить сервер libp2p для `node 1` для последующего прослушивания этого порта. + +Наконец, нам потребуется ``, который мы получим из вывода ранее выполненной команды `polygon-edge secrets init --data-dir test-chain-1` (которая использовалась для генерирования ключей и каталогов данных для `node1`) + +После сборки строка подключения multiaddr для нода `node 1`, который мы будем использовать как загрузочный нод, будет выглядеть примерно так (отличаться будет только `` в конце): +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Точно так же мы построим мультиадресную строку multiaddr для второго загрузочного нода, как показано ниже +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info Имена хостов DNS вместо IP-адресов + +Polygon Edge поддерживает использование имен хостов DNS для конфигурации нодов. Это очень полезная функция при облачном развертывании, поскольку IP-адрес нода может измениться в связи с различными причинами. + +Мультиадресный формат строки подключения multiaddr с использованием имен хостов DNS выглядит следующим образом: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## Шаг 3: генерирование файла генезиса с 4 нодами в качестве валидаторов {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +Что делает эта команда: + +* `--ibft-validators-prefix-path` устанавливает указанный путь папки префиксов, который может использовать +IBFT в Polygon Edge. Этот каталог используется для размещения папки `consensus/`, в которой хранится приватный ключ валидатора. При этом +публичный ключ валидатора потребуется для создания файла генезиса — первоначального списка загрузочных нодов. +Этот параметр имеет смысл использовать только при настройке сети в локальной системе localhost, поскольку в реальных условиях нельзя ожидать, что все +каталоги данных нодов будут находиться в одной файловой системе, откуда мы сможем легко считать их публичные ключи. +* `--bootnode` устанавливает адрес загрузочного нода, который позволит нодам находить друг друга. +Мы будем использовать строку multiaddr из `node 1`, как описано в **шаге 2**. + +В результате выполнения этой команды мы получим файл `genesis.json`, содержащий блок генезиса нашего нового блокчейна с заданным набором валидаторов и конфигурацией, которая покажет, с каким нодом следует связаться в первую очередь для установления подключения. + +:::info Переключить в ECDSA + +BLS — это режим валидации заголовков блока по умолчанию. Если вы хотите, чтобы ваша цепочка работала в режиме ECDSA, вы можете использовать `—ibft-validator-type`флаг , с `ecdsa`аргументом: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info Предварительное пополнение аккаунта + +Возможно, вы захотите настроить свою сеть блокчейна так, чтобы на некоторых адресах был предварительно пополнен баланс. + +Для этого можно передать любое количество параметров `--premine` на каждый адрес, который вы захотите инициализировать с определенным балансом +в блокчейне. + +Например, если вы захотите предварительно загрузить 1000 ETH на адрес `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` в нашем блоке генезиса, нам нужно будет предоставить следующий аргумент: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Обратите внимание, что предварительно загружаемая сумма указывается в WEI, а не ETH.** + +::: + +:::info Установите лимит газа для блока + +По умолчанию для каждого блока установлен лимит газа `5242880`. Это значение записывается в файл генезиса, но, возможно, вы захотите +увеличить или уменьшить его. + +Для этого вы можете использовать параметр `--block-gas-limit` с желаемым значением, как показано ниже : + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Установка лимита дескрипторов системного файла + +Некоторые операционные системы имеют невысокий лимит дескрипторов файла по умолчанию (максимальное количество открытых файлов). +Если ожидается, что для нодов потребуется высокая пропускная способность, вы можете попробовать увеличить этот лимит на уровне ОС. + +Для дистрибутива Ubuntu процедура будет выглядеть следующим образом (если вы не используете дистрибутив Ubuntu/Debian, воспользуйтесь официальной документацией для вашей ОС) : +- Проверьте текущие лимиты ОС (по количеству открытых файлов) +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- Увеличьте лимит открытых файлов + - Локально — влияет только на текущую сессию: + ```shell + ulimit -u 65535 + ``` + - Глобально или на пользователя (лимиты добавляются в конец файла /etc/security/limits.conf) : + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +Также вы можете изменить дополнительные параметры, сохранить файл и перезапустить систему. +После перезапуска проверьте лимит дескриптора файлов еще раз. +Для него необходимо будет установить значение, которое вы определили в файле limits.conf. + +::: + + +## Шаг 4: запуск всех клиентов {#step-4-run-all-the-clients} + +Поскольку мы пытаемся запустить сеть Polygon Edge из 4 нодов на одном компьютере, нам нужно следить за тем, чтобы +избежать конфликтов портов. Поэтому мы выделим порты прослушивания каждого сервера нода на следующих основаниях: + +- `10000` для сервера gRPC `node 1`, `20000` для сервера GRPC `node 2` и т. д. +- `10001` для сервера libp2p `node 1`, `20001` для сервера libp2p `node 2` и т. д. +- `10002` для сервера JSON-RPC `node 1`, `20002` для сервера JSON-RPC `node 2` и т. д. + +Запустите **первый** клиент (обратите внимание на порт `10001`, потому что он использовался в составе libp2p multiaddr на **шаге 2** вместе с идентификатором нода 1): + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +Запустите **второй** клиент: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +Запустите **третий** клиент: + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +Запустите **четвертый** клиент: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +Краткий обзор уже выполненных задач: + +* Указана диретория данных клиента **./test-chain-\*** +* Серверы GRPC запущены для каждого нода на портах **10000**, **20000**, **30000** и **40000** соответственно +* Серверы libp2p запущены для каждого нода на портах **10001**, **20001**, **30001** и **40001** соответственно +* Серверы JSON-RPC запущены для каждого нода на портах **10002**, **20002**, **30002** и**40002** соответственно +* Параметр *seal* указывает, что запускаемый нод будет участвовать в запечатывании блока +* Параметр *chain* указывает, какой файл генезиса следует использовать для конфигурации цепочки + +Структура файла генезиса описана в разделе [Команды интерфейса командной строки (CLI)](/docs/edge/get-started/cli-commands). + +Запустив предыдущие команды, вы настроили сеть Polygon Edge из 4 нодов, которая способна запечатывать блоки и восстанавливаться после выхода нода из строя. + +:::info Запустите клиент, используя файл конфигурации + +Вместо того чтобы указывать все параметры конфигурации как аргументы CLI, клиент также можно запустить с использованием файла конфигурации, выполнив следующую команду: + +````bash +polygon-edge server --config +```` +Пример: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +В настоящее время мы поддерживаем `yaml`и `json`основанные файлы конфигурации, файлы конфигурации образца можно найти **[здесь](/docs/edge/configuration/sample-config)** + +::: + +:::info Шаги для запуска нода, который не является валидатором + +Нод, не являющийся валидатором, всегда будет синхронизировать последние блоки, получаемые от нода валидатора. Для запуска нода, не являющегося валидатором, служит следующая команда. + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +Например, вы можете добавить **пятый** клиент, не являющийся валидатором, выполнив следующую команду : + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info Укажите лимит цены + +Нод Polygon Edge можно запустить с заданным **лимитом цены** для входящих транзакций. + +Единица измерения лимита цены: `wei`. + +Установка лимита цены означает, что любые транзакции, обработанные текущим нодом, должны иметь цену на газ **выше**, +чем заданный лимит цены, или они не будут включены в блок. + +Если для большинства нодов установлен определенный лимит цены, вводится правило, что транзакции в сети +не могут опускаться ниже определенного порога цены. + +По умолчанию лимит цены имеет значение `0`, т. е. он не применяется принудительно. + +Пример использования параметра `--price-limit`: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Следует отметить, что лимиты цены **принудительно устанавливаются только для транзакций, не являющихся локальными**, т. е. +лимит цены не относится к транзакциям, которые добавляются на нод локально. +::: + +:::info URL-адрес WebSocket +По умолчанию при запуске Polygon Edge генерируется WebSocket URL на базе расположения цепочки. +Схема URL `wss://` используется для ссылок HTTPS, а `ws://` — для HTTP. + +URL-адрес Localhost WebSocket: +````bash +ws://localhost:10002/ws +```` +Обратите внимание, что номер порта зависит от выбранного для нода порта JSON-RPC. + +URL-адрес Edgenet WebSocket: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## Шаг 5: взаимодействие с сетью Polygon Edge {#step-5-interact-with-the-polygon-edge-network} + +Теперь мы настроили хотя бы 1 работающий клиент и можем начать взаимодействие с блокчейном, используя указанный выше предварительно пополненный аккаунт, и указать JSON-RPC URL для любого из 4 нодов: +- Нод 1: `http://localhost:10002` +- Нод 2: `http://localhost:20002` +- Нод 3: `http://localhost:30002` +- Нод 4: `http://localhost:40002` + +Для отправки команд оператора на новый кластер следуйте указаниям этого руководства: [Как запрашивать информацию оператора](/docs/edge/working-with-node/query-operator-info) (порты GRPC построенного нами кластера `10000`/`20000`/`30000`/`40000` для каждого нода соответственно) diff --git a/archive/edge/ru-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/ru-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..c51ebab1b9 --- /dev/null +++ b/archive/edge/ru-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,430 @@ +--- +id: set-up-ibft-on-the-cloud +title: Облачная настройка +description: "Пошаговое руководство по облачной настройке." +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info Данное руководство описывает настройку основной сети mainnet или тестовой сети testnet + +Руководство, приведенное ниже, предоставит вам инструкции о том, как настроить сеть Polygon Edge на облачном провайдере для работы вашей тестовой сети testnet или основной сети mainnet. + +Если вы хотите установить сеть Polygon Edge локально для быстрой проверки `polygon-edge` перед тем, как осуществить установку для производства, обратитесь к разделу **[Локальная настройка](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## Требования {#requirements} + +В разделе [Установка](/docs/edge/get-started/installation) описывается установка Polygon Edge. + +### Настройка подключения VM (виртуальных машин) {#setting-up-the-vm-connectivity} + +В зависимости от выбора облачного провайдера вы можете настроить подключение и правила между VM (виртуальными машинами) с помощью брандмауэра, групп безопасности или списков контроля доступа. + +Поскольку единственной частью `polygon-edge`, которая должна быть открыта для других VM, является сервер libp2p, достаточно просто разрешить все коммуникации между VM через порт libp2p `1478` по умолчанию. + +## Обзор {#overview} + +![Облачная настройка](/img/edge/ibft-setup/cloud.svg) + +Цель этого руководства — развернуть рабочую `polygon-edge` сеть блокчейна, использующую [протокол консенсуса IBFT](https://github.com/ethereum/EIPs/issues/650). +Сеть блокчейна будет состоять из 4 нодов, все из которых будут являться валидаторами и соответственно будут иметь полномочия предлагать блоки и подтверждать блоки, поступившие от других авторов предложений. +Каждый из 4 нодов будет работать на своей собственной VM, поскольку идея данного руководства заключается в том, чтобы предоставить вам полностью функциональную сеть Polygon Edge, сохраняя ключи валидатора в тайне, чтобы обеспечить надежную настройку сети. + +Для этого мы выполним 4 простых шага: + +0. Ознакомьтесь со списком **требований**, который приведен выше +1. Сгенерируйте приватный ключ для каждого из валидаторов и инициализируйте директорию данных +2. Подготовьте строку подключения для загрузочного нода, который будет помещен в общий `genesis.json` +3. Создайте `genesis.json` на своей локальной машине и отправьте/переведите его на каждый из нодов +4. Запустите все ноды + +:::info Количество валидаторов + +Минимального ограничения количества нодов в кластере нет, т. е. можно создавать кластеры только с одним нодом валидатора. +Необходимо помнить, что кластер с _единственным_ нодом не имеет **отказоустойчивости** и **гарантии BFT**. + +Для достижения гарантии BFT рекомендуется использовать кластер, содержащий не менее 4 нодов, потому что такой кластер выдерживает выход из строя 1 нода при нормальной работе остальных 3 нодов. + +::: + +## Шаг 1: инициализируйте папки данных и сгенерируйте ключи валидатора {#step-1-initialize-data-folders-and-generate-validator-keys} + +Чтобы начать работу с Polygon Edge, необходимо инициализировать папки данных на каждом ноде: + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +Каждая из этих команд выводит на печать ключ валидатора, публичный ключ BLS и [идентификатор нода](https://docs.libp2p.io/concepts/peer-id/). Для следующего шага вам потребуется идентификатор первого нода. + +### Секреты {#outputting-secrets} +Вывод секретов может быть возвращен снова, если это необходимо. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning Держите свою директорию данных в секрете! + +Созданные выше директории данных, помимо инициализации директорий для хранения состояния блокчейна, также будут генерировать приватный ключ вашего валидатора. **Этот ключ должен храниться в секрете, поскольку его кража приведет к тому, что кто-то сможет выдать вас за валидатора в сети!** +::: + +## Шаг 2: подготовьте мультиадресную строку подключения для загрузочного нода {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Для успешного подключения нода необходимо знать, к какому серверу `bootnode` этот нод должен подключиться для получения информации обо всех остальных нодах в сети. На жаргоне p2p `bootnode` иногда также называют сервером `rendezvous`. + +`bootnode`не является особенным экземпляром нода Polygon Edge. Каждый нод Polygon Edge может работать в качестве `bootnode`, и каждый нод Polygon Edge должен иметь набор загрузочных нодов, к которым будут обращаться для получения информации о том, как подключиться ко всем остальным нодам в сети. + +Чтобы создать строку подключения для указания загрузочного нода, необходимо соблюдать мультиадресный формат [multiaddr](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +В этом руководстве мы будем рассматривать первый и второй ноды как загрузочные ноды для всех остальных нодов. В этом сценарии ноды, подключающиеся к `node 1` или `node 2`, получат информацию о подключении друг к другу через общий загрузочный нод, с которым они контактируют. + +:::info Для запуска нода необходимо указать хотя бы один загрузочный нод + +Чтобы ноды в сети могли находить друг друга, требуется хотя бы **один** загрузочный нод. Рекомендуется использовать больше загрузочных нодов, поскольку они обеспечивают устойчивость сети в случае неполадок. +В этом руководстве мы укажем два нода, но это можно изменить в любое время, что не повлияет на действительность файла `genesis.json`. + +::: + +Поскольку первая часть строки получения multiaddr — это ``, сюда вам нужно ввести IP-адрес, который могут достичь другие ноды, в зависимости от вашей настройки, это может быть приватный или публичный IP-адрес, а не `127.0.0.1`. + +Для `` мы будем использовать `1478`, поскольку это является портом libp2p по умолчанию. + +Наконец, нам потребуется ``, который мы получим из вывода ранее выполненной команды `polygon-edge secrets init --data-dir data-dir` (которая использовалась для генерирования ключей и каталогов данных для `node 1`) + +После сборки строка подключения multiaddr для нода `node 1`, который мы будем использовать как загрузочный нод, будет выглядеть примерно так (отличаться будет только `` в конце): +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Точно так же мы построим мультиадресную строку multiaddr для второго загрузочного нода, как показано ниже +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info Имена хостов DNS вместо IP-адресов + +Polygon Edge поддерживает использование имен хостов DNS для конфигурации нодов. Это очень полезная функция при облачном развертывании, поскольку IP-адрес нода может измениться в связи с различными причинами. + +Мультиадресный формат строки подключения multiaddr с использованием имен хостов DNS выглядит следующим образом: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## Шаг 3: сгенерируйте файл генезиса с 4 нодами в качестве валидаторов {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +Этот шаг может быть осуществлен на вашей локальной машине, но вам понадобятся публичные ключи валидатора для каждого из 4 валидаторов. + +Валидаторы могут безопасно разделить `Public key (address)`, как показано ниже в выводе на их команды `secrets init`, чтобы вы могли безопасно сгенерировать genesis.json с теми валидаторами в первоначальном наборе, которые идентифицированы их публичным ключами: + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +Учитывая, что вы получили все 4 публичных ключа валидатора, вы сможете запустить следующую команду, чтобы сгенерировать `genesis.json` + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +Что делает эта команда: + +* `--ibft-validator` устанавливает публичный ключ валидатора, который должен быть включен в первоначальный набор валидаторов в генезисном блоке. Первоначальных валидаторов может быть много. +* `--bootnode` устанавливает адрес загрузочного нода, который позволит нодам находить друг друга. +Мы будем использовать строку multiaddr `node 1`, как упоминается в **шаге 2**, также вы можете добавить столько загрузочных нодов, сколько захотите, как показано выше. + +:::info Переключить в ECDSA + +BLS — это режим валидации заголовков блока по умолчанию. Если вы хотите, чтобы ваша цепочка работала в режиме ECDSA, вы можете использовать `—ibft-validator-type`флаг , с `ecdsa`аргументом: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info Предварительное пополнение аккаунта + +Возможно, вы захотите настроить свою сеть блокчейна так, чтобы на некоторых адресах был предварительно пополнен баланс. + +Для этого можно передать любое количество параметров `--premine` на каждый адрес, который вы захотите инициализировать с определенным балансом +в блокчейне. + +Например, если вы захотите предварительно загрузить 1000 ETH на адрес `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` в нашем блоке генезиса, нам нужно будет предоставить следующий аргумент: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Обратите внимание, что предварительно загружаемая сумма указывается в WEI, а не ETH.** + +::: + +:::info Установите лимит газа для блока + +По умолчанию для каждого блока установлен лимит газа `5242880`. Это значение записывается в файл генезиса, но, возможно, вы захотите +увеличить или уменьшить его. + +Для этого вы можете использовать параметр `--block-gas-limit` с желаемым значением, как показано ниже : + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Установка лимита дескрипторов системного файла + +Некоторые операционные системы имеют невысокий лимит дескрипторов файла по умолчанию (максимальное количество открытых файлов). +Если ожидается, что для нодов потребуется высокая пропускная способность, вы можете попробовать увеличить этот лимит на уровне ОС. + +Для дистрибутива Ubuntu процедура будет выглядеть следующим образом (если вы не используете дистрибутив Ubuntu/Debian, воспользуйтесь официальной документацией для вашей ОС) : +- Проверьте текущие лимиты ОС (по количеству открытых файлов) +```shell title="ulimit -a" +ubuntu@ubuntu:~$ ulimit -a +core file size (blocks, -c) 0 +data seg size (kbytes, -d) unlimited +scheduling priority (-e) 0 +file size (blocks, -f) unlimited +pending signals (-i) 15391 +max locked memory (kbytes, -l) 65536 +max memory size (kbytes, -m) unlimited +open files (-n) 1024 +pipe size (512 bytes, -p) 8 +POSIX message queues (bytes, -q) 819200 +real-time priority (-r) 0 +stack size (kbytes, -s) 8192 +cpu time (seconds, -t) unlimited +max user processes (-u) 15391 +virtual memory (kbytes, -v) unlimited +file locks (-x) unlimited +``` + +- Увеличьте лимит открытых файлов + - Локально — влияет только на текущую сессию: + ```shell + ulimit -u 65535 + ``` + - Глобально или на пользователя (лимиты добавляются в конец файла /etc/security/limits.conf) : + ```shell + sudo vi /etc/security/limits.conf # we use vi, but you can use your favorite text editor + ``` + ```shell title="/etc/security/limits.conf" + # /etc/security/limits.conf + # + #Each line describes a limit for a user in the form: + # + # + # + #Where: + # can be: + # - a user name + # - a group name, with @group syntax + # - the wildcard *, for default entry + # - the wildcard %, can be also used with %group syntax, + # for maxlogin limit + # - NOTE: group and wildcard limits are not applied to root. + # To apply a limit to the root user, must be + # the literal username root. + # + # can have the two values: + # - "soft" for enforcing the soft limits + # - "hard" for enforcing hard limits + # + # can be one of the following: + # - core - limits the core file size (KB) + # - data - max data size (KB) + # - fsize - maximum filesize (KB) + # - memlock - max locked-in-memory address space (KB) + # - nofile - max number of open file descriptors + # - rss - max resident set size (KB) + # - stack - max stack size (KB) + # - cpu - max CPU time (MIN) + # - nproc - max number of processes + # - as - address space limit (KB) + # - maxlogins - max number of logins for this user + + # - maxsyslogins - max number of logins on the system + # - priority - the priority to run user process with + # - locks - max number of file locks the user can hold + # - sigpending - max number of pending signals + # - msgqueue - max memory used by POSIX message queues (bytes) + # - nice - max nice priority allowed to raise to values: [-20, 19] + # - rtprio - max realtime priority + # - chroot - change root to directory (Debian-specific) + # + # + # + + #* soft core 0 + #root hard core 100000 + #* hard rss 10000 + #@student hard nproc 20 + #@faculty soft nproc 20 + #@faculty hard nproc 50 + #ftp hard nproc 0 + #ftp - chroot /ftp + #@student - maxlogins 4 + + * soft nofile 65535 + * hard nofile 65535 + + # End of file + ``` +Также вы можете изменить дополнительные параметры, сохранить файл и перезапустить систему. +После перезапуска проверьте лимит дескриптора файлов еще раз. +Для него необходимо будет установить значение, которое вы определили в файле limits.conf. + +::: + +После уточнения следующих параметров: +1. Публичные ключи валидатора, которые включены в генезисный блок в качестве набора валидаторов +2. Строки подключения загрузочного нода multiaddr +3. Предварительно созданные аккаунты и балансы, которые включены в генезесный блок + +и генерируя `genesis.json`, вы должны скопировать его во все VM в сети. В зависимости от вашей настройки вы можете скопировать/вставить его, отправить его оператору нода или просто передать по SCP/FTP. + +Структура файла генезиса описана в разделе [Команды интерфейса командной строки (CLI)](/docs/edge/get-started/cli-commands). + +## Шаг 4: запустите все клиенты {#step-4-run-all-the-clients} + +:::note Сетевое взаимодействие с облачными провайдерами + +Большинство облачных провайдеров не раскрывают IP-адреса (особенно если они публичные) в качестве прямого сетевого интерфейса на вашей виртуальной машине (VM), а устанавливают невидимый прокси-сервер NAT. + + +Чтобы позволить нодам подключиться друг к другу в этом случае, вам необходимо прослушать IP-адрес `0.0.0.0` для связывания на всех интерфейсах, но вам все равно потребуется указать IP-адрес или DNS-адрес, который другие ноды могут использовать для подключения к вашему экземпляру. Это достигается с помощью аргумента `--nat` или `--dns`, где вы можете указать внешний адрес IP или DNS соответственно. + +#### Пример {#example} + +Связанный IP-адрес, который вы хотите прослушать, — это `192.0.2.1`, но он не связан напрямую ни с одним из интерфейсов вашей сети. + +Чтобы разрешить нодам соединяться друг с другом, вы должны передать следующие параметры: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +Или, если вы хотите указать DNS-адрес `dns/example.io`, передайте следующие параметры: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +Это заставит ваш нод прослушать все интерфейсы, но также даст ему понять, что клиенты подключаются к нему через указанный адрес `--nat`или `--dns`. + +::: + +Запустите **первый** клиент: + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Запустите **второй** клиент: + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Запустите **третий** клиент: + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Запустите **четвертый** клиент: + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Запустив предыдущие команды, вы настроили сеть Polygon Edge из 4 нодов, которая способна запечатывать блоки и восстанавливаться после выхода нода из строя. + +:::info Запустите клиент, используя файл конфигурации + +Вместо того чтобы указывать все параметры конфигурации как аргументы CLI, клиент также можно запустить с использованием файла конфигурации, выполнив следующую команду: + +````bash +polygon-edge server --config +```` +Пример: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +В настоящее время мы `json`поддерживаем только файл конфигурации, файл конфигурации можно найти **[здесь](/docs/edge/configuration/sample-config)** + +::: + +:::info Шаги для запуска нода, который не является валидатором + +Нод, не являющийся валидатором, всегда будет синхронизировать последние блоки, получаемые от нода валидатора. Для запуска нода, не являющегося валидатором, служит следующая команда. + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +Например, вы можете добавить **пятый** клиент, не являющийся валидатором, выполнив следующую команду : + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info Укажите лимит цены + +Нод Polygon Edge можно запустить с заданным **лимитом цены** для входящих транзакций. + +Единица измерения лимита цены: `wei`. + +Установка лимита цены означает, что любые транзакции, обработанные текущим нодом, должны иметь цену на газ **выше**, +чем цена заданного лимита, в противном случае он не будет включен в блок. + +Если для большинства нодов установлен определенный лимит цены, вводится правило, что транзакции в сети +не могут опускаться ниже определенного порога цены. + +По умолчанию лимит цены имеет значение `0`, т. е. он не применяется принудительно. + +Пример использования параметра `--price-limit`: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Следует отметить, что лимиты цены **принудительно устанавливаются только для транзакций, не являющихся локальными**, т. е. +лимит цены не относится к транзакциям, которые добавляются на нод локально. +::: + +:::info URL-адрес WebSocket +По умолчанию при запуске Polygon Edge генерируется WebSocket URL на базе расположения цепочки. +Схема URL `wss://` используется для ссылок HTTPS, а `ws://` — для HTTP. + +URL-адрес Localhost WebSocket: +````bash +ws://localhost:10002/ws +```` +Обратите внимание, что номер порта зависит от выбранного для нода порта JSON-RPC. + +URL-адрес Edgenet WebSocket: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/ru-edge/get-started/terraform-aws-deployment.md b/archive/edge/ru-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..3697816358 --- /dev/null +++ b/archive/edge/ru-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,150 @@ +--- +id: terraform-aws-deployment +title: Развертывание AWS с помощью Terraform +description: "Развертывание сети Polygon Edge на облачном провайдере AWS с помощью Terraform" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info Руководство по развертыванию +Это официальное готовое к применению и полностью автоматизированное руководство по развертыванию AWS. + +Развертывание вручную в ***[облаке](set-up-ibft-on-the-cloud)*** или ***[локально](set-up-ibft-locally)*** рекомендуется для тестирования и/или если ваш облачный провайдер не AWS. +::: + +:::info +Данное развертывание применяется только для PoA. Если необходим механизм PoS, просто следуйте этому ***[руководству](/docs/edge/consensus/migration-to-pos)***, чтобы переключиться с PoA на PoS. +::: + +В данном руководстве будет подробно описан процесс развертывания сети блокчейн Polygon Edge на облачном провайдере AWS, которая готова к производству, поскольку ноды валидаторов распределены по нескольким зонам доступности. + +## Предварительные условия {#prerequisites} + +### Системные инструменты {#system-tools} +* [terraform](https://www.terraform.io/) +* [aws cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [идентификатор ключа доступа к aws и секретный ключ доступа](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Переменные Terraform {#terraform-variables} +Перед запуском развертывания необходимо предоставить две переменные: + +* `alb_ssl_certificate`— ARN сертификата от диспетчера сертификатов AWS, который будет использоваться ALB для протокола http. Перед началом развертывания необходимо создать сертификат, и он должен иметь статус **Выдан** +* `premine` — аккаунт, на который будет поступать предварительно добытая нативная валюта. Значение должно соответствовать официальной спецификации флага [CLI](/docs/edge/get-started/cli-commands#genesis-flags) + +## Информация о развертывании {#deployment-information} +### Развернутые ресурсы {#deployed-resources} +Высокоуровневый обзор ресурсов, которые будут развернуты: + +* Выделенный VPC +* 4 нода валидаторов (которые также являются загрузочными узлами) +* 4 шлюза NAT, чтобы разрешить нодам исходящий интернет-трафик +* Функция Lambda, используемая для генерации первого (генезисного) блока и запуска цепочки +* Выделенные группы безопасность и роли IAM +* Выделенная память S3, используемая для хранения файла genesis.json +* Балансировщик нагрузки приложения, используемый для открытия конечной точки JSON-RPC + +### Отказоустойчивость {#fault-tolerance} + +Для такого развертывания требуется только регионы, имеющие 4 зоны доступности. Каждый нод развертывается в одиночном AZ. + +Благодаря размещению каждого нода на одиночном AZ весь кластер блокчейна отказоустойчив к поломке одиночного нода (AZ), поскольку Polygon Edge реализует консенсус IBFT, который допускает отказ одного нода в кластере из 4 нодов-валидаторов. + +### Доступ к командной строке {#command-line-access} + +Ноды-валидаторы никак не открыты для публичного доступа в интернет (доступ к JSON-PRC осуществляется только через ALB), и у них даже нет публичных IP-адресов, привязанных к ним. Доступ к командной строке нод возможен только через [AWS Systems Manager - Session Manager](https://aws.amazon.com/systems-manager/features/). + +### Обновление AMI Base {#base-ami-upgrade} + +Данное развертывание использует `ubuntu-focal-20.04-amd64-server`AWS AMI. При обновлении AWS AMI *повторное развертывание* EC2 **не** предусмотрено. + +Если по каким-то причинам требуется обновление базы AMI, это можно осуществить, запустив перед этим команду `terraform taint` для каждого отдельного экземпляра `terraform apply`. Экземпляры можно задействовать, запустив `terraform taint module.instances[].aws_instance.polygon_edge_instance`команду. + +Пример: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info +В производственной среде `terraform taint`должны запускаться один за другим, чтобы поддерживать функциональность сети блокчейн. +::: + +## Процедура развертывания {#deployment-procedure} + +### Шаги перед развертыванием {#pre-deployment-steps} +* прочитайте файл readme реестра terraform [polygon-technology-edge](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) +* добавьте модуль `polygon-technology-edge` в ваш файл `main.tf`с помощью *инструкций по обеспечению* на странице readme модулей +* запустите команду `terraform init`, чтобы установить все необходимые зависимые Terraform +* предоставьте новый сертификат в [Диспетчер сертификатов AWS](https://aws.amazon.com/certificate-manager/) +* убедитесь, что предоставленный сертификат имеет статус **Выдан**, и обратите внимание на сертификат **ARN** +* настройте оператор вывода, чтобы получить вывод модулей в cli + +#### `main.tf`пример {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### `terraform.tfvars`пример {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### Шаги по развертыванию {#deployment-steps} +* создайте файл `terraform.tfvars` +* установите требуемые переменные terraform в файл (как поясняется выше).:::info +Существуют и другие необязательные переменные, которые могут полностью настроить это развертывание. Вы можете отменить значения по умолчанию путем добавления своих собственных в файл `terraform.tfvars`. + +Спецификации всех доступных переменных можно найти в ***[реестре](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)*** модулей Terraform +::: +* убедитесь, что вы правильно установили аутентификацию aws cli, запустив `aws s3 ls`, — там не должно быть никаких ошибок. +* разверните инфраструктуру `terraform apply` + +### Шаги после развертывания {#post-deployment-steps} +* после завершения развертывания обратите внимание на значение переменной `json_rpc_dns_name` в cli +* создайте публичную запись dns cname, указывающую ваше доменное имя на предоставленное значение`json_rpc_dns_name`. Например: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* как только запись cname распространится, проверьте, правильно ли работает цепочка, путем вызова конечной точки JSON-PRC. Из приведенного выше примера: + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## Процедура уничтожения {#destroy-procedure} +:::warning +Следующая процедура будет постоянно удалять всю вашу инфраструктуру, развернутую с помощью этих скриптов terraform. Убедитесь, что у вас есть надлежащие [резервные копии данных блокчейна](docs/edge/working-with-node/backup-restore) и/или вы работаете с тестовой средой. +::: + +Если вам нужно удалить всю инфраструктуру, запустите следующую команду `terraform destroy`. Кроме того, вам нужно вручную удалить секреты, хранящиеся в [магазине параметров](https://aws.amazon.com/systems-manager/features/) AWS, для региона, в котором осуществлялось развертывание. diff --git a/archive/edge/ru-edge/overview.md b/archive/edge/ru-edge/overview.md new file mode 100644 index 0000000000..91b760ab3f --- /dev/null +++ b/archive/edge/ru-edge/overview.md @@ -0,0 +1,35 @@ +--- +id: overview +title: Polygon Edge +sidebar_label: What is Edge +description: "Введение в Polygon Edge." +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +Polygon Edge — это модульная расширяемая основа для построения совместимых с Ethereum сетей блокчейн, сайдчейнов и решений общего масштабирования. + +Основное назначение Polygon Edge — создание новой сети блокчейн при полной совместимости со смарт-контрактами и транзакциями Ethereum. Эта основа использует механизм консенсуса IBFT (Стамбульская византийская отказоустойчивость), поддерживаемый в двух вариантах: [PoA (доказательство полномочий)](/docs/edge/consensus/poa) и [PoS (доказательство доли владения](/docs/edge/consensus/pos-stake-unstake)). + +Polygon Edge также поддерживает связь с множественными сетями блокчейн и позволяет передавать как токены [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20), так и [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721), используя [централизованное решение моста](/docs/edge/additional-features/chainbridge/overview). + +Кошельки промышленного стандарта могут использоваться для взаимодействия с Polygon Edge через конечные точки [JSON-RPC](/docs/edge/working-with-node/query-json-rpc), а операторы нод могут выполнять различные действия на нодах через протокол [gRPC](/docs/edge/working-with-node/query-operator-info). + +Чтобы получить более детальную информацию про Polygon, вы можете посетить [официальный сайт](https://polygon.technology). + +**[Репозиторий GitHub](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +Это незавершенная работа, поэтому в будущем возможны архитектурные изменения. Код еще не прошел проверку, поэтому просим вас связаться с командой Polygon, если вы хотите использовать его в производстве. + +::: + + + +Для начала работы с `polygon-edge`сетью локально, просим вас ознакомиться с разделами [Установка](/docs/edge/get-started/installation) и [Локальная настройка](/docs/edge/get-started/set-up-ibft-locally). diff --git a/archive/edge/ru-edge/performance-reports/overview.md b/archive/edge/ru-edge/performance-reports/overview.md new file mode 100644 index 0000000000..bb3d4cfd43 --- /dev/null +++ b/archive/edge/ru-edge/performance-reports/overview.md @@ -0,0 +1,29 @@ +--- +id: overview +title: Обзор +description: "Введение в процедуру тестирования Polygon Edge. " +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +Обратите внимание, что наш , `loadbot`использованный для выполнения этих тестов, теперь обесценивается. +::: + +| Тип | Значение | Ссылка не тестирование | +| ---- | ----- | ------------ | +| Регулярные трансферы | 1428 токенов в секунду | [4 июля 2022 года](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| Трансферы ERC-20 | 1111 токенов в секунду | [4 июля 2022 года](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| Минтинг NFT | 714 токенов в секунду | [4 июля 2022 года](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +Наша цель состоит в том, чтобы создать высокопроизводительное, многофункциональное и простое в настройке и обслуживании программное обеспечение для блокчейна. Все испытания были проведены с помощью Polygon Edge Loadbot. Каждый отчет о производительности, который вы найдете в этом разделе, правильно датирован, среда четко описана, а метод тестирования подробно описан. + +Цель проведения тестирования производительности — показать реальную производительность сети блокчейн Polygon Edge. При проведении тестирования с помощью нашего loadbot в такой же среде каждый должен получить результаты, аналогичные указанным здесь. + +Все испытания производительности были проведены на платформе AWS на цепочке, которая состоит из нод-экземпляров EC2. \ No newline at end of file diff --git a/archive/edge/ru-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/ru-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..581c5bc6ce --- /dev/null +++ b/archive/edge/ru-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,132 @@ +--- +id: test-2022-01-21 +title: 21 января 2022 г. +description: "Проверка производительности от 21 января." +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## 21 января 2022 г. {#january-21st-2022} + +### Краткая информация {#summary} + +:::caution +Обратите внимание, что наш , `loadbot`использованный для выполнения этих тестов, теперь обесценивается. +::: + +Данная проверка была проведена после модификации TxPool, которая существенно улучшила производительность (выпущена в версии [v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0)). + +Цель заключалась в том, чтобы настроить большую сеть, состоящую из 30 активных валидаторов, для надлежашего нагрузочного тестирования +консенсуса и передачи информации о транзакциях TxPool при отправке всех транзакций на JSON-RPC одного нода. + +Наша цель не заключалась в том, чтобы достичь максимального TPS, поскольку размер сети отрицательно влияет на производительность, +а поскольку для лимита газа на блок и времени блока установлены разумные значения, потребление ресурсов системы не очень высокое и для работы можно использовать стандартное аппаратное обеспечение. + +### Результаты {#results} + +| Показатель | Значение | +| ------ | ----- | +| Кол-во транзакций в секунду | 344 | +| Кол-во неудачных транзакций | 0 | +| Кол-во успешных транзакций | 10000 | +| Общее время исполнения | 30 с | + +### Среда {#environment} + +
+ Конфигурация хоста +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Облачный провайдерAWS
Размер экземпляраt2.xlarge
Сетевое взаимодействиечастная подсеть
Операционная системаLinux Ubuntu 20.04 LTS — Focal Fossa
Лимит дескриптора файла65535
Макс. кол-во пользовательских процессов65535
+
+
+
+
+ +
+ Конфигурация блокчейна +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Версия Polygon EdgeCommit 8377162281d1a2e4342ae27cd4e5367c4364aee2 в ответвлении для разработки
Ноды валидатора30
Ноды без валидатора0
КонсенсусIBFT PoA
Время блока2000 мс
Лимит газа для блока5242880
+
+
+
+
+ +
+ Конфигурация Loadbot +
+
+ + + + + + + + + + + + + +
Общее кол-во транзакций10000
Кол-во отправленных транзакций в секунду400
Тип транзакцийТрансферы между EOA и EOA
+
+
+
+
diff --git a/archive/edge/ru-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/ru-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..f305db9806 --- /dev/null +++ b/archive/edge/ru-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,390 @@ +--- +id: test-2022-03-02 +title: 2 марта 2022 г. +description: "Тест производительности от 2 марта." +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### Краткая информация {#summary} + +:::caution +Обратите внимание, что наш , `loadbot`использованный для выполнения этих тестов, теперь обесценивается. +::: + +Данный тест был проведен для измерения параметров трансфера токенов SC ERC20 и функции минтинга токенов SC ERC721 при высоких нагрузках и высокой скорости транзакций. + +Целью было проверить выполнение всех задач при высокой нагрузке в соответствии с ожиданиями. Поэтому в вывод бота loadbot были добавлены показатели, связанные с газом, которые демонстрируют правильное заполнение блоков транзакциями. + +Все транзакции были отправлены в один нод через GRPC API, подтверждения были получены через JSON-RPC API. После выполнения всех транзакций информация по газу была считана из всех блоков с помощью метода eth_getBlockByNumber JSON-RPC. + +Наша цель не заключалась в том, чтобы стремиться достичь максимально возможного показателя TPS, +а поскольку для лимита газа на блок и времени блока установлены разумные значения, потребление ресурсов системы не очень высокое и для работы можно использовать стандартное аппаратное обеспечение. + +### Результаты ERC20 {#results-erc20} + +| Показатель | Значение | +| ------ | ----- | +| Тип транзакции | ERC20 | +| Кол-во транзакций в секунду | 65 | +| Кол-во неудачных транзакций | 0 | +| Кол-во успешных транзакций | 5000 | +| Время исполнения транзакции ERC20 | 76,681690 с | +| Время развертывания SC | 4,048250 с | + +### Результаты ERC721 {#results-erc721} + +| Показатель | Значение | +| ------ | ----- | +| Тип транзакции | ERC721 | +| Кол-во транзакций в секунду | 20 | +| Кол-во неудачных транзакций | 0 | +| Кол-во успешных транзакций | 2000 | +| Время выполнения транзакции ERC721 | 97,239920 с | +| Время развертывания SC | 3,048970 с | + +### Среда ERC20 {#environment-erc20} + +
+ Конфигурация хоста +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Облачный провайдерAWS
Размер экземпляраt2.micro
Сетевое взаимодействиечастная подсеть
Операционная системаLinux Ubuntu 20.04 LTS — Focal Fossa
Лимит дескриптора файла65535
Макс. кол-во пользовательских процессов65535
+
+
+
+
+ +
+ Конфигурация блокчейна +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Версия Polygon EdgeCommit 8a033aa1afb191abdac04636d318f83f32511f3c в ответвлении для разработки
Ноды валидатора6
Ноды без валидатора0
КонсенсусIBFT PoA
Время блока2 с
Лимит газа для блока5242880
Среднее использование блока95%
+
+
+
+
+ +
+ Конфигурация Loadbot +
+
+ + + + + + + + + + + + + +
Общее кол-во транзакций5000
Кол-во отправленных транзакций в секунду200
Тип транзакцийТрансферы между ERC20 и ERC20
+
+
+
+
+ +
+ Журнал Loadbot + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### Среда ERC721 {#environment-erc721} + +
+ Конфигурация хоста +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Облачный провайдерAWS
Размер экземпляраt2.micro
Сетевое взаимодействиечастная подсеть
Операционная системаLinux Ubuntu 20.04 LTS — Focal Fossa
Лимит дескриптора файла65535
Макс. кол-во пользовательских процессов65535
+
+
+
+
+ +
+ Конфигурация блокчейна +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Версия Polygon EdgeCommit 8a033aa1afb191abdac04636d318f83f32511f3c в ответвлении для разработки
Ноды валидатора6
Ноды без валидатора0
КонсенсусIBFT PoA
Время блока2 с
Лимит газа для блока5242880
Среднее использование блока94%
+
+
+
+
+ +
+ Конфигурация Loadbot +
+
+ + + + + + + + + + + + + +
Общее кол-во транзакций2000
Кол-во отправленных транзакций в секунду200
Тип транзакцийМинтинг токенов ERC721
+
+
+
+
+ +
+ Журнал Loadbot + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/ru-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/ru-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..fea9dc9cb2 --- /dev/null +++ b/archive/edge/ru-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,958 @@ +--- +id: test-2022-03-23 +title: 23 марта 2022 г. +description: "Проверка производительности от 23 марта." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### Краткая информация {#summary} + +:::caution +Обратите внимание, что наш , `loadbot`использованный для выполнения этих тестов, теперь обесценивается. +::: + +Эта проверка была проведена для измерения параметров трансфера токенов SC ERC20, минтинга токенов SC ERC721 и функционала транзакций между EOA и EOA при высокой нагрузке и скорости транзакций на нодах со значительными ресурсами аппаратного обеспечения. + +Целью было проверить выполнение всех задач при высокой нагрузке в соответствии с ожиданиями. Поэтому в вывод бота loadbot были добавлены показатели, связанные с газом, которые демонстрируют правильное заполнение блоков транзакциями. + +Все транзакции были отправлены в один нод через GRPC API, подтверждения были получены через API JSON-RPC. После выполнения всех транзакций информация по газу была считана из всех блоков с помощью метода eth_getBlockByNumber JSON-RPC. + +Нашей целью было попытаться достичь максимально возможного показателя TPS на доступных аппаратных ресурсах. +Для этого мы изменили параметры лимита газа для блоков и времени блоков, что позволило нам получить наилучшие возможные показатели tps и сохранить целостность и стабильность системы. + +:::info Лимит газа для блоков +Если для выполнения транзакций используется много газа, лимит газа для блоков можно увеличить до достаточно высокого значения. В приведенном ниже примере минтинг токенов ERC721 выполнялся намного быстрее при лимите газа для блоков 80 000 000 (вместо 20 миллионов), однако при попытке трансфера токенов ERC20 с лимитом газа для блоков в 80 миллионов произошел сбой на сервере. + +::: + +:::info Рабочие среды + +При настройке рабочей среды с целью добиться высокой производительности цепочки необходимо соблюдать осторожность. +Если установить высокое значение лимита газа для блоков и время блока 1 с, то при высокой транзакционной нагрузке на один нод этот нод будет потреблять очень много ресурсов памяти (если не все ресурсы памяти), что вызовет сбой на сервере. +Используйте loadbot для тщательной проверки всех параметров, следите за использованием ресурсов системы и настройте параметры конфигурации соответствующим образом. + +::: + +:::info Ошибки перегрузки памяти + +Для сохранения стабильности системы некоторые дистрибутивы Linux автоматически прекращают процессы, потребляющие очень много оперативной памяти (ошибки перегрузки памяти). +Эти ошибки перегрузки памяти отображаются в памяти примерно так, как показано ниже. +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### Результаты трансферов между EOA и EOA {#results-of-eoa-to-eoa-transfers} +| Показатель | Значение | +| ------ | ----- | +| Тип транзакции | Между EOA и EOA | +| Кол-во транзакций в секунду | 689 | +| Кол-во неудачных транзакций | 0 | +| Кол-во успешных транзакций | 20000 | +| Общее кол-во использованных блоков | 25 | +| Общее время исполнения | 29,921110 с | + +### Результаты трансфера токенов ERC20 {#results-of-erc20-token-transfers} + +| Показатель | Значение | +| ------ | ----- | +| Тип транзакции | ERC20 | +| Кол-во транзакций в секунду | 500 | +| Кол-во неудачных транзакций | 0 | +| Кол-во успешных транзакций | 20000 | +| Общее кол-во использованных блоков | 33 | +| Время исполнения транзакции ERC20 | 40,402900 с | +| Время развертывания SC | 2,004140 с | + +### Результаты минтинга токена erc721 {#results-of-erc721-token-minting} + +| Показатель | Значение | +| ------ | ----- | +| Тип транзакции | ERC721 | +| Кол-во транзакций в секунду | 157 | +| Кол-во неудачных транзакций | 0 | +| Кол-во успешных транзакций | 20000 | +| Общее кол-во использованных блоков | 124 | +| Время выполнения транзакции ERC721 | 127,537340 с | +| Время развертывания SC | 2,004420 с | + + +### Результаты минтинга токена ERC721 при очень высоком лимите газа для блоков (80 млн) {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| Показатель | Значение | +| ------ | ----- | +| Тип транзакции | ERC721 | +| Кол-во транзакций в секунду | 487 | +| Кол-во неудачных транзакций | 0 | +| Кол-во успешных транзакций | 20000 | +| Общее кол-во использованных блоков | 34 | +| Время выполнения транзакции ERC721 | 41,098410 с | +| Время развертывания SC | 2,004300 с | + + +### Среда при передаче между EOA и EOA {#environment-eoa-to-eoa} +
+ Конфигурация хоста +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Облачный провайдерAWS
Размер экземпляраc5.2xlarge
Сетевое взаимодействиечастная подсеть
Операционная системаAmazon Linux 2 AMI (HVM) — Kernel 5.10
Лимит дескриптора файла65535
Макс. кол-во пользовательских процессов65535
+
+
+
+
+ +
+ Конфигурация блокчейна +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Версия Polygon EdgeВыполните Commit 06e11eac8da98c79c938fc53dda2da3318cfbe04 в ответвлении для разработки
Ноды валидатора4
Ноды без валидатора0
КонсенсусIBFT PoA
Время блока1 с
Лимит газа для блока20000000
Макс. кол-во слотов1000000
Среднее использование блока84,00%
+
+
+
+
+ +
+ Конфигурация Loadbot +
+
+ + + + + + + + + + + + + +
Общее кол-во транзакций20000
Кол-во отправленных транзакций в секунду689
Тип транзакцийТрансферы между EOA и EOA
+
+
+
+
+ +
+ Журнал Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### Среда ERC20 {#environment-erc20} +
+ Конфигурация хоста +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Облачный провайдерAWS
Размер экземпляраc5.2xlarge
Сетевое взаимодействиечастная подсеть
Операционная системаAmazon Linux 2 AMI (HVM) — Kernel 5.10
Лимит дескриптора файла65535
Макс. кол-во пользовательских процессов65535
+
+
+
+
+ +
+ Конфигурация блокчейна +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Версия Polygon EdgeВыполните Commit 06e11eac8da98c79c938fc53dda2da3318cfbe04 в ответвлении для разработки
Ноды валидатора4
Ноды без валидатора0
КонсенсусIBFT PoA
Время блока1 с
Лимит газа для блока20000000
Макс. кол-во слотов1000000
Среднее использование блока88,38%
+
+
+
+
+ +
+ Конфигурация Loadbot +
+
+ + + + + + + + + + + + + +
Общее кол-во транзакций20000
Кол-во отправленных транзакций в секунду500
Тип транзакцийТрансферы между ERC20 и ERC20
+
+
+
+
+ +
+ Журнал Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### Среда ERC721 {#environment-erc721} +
+ Конфигурация хоста +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Облачный провайдерAWS
Размер экземпляраc5.2xlarge
Сетевое взаимодействиечастная подсеть
Операционная системаAmazon Linux 2 AMI (HVM) — Kernel 5.10
Лимит дескриптора файла65535
Макс. кол-во пользовательских процессов65535
+
+
+
+
+ +
+ Конфигурация блокчейна +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Версия Polygon EdgeВыполните Commit 06e11eac8da98c79c938fc53dda2da3318cfbe04 в ответвлении для разработки
Ноды валидатора4
Ноды без валидатора0
КонсенсусIBFT PoA
Время блока1 с
Лимит газа для блока20000000
Макс. кол-во слотов1000000
Среднее использование блока92,90%
+
+
+
+
+ +
+ Конфигурация Loadbot +
+
+ + + + + + + + + + + + + +
Общее кол-во транзакций20000
Кол-во отправленных транзакций в секунду157
Тип транзакцийМинтинг токенов ERC721
+
+
+
+
+ +
+ Журнал Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### Среда ERC20 — очень высокий лимит газа на блок {#environment-erc20-very-high-block-gas-limit} +
+ Конфигурация хоста +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Облачный провайдерAWS
Размер экземпляраc5.2xlarge
Сетевое взаимодействиечастная подсеть
Операционная системаAmazon Linux 2 AMI (HVM) — Kernel 5.10
Лимит дескриптора файла65535
Макс. кол-во пользовательских процессов65535
+
+
+
+
+ +
+ Конфигурация блокчейна +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Версия Polygon EdgeВыполните Commit 06e11eac8da98c79c938fc53dda2da3318cfbe04 в ответвлении для разработки
Ноды валидатора4
Ноды без валидатора0
КонсенсусIBFT PoA
Время блока1 с
Лимит газа для блока80000000
Макс. кол-во слотов1000000
Среднее использование блока---
+
+
+
+
+ +
+ Конфигурация Loadbot +
+
+ + + + + + + + + + + + + +
Общее кол-во транзакций20000
Кол-во отправленных транзакций в секунду---
Тип транзакцийТрансферы между ERC20 и ERC20
+
+
+
+
+ +
+ Журнал ошибок OOM + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### Среда ERC721 — очень высокий лимит газа на блок {#environment-erc721-very-high-block-gas-limit} +
+ Конфигурация хоста +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Облачный провайдерAWS
Размер экземпляраc5.2xlarge
Сетевое взаимодействиечастная подсеть
Операционная системаAmazon Linux 2 AMI (HVM) — Kernel 5.10
Лимит дескриптора файла65535
Макс. кол-во пользовательских процессов65535
+
+
+
+
+ +
+ Конфигурация блокчейна +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Версия Polygon EdgeВыполните Commit 06e11eac8da98c79c938fc53dda2da3318cfbe04 в ответвлении для разработки
Ноды валидатора4
Ноды без валидатора0
КонсенсусIBFT PoA
Время блока1 с
Лимит газа для блока80000000
Макс. кол-во слотов1000000
Среднее использование блока84,68%
+
+
+
+
+ +
+ Конфигурация Loadbot +
+
+ + + + + + + + + + + + + +
Общее кол-во транзакций20000
Кол-во отправленных транзакций в секунду487
Тип транзакцийМинтинг токенов ERC721
+
+
+
+
+ +
+ Журнал Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/ru-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/ru-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..e1b39ed030 --- /dev/null +++ b/archive/edge/ru-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,568 @@ +--- +id: test-2022-07-04 +title: 4 июля 2022 года +description: "Проверка производительности от 4-го июля." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### Краткая информация {#summary} + +:::caution +Обратите внимание, что наш , `loadbot`использованный для выполнения этих тестов, теперь обесценивается. +::: + +Эта проверка была проведена для измерения параметров трансфера токенов SC ERC20, минтинга токенов SC ERC721 и функционала транзакций между EOA и EOA при высокой нагрузке и скорости транзакций на нодах со значительными ресурсами аппаратного обеспечения. + +Целью было проверить выполнение всех задач при высокой нагрузке в соответствии с ожиданиями. Поэтому в вывод бота loadbot были добавлены показатели, связанные с газом, которые демонстрируют правильное заполнение блоков транзакциями. + +Все транзакции были отправлены в один нод через GRPC API, подтверждения были получены через API JSON-RPC. После выполнения всех транзакций информация по газу была считана из всех блоков с помощью метода eth_getBlockByNumber JSON-RPC. + +Нашей целью было попытаться достичь максимально возможного показателя TPS на доступных аппаратных ресурсах. +Для этого мы изменили параметры лимита газа для блоков и времени блоков, что позволило нам получить наилучшие возможные показатели tps и сохранить целостность и стабильность системы. + + +:::info Рабочие среды + +При настройке рабочей среды с целью добиться высокой производительности цепочки необходимо соблюдать осторожность. +Если установить высокое значение лимита газа для блоков и время блока 1 с, то при высокой транзакционной нагрузке на один нод этот нод будет потреблять очень много ресурсов памяти (если не все ресурсы памяти), что вызовет сбой на сервере. +Используйте loadbot для тщательной проверки всех параметров, следите за использованием ресурсов системы и настройте параметры конфигурации соответствующим образом. + +::: + + + +### Результаты трансферов между EOA и EOA {#results-of-eoa-to-eoa-transfers} +| Показатель | Значение | +| ------ | ----- | +| Тип транзакции | Между EOA и EOA | +| Кол-во транзакций в секунду | 1428 | +| Кол-во неудачных транзакций | 0 | +| Кол-во успешных транзакций | 30000 | +| Общее кол-во использованных блоков | 15 | +| Общее время исполнения | 21,374620 с | + +### Результаты трансфера токенов ERC20 {#results-of-erc20-token-transfers} + +| Показатель | Значение | +| ------ | ----- | +| Тип транзакции | ERC20 | +| Кол-во транзакций в секунду | 1111 | +| Кол-во неудачных транзакций | 0 | +| Кол-во успешных транзакций | 50000 | +| Общее кол-во использованных блоков | 38 | +| Время исполнения транзакции ERC20 | 45,906450 с | +| Время развертывания SC | 2,006580 с | + +### Результаты минтинга токена erc721 {#results-of-erc721-token-minting} + +| Показатель | Значение | +| ------ | ----- | +| Тип транзакции | ERC721 | +| Кол-во транзакций в секунду | 714 | +| Кол-во неудачных транзакций | 0 | +| Кол-во успешных транзакций | 30000 | +| Общее кол-во использованных блоков | 39 | +| Время выполнения транзакции ERC721 | 42,864140 с | +| Время развертывания SC | 2,005500 с | + + + + +### Среда при передаче между EOA и EOA {#environment-eoa-to-eoa} +
+ Конфигурация хоста +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Облачный провайдерAWS EC2
Размер экземпляраc6a.48xlarge
Сетевое взаимодействиечастная подсеть
Операционная системаLinux Ubuntu 20.04 LTS — Focal Fossa
Лимит дескриптора файла65535
Макс. кол-во пользовательских процессов65535
+
+
+
+
+ +
+ Конфигурация блокчейна +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Версия Polygon EdgeРелиз v0.4.1
Ноды валидатора4
Ноды без валидатора0
КонсенсусIBFT PoA
Время блока1 с
Лимит газа для блока70778880
Макс. кол-во слотов276480
Среднее использование блоков59,34%
+
+
+
+
+ +
+ Конфигурация Loadbot +
+
+ + + + + + + + + + + + + +
Общее кол-во транзакций30000
Кол-во отправленных транзакций в секунду1428
Тип транзакцийТрансферы между EOA и EOA
+
+
+
+
+ +
+ Журнал Loadbot + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### Среда ERC20 {#environment-erc20} +
+ Конфигурация хоста +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Облачный провайдерAWS EC2
Размер экземпляраc6a.48xlarge
Сетевое взаимодействиечастная подсеть
Операционная системаLinux Ubuntu 20.04 LTS — Focal Fossa
Лимит дескриптора файла65535
Макс. кол-во пользовательских процессов65535
+
+
+
+
+ +
+ Конфигурация блокчейна +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Версия Polygon EdgeРелиз v0.4.1
Ноды валидатора4
Ноды без валидатора0
КонсенсусIBFT PoA
Время блока1 с
Лимит газа для блока47185920
Макс. кол-во слотов184320
Среднее использование блоков81,29%
+
+
+
+
+ +
+ Конфигурация Loadbot +
+
+ + + + + + + + + + + + + +
Общее кол-во транзакций50000
Кол-во отправленных транзакций в секунду1111
Тип транзакцийТрансферы между ERC20 и ERC20
+
+
+
+
+ +
+ Журнал Loadbot + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### Среда ERC721 {#environment-erc721} +
+ Конфигурация хоста +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Облачный провайдерAWS EC2
Размер экземпляраc6a.48xlarge
Сетевое взаимодействиечастная подсеть
Операционная системаLinux Ubuntu 20.04 LTS — Focal Fossa
Лимит дескриптора файла65535
Макс. кол-во пользовательских процессов65535
+
+
+
+
+ +
+ Конфигурация блокчейна +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Версия Polygon EdgeРелиз v0.4.1
Ноды валидатора4
Ноды без валидатора0
КонсенсусIBFT PoA
Время блока1 с
Лимит газа для блока94371840
Макс. кол-во слотов1000000
Среднее использование блоков93,88%
+
+
+
+
+ +
+ Конфигурация Loadbot +
+
+ + + + + + + + + + + + + +
Общее кол-во транзакций30000
Кол-во отправленных транзакций в секунду714
Тип транзакцийМинтинг токенов ERC721
+
+
+
+
+ +
+ Журнал Loadbot + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/ru-edge/troubleshooting.md b/archive/edge/ru-edge/troubleshooting.md new file mode 100644 index 0000000000..34e1c9323b --- /dev/null +++ b/archive/edge/ru-edge/troubleshooting.md @@ -0,0 +1,71 @@ +--- +id: troubleshooting +title: Диагностика и устранение неисправностей +description: "Раздел диагностики и устранения неисправностей для Polygon Edge" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# Диагностика и устранение неисправностей {#troubleshooting} + +## Ошибка `method=eth_call err="invalid signature"` {#error} + +Если вы используете кошелек для совершения транзакции в Polygon Edge, убедитесь, что в настройках локальной сети вашего кошелька: + +1. `chainID` является подходящим вариантом. По умолчанию `chainID` для Edge имеет значение `100`, но его можно настроить с помощью флага генезиса `--chain-id`. + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. Убедитесь, что в поле RPC URL вы используете порт JSON RPC нода, к которому вы подключаетесь. + + +## Как получить WebSocket URL {#how-to-get-a-websocket-url} + +По умолчанию при запуске Polygon Edge открывается конечная точка WebSocket на базе расположения цепочки. +Схема URL `wss://` используется для ссылок HTTPS, а `ws://` — для HTTP. + +URL-адрес Localhost WebSocket: +````bash +ws://:/ws +```` +Обратите внимание, что номер порта зависит от выбранного для нода порта JSON-RPC. + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## Ошибка `insufficient funds` при попытке развертывания контракта {#error-when-trying-to-deploy-a-contract} + +Если вы получаете сообщение об этой ошибке, убедитесь, что у вас имеются достаточные средства на желаемом адресе и что вы используете правильный адрес.
+Чтобы задать начальный остаток баланса, вы можете использовать флаг генезиса `genesis [--premine ADDRESS:VALUE]` при генерировании файла генезиса. +Пример использования этого флага: +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +Пополняет предварительный баланс в 1000000000000000000000 WEI на адрес 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862. + + +## Токены ERC20 не выпускаются при использовании Chainbridge {#erc20-tokens-not-released-while-using-chainbridge} + +Если вы пытаетесь выполнить трансфер токенов ERC20 между Polygon POS и локальной сетью Edge, ваши токены ERC20 внесены на депозит, предложение выполняется на ретрансляторе, однако токены не выпускаются в сеть Edge, убедитесь, что обработчик ERC20 в цепочке Polygon Edge имеет достаточно токенов для выпуска.
+Контракт Handler в цепочке назначения должен иметь достаточно токенов для выпуска в режиме блокировка-выпуск. Если у вас нет токенов ERC20 в обработчике ERC20 локальной сети Edge, выполните минтинг новых токенов и выполните их трансфер в обработчик ERC20. + +## Ошибка `Incorrect fee supplied` при использовании Chainbridge {#error-when-using-chainbridge} + +Вы можете получить сообщение об этой ошибке при попытке трансфера токенов ERC20 между цепочкой Mumbai Polygon POS и локальной сетью Polygon Edge. Эта ошибка происходит, когда вы установили комиссию за развертывание с помощью флага `--fee`, но не установили то же значение в транзакции депозита. +Для изменения комиссии можно использовать следующую команду: +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +Более подробную информацию об этом флаге можно найти [здесь](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md). + + + + + diff --git a/archive/edge/ru-edge/validator-hosting.md b/archive/edge/ru-edge/validator-hosting.md new file mode 100644 index 0000000000..670576e642 --- /dev/null +++ b/archive/edge/ru-edge/validator-hosting.md @@ -0,0 +1,226 @@ +--- +id: validator-hosting +title: Хостинг валидатора +description: "Требования к хостингу для Polygon Edge" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +Ниже приведены рекомендации для правильного хостинга узла валидатора в сети Polygon Edge. Просим вас обратить особое внимание на все ниже перечисленные пункты, чтобы убедиться, что ваш валидатор настроен должным образом для обеспечения безопасности, стабильности и эффективности. + +## База знаний {#knowledge-base} + +Прежде чем запустить узел валидатора, внимательно ознакомьтесь с этим документом. Ниже приведена другая полезная документация: + +- [Установка](get-started/installation) +- [Облачная настройка](get-started/set-up-ibft-on-the-cloud) +- [Команды CLI](get-started/cli-commands) +- [Файл конфигурации сервера](configuration/sample-config) +- [Приватные ключи](configuration/manage-private-keys) +- [Метрика Prometheus](configuration/prometheus-metrics) +- [Диспетчеры секретов](/docs/category/secret-managers) +- [Резервное копирование/восстановление](working-with-node/backup-restore) + +## Минимальные системные требования {#minimum-system-requirements} + +| Тип | Значение | Под воздействием | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| Процессор | 2 ядра |
  • Количество запросов JSON-RPC
  • Размер состояния блокчейна
  • Лимит газа для блока
  • Время блока
| +| ОЗУ | 2 ГБ |
  • Количество запросов JSON-RPC
  • Размер состояния блокчейна
  • Лимит газа для блока
| +| Диск |
  • Корневой раздел 10 ГБ
  • Корневой раздел 30 ГБ с LVM для расширения диска
|
  • Размер состояния блокчейна
| + + +## Конфигурация сервиса {#service-configuration} + +Двоичный файл `polygon-edge` должен запускаться как системная служба автоматически при установления сетевого соединения и иметь функции запуска/остановки/перезапуска . Рекомендуем использовать диспетчер служб, например `systemd.` + +Пример `systemd`файла конфигурации системы: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### Двоичный файл {#binary} + +В производственных рабочих нагрузках `polygon-edge` двоичный файл должен быть развернут только из предварительно созданных на GitHub двоичных файлах релиза, а не компиляцией его вручную.:::info +Компилируя вручную ветвь GitHub `develop`, вы можете внести серьезные изменения в вашу среду. Поэтому рекомендуется развертывать двоичный файл Polygon Edge исключительно из релизов, поскольку он будет содержать информацию о серьезных изменениях и о том, как их исправить. +::: + +Полный обзор метода установки можно посмотреть в разделе [Установка](/docs/edge/get-started/installation). + +### Хранение данных {#data-storage} + +`data/`Папка, содержащая все состояния блокчейна, должна быть смонтирована на выделенном диске/томе, что позволяет автоматически создавать резервные копии диска, расширять том и, по желанию, устанавливать диск/том на другой экземпляр в случае сбоя. + + +### Файлы журнала {#log-files} + +Файлы журнала необходимо ежедневно ротировать (при помощи такого инструмента: `logrotate`).:::warning +Если конфигурация настроена без ротации журналов, файлы журнала могут использовать все доступное дисковое пространство, что может нарушить время работы валидатора. +::: + +Пример `logrotate` конфигурации: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +Рекомендации по хранению журналов можно найти в разделе [Ведение журналов](#logging) ниже. + +### Дополнительные зависимости {#additional-dependencies} + +`polygon-edge`статически компилируется, не требуя дополнительных зависимостей от ОС хоста. + +## Техническое обслуживание {#maintenance} + +Ниже приведены лучшие советы по техническому обслуживанию узла валидатора сети Polygon Edge. + +### Резервное копирование {#backup} + +Для нодов Polygon Edge рекомендуется проводить два типа процедур резервного копирования. + +Мы предлагаем использовать обе процедуры, когда это возможно, при этом резервная копия Polygon Edge всегда остается доступным вариантом. + +* ***Резервное копирование тома***: Ежедневное инкрементальное резервное копирование `data/`тома нода Polygon Edge или полного VM по возможности. + + +* ***Резервное копирование Polygon Edge***: Рекомендуется ежедневно выполнять процедуру CRON, которая регулярно создает резервные копии Polygon Edge и перемещает `.dat`файлы в удаленное место или в безопасное облачное хранилище объектов. + +Резервное копирование Polygon Edge в идеале не должно совпадать с описанным выше резервным копированием тома. + +Инструкции по выполнению резервного копирования Polygon Edge можно найти в разделе [Резервное копирование/восстановление экземпляра нода](working-with-node/backup-restore). + +### Ведение журнала {#logging} + +Журналы, выводимые нодами Polygon Edge, должны иметь следующие характеристики: +- отправляться во внешнее хранилище данных с возможностью индексирования и поиска; +- иметь срок хранения журнала 30 дней. + +Если вы настраиваете валидатор Polygon Edge впервые, рекомендуем запустить нод с опцией `--log-level=DEBUG`, чтобы иметь возможность быстро отладить любые проблемы, с которыми вы можете столкнуться. + +:::info +`--log-level=DEBUG`сделает вывод журнала нода максимально подробным. Журналы отладки резко увеличат размер файл журнала, который необходимо учитывать при настройке решения по ротации журналов. +::: +### Патчи безопасности ОС {#os-security-patches} + +Администраторам необходимо следить за тем, чтобы ОС экземпляра валидатора всегда обновлялась с последними патчами не реже одного раза в месяц. + +## Метрика {#metrics} + +### Системная метрика {#system-metrics} + +Администраторам необходимо установить какой-либо монитор для системной метрики (например, Telegraf + InfluxDB + Grafana или сторонний SaaS). + +Метрика, которую необходимо мониторить и которая требует настройки уведомлений о тревоге: + +| Название метрики | Порог сигнала тревоги | +|-----------------------|-------------------------------| +| Использование процессора (%) | > 90% в течение более 5 минут | +| Использование ОЗУ (%) | > 90% в течение более 5 минут | +| Использование корневого диска | > 90% | +| Использование диска данных | > 90% | + +### Метрика валидатора {#validator-metrics} + +Администраторам необходимо настроить сбор метрики API Prometheus Polygon Edge, чтобы иметь возможность отслеживать производительность блокчейн-сети. + +См. раздел [Метрика Prometheus](configuration/prometheus-metrics) для понимания того, какая метрика подвергается воздействию и как настроить сбор метрики Prometheus. + + +Особое внимание следует уделить следующей метрике: +- ***Время производства блока***: если время производства блока превышает норму, возможна проблема с сетью +- ***Количество раундов консенсуса***: если имеется более 1 раунда, возможна проблема с набором валидаторов в сети +- ***Количество одноранговых узлов (пиров)***: если количество пиров падает, возможны проблемы с подключением сети + +## Безопасность {#security} + +Ниже приведены лучшие советы по обеспечению безопасности узла валидатора сети Polygon Edge. + +### Сервисы API {#api-services} + +- ***JSON-RPC*** — Только сервис API, который должен быть открыт для публики (через балансировщик или напрямую). Этот API должен быть запущен на всех интерфейсах или на определенном IP-адресе (например: `--json-rpc 0.0.0.0:8545` или `--json-prc 192.168.1.1:8545`).:::info +Поскольку это публично доступный API, рекомендуется установить балансировщик / обратный прокси-сервер для обеспечения безопасности и ограничения скорости. +::: + + +- ***LibP2P*** — Это API сетевого взаимодействия, который используют ноды для взаимодействия с пирами. Он должен быть запущен на всех интерфейсах или на определенном IP-адресе ( `--libp2p 0.0.0.0:1478`или `--libp2p 192.168.1.1:1478`). Этот API не должен иметь публичный доступ, но он должен быть доступен со всех других нодов.:::info +При запуске на localhost ( `--libp2p 127.0.0.1:1478` ) другие ноды подключиться не смогут. +::: + + +- ***GRPC*** — Этот API используется только для запуска команд оператора и больше ни для чего. Как таковой он должен работать исключительно на localhost ( `--grpc-address 127.0.0.1:9632`). + +### Секреты Polygon Edge {#polygon-edge-secrets} + +Секреты Polygon Edge ( `ibft`и `libp2p`) не должны храниться на локальной файловой системе. Вместо этого следует использовать поддерживаемый [диспетчер секретов](configuration/secret-managers/set-up-aws-ssm). Хранение секретов на локальной файловой системе следует применять только в непроизводственных средах. + +## Обновление {#update} + +Ниже приведена желаемая процедура обновления нодов валидатора, описанная в виде пошаговой инструкции. + +### Процедура обновления {#update-procedure} + +- Загрузите последний двоичный файл Polygon Edge из официальных [релизов](https://github.com/0xPolygon/polygon-edge/releases) GitHub +- Остановить сервис Polygon Edge ( пример: `sudo systemctl stop polygon-edge.service`) +- Замените существующий двоичный файл `polygon-edge` на загруженный файл (Например: `sudo mv polygon-edge /usr/local/bin/`) +- Проверьте при помощи запуска `polygon-edge version`, работает ли правильная версия `polygon-edge` — она должна соответствовать версии релиза +- Проверьте документацию по релизу, есть ли какие-либо шаги для обратной совместимости, которые необходимо сделать перед запуском сервиса `polygon-edge` +- Запустите сервис `polygon-edge` (пример: `sudo systemctl start polygon-edge.service`) +- Наконец, проверьте вывод журнала `polygon-edge` и убедитесь, что все работает без каких-либо журналов `[ERROR]` + +:::warning +При выходе нового релиза эта процедура обновления должна быть выполнена на всех нодах, поскольку работающий в настоящее время двоичный файл не совместим с новым релизом. + +Это означает, что цепочка должна быть приостановлена на короткий период времени (пока не будут заменены двоичные файлы `polygon-edge`, а сервис — заново запущен) поэтому планируйте соответствующим образом. + +Вы можете использовать такие инструменты, как **[Ansible](https://www.ansible.com/)** , или пользовательский скрипт для эффективного выполнения обновления и минимизации времени простоя цепочки. +::: + +## Процедура запуска {#startup-procedure} + +Ниже приведен желаемый порядок процедуры запуска валидатора Polygon Edge + +- Прочитайте документацию в разделе [База знаний](#knowledge-base) +- Примените последние патчи ОС на узле валидатора +- Загрузите последний двоичный файл `polygon-edge` из официальных [релизов](https://github.com/0xPolygon/polygon-edge/releases) GitHub и поместите его в локальный экземпляр`PATH` +- Запустите один из [диспетчеров секретов](/docs/category/secret-managers) с помощью команды CLI `polygon-edge secrets generate` +- Генерируйте и храните секреты с помощью `polygon-edge secrets init` [команды CLI](/docs/edge/get-started/cli-commands#secrets-init-flags) +- Обратите внимание на значения `NodeID` и `Public key (address)` +- Сгенерируйте файл `genesis.json`, как это описывается в [облачной настройке](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators) с помощью `polygon-edge genesis` [команды CLI](/docs/edge/get-started/cli-commands#genesis-flags) +- Сгенерируйте файл конфигурации по умолчанию с помощью `polygon-edge server export` [команды CLI](/docs/edge/configuration/sample-config) +- Отредактируйте файл `default-config.yaml`, чтобы разместить узел проверки локальной среды (пути файлов и т. д.) +- Создайте сервис Polygon Edge (`systemd`или подобный), в котором `polygon-edge`двоичный файл будет запускать сервер из файла `default-config.yaml` +- Запустите сервер Polygon Edge с помощью сервиса (например: `systemctl start polygon-edge`) +- Проверьте вывод журнала `polygon-edge` и убедитесь, что блоки генерируются, а журналы `[ERROR]` отсутствуют +- Проверьте функциональность цепочки с помощью метода JSON-RPC [`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid) diff --git a/archive/edge/ru-edge/working-with-node/backup-restore.md b/archive/edge/ru-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..5a5c1f3817 --- /dev/null +++ b/archive/edge/ru-edge/working-with-node/backup-restore.md @@ -0,0 +1,83 @@ +--- +id: backup-restore +title: Экземпляр резервного копирования/восстановления нода +description: "Как создать резервную копию и восстановить экземпляр нода Polygon Edge." +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## Обзор {#overview} + +Руководство подробно описывает создание резервной копии и восстановления экземпляра нода Polygon Edge. В нем рассказывается о базовых папках, их содержании, а также о том, какие файлы имеют решающее значение для выполнения успешной резервной копии и восстановления. + +## Базовые папки {#base-folders} + +Polygon Edge использует LevelDB как двигатель хранилища. При запуске нода Polygon Edge в указанной рабочей директории создаются следующие подпапки: +* **блокчейн** — хранение данных блокчейна +* **дерево** — хранение деревьев Меркла (данные о мировом состоянии) +* **хранилище ключей** — хранение приватных ключей для клиента. Это включает приватный ключ libp2p и приватный ключ запечатывания/валидатора +* **консенсус** — хранение любой информации о консенсусе, которая может понадобиться клиенту во время работы. На данный момент он хранит *приватный ключ валидатора* нода + +Крайне важно сохранить эти папки, чтобы экземпляр Polygon Edge мог быть запущен без проблем. + +## Создание резервной копии из работающего нода и восстановление для нового нода {#create-backup-from-a-running-node-and-restore-for-new-node} + +Этот раздел поможет вам создать архивные данные блокчейна на работающем ноде и восстановить их в другом экземпляре. + +### Резервное копирование {#backup} + +`backup`команда собирает блоки из работающего нода с помощью gRPC и генерирует архивный файл. Если `--from` и `--to` не указаны в команде, это команда будет собирать блоки от генезиса до последнего. + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### Восстановление {#restore} + +Сервер импортирует блоки из архива на старте, когда запуск осуществлен с флагом `--restore`. Убедитесь, что для нового нода существует ключ. Более полную информацию об импорте или генерировании ключей можно найти в разделе [Диспетчеры секретов](/docs/edge/configuration/secret-managers/set-up-aws-ssm). + +```bash +$ polygon-edge server --restore archive.dat +``` + +## Резервная копия / восстановление данных полностью {#back-up-restore-whole-data} + +Этот раздел поможет вам создать резервную копию данных, включая данные о состоянии и ключ, а также восстановить в виде нового экземпляра. + +### Шаг 1: остановите работающий клиент {#step-1-stop-the-running-client} + +Поскольку Polygon Edge использует **LevelDB** для хранения данных, нод необходимо остановить на время резервного копирования, так как **LevelDB** не позволяет одновременный доступ к файлам базы данных. + +Кроме того, Polygon Edg также выполняет промывку данных при закрытии. + +Первый шаг предполагает остановку работающего клиента (либо через диспетчера служб, либо через другой механизм, посылающий процессу сигнал SIGINT), чтобы он мог вызвать 2 события при изящном завершении работы: +* Выполнение сброса данных на диск +* Освобождение файлов БД от блокировки со стороны LevelDB + +### Шаг 2: резервное копирование директории {#step-2-backup-the-directory} + +Теперь, когда клиент не работает, данные директории можно резервировать на другой носитель. Не забывайте, что файлы с расширением `.key` содержат данные приватного ключа, которые могут быть использованы для выдачи себя за текущий нод, и они никогда не должны передаваться третьим/неизвестным лицам. + +:::info +Создайте резервную копию и восстановите сгенерированный файл `genesis` вручную, чтобы восстановленный нод был полностью работоспособен. +::: + +## Восстановление {#restore-1} + +### Шаг 1: остановите работающий клиент {#step-1-stop-the-running-client-1} + +Если какой-либо экземпляр Polygon Edge запущен, его необходимо остановить, чтобы успешно осуществить шаг 2. + +### Шаг 2: скопируйте резервную копию директории данных в нужную папку {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +Если клиент не запущен в работу, данные директории, в которой была ранее сделана резервная копия, можно скопировать в нужную папку. Кроме того, восстановите ранее скопированный файл `genesis`. + +### Шаг 3: запустите клиент Polygon Edge, указав при этом данные правильной директории {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +Чтобы Polygon Edge использовал восстановленную директорию данных, при запуске пользователю необходимо указать путь к директории данных. Подробнее о флаге `data-dir` см. в разделе [Команды CLI](/docs/edge/get-started/cli-commands). diff --git a/archive/edge/ru-edge/working-with-node/query-json-rpc.md b/archive/edge/ru-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..367ba6db7b --- /dev/null +++ b/archive/edge/ru-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,91 @@ +--- +id: query-json-rpc +title: Запрос конечных точек JSON RPC +description: "Запрос данных и запуск цепочки с предварительно пополненным аккаунтом." +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## Обзор {#overview} + +Уровень JSON-RPC в Polygon Edge предоставляет разработчикам функцию удобного взаимодействия с блокчейном через запросы HTTP. + +В этом примере описывается использование **curl** и других инструментов для запроса информации, а также запуск цепочки с предварительно пополненным аккаунтом +и отправка транзакции. + +## Шаг 1: создайте файл генезиса с предварительно пополненным аккаунтом {#step-1-create-a-genesis-file-with-a-premined-account} + +Запустите следующую команду для генерирования файла генезиса: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +Флаг **premine** указывает адрес, который необходимо включить с начальным балансом в файл генезиса **genesis**.
+В данном случае адрес `0x1010101010101010101010101010101010101010` будет иметь начальный **баланс по умолчанию** в размере +`0xD3C21BCECCEDA1000000`(1 миллион токенов нативной валюты). + +Чтобы указать баланс, можно разделить баланс и адрес с помощью `:`, например так: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +Баланс может иметь значение `hex` или `uint256`. + +:::warning Предварительно пополняйте только те аккаунты, к которым у вас имеется приватный ключ! + +Если у вас отсутствует приватный ключ для доступа к аккаунту, вы не сможете использовать предварительно пополненный остаток + +::: + +## Шаг 2: запустите Polygon Edge в режиме разработчика {#step-2-start-the-polygon-edge-in-dev-mode} + +Чтобы запустить Polygon Edge в режиме разработчика, как описано в разделе [Команды CLI](/docs/edge/get-started/cli-commands), +выполните следующую команду: +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## Шаг 3: запросите баланс аккаунта {#step-3-query-the-account-balance} + +После запуска клиента в режиме разработчика с файлом генезиса, сгенерированным на **шаге 1**, мы можем использовать **curl** или подобный инструмент для запроса остатка баланса аккаунта: +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +Вывод команды должен выглядеть так: +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## Шаг 4: отправьте транзакцию трансфера {#step-4-send-a-transfer-transaction} + +Мы убедились, что созданный предварительно пополненный аккаунт имеет правильный остаток на балансе, и теперь мы можем выполнить трансфер эфира: + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/ru-edge/working-with-node/query-operator-info.md b/archive/edge/ru-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..ea3844622c --- /dev/null +++ b/archive/edge/ru-edge/working-with-node/query-operator-info.md @@ -0,0 +1,84 @@ +--- +id: query-operator-info +title: Информация об операторе запросов +description: "Детальная информация об операторе запросов." +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## Предварительные условия {#prerequisites} + +Данное руководство предполагает, что вы следовали инструкциям [Локальной настройки](/docs/edge/get-started/set-up-ibft-locally) или [руководству по настройке кластера IBFT в облаке](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +Для запроса любой информация об операторе необходим функционирующий нод. + +С помощью Polygon Edge операторы нодов контролируют и получают информацию о том, чем занимается нод, которым они управляют.
В любой момент они могут использовать информационный слой нода, построенный на базе gRPC, и получать значимую информацию, при этом пролистывать журналы не требуется. + +:::note + +Если ваш нод не работает на `127.0.0.1:8545`, нужно добавить флаг `--grpc-address ` в команды, перечисленные в этом документе. + +::: + +## Информация о пирах (одноранговых узлах) {#peer-information} + +### Список пиров (одноранговых узлов) {#peers-list} + +Чтобы получить полный список подключенных пиров (включая сам работающий нод), выполните следующую команду: +````bash +polygon-edge peers list +```` + +Это вернет список адресов libp2p, которые в настоящее время являются пирами запущенного клиента. + +### Статус пира {#peer-status} + +Чтобы определить статус конкретного пира, запустите: +````bash +polygon-edge peers status --peer-id
+```` +Параметром *адрес* является адрес libp2p пира. + +## Информация IBFT {#ibft-info} + +Во многих случаях оператор может захотеть узнать о состоянии рабочего нода в консенсусе IBFT. + +К счастью, Polygon Edge предоставляет простой способ найти такую информацию. + +### Снимки {#snapshots} + +Запуск следующей команды возвращает самый последний снимок. +````bash +polygon-edge ibft snapshot +```` +Оператор может запустить следующую команду, чтобы запросить список на определенной высоте (номере блока): +````bash +polygon-edge ibft snapshot --num +```` + +### Кандидаты {#candidates} + +Оператор может запустить следующую команду, чтобы получить последнюю информацию о кандидатах: +````bash +polygon-edge ibft candidates +```` +Эта команда запрашивает текущий набор предложенных кандидатов, а также кандидатов, которые еще не были включены + +### Статус {#status} + +Следующая команда возвращает ключ текущего валидатора, запушенного клиента IBFT: +````bash +polygon-edge ibft status +```` + +## Пул транзакций {#transaction-pool} + +Оператор может запустить следующую команду, чтобы определить текущее количество транзакций в пуле транзакций: +````bash +polygon-edge txpool status +```` diff --git a/archive/edge/th-edge/additional-features/blockscout.md b/archive/edge/th-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..76f986f7e3 --- /dev/null +++ b/archive/edge/th-edge/additional-features/blockscout.md @@ -0,0 +1,377 @@ +--- +id: blockscout +title: Blockscout +description: วิธีตั้งค่าอินสแตนซ์ Blockscout ให้ทำงานกับ Polygon Edge +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## ภาพรวม {#overview} +คู่มือนี้มีรายละเอียดเกี่ยวกับวิธีคอมไพล์และปรับใช้อินสแตนซ์ Blockscout เพื่อทำงานกับ Polygon-EdgeBlockscout มี[เอกสารประกอบ](https://docs.blockscout.com/for-developers/manual-deployment)ของตัวเอง แต่คู่มือนี้จะเน้นไปที่คำแนะนำทีละขั้นตอนอย่างละเอียดและเรียบง่ายเกี่ยวกับวิธีตั้งค่าอินสแตนซ์ Blockscout + +## สภาพแวดล้อม {#environment} +* ระบบปฏิบัติการ: Ubuntu Server 20.04 LTS [ลิงก์สำหรับดาวน์โหลด](https://releases.ubuntu.com/20.04/) พร้อมสิทธิ์ Sudo +* ฮาร์ดแวร์เซิร์ฟเวอร์: 8CPU / 16GB RAM / HDD 50GB (LVM) +* เซิร์ฟเวอร์ฐานข้อมูล: เซิร์ฟเวอร์เฉพาะที่มี 2 CPU / 4GB RAM / 100GB SSD / PostgreSQL 13.4 + +### เซิร์ฟเวอร์ DB {#db-server} +ข้อกำหนดสำหรับการปฏิบัติตามคู่มือนี้คือ ต้องมีเซิร์ฟเวอร์ฐานข้อมูลพร้อมใช้ และกำหนดค่าฐานข้อมูลและผู้ใช้ฐานข้อมูลไว้แล้วคู่มือนี้จะไม่ลงรายละเอียดเกี่ยวกับวิธีปรับใช้และกำหนดค่าเซิร์ฟเวอร์ PostgreSQLมีคู่มือมากมายในการทำเช่นนี้ ตัวอย่างเช่น [คู่มือ DigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart) + +:::info ข้อจำกัดความรับผิดชอบ +คู่มือนี้จัดทำขึ้นเพื่อช่วยคุณรับและติดตั้ง Blockscout และรันบนอินสแตนซ์เดียวเท่านั้น ซึ่งไม่ใช่การตั้งค่าสำหรับการใช้งานที่เอื้ออำนวยนัก สำหรับการใช้งานจริง คุณอาจต้องการเพิ่มพร็อกซีย้อนกลับ โหลดบาลานเซอร์ ตัวเลือกความสามารถในการปรับขนาด ฯลฯ เข้าในสถาปัตยกรรม +::: + +# ขั้นตอนปรับใช้ Blockscout {#blockscout-deployment-procedure} + +## ส่วนที่ 1 - ติดตั้งรูปแบบการขึ้นต่อกัน {#part-1-install-dependencies} +ก่อนเริ่ม เราจำเป็นต้องตรวจสอบให้แน่ใจว่า เราได้ติดตั้งไบนารีทั้งหมดที่ Blockscout ต้องใช้แล้ว + +### อัปเดตและอัปเกรดระบบ {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### เพิ่มพื้นที่เก็บข้อมูล erlang {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### เพิ่มพื้นที่เก็บข้อมูล NodeJS {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### ติดตั้ง Rust {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### ติดตั้ง Erlang เวอร์ชันที่กำหนด {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### ติดตั้ง Elixir เวอร์ชันที่กำหนด {#install-required-version-of-elixir} +เวอร์ชัน Elixir ต้องเป็น `1.13`หากเราพยายามติดตั้งเวอร์ชันนี้จากพื้นที่เก็บข้อมูลที่เป็นทางการ`erlang` จะอัปเดตเป็น `Erlang/OTP 25` ซึ่งเราไม่ต้องการอย่างนั้น ด้วยเหตุนี้ เราจึงต้องติดตั้งเวอร์ชัน `elixir` ที่คอมไพล์ไว้ล่วงหน้าโดยเฉพาะจากหน้าการเผยแพร่ GitHub + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +ตอนนี้ เราต้องตั้งค่าระบบไบนารี `exlixir`อย่างถูกต้อง +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +ตรวจว่าติดตั้ง `elixir` และ `erlang` ถูกต้องหรือไม่ โดยเรียกใช้ `elixir -v`ควรเป็นเอาต์พุต: +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning + +`Erlang/OTP` ต้องเป็นเวอร์ชัน `24` และ `Elixir` ต้องเป็นเวอร์ชัน `1.13.*` หากไม่เป็นเช่นนั้น คุณจะประสบปัญหาในการคอมไพล์และ/หรือเรียกใช้ Blockscout +::: +:::info +ลองดู***[หน้าข้อกำหนดของ Blockscout](https://docs.blockscout.com/for-developers/information-and-settings/requirements)*** อย่างเป็นทางการ +::: + +### ติดตั้ง NodeJS {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### ติดตั้ง Cargo {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### ติดตั้งรูปแบบการขึ้นต่อกันอื่นๆ {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### เลือกติดตั้งไคลเอ็นต์ postgresql เพื่อตรวจสอบการเชื่อมต่อฐานข้อมูลของคุณ {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## ส่วนที่ 2 - ตั้งค่าตัวแปรแวดล้อม {#part-2-set-environment-variables} +เราจำเป็นต้องตั้งค่าตัวแปรแวดล้อมก่อนเริ่มการคอมไพล์ Blockscoutในคู่มือนี้ เราจะตั้งค่าขั้นต่ำพื้นฐานเท่านั้นเพื่อให้ใช้งานได้คุณสามารถดูรายการตัวแปรทั้งหมดที่สามารถทำการตั้งค่าได้[ที่นี่](https://docs.blockscout.com/for-developers/information-and-settings/env-variables) + +### ตั้งค่าการเชื่อมต่อฐานข้อมูลเป็นตัวแปรแวดล้อม {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +คราวนี้ทดสอบการเชื่อมต่อฐานข้อมูลของคุณด้วยพารามิเตอร์ที่ให้มาเนื่องจากคุณได้จัดเตรียมตัวแปรแวดล้อม PG ไว้ คุณควรสามารถเชื่อมต่อกับฐานข้อมูลได้โดยเพียงแค่เรียกใช้: +```bash +psql +``` + +หากกำหนดค่าฐานข้อมูลอย่างถูกต้อง คุณควรเห็นพรอมต์ psql: +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +หากกำหนดค่าไม่ถูกต้อง คุณอาจเห็นข้อผิดพลาดดังนี้: +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +หากเป็นเช่นนั้น [เอกสารเหล่านี้](https://ubuntu.com/server/docs/databases-postgresql)อาจช่วยคุณได้ + +:::info การเชื่อมต่อฐานข้อมูล +ตรวจให้แน่ใจว่าคุณได้แยกแยะปัญหาการเชื่อมต่อฐานข้อมูลทั้งหมดก่อนดำเนินการในส่วนถัดไป คุณจะต้องให้สิทธิ์การใช้งาน Superuser แก่ผู้ใช้ Blockcout +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## ส่วนที่ 3 - โคลนและคอมไพล์ Blockscout {#part-3-clone-and-compile-blockscout} +ในที่สุด ตอนนี้เราก็จะได้เริ่มติดตั้ง Blockscout แล้ว + +### โคลนพื้นที่เก็บข้อมูล Blockscout {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### สร้างฐานคีย์ลับเพื่อปกป้องบิลด์สำหรับใช้งานจริง {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +ที่บรรทัดสุดท้าย คุณจะเห็นอักขระสุ่มเป็นสตริงยาว ซึ่งควรตั้งค่าเป็นตัวแปรแวดล้อม `SECRET_KEY_BASE` ของคุณก่อนขั้นตอนถัดไป ตัวอย่างเช่น: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### ตั้งค่าโหมดการใช้งานจริง {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### คอมไพล์ {#compile} +เปลี่ยนไปยังไดเรกทอรีโคลนและเริ่มคอมไพล์ + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info +หากคุณได้ปรับใช้ก่อนหน้านี้ ให้ลบสินทรัพย์แบบคงที่ออกจากบิลด์ก่อนหน้า ***mix phx.digest.clean*** +::: + +### ย้ายฐานข้อมูล {#migrate-databases} +:::info +ส่วนนี้จะล้มเหลวหากคุณไม่ได้ตั้งค่าการเชื่อมต่อฐานข้อมูลของคุณอย่างถูกต้อง คุณไม่ได้ระบุหรือคุณกำหนดพารามิเตอร์ผิดที่ตัวแปรแวดล้อม DATABASE_URLผู้ใช้ฐานข้อมูลต้องมีสิทธิ์การใช้งาน Superuser +::: +```bash +mix do ecto.create, ecto.migrate +``` + +หากคุณต้องการวางฐานข้อมูลก่อน ให้เรียกใช้ +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### ติดตั้งรูปแบบการขึ้นต่อกัน npm และคอมไพล์สินทรัพย์ส่วนหน้า {#install-npm-dependencies-and-compile-frontend-assets} +คุณจำเป็นต้องเปลี่ยนไดเรกทอรีเป็นโฟลเดอร์ที่มีสินทรัพย์ส่วนหน้า + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info อดทนไว้ +การคอมไพล์สินทรัพย์เหล่านี้อาจใช้เวลาสองสามนาที และจะไม่แสดงเอาต์พุตใดๆอาจดูเหมือนกระบวนการติดขัด แต่โปรดอดทนไว้เมื่อกระบวนการคอมไพล์เสร็จสิ้น ก็ควรเอาต์พุตสิ่งที่ดูเหมือนสิ่งนี้: `webpack 5.69.1 compiled with 3 warnings in 104942 ms` +::: + +### สร้างสินทรัพย์แบบคงที่ {#build-static-assets} +สำหรับขั้นตอนนี้ คุณต้องกลับไปที่รูทของโฟลเดอร์โคลน Blockscout +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### สร้างใบรับรองที่ลงนามเอง {#generate-self-signed-certificates} +:::info +คุณสามารถข้ามขั้นตอนนี้ หากคุณจะไม่ใช้ `https` +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## ส่วนที่ 4 - สร้างและเรียกใช้บริการ Blockscout {#part-4-create-and-run-blockscout-service} +ในส่วนนี้ เราจำเป็นต้องตั้งค่าบริการระบบ เนื่องจากเราต้องการให้ Blockscout ทำงานในพื้นหลังและคงอยู่หลังการรีบูตระบบ + +### สร้างไฟล์บริการ {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### แก้ไขไฟล์บริการ {#edit-service-file} +ใช้โปรแกรมแก้ไขข้อความ Linux ที่คุณชื่นชอบเพื่อแก้ไขไฟล์นี้และกำหนดค่าบริการ +```bash +sudo vi /etc/systemd/system/explorer.service +``` +เนื้อหาของไฟล์ explorer.service ควรมีลักษณะดังนี้: +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### เปิดใช้งานการเริ่มต้นบริการในการบูตระบบ {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### ย้ายโฟลเดอร์โคลน Blockscout ของคุณไปยังตำแหน่งทั้งระบบ {#move-your-blockscout-clone-folder-to-system-wide-location} +บริการ Blockscout ต้องมีสิทธิ์เข้าถึงโฟลเดอร์ที่คุณโคลนจากพื้นที่เก็บข้อมูล Blockscout และคอมไพล์สินทรัพย์ทั้งหมด +```bash +sudo mv ~/blockscout /usr/local +``` + +### สร้างไฟล์ตัวแปรแวดล้อมที่บริการ Blockscout จะใช้ {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info +ใช้ `SECRET_KEY_BASE` ที่คุณสร้างในส่วนที่ 3 +:::บันทึกไฟล์และออก + +### สุดท้าย เริ่มบริการ Blockscout {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## ส่วนที่ 5 - ทดสอบการทำงานของอินสแตนซ์ Blockscout ของคุณ {#part-5-test-out-the-functionality-of-your-blockscout-instance} +ตอนนี้เหลือเพียงตรวจสอบว่าบริการ Blockscout ทำงานอยู่หรือไม่ตรวจสอบสถานะบริการด้วย: +```bash +sudo systemctl status explorer.service +``` + +การตรวจสอบเอาต์พุตบริการ: +```bash +sudo journalctl -u explorer.service -f +``` + +คุณสามารถตรวจสอบว่ามีพอร์ตรอรับการสื่อสารใหม่หรือไม่: +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +คุณควรได้รับรายการพอร์ตรับการเชื่อมต่อและในรายการควรมีสิ่งที่ดูเหมือนสิ่งนี้: +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +บริการเว็บ Blockscout เรียกใช้พอร์ตและโปรโตคอลที่กำหนดไว้ในไฟล์ envในตัวอย่างนี้ บริการเว็บจะเรียกใช้บน `4000`(http) หากทุกอย่างเรียบร้อย คุณควรสามารถเข้าถึงเว็บพอร์ทัล Blockscout ด้วย `http://:4000` + +## ข้อควรพิจารณา {#considerations} +เพื่อประสิทธิภาพที่ดีที่สุด ขอแนะนำให้มี `polygon-edge` ซึ่งเป็นโหนดที่ไม่ใช้โหนดตัวตรวจสอบความถูกต้องแบบเก็บถาวรเต็มรูปแบบเฉพาะงาน/ในเครื่องที่จะใช้สำหรับการสืบค้น Blockscout เท่านั้น API `json-rpc` ของโหนดนี้ ไม่จำเป็นต้องเปิดเผยต่อสาธารณะ เนื่องจาก Blockscout เรียกใช้การสืบค้นทั้งหมดจากแบ็กเอนด์ + + +## ความคิดสุดท้าย {#final-thoughts} +เราเพิ่งปรับใช้อินสแตนซ์ Blockscout เดียว ซึ่งทำงานได้ดี แต่สำหรับการใช้งานจริง คุณควรพิจารณาวางอินสแตนซ์นี้ไว้ด้านหลังพร็อกซีย้อนกลับ เช่น Nginxคุณยังควรคำนึงถึงความสามารถในการปรับขนาดฐานข้อมูลและอินสแตนซ์ด้วย ทั้งนี้ขึ้นอยู่กับกรณีการใช้งานของคุณ + +คุณควรตรวจสอบ[เอกสาร Blockscout](https://docs.blockscout.com/) อย่างเป็นทางการให้ชัดเจน เนื่องจากมีตัวเลือกการปรับแต่งมากมาย \ No newline at end of file diff --git a/archive/edge/th-edge/additional-features/chainbridge/definitions.md b/archive/edge/th-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..8392e9a132 --- /dev/null +++ b/archive/edge/th-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,216 @@ +--- +id: definitions +title: คำนิยามทั่วไป +description: นิยามทั่วไปสำหรับคำที่ใช้ใน ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## ตัวรีเลย์ {#relayer} +Chainbridge เป็นบริดจ์ประเภทตัวรีเลย์ บทบาทของตัวรีเลย์คือการโหวตเพื่อดำเนินการคำขอ (เช่น มีจำนวนโทเค็นที่ต้องเบิร์น/ปลดล็อกเท่าใด)โดยจะตรวจสอบอีเวนต์จากทุกเชนและโหวตข้อเสนอในสัญญาบริดจ์ของเชนปลายทางเมื่อได้รับอีเวนต์ `Deposit` จากเชนตัวรีเลย์จะเรียกเมธอดในสัญญาบริดจ์เพื่อดำเนินการกับข้อเสนอหลังจากส่งการโหวตในจำนวนที่ต้องการบริดจ์จะ Delegate การดำเนินการให้กับสัญญา Handler + + +## ประเภทของสัญญา {#types-of-contracts} +ใน ChainBridge มีสัญญา 3 ประเภทในแต่ละเชน ซึ่งเรียกว่าบริดจ์/Handler/Target + +| **ประเภท** | **คำอธิบาย** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| สัญญาบริดจ์ | สัญญาบริดจ์ที่จัดการคำขอ โหวต และการดำเนินการที่ต้องปรับใช้ในแต่ละเชนผู้ใช้จะเรียก `deposit` ในบริดจ์เพื่อเริ่มการโอน แล้วบริดจ์จะ Delegate กระบวนการให้กับสัญญา Handler ที่สอดคล้องกับสัญญา Targetเมื่อสัญญา Handler เรียกสัญญา Target สำเร็จแล้ว สัญญาบริดจ์จะปล่อยอีเวนต์ `Deposit` เพื่อแจ้งตัวรีเลย์ | +| สัญญา Handler | สัญญานี้จะโต้ตอบกับสัญญา Target เพื่อดำเนินการกับการฝากหรือข้อเสนอ โดยจะตรวจสอบความถูกต้องที่คำขอของผู้ใช้, เรียกสัญญา Target และช่วยการตั้งค่าบางอย่างให้สัญญา Targetมีสัญญา Handler เฉพาะที่จะเรียกสัญญา Target แต่ละสัญญาโดยจะมีอินเทอร์เฟซที่แตกต่างกันการเรียกโดยอ้อมด้วยสัญญา Handler ทำให้บริดจ์สามารถทำการโอนสินทรัพย์หรือข้อมูลได้ทุกประเภท ในขณะนี้จะมีสัญญา Handler อยู่ 3 ประเภทที่ ChainBridge นำไปใช้งานคือ: ERC20, ERC721, และ GenericHandler | +| สัญญา Target | สัญญาที่จัดการสินทรัพย์ที่จะทำการแลกเปลี่ยนหรือข้อความที่จะทำการโอนระหว่างเชนการโต้ตอบกับสัญญานี้จะเกิดขึ้นจากทั้งสองฝั่งของบริดจ์ | + +
+ +![สถาปัตยกรรม ChainBridge](/img/edge/chainbridge/architecture.svg)*สถาปัตยกรรม ChainBridge* + +
+ +
+ +![กระบวนการทำงานของการโอนโทเค็น ERC20](/img/edge/chainbridge/erc20-workflow.svg)*ตัวอย่างกระบวนการทำงานของการโอนโทเค็น ERC20* + +
+ +## ประเภทของบัญชี {#types-of-accounts} + +โปรดตรวจสอบให้แน่ใจว่าบัญชีมีโทเค็นของเชนเพียงพอสำหรับการสร้างธุรกรรมก่อนที่จะเริ่มดำเนินการใน Polygon Edge คุณสามารถกำหนดยอดคงเหลือที่วางไว้ล่วงหน้า (Premined) ให้กับบัญชีเมื่อสร้างบล็อก Genesis + +| **ประเภท** | **คำอธิบาย** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| แอดมิน | บัญชีนี้จะได้รับบทบาทแอดมินเป็นค่าเริ่มต้น | +| ผู้ใช้ | บัญชีผู้ส่ง/ผู้รับที่ส่ง/รับสินทรัพย์บัญชีผู้ส่งจะจ่ายค่าแก๊สเมื่ออนุมัติการโอนโทเค็นและเรียกการฝากในสัญญาบริดจ์เพื่อเริ่มการโอน | + +:::info บทบาทแอดมิน + +การดำเนินการบางอย่างสามารถทำได้โดยบัญชีที่มีบทบาทแอดมินเท่านั้นตามค่าเริ่มต้น ผู้ที่ปรับใช้สัญญาบริดจ์จะได้รับบทบาทแอดมินคุณสามารถดูวิธีการกำหนดบทบาทแอดมินให้กับบัญชีอื่นหรือวิธีการลบออกได้ที่ด้านล่างนี้ + +### เพิ่มบทบาทแอดมิน {#add-admin-role} + +เพิ่มเป็นแอดมิน + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### เพิกถอนบทบาทแอดมิน {#revoke-admin-role} + +ลบออกจากการเป็นแอดมิน + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## การดำเนินงานที่บัญชี `admin` สามารถทำได้มีดังนี้ {#account-are-as-below} + +### กำหนดทรัพยากร {#set-resource} + +ตั้งค่า Resource ID ด้วยที่อยู่สัญญาสำหรับ Handler + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### สร้างสัญญาที่เบิร์น/สร้างได้ {#make-contract-burnable-mintable} + +กำหนดสัญญาโทเค็นให้สร้าง/เบิร์นได้ใน Handler + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### ยกเลิกข้อเสนอ {#cancel-proposal} + +ยกเลิกข้อเสนอสำหรับการดำเนินการ + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### หยุดชั่วคราว/ยกเลิกการหยุดชั่วคราว {#pause-unpause} + +หยุดการฝาก การสร้างข้อเสนอ การโหวต และการดำเนินการฝากชั่วคราว + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### เปลี่ยนแปลงค่าธรรมเนียม {#change-fee} + +เปลี่ยนแปลงค่าธรรมเนียมที่จ่ายให้สัญญาบริดจ์ + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### เพิ่ม/ลบตัวรีเลย์ {#add-remove-a-relayer} + +เพิ่มบัญชีเป็นตัวรีเลย์ใหม่หรือลบบัญชีออกจากตัวรีเลย์ + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### เปลี่ยนเกณฑ์ของตัวรีเลย์ {#change-relayer-threshold} + +เปลี่ยนจำนวนโหวตที่จำเป็นสำหรับการดำเนินการข้อเสนอ + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## Chain ID {#chain-id} + +`chainId` ของ Chainbridge เป็นค่าแบบกำหนดเอง ซึ่งใช้ในบริดจ์เพื่อแยกความแตกต่างระหว่างเครือข่ายบล็อกเชนต่างๆ โดยต้องอยู่ในช่วงของ uint8อย่าสับสนกับ Chain ID ของเครือข่าย สองอย่างนี้ไม่เหมือนกันค่านี้จะต้องไม่ซ้ำกับค่าอื่น แต่ไม่จำเป็นต้องเหมือนกับ ID ของเครือข่าย + +ในตัวอย่างนี้ เรากำหนดให้ `99` เป็น `chainId` เนื่องจาก Chain ID ของ Mumbai Testnet คือ `80001` ซึ่งไม่สามารถนำไปแสดงค่าใน uint8 ได้ + +## Resource ID {#resource-id} + +Resource ID เป็นค่า 32 ไบต์ที่ไม่ซ้ำกับค่าอื่นในสภาพแวดล้อมแบบข้ามเชน ซึ่งจะสอดคล้องกับสินทรัพย์หนึ่ง (Resource) ที่ทำการโอนระหว่างเครือข่าย + +Resource ID เป็นค่าแบบกำหนดเอง แต่ตามธรรมเนียมไบต์สุดท้ายมักจะเป็น Chain ID ของเชนต้นทาง (เครือข่ายที่สินทรัพย์นี้กำเนิดขึ้น) + +## JSON-RPC URL สำหรับ Polygon PoS {#json-rpc-url-for-polygon-pos} + +สำหรับคู่มือนี้ เราจะใช้ https://rpc-mumbai.matic.today ซึ่งเป็น JSON-RPC URL สาธารณะที่ให้บริการโดย Polygon ซึ่งอาจมีการแออัดหรือการจำกัดอัตราการใช้งานโดยจะใช้เพื่อเชื่อมต่อกับ Polygon Mumbai Testnet เท่านั้นเราขอแนะนำให้คุณใช้ JSON-RPC URL จากบริการภายนอก เช่น Infura เนื่องจากการปรับใช้สัญญาจะการสืบค้น/คำขอจำนวนมากไปยัง JSON-RPC + +## วิธีการประมวลผลการโอนโทเค็น {#ways-of-processing-the-transfer-of-tokens} +ในการโอนโทเค็น ERC20 ระหว่างเชน จะสามารถประมวลผลโทเค็นได้ใน 2 โหมดที่แตกต่างกัน: + +### โหมดล็อก/ปลดล็อก {#lock-release-mode} +เชนต้นทาง: โทเค็นที่คุณส่งจะได้รับการล็อกไว้ในสัญญา Handler
เชนปลายทาง: โทเค็นในจำนวนเท่ากับที่คุณส่งมาจากเชนต้นทางจะได้รับการปลดล็อกและโอนจากสัญญา Handler ไปยังบัญชีผู้รับในเชนปลายทาง + +### โหมดเบิร์น/สร้าง {#burn-mint-mode} +เชนต้นทาง: โทเค็นที่คุณส่งจะได้รับการเบิร์น
เชนปลายทาง: โทเค็นในจำนวนเท่ากับที่คุณส่งและเบิร์นในเชนต้นทางจะได้รับการสร้างขึ้นในเชนปลายทางและส่งไปยังบัญชีผู้รับ + +คุณสามารถใช้โหมดที่แตกต่างกันไปได้ในแต่ละเชนซึ่งหมายความว่าคุณสามารถล็อกโทเค็นในเชนหลักไปพร้อมๆ กับสร้างโทเค็นในเชนย่อยสำหรับการโอนได้ยกตัวอย่างเช่น การล็อก/ปลดล็อกโทเค็นอาจเหมาะสมกว่า หากมีการควบคุมจำนวนทั้งหมดหรือกำหนดการสร้างไว้จะมีการสร้าง/เบิร์นโทเค็น หากสัญญาในเชนย่อยต้องเป็นไปตามอุปทานในเชนหลัก + +โหมดเริ่มต้นคือโหมดล็อก/ปลดล็อกหากคุณต้องการกำหนดให้โทเค็นสามารถสร้าง/เบิร์นได้ คุณต้องเรียกเมธอด `adminSetBurnable`หากคุณต้องการสร้างโทเค็นเมื่อมีการดำเนินการ คุณจะต้องกำหนดบทบาท `minter` ให้กับสัญญา ERC20 Handler + + diff --git a/archive/edge/th-edge/additional-features/chainbridge/overview.md b/archive/edge/th-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..a347812ea9 --- /dev/null +++ b/archive/edge/th-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: ภาพรวม +description: ภาพรวมของ ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## ChainBridge คืออะไร {#what-is-chainbridge} + +ChainBridge เป็นบริดจ์สำหรับบล็อกเชนแบบหลายทิศทางชนิดโมดูลาร์ ที่รองรับเชนที่เข้ากันได้กับ EVM และ Substrate ซึ่ง ChainSafe สร้างขึ้นโดยจะช่วยให้ผู้ใช้สามารถโอนสินทรัพย์หรือสารต่างๆ ทุกประเภทระหว่างสองเชนที่แตกต่างกัน + +หากต้องการทราบเพิ่มเติมเกี่ยวกับ ChainBridge โปรดไปที่[เอกสารอย่างเป็นทางการ](https://chainbridge.chainsafe.io/)ที่ผู้พัฒนาเขียนไว้ + +คู่มือนี้มีวัตถุประสงค์เพื่อช่วยให้ความช่วยเหลือในการผสานรวม Chainbridge เข้ากับ Polygon Edgeโดยจะอธิบายการตั้งค่าบริดจ์ระหว่าง Polygon PoS (Mumbai Testnet) ที่ดำเนินการอยู่กับเครือข่าย Polygon Edge ภายในอย่างละเอียด + +## ข้อกำหนด {#requirements} + +ในคู่มือนี้ คุณจะรันโหนด Polygon Edge, ตัวรีเลย์ ChainBridge (ดูข้อมูลเพิ่มเติม[ที่นี่](/docs/edge/additional-features/chainbridge/definitions)) และเครื่องมือ cb-sol-cli ซึ่งเป็นเครื่องมือ CLI เพื่อปรับใช้สัญญาภายใน ลงทะเบียนทรัพยากร และเปลี่ยนการตั้งค่าของบริดจ์ (คุณสามารถดูเพิ่มเติมได้[ที่นี่](https://chainbridge.chainsafe.io/cli-options/#cli-options)อีกด้วย)ต้องมีสภาพแวดล้อมดังต่อไปนี้ก่อนที่จะเริ่มการตั้งค่า: + +* Go: >= 1.17 +* Node.js >= 16.13.0 +* Git + + +นอกจากนี้ คุณจะต้องโคลนพื้นที่เก็บข้อมูลต่อไปนี้พร้อมกับเวอร์ชันต่างๆ เพื่อรันแอปพลิเคชันบางตัว + +* [Polygon Edge](https://github.com/0xPolygon/polygon-edge): ใน Branch ที่ชื่อ `develop` +* [ChainBridge](https://github.com/ChainSafe/ChainBridge): v1.1.5 +* [ChainBridge Deploy Tools](https://github.com/ChainSafe/chainbridge-deploy): `f2aa093` ใน Branch ที่ชื่อ `main` + + +คุณต้องตั้งค่าเครือข่าย Polygon Edge ก่อนดำเนินการต่อไปยังส่วนต่อไปโปรดดูรายละเอียดเพิ่มเติมที่[การตั้งค่าภายใน](/docs/edge/get-started/set-up-ibft-locally)หรือ[การตั้งค่าในระบบคลาวด์](/docs/edge/get-started/set-up-ibft-on-the-cloud) \ No newline at end of file diff --git a/archive/edge/th-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/th-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..ac7b70ff83 --- /dev/null +++ b/archive/edge/th-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,142 @@ +--- +id: setup-erc20-transfer +title: การโอนโทเค็น ERC20 +description: วิธีการตั้งค่าการโอน ERC-20 ใน ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +จนถึงตอนนี้ เราได้ตั้งค่าบริดจ์เพื่อแลกเปลี่ยนสินทรัพย์/ข้อมูลระหว่าง Polygon PoS กับเชน Polygon Edgeคู่มือส่วนนี้จะแนะนำวิธีการตั้งค่าบริดจ์ ERC20 และส่งโทเค็นระหว่างบล็อกเชนที่แตกต่างกัน + +## ขั้นตอนที่ 1: ลงทะเบียน Resource ID {#step-1-register-resource-id} + +ก่อนอื่น คุณจะต้องลงทะเบียน Resource ID ที่เชื่อมโยงทรัพยากรในสภาพแวดล้อมแบบข้ามเชนResource ID เป็นค่า 32 ไบต์ที่ต้องเป็นค่าเฉพาะตัวของทรัพยากรนั้นที่เรากำลังโอนระหว่างบล็อกเชนResource ID เป็นค่าแบบกำหนดเอง แต่ตามธรรมเนียมไบต์สุดท้ายจะเป็น Chain ID ของ Home Chain (Home Chain หมายถึงเครือข่ายที่ทรัพยากรนี้กำเนิดขึ้น) + +ในการลงทะเบียน Resource ID คุณสามารถใช้คำสั่ง `cb-sol-cli bridge register-resource`คุณจะต้องให้คีย์ส่วนตัวของบัญชี `admin` + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (ไม่บังคับ) ทำให้สัญญาสร้าง/เบิร์นได้ {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## ขั้นตอนที่ 2: โอนโทเค็น ERC20 {#step-2-transfer-erc20-token} + +เราจะส่งโทเค็น ERC20 จากเชน Polygon PoS ไปยังเชน Polygon Edge + +ก่อนอื่น คุณจะต้องได้โทเค็นจากการสร้างโทเค็นบัญชีที่มีบทบาท `minter` สามารถสร้างโทเค็นใหม่ได้ตามค่าเริ่มต้น บัญชีที่ปรับใช้สัญญา ERC20 จะได้รับบทบาท `minter`ในการกำหนดบัญชีอื่นๆ ให้เป็นสมาชิกของบทบาท `minter` คุณจะต้องรันคำสั่ง `cb-sol-cli erc20 add-minter` + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +ในการตรวจสอบยอดคงเหลือปัจจุบัน คุณสามารถใช้คำสั่ง `cb-sol-cli erc20 balance` ได้ + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +ถัดไป คุณจะต้องอนุมัติการโอนโทเค็น ERC20 จากบัญชีโดย ERC20 Handler + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +ในการโอนโทเค็นไปยังเชน Polygon Edge คุณจะต้องเรียก `deposit` + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +หลังธุรกรรมการฝากสำเร็จ ตัวรีเลย์จะได้รับอีเวนต์และการโหวตสำหรับข้อเสนอตัวรีเลย์จะดำเนินการธุรกรรมเพื่อส่งโทเค็นไปยังบัญชีผู้รับในเชน Polygon Edge หลังจากส่งการโหวตในจำนวนที่ต้องการ + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +เมื่อธุรกรรมดำเนินการสำเร็จ คุณจะได้รับโทเค็นในเชน Polygon Edge + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/th-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/th-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..9b7fbe73d4 --- /dev/null +++ b/archive/edge/th-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,134 @@ +--- +id: setup-erc721-transfer +title: การโอน NFT มาตรฐาน ERC721 +description: วิธีการตั้งค่าการโอน ERC721 ใน ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +ส่วนนี้แนะนำคุณตลอดการตั้งค่าบริดจ์ ERC721 และการส่ง NFT ระหว่างเครือข่ายบล็อกเชน + +## ขั้นตอนที่ 1: ลงทะเบียน Resource ID {#step-1-register-resource-id} + +ก่อนอื่นคุณจะต้องลงทะเบียน Resource ID สำหรับโทเค็น ERC721 ในสัญญาบริดจ์ทั้งสองเชน + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (ไม่บังคับ): ทำให้สัญญาสร้าง/เบิร์นได้ {#optional-make-contracts-mintable-burnable} + +ในการทำให้โทเค็นสร้าง/เบิร์นได้ คุณจะต้องเรียกคำสั่งต่อไปนี้: + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## ขั้นตอนที่ 2: โอน NFT {#step-2-transfer-nft} + +ก่อนอื่น คุณจะสร้าง NFT หากคุณต้องการ NFT + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +คุณสามารถใช้ `cb-sol-cli erc721 owner` ในการตรวจสอบเจ้าของ NFT ได้ + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +จากนั้น คุณจะต้องอนุมัติการโอน NFT โดย ERC721 Handler + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +สุดท้ายนี้ คุณจะต้องเริ่มการโอน + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +ตัวรีเลย์จะได้รับอีเวนต์และการโหวตสำหรับข้อเสนอตัวรีเลย์จะดำเนินการธุรกรรมเพื่อส่ง NFT ไปยังบัญชีผู้รับในเชน Polygon Edge หลังจากส่งการโหวตในจำนวนที่ต้องการ + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +คุณสามารถตรวจสอบเจ้าของ NFT บนเครือข่าย Polygon Edge ได้หลังจากการดำเนินการเสร็จสิ้นแล้ว + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/th-edge/additional-features/chainbridge/setup.md b/archive/edge/th-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..c5f849afe1 --- /dev/null +++ b/archive/edge/th-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,197 @@ +--- +id: setup +title: การตั้งค่า +description: วิธีตั้งค่า ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## การปรับใช้สัญญา {#contracts-deployment} + +ในส่วนนี้ คุณจะปรับใช้สัญญาที่จำเป็นไปยังเชน Polygon PoS และ Polygon Edge ด้วย `cb-sol-cli` + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +ประการแรก เราจะปรับใช้สัญญากับเชน Polygon PoS โดยใช้คำสั่ง `cb-sol-cli deploy` ค่าสถานะ `--all` ทำให้คำสั่งปรับใช้สัญญาทั้งหมด รวมถึงบริดจ์, ERC20 Handler, ERC721 Handler, Generic Handler, ERC20 และสัญญา ERC721นอกจากนี้ ยังจะตั้งค่าที่อยู่บัญชีตัวรีเลย์เริ่มต้นและหลักเกณฑ์ + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +เรียนรู้เกี่ยวกับ chainID และ JSON-RPC URL [ที่นี่](/docs/edge/additional-features/chainbridge/definitions) + +:::caution + +ราคาแก๊สเริ่มต้นใน `cb-sol-cli` คือ `20000000` (`0.02 Gwei`)หากต้องการกำหนดราคาแก๊สที่เหมาะสมในธุรกรรม โปรดตั้งค่าโดยใช้อาร์กิวเมนต์ `--gasPrice` + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +สัญญาบริดจ์ใช้ค่าแก๊สประมาณ 0x3f97b8 (4167608) ในการปรับใช้โปรดตรวจสอบให้แน่ใจว่าบล็อกที่กำลังสร้างมีขีดจำกัดค่าแก๊สต่อบล็อกเพียงพอสำหรับการทำธุรกรรมการสร้างสัญญาหากต้องการเรียนรู้เพิ่มเติมเกี่ยวกับการเปลี่ยนขีดจำกัดค่าแก๊สต่อบล็อกใน Polygon Edge โปรดไปที่[การตั้งค่าภายใน](/docs/edge/get-started/set-up-ibft-locally) + +::: + +เมื่อปรับใช้งานสัญญาแล้ว คุณจะได้รับผลลัพธ์ต่อไปนี้: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +ตอนนี้เราอาจปรับใช้สัญญากับเชน Polygon Edge + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +บันทึกเอาต์พุตเทอร์มินัลด้วยที่อยู่สัญญาอัจฉริยะที่ปรับใช้ เนื่องจากเราต้องมีไว้สำหรับขั้นตอนต่อไป + +## การตั้งค่าตัวรีเลย์ {#relayer-setup} + +ในส่วนนี้ คุณจะเริ่มต้นตัวรีเลย์เพื่อแลกเปลี่ยนข้อมูลระหว่าง 2 เชน + +ขั้นแรก เราต้องโคลนและสร้างพื้นที่เก็บข้อมูล ChainBridge + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +ถัดไป คุณต้องสร้าง `config.json` และตั้งค่า JSON-RPC URL, ที่อยู่ตัวรีเลย์ และที่อยู่สัญญาสำหรับแต่ละเชน + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +ในการเริ่มต้นตัวรีเลย์ คุณต้องนำเข้าคีย์ส่วนตัวที่สอดคล้องกับที่อยู่บัญชีของตัวรีเลย์คุณจะต้องป้อนรหัสผ่านเมื่อคุณนำเข้าคีย์ส่วนตัวเมื่อการนำเข้าสำเร็จ คีย์จะได้รับการเก็บไว้ใต้ `keys/
.key` + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +จากนั้น คุณก็สามารถเริ่มตัวรีเลย์ได้คุณจะต้องป้อนรหัสผ่านเดียวกับที่คุณเลือกไว้สำหรับการจัดเก็บคีย์ในตอนเริ่มต้น + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +เมื่อตัวรีเลย์เริ่มต้นขึ้นแล้ว ตัวรีเลย์จะเริ่มดูบล็อกใหม่ๆ ในแต่ละเชน diff --git a/archive/edge/th-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/th-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..aba350ad5f --- /dev/null +++ b/archive/edge/th-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,255 @@ +--- +id: use-case-erc20-bridge +title: กรณีการใช้งาน - บริดจ์ ERC20 +description: ตัวอย่างสำหรับการบริดจ์สัญญา ERC20 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +ส่วนนี้มีจุดมุ่งหมายเพื่อให้คุณมีขั้นตอนการตั้งค่าบริดจ์ ERC20 สำหรับกรณีการใช้งานจริง + +ในคำแนะนำนี้ คุณจะใช้ Mumbai Polygon PoS Testnet และเชนภายใน Polygon Edgeโปรดตรวจสอบให้แน่ใจว่าคุณมี JSON-RPC Endpoint สำหรับ Mumbai และคุณได้ตั้งค่า Polygon Edge ในสภาพแวดล้อมภายในแล้วโปรดดูรายละเอียดเพิ่มเติมที่[การตั้งค่าภายใน](/docs/edge/get-started/set-up-ibft-locally)หรือ[การตั้งค่าในระบบคลาวด์](/docs/edge/get-started/set-up-ibft-on-the-cloud) + +## สถานการณ์จำลอง {#scenario} + +สถานการณ์จำลองนี้คือการตั้งค่าบริดจ์สำหรับโทเค็น ERC20 ที่ได้รับการปรับใช้ในเชนสาธารณะ (Polygon PoS) แล้วเพื่อเปิดใช้งานการถ่ายโอนต้นทุนต่ำในเชนส่วนตัว (Polygon Edge) สำหรับผู้ใช้ในกรณีปกติในกรณีดังกล่าว จะมีการกำหนดจำนวนทั้งหมดของโทเค็นไว้แล้วในเชนสาธารณะ และจะต้องมีเฉพาะโทเค็นในจำนวนที่โอนจากเชนสาธารณะไปยังเชนส่วนตัวอยู่ในเชนส่วนตัวเท่านั้นด้วยเหตุผลดังกล่าว คุณจะต้องใช้โหมดล็อก/ปลดล็อกในเชนสาธารณะและโหมดเบิร์น/สร้างในเชนส่วนตัว + +เมื่อส่งโทเค็นจากเชนสาธารณะไปยังเชนส่วนตัว จะมีการล็อกโทเค็นในสัญญา ERC20 Handler ของเชนสาธารณะ และสร้างโทเค็นจำนวนเท่ากันในเชนส่วนตัวในทางกลับกัน ในกรณีที่โอนจากเชนส่วนตัวไปยังเชนสาธารณะ จะมีการเบิร์นโทเค็นในเชนส่วนตัวและปล่อยโทเค็นในจำนวนที่เท่ากันนี้จากสัญญา ERC20 Handler ในเชนสาธารณะ + +## สัญญา {#contracts} + +การอธิบายด้วยสัญญา ERC20 อย่างง่าย แทนที่จะเป็นสัญญาที่ ChainBridge พัฒนาขึ้นสำหรับโหมดเบิร์น/สร้าง สัญญา ERC20 ต้องมีเมธอด `mint` และ `burnFrom` นอกจากเมธอดสำหรับ ERC20 ดังนี้: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +โค้ดและสคริปต์ทั้งหมดอยู่ในพื้นที่เก็บข้อมูล Github [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example) + +## ขั้นตอนที่ 1: ปรับใช้สัญญาบริดจ์และ ERC20 Handler {#step1-deploy-bridge-and-erc20-handler-contracts} + +ประการแรก คุณจะปรับใช้สัญญาบริดจ์และ ERC20Handler โดยใช้ `cb-sol-cli` ในทั้งสองเชน + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +คุณจะได้รับที่อยู่สัญญาบริดจ์และ ERC20Handler ดังนี้: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## ขั้นตอนที่ 2: ปรับใช้สัญญา ERC20 ของคุณ {#step2-deploy-your-erc20-contract} + +คุณจะปรับใช้สัญญา ERC20 ของคุณตัวอย่างนี้จะแนะนำคุณเกี่ยวกับโครงการ Hardhat [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example) + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +โปรดสร้างไฟล์ `.env` และตั้งค่าต่อไปนี้ + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +ต่อไปคุณจะปรับใช้สัญญา ERC20 ในทั้งสองเชน + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +หลังการปรับใช้สำเร็จ คุณจะได้รับที่อยู่ของสัญญาดังนี้: + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## ขั้นตอนที่ 3: ลงทะเบียน Resource ID ใน Bridge {#step3-register-resource-id-in-bridge} + +คุณจะลงทะเบียน Resource ID ที่เชื่อมโยงทรัพยากรในสภาพแวดล้อมแบบข้ามเชนคุณต้องตั้งค่า Resource ID เดียวกันในทั้งสองเชน + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## ขั้นตอนที่ 4: ตั้งค่าโหมดสร้าง/เบิร์น ในบริดจ์ ERC20 ของ Edge {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +Bridge คาดว่าจะทำงานในโหมดเบิร์น/สร้างใน Polygon Edgeคุณจะตั้งค่าโหมดเบิร์น/สร้างโดยใช้ `cb-sol-cli` + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +และคุณจำเป็นต้องมอบบทบาทผู้สร้างและผู้เบิร์นให้สัญญา ERC20 Handler + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## ขั้นตอนที่ 5: สร้างโทเค็น {#step5-mint-token} + +คุณจะสร้างโทเค็น ERC20 ใหม่ในเชน Mumbai + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +หลังธุรกรรมสำเร็จแล้ว บัญชีจะมีโทเค็นที่สร้าง + +## ขั้นตอนที่ 6: เริ่มการโอน ERC20 {#step6-start-erc20-transfer} + +ก่อนเริ่มขั้นตอนนี้ โปรดตรวจสอบให้แน่ใจว่าคุณได้เริ่มต้นตัวรีเลย์แล้วโปรดดูรายละเอียดเพิ่มเติมที่[การตั้งค่า](/docs/edge/additional-features/chainbridge/setup) + +ระหว่างการโอนโทเค็นจาก Mumbai ไปยัง Edge สัญญา ERC20 Handler ใน Mumbai จะถอนโทเค็นจากบัญชีของคุณคุณจะเรียก approve ก่อนโอน + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +สุดท้าย คุณจะเริ่มโอนโทเค็นจาก Mumbai ไปยัง Edge โดยใช้ `cb-sol-cli` + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +หลังธุรกรรมฝากเงินสำเร็จ ตัวรีเลย์จะได้รับอีเวนต์และโหวตข้อเสนอตัวรีเลย์ดำเนินการธุรกรรมเพื่อส่งโทเค็นไปยังบัญชีผู้รับในเชน Polygon Edge หลังจากส่งการโหวตในจำนวนที่ต้องการ + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +เมื่อธุรกรรมดำเนินการสำเร็จ คุณจะได้รับโทเค็นในเชน Polygon Edge diff --git a/archive/edge/th-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/th-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..5379a26bc8 --- /dev/null +++ b/archive/edge/th-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,307 @@ +--- +id: use-case-erc721-bridge +title: กรณีการใช้งาน - บริดจ์ ERC721 +description: ตัวอย่างของการบริดจ์สัญญา ERC721 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +ส่วนนี้มีจุดมุ่งหมายเพื่อให้คุณมีขั้นตอนการตั้งค่าบริดจ์ ERC721 สำหรับกรณีการใช้งานจริง + +ในคู่มือนี้ คุณจะใช้ Mumbai Polygon PoS Testnet และเชน Polygon Edge ภายในโปรดตรวจสอบให้แน่ใจว่าคุณมี JSON-RPC Endpoint สำหรับ Mumbai และคุณได้ตั้งค่า Polygon Edge ในสภาพแวดล้อมภายในแล้วโปรดดูรายละเอียดเพิ่มเติมที่[การตั้งค่าภายใน](/docs/edge/get-started/set-up-ibft-locally)หรือ[การตั้งค่าในระบบคลาวด์](/docs/edge/get-started/set-up-ibft-on-the-cloud) + +## สถานการณ์จำลอง {#scenario} + +สถานการณ์นี้คือการตั้งค่าบริดจ์สำหรับ NFT มาตรฐาน ERC721 ที่ได้รับการปรับใช้ในเชนสาธารณะ (Polygon PoS) แล้วเพื่อเปิดใช้งานการโอนต้นทุนต่ำในเชนส่วนตัว (Polygon Edge) สำหรับผู้ใช้ในกรณีปกติในกรณีดังกล่าว มีการกำหนดข้อมูลเมตาต้นฉบับไว้ในเชนสาธารณะแล้ว และมีแต่ NFT ที่ได้รับการโอนมาจากเชนสาธารณะเท่านั้นที่จะสามารถอยู่ในเชนส่วนตัวได้ด้วยเหตุผลดังกล่าว คุณจะต้องใช้โหมดล็อก/ปลดล็อกในเชนสาธารณะและโหมดเบิร์น/สร้างในเชนส่วนตัว + +เมื่อส่ง NFT จากเชนสาธารณะไปยังเชนส่วนตัว จะมีการล็อก NFT ในสัญญา ERC721 Handler ในเชนสาธารณะ และสร้าง NFT เดียวกันในเชนส่วนตัวในทางกลับกัน ในกรณีที่โอนจากเชนส่วนตัวไปยังเชนสาธารณะ จะมีการเบิร์น NFT ในเชนส่วนตัวและปลดล็อก NFT เดียวกันจากสัญญา ERC721 Handler ในเชนสาธารณะ + +## สัญญา {#contracts} + +การอธิบายด้วยสัญญา ERC721 อย่างง่าย แทนที่จะเป็นสัญญาที่ ChainBridge พัฒนาขึ้นสำหรับโหมดเบิร์น/สร้าง สัญญา ERC721 ต้องมีเมธอด `mint` และ `burn` นอกจากเมธอดสำหรับ ERC721 ดังนี้: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +โค้ดและสคริปต์ทั้งหมดอยู่ในพื้นที่เก็บข้อมูล Github [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example) + +## ขั้นตอนที่ 1: ปรับใช้สัญญาบริดจ์และ ERC721 Handler {#step1-deploy-bridge-and-erc721-handler-contracts} + +ก่อนอื่นคุณจะต้องปรับใช้สัญญาบริดจ์และ ERC721Handler โดยใช้ `cb-sol-cli` ในทั้งสองเชน + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +คุณจะได้รับที่อยู่สัญญาบริดจ์และ ERC721Handler ดังนี้: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## ขั้นตอนที่ 2: ปรับใช้สัญญา ERC721 ของคุณ {#step2-deploy-your-erc721-contract} + +คุณจะต้องปรับใช้สัญญา ERC721 ของคุณตัวอย่างนี้จะแนะนำคุณเกี่ยวกับโครงการ Hardhat [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example) + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +โปรดสร้างไฟล์ `.env` และตั้งค่าต่อไปนี้ + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +ต่อไปคุณจะต้องปรับใช้สัญญา ERC721 ในทั้งสองเชน + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +หลังจากการปรับใช้สำเร็จ คุณจะได้รับที่อยู่ของสัญญาดังนี้: + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## ขั้นตอนที่ 3: ลงทะเบียน Resource ID ในบริดจ์ {#step3-register-resource-id-in-bridge} + +คุณจะต้องลงทะเบียน Resource ID ที่เชื่อมโยงทรัพยากรในสภาพแวดล้อมแบบข้ามเชน + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## ขั้นตอนที่ 4: ตั้งค่าโหมดสร้าง/เบิร์นในบริดจ์ ERC721 ของ Edge {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +บริดจ์จะทำงานในโหมดเบิร์น/สร้างใน Edgeคุณจะต้องตั้งค่าโหมดเบิร์น/สร้าง + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +และคุณจะต้องมอบบทบาทผู้สร้างและผู้เบิร์นให้สัญญา ERC721 Handler + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## ขั้นตอนที่ 5: สร้าง NFT {#step5-mint-nft} + +คุณจะต้องสร้าง NFT มาตรฐาน ERC721 ใหม่ในเชน Mumbai + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +หลังธุรกรรมสำเร็จแล้ว บัญชีจะมี NFT ที่สร้างขึ้น + +## ขั้นตอนที่ 6: เริ่มการโอน ERC721 {#step6-start-erc721-transfer} + +ก่อนเริ่มขั้นตอนนี้ โปรดตรวจสอบให้แน่ใจว่าคุณได้เริ่มต้นตัวรีเลย์แล้วโปรดดูรายละเอียดเพิ่มเติมที่[การตั้งค่า](/docs/edge/additional-features/chainbridge/setup) + +ระหว่างการโอน NFT จาก Mumbai ไปยัง Edge สัญญา ERC721 Handler ใน Mumbai จะถอน NFT จากบัญชีของคุณคุณจะต้องเรียก approve ก่อนโอน + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +สุดท้ายนี้ คุณจะต้องเริ่มต้นการโอน NFT จาก Mumbai ไปยัง Edge + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +หลังธุรกรรมการฝากสำเร็จ ตัวรีเลย์จะได้รับอีเวนต์และการโหวตสำหรับข้อเสนอ ตัวรีเลย์จะดำเนินการธุรกรรมเพื่อส่ง NFT ไปยังบัญชีผู้รับในเชน Polygon Edge หลังจากส่งการโหวตในจำนวนที่ต้องการ + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +เมื่อธุรกรรมดำเนินการสำเร็จ คุณจะได้รับ NFT ในเชน Polygon Edge diff --git a/archive/edge/th-edge/additional-features/permission-contract-deployment.md b/archive/edge/th-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..0e0b1474b0 --- /dev/null +++ b/archive/edge/th-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,85 @@ +--- +id: permission-contract-deployment +title: การอนุญาตให้ปรับใช้สัญญาอัจฉริยะ +description: วิธีการเพิ่มการอนุญาตให้ปรับใช้สัญญาอัจฉริยะ +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## ภาพรวม {#overview} + +คู่มือนี้จะลงรายละเอียดถึงวิธีการให้การอนุญาตที่อยู่เพื่อให้สามารถปรับใช้สัญญาอัจฉริยะได้ในบางครั้งตัวดำเนินการเครือข่ายต้องการที่จะป้องกันไม่ให้ผู้ใช้ปรับใช้สัญญาอัจฉริยะที่ไม่เกี่ยวกับวัตถุประสงค์ของเครือข่ายตัวดำเนินการเครือข่ายสามารถ: + +1. เพิ่มที่อยู่สำหรับการปรับใช้สัญญาอัจฉริยะเข้าในรายการอนุญาต +2. ลบที่อยู่สำหรับการปรับใช้สัญญาอัจฉริยะออกจากรายการอนุญาต + +## นำเสนอวิดีโอ {#video-presentation} + +[![การใช้งานสัญญาอนุญาต - วิดีโอ](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## วิธีการใช้งาน {#how-to-use-it} + + +คุณสามารถดูคำสั่ง cli ทั้งหมดที่เกี่ยวกับรายการอนุญาตให้ปรับใช้ได้ในหน้า[คำสั่ง CLI](/docs/edge/get-started/cli-commands#whitelist-commands) + +* `whitelist show`: แสดงข้อมูลของรายการอนุญาต +* `whitelist deployment --add`: เพิ่มที่อยู่ใหม่ไปยังรายการอนุญาตให้ปรับใช้สัญญา +* `whitelist deployment --remove`: ลบที่อยู่ใหม่ออกจากรายการอนุญาตให้ปรับใช้สัญญา + +#### การแสดงที่อยู่ทั้งหมดในรายการอนุญาตให้ปรับใช้ {#show-all-addresses-in-the-deployment-whitelist} + +การค้นหาที่อยู่ในรายการอนุญาตให้ปรับใช้มี 2 วิธี +1. ดู `genesis.json` ที่บันทึกรายการอนุญาตไว้ +2. ใช้ `whitelist show` ซึ่งจะแสดงข้อมูลรายการอนุญาตทั้งหมดที่ Polygon Edge รองรับ + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### การเพิ่มที่อยู่ในรายการอนุญาตให้ปรับใช้ {#add-an-address-to-the-deployment-whitelist} + +หากต้องการเพิ่มที่อยู่ใหม่ในรายการอนุญาตให้ปรับใช้ โปรดใช้คำสั่ง CLI `whitelist deployment --add [ADDRESS]`โดยจะไม่มีการจำกัดจำนวนของที่อยู่ที่สามารถมีในรายการอนุญาตที่อยู่ที่มีในรายการอนุญาตให้ปรับใช้สัญญาเท่านั้นที่จะสามารถปรับใช้สัญญาได้หากรายการอนุญาตว่างเปล่า ทุกที่อยู่จะสามารถทำการปรับใช้ได้ + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### การลบที่อยู่ออกจากรายการอนุญาตให้ปรับใช้ {#remove-an-address-from-the-deployment-whitelist} + +หากต้องการลบที่อยู่ออกจากรายการอนุญาตให้ปรับใช้ โปรดใช้คำสั่ง CLI `whitelist deployment --remove [ADDRESS]`ที่อยู่ที่มีในรายการอนุญาตให้ปรับใช้สัญญาเท่านั้นที่จะสามารถปรับใช้สัญญาได้หากรายการอนุญาตว่างเปล่า ทุกที่อยู่จะสามารถทำการปรับใช้ได้ + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/th-edge/architecture/modules/blockchain.md b/archive/edge/th-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..89000d58be --- /dev/null +++ b/archive/edge/th-edge/architecture/modules/blockchain.md @@ -0,0 +1,156 @@ +--- +id: blockchain +title: บล็อกเชน +description: คำอธิบายสำหรับบล็อกเชนและโมดูลสถานะของ Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## ภาพรวม {#overview} + +หนึ่งในโมดูลหลักของ Polygon Edge คือ**บล็อกเชน**และ**สถานะ**
+ +**บล็อกเชน**เป็นขุมพลังที่จัดการกับการปรับโครงสร้างบล็อกซึ่งหมายความว่าบล็อกเชนจัดการกับลอจิกทั้งหมดที่เกิดขึ้นเมื่อรวมบล็อกใหม่ไว้ในบล็อกเชน + +**สถานะ**แสดงอ็อบเจ็กต์*การเปลี่ยนผ่านสถานะ*สถานะจัดการกับการเปลี่ยนแปลงสถานะ เมื่อมีการรวมบล็อกใหม่
ตัวอย่างเช่น **สถานะ**จะจัดการกับ: +* การดำเนินการธุรกรรม +* การดำเนินการ EVM +* การเปลี่ยนแปลง Merkle Tries +* อีกมากมาย ซึ่งได้รับการรวมไว้ในส่วน**สถานะ** 🙂 + +ประเด็นสำคัญคือ 2 ส่วนนี้เชื่อมโยงกันอย่างมากและทำงานร่วมกันอย่างใกล้ชิดเพื่อให้ไคลเอ็นต์ทำงานได้
ตัวอย่างเช่น เมื่อเลเยอร์**บล็อกเชน**ได้รับบล็อกใหม่ (และไม่มีการจัดระเบียบใหม่เกิดขึ้น) เลเยอร์ก็จะเรียก**สถานะ**เพื่อดำเนินการเปลี่ยนผ่านสถานะ + +**บล็อกเชน**ยังต้องจัดการกับบางส่วนที่เกี่ยวข้องกับฉันทามติ (เช่น *ethHash นี้ถูกต้องหรือไม่*, *PoW นี้ถูกต้องหรือไม่*)
หากจะสรุปเป็นหนึ่งประโยคก็คือ **บล็อกเชนคือแกนหลักของลอจิก ซึ่งรวมบล็อกทั้งหมดไว้** + +## *WriteBlocks* + +หนึ่งในส่วนที่สำคัญที่สุดที่เกี่ยวข้องกับเลเยอร์**บล็อกเชน** คือเมธอด *WriteBlocks*: + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +เมธอด *WriteBlocks* เป็นจุดเริ่มต้นในการเขียนบล็อกลงในบล็อกเชนซึ่งจะนำไปใช้ในหลายๆ บล็อกในฐานะพารามิเตอร์
ขั้นตอนแรก จะเริ่มจากการตรวจสอบความถูกต้องของบล็อกจากนั้น ก็เขียนข้อมูลของบล็อกดังกล่าวเข้าในเชน + +*การเปลี่ยนผ่านสถานะ*จริงจะได้รับการดำเนินการโดยเรียกเมธอด *processBlock* ภายใน *WriteBlocks* + +ควรกล่าวว่า เนื่องจากเป็นจุดเริ่มต้นสำหรับการเขียนบล็อกไปยังบล็อกเชน โมดูลอื่นๆ (เช่น **Sealer**) จึงใช้เมธอดนี้ + +## การสมัครติดตามบล็อกเชน {#blockchain-subscriptions} + +จำเป็นต้องมีวิธีการติดตามการเปลี่ยนแปลงที่เกี่ยวข้องกับบล็อกเชน
**การสมัครติดตาม**มีประโยชน์ตรงนี้นั่นเอง + +การสมัครติดตามเป็นวิธีหนึ่งในการเข้าสู่สตรีมของอีเวนต์บล็อกเชนและรับข้อมูลที่มีความหมายทันที + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +**อีเวนต์บล็อกเชน**มีข้อมูลเกี่ยวกับการเปลี่ยนแปลงใดๆ ที่เกิดขึ้นกับเชนจริงซึ่งรวมถึงการปรับโครงสร้างใหม่ รวมทั้งบล็อกใหม่ๆ: + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip ทบทวนข้อมูล +คุณจำตอนที่เราพูดถึงคำสั่ง ***monitor*** ใน[คำสั่ง CLI](/docs/edge/get-started/cli-commands) ได้หรือไม่ + +อีเวนต์บล็อกเชนเป็นอีเวนต์ดั้งเดิมที่เกิดขึ้นใน Polygon Edge และจะมีการแมปกับรูปแบบข้อความของ Protocol Buffers ในภายหลังเพื่อให้ถ่ายโอนได้ง่าย +::: \ No newline at end of file diff --git a/archive/edge/th-edge/architecture/modules/consensus.md b/archive/edge/th-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..db58618e9b --- /dev/null +++ b/archive/edge/th-edge/architecture/modules/consensus.md @@ -0,0 +1,494 @@ +--- +id: consensus +title: ฉันทามติ +description: คำอธิบายสำหรับโมดูลฉันทามติของ Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## ภาพรวม {#overview} + +โมดูล**ฉันทามติ**ให้อินเทอร์เฟซสำหรับกลไกฉันทามติ + +ปัจจุบันมีเอนจิ้นฉันทามติดังต่อไปนี้: +* **IBFT PoA** +* **IBFT PoS** + +Polygon Edge ต้องการรักษาสถานะของ Modularity และ Pluggability
นี่คือเหตุผลที่มีการแยกลอจิกฉันทามติหลักออกไป ดังนั้นจึงสามารถสร้างกลไกฉันทามติใหม่ได้ โดยไม่กระทบความสามารถในการใช้และความง่ายในการใช้งาน + +## อินเทอร์เฟซฉันทามติ {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + +อินเทอร์เฟซ***ฉันทามติ*** เป็นแกนหลักของ Abstraction ที่กล่าวถึง
+* เมธอด **VerifyHeader** แสดงถึงฟังก์ชันตัวช่วยที่เลเยอร์ฉันทามติแสดงให้เลเยอร์ **บล็อกเชน**เห็นมีไว้เพื่อจัดการการตรวจสอบส่วนหัว +* เมธอด **Start** เพียงแค่เริ่มต้นกระบวนการฉันทามติและทุกอย่างที่เกี่ยวข้อง ซึ่งรวมถึงการซิงค์การซีล และทุกอย่างที่ต้องทำ +* เมธอด **Close** จะปิดการเชื่อมต่อฉันทามติ + +## การกำหนดค่าฉันทามติ {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +อาจมีบางครั้งที่คุณอาจต้องการส่งผ่านตำแหน่งที่กำหนดเองสำหรับโปรโตคอลฉันทามติเพื่อจัดเก็บข้อมูล หรือบางทีก็จัดเก็บการแมปคีย์-ค่าที่กำหนดเองที่คุณต้องการให้กลไกฉันทามติใช้ซึ่งสามารถทำได้ผ่านโครงสร้าง ***Config***ซึ่งจะมีการอ่านเมื่อสร้างอินสแตนซ์ฉันทามติใหม่ขึ้น + +## IBFT {#ibft} + +### ExtraData {#extradata} + +อ็อบเจ็กต์ส่วนหัวของบล็อกเชน ซึ่งเป็นหนึ่งในฟิลด์ต่างๆ ที่เรียกว่า **ExtraData** + +IBFT ใช้ฟิลด์พิเศษนี้เพื่อจัดเก็บข้อมูลการดำเนินงานเกี่ยวกับบล็อก โดยตอบคำถามเช่น: +* "ใครลงนามบล็อกนี้" +* "ใครคือตัวตรวจสอบความถูกต้องของบล็อกนี้" + +มีการกำหนดฟิลด์พิเศษเหล่านี้สำหรับ IBFT ไว้ดังนี้: +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### การลงนามในข้อมูล {#signing-data} + +เพื่อให้โหนดลงนามข้อมูลใน IBFT โหนดจะใช้ประโยชน์จากเมธอด *signHash*: +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +อีกเมธอดที่สำคัญคือเมธอด *VerifyCommittedFields* ซึ่งตรวจสอบว่าซีลที่คอมมิตมาจากตัวตรวจสอบความถูกต้องที่ถูกต้อง: +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### สแนปชอต {#snapshots} + +ตามที่ชื่อบอกโดยนัย สแนปชอตมีไว้เพื่อแสดง*ภาพ*หรือ*สถานะ*ของระบบที่ทุกระดับความสูงของบล็อก (ตัวเลข) + +สแนปชอตประกอบด้วยชุดโหนดที่เป็นตัวตรวจสอบความถูกต้อง เช่นเดียวกับข้อมูลการโหวต (ตัวตรวจสอบความถูกต้องสามารถโหวตให้กับตัวตรวจสอบความถูกต้องอื่นๆ)ตัวตรวจสอบความถูกต้องรวมข้อมูลการโหวตในฟิลด์หัวข้อ **Miner** และเปลี่ยนค่าของ **Nonce**: +* Nonce จะเป็น **1 ทั้งหมด** หากโหนดต้องการลบตัวตรวจสอบความถูกต้อง +* Nonce จะเป็น **0 ทั้งหมด** หากโหนดต้องการเพิ่มตัวตรวจสอบความถูกต้อง + +คำนวณสแนปชอตโดยใช้เมธอด ***processHeaders***: + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +โดยปกติ จะมีการเรียกเมธอดนี้พร้อมกับ 1 ส่วนหัว แต่ขั้นตอนการประมวลผลจะเหมือนกัน แม้ว่าจะมีหลายส่วนหัว
+สำหรับแต่ละส่วนหัวที่ส่งผ่าน IBFT จำเป็นต้องตรวจสอบว่าผู้เสนอส่วนหัวเป็นตัวตรวจสอบความถูกต้องหรือไม่ซึ่งสามารถทำได้ง่ายๆ โดยการนำสแนปชอตล่าสุดมาตรวจสอบว่าโหนดอยู่ในชุดตัวตรวจสอบความถูกต้องหรือไม่ + +จากนั้น จะทำการตรวจสอบ Nonceการโหวตจะได้รับการรวมและนับ - และหากมีการโหวตเพียงพอ จะมีการเพิ่ม/ลบโหนดจากชุดตัวตรวจสอบความถูกต้อง จากนั้นจึงบันทึกสแนปชอตใหม่ + +#### Snapshot Store {#snapshot-store} + +บริการสแนปชอตจะจัดการและอัปเดตเอนทิตีที่เรียกว่า **snapshotStore** ซึ่งจัดเก็บรายการสแนปชอตที่มีอยู่ทั้งหมดบริการใช้รายการนี้เพื่อให้ทราบได้อย่างรวดเร็วว่าเกี่ยวข้องกับสแนปชอตใดที่ความสูงของบล็อกในระดับใด +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### การเริ่มต้น IBFT {#ibft-startup} + +Polygon Edge จำเป็นต้องตั้งค่าการขนส่ง IBFT ก่อนถึงจะเริ่มต้น IBFT ได้: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +โดยหลักแล้ว จะมีการสร้างหัวข้อใหม่ด้วย IBFT Proto พร้อมข้อความ Proto Buff ใหม่
ควรใช้ข้อความดังกล่าวโดยตัวตรวจสอบความถูกต้องจากนั้น Polygon Edge จะสมัครติดตามหัวข้อและจัดการข้อความตามนั้น + +#### MessageReq {#messagereq} + +ข้อความที่แลกเปลี่ยนโดยตัวตรวจสอบความถูกต้อง: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +ฟิลด์ **View** ใน **MessageReq** จะแสดงตำแหน่งโหนดปัจจุบันภายในเชนซึ่งมีแอตทริบิวต์ *round* และ *sequence* +* **round** แสดงถึงรอบของผู้เสนอสำหรับความสูงดังกล่าว +* **sequence** แสดงถึงความสูงของบล็อกเชน + +*msgQueue* ที่ยื่นในการนำ IBFT ไปใช้มีวัตถุประสงค์เพื่อจัดเก็บคำขอข้อความโดยออกคำสั่งข้อความตาม*View* (เริ่มจากตามลำดับ จากนั้นก็ตามรอบ)การนำ IBFT ไปใช้ยังมีคิวที่แตกต่างกันสำหรับสถานะที่แตกต่างกันในระบบ + +### สถานะ IBFT {#ibft-states} + +หลังจากเริ่มกลไกฉันทามติโดยใช้เมธอด **Start** กลไกจะเรียกใช้ลูปไม่จำกัด ซึ่งจำลอง State Machine: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### SyncState {#syncstate} + +เบื้องต้นโหนดทั้งหมดจะเริ่มต้นในสถานะ **Sync** + +เนื่องจากจำเป็นต้องดึงข้อมูลใหม่จากบล็อกเชนไคลเอ็นต์ต้องค้นหาว่าเป็นตัวตรวจสอบความถูกต้องหรือไม่ค้นหาสแนปชอตปัจจุบันสถานะนี้จะแก้ไขบล็อกที่รอดำเนินการ + +หลังการซิงค์เสร็จสิ้น และไคลเอ็นต์พิจารณาแล้วว่าเป็นตัวตรวจสอบความถูกต้อง ก็จำเป็นต้องถ่ายโอนไปยัง **AcceptState**แต่ถ้าไคลเอ็นต์ **ไม่ใช่** ตัวตรวจสอบความถูกต้อง ไคลเอ็นต์จะทำการซิงค์ต่อไป และอยู่ใน **SyncState** + +#### AcceptState {#acceptstate} + +สถานะ **Accept** จะตรวจสอบสแนปชอตและชุดตัวตรวจสอบความถูกต้องเสมอ หากโหนดปัจจุบันไม่อยู่ในชุดตัวตรวจสอบความถูกต้องก็จะย้ายกลับไปที่สถานะ **Sync** + +ในทางกลับกัน ถ้าโหนด **เป็น** ตัวตรวจสอบความถูกต้อง โหนดก็จะคำนวณผู้เสนอหากปรากฎว่าโหนดปัจจุบันคือผู้เสนอสร้าง โหนดจะสร้างบล็อกและส่งข้อความ preprepare จากนั้นก็เป็นข้อความ prepare + +* ข้อความ Preprepare - ข้อความที่ผู้เสนอส่งถึงตัวตรวจสอบความถูกต้องเพื่อแจ้งให้ทราบเกี่ยวกับข้อเสนอ +* ข้อความ Prepare - ข้อความที่ตัวตรวจสอบความถูกต้องเห็นด้วยกับข้อเสนอโหนดทั้งหมดได้รับข้อความ prepare ทั้งหมด +* ข้อความ Commit - ข้อความที่มีข้อมูล Commit สำหรับข้อเสนอ + +ถ้าโหนดปัจจุบัน **ไม่ใช่** ตัวตรวจสอบความถูกต้อง โหนดดังกล่าวจะใช้เมธอด *getNextMessage* เพื่ออ่านข้อความจากคิวที่แสดงไว้ก่อนหน้านี้
โหนดจะรอข้อความ preprepareเมื่อยืนยันแล้วว่าทุกอย่างถูกต้อง โหนดจะย้ายไปยังสถานะ **Validate** + +#### ValidateState {#validatestate} + +สถานะ **Validate** ค่อนข้างเรียบง่าย - สิ่งที่โหนดทั้งหมดทำในสถานะนี้คือการอ่านข้อความและเพิ่มลงในสถานะสแนปชอตภายในของตน diff --git a/archive/edge/th-edge/architecture/modules/json-rpc.md b/archive/edge/th-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..e36fbf98cf --- /dev/null +++ b/archive/edge/th-edge/architecture/modules/json-rpc.md @@ -0,0 +1,175 @@ +--- +id: json-rpc +title: JSON RPC +description: คำอธิบายเกี่ยวกับโมดูล JSON RPC ของ Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## ภาพรวม {#overview} + +โมดูล **JSON RPC** ใช้ **เลเยอร์ JSON RPC API** ซึ่งเป็นสิ่งที่นักพัฒนา dApp ใช้ในการโต้ตอบกับบล็อกเชน + +โมดูลดังกล่าวรองรับ **[json-rpc Endpoint](https://eth.wiki/json-rpc/API)** มาตรฐานและ websocketEndpoint + +## อินเทอร์เฟซของบล็อกเชน {#blockchain-interface} + +Polygon Edge ใช้***อินเทอร์เฟซของบล็อกเชน*** เพื่อกำหนดเมธอดทั้งหมดที่โมดูล JSON RPC จำเป็นต้องใช้เพื่อส่งมอบ Endpoint + +เซิร์ฟเวอร์ **[Minimal](/docs/edge/architecture/modules/minimal)** จะนำอินเทอร์เฟซของบล็อกเชนมาใช้ซึ่งเป็นการนำไปใช้พื้นฐานที่ผ่านเข้าสู่เลเยอร์ JSON RPC + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## ETH Endpoint {#eth-endpoints} + +JSON RPC Endpoint มาตรฐานทั้งหมดจะได้รับการนำไปใช้ใน: + +````bash +jsonrpc/eth_endpoint.go +```` + +## ตัวจัดการตัวกรอง {#filter-manager} + +**ตัวจัดการตัวกรอง**เป็นบริการที่ทำงานควบคู่ไปกับเซิร์ฟเวอร์ JSON RPC + +ซึ่งจะให้การรองรับการกรองบล็อกบนบล็อกเชน
ยิ่งไปกว่านั้น ยังรวมถึงตัวกรองมีทั้งตัวกรองระดับ **log** และ **block** + +ตัวจัดการตัวกรองอาศัยอีเวนต์การสมัครติดตามที่กล่าวถึงในส่วน[บล็อกเชน](blockchain#blockchain-subscriptions)อย่างมาก + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +อีเวนต์ตัวจัดการตัวกรองจะได้รับการส่งในเมธอด *Run*: + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## ทรัพยากร 📜 {#resources} +* **[Ethereum JSON-RPC](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/th-edge/architecture/modules/minimal.md b/archive/edge/th-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..b198e4068d --- /dev/null +++ b/archive/edge/th-edge/architecture/modules/minimal.md @@ -0,0 +1,117 @@ +--- +id: minimal +title: Minimal +description: คำอธิบายเกี่ยวกับโมดูล Minimal ของ Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## ภาพรวม {#overview} + +ตามที่ได้ระบุไว้ด้านบน Polygon Edge เป็นชุดของโมดูลต่างๆ ที่เชื่อมต่อซึ่งกันและกัน
**บล็อกเชน**ได้รับการเชื่อมโยงกับ **State** ตัวอย่างเช่น **Synchronization** ที่ลำเลียงบล็อกใหม่ไปยัง**บล็อกเชน** + +**Minimal** เป็นรากฐานสำหรับบรรดาโมดูลซึ่งเชื่อมต่อกัน
ซึ่งทำหน้าที่เป็นฮับศูนย์กลางสำหรับบริการทั้งหมดซึ่งเรียกใช้ใน Polygon Edge + +## สุดยอดตัวช่วยในการเริ่มต้นระบบ {#startup-magic} + +นอกจากเรื่องอื่นๆ แล้ว Minimal รับผิดชอบในส่วน: +* การกำหนดค่าไดเรคทอรีเกี่ยวกับข้อมูล +* การสร้าง KeyStore สำหรับการสื่อสารแบบ libp2p +* การสร้างที่เก็บข้อมูล +* การกำหนดค่าฉันทามติ +* การกำหนดค่าอ็อบเจ็กต์ของบล็อกเชนผ่านการใช้ GRPC, JSON RPC และการซิงค์ + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/th-edge/architecture/modules/networking.md b/archive/edge/th-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..62363c4374 --- /dev/null +++ b/archive/edge/th-edge/architecture/modules/networking.md @@ -0,0 +1,74 @@ +--- +id: networking +title: ระบบเครือข่าย +description: คำอธิบายเกี่ยวกับโมดูลระบบเครือข่ายของ Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## ภาพรวม {#overview} + +โหนดต้องสื่อสารกับโหนดอื่นๆ ในเครือข่ายเพื่อให้สามารถแลกเปลี่ยนข้อมูลที่มีประโยชน์
เพื่อให้งานนี้สำเร็จ Polygon Edge ใช้เฟรมเวิร์ก **libp2p** ซึ่งได้ทดสอบแล้วในการใช้งานจริง + +การตัดสินใจในการใช้ **libp2** เน้นประเด็นหลักดังต่อไปนี้: +* **ความเร็ว** - libp2p ได้รับการปรับปรุงเป็นอย่างมากในส่วนการใช้งาน เมื่อเปรียบเทียบกับ devp2p (ซึ่งใช้ใน GETH และไคลเอ็นต์อื่นๆ) +* **ความสามารถในการขยาย** - มีบทบาทในการเป็นพื้นฐานที่ดีสำหรับคุณสมบัติอื่นๆ ของระบบ +* **Modularity** - libp2p มีลักษณะเป็นโมดูลาร์ในตนเองแล้ว เหมือนกับ Polygon Edgeซึ่งจะให้ความยืดหยุ่นมากขึ้น โดยเฉพาะเมื่อส่วนใดส่วนหนึ่งของ Polygon Edge ต้องมีสามารถแลกเปลี่ยนได้ + +## GRPC {#grpc} + +นอกจาก **libp2p** แล้ว Polygon Edge ต้องใช้โปรโตคอล **GRPC**
ในมุมมองด้านเทคนิค Polygon Edge ใช้โปรโตคอล GRPC หลายอย่าง โดยเราจะกล่าวถึงในภายหลัง + +เลเยอร์ GRPC ช่วยสรุปโปรโตคอลคำขอ/การตอบกลับทั้งหมด และยังช่วยทำให้โปรโตคอลสตรีมมิ่งง่ายขึ้น ซึ่งต้องใช้สำหรับการดำเนินงานของ Polygon Edge + +GRPC ใช้ **Protocol Buffers** ในการนิยาม *services* และ *message structures*
โดยมีการนิยาม services และ structures ไว้ในไฟล์ *.proto* ซึ่งเป็นไฟล์คอมไพล์และใช้หลัก Language-Agnostic + +ก่อนหน้านี้ เราได้กล่าวว่า Polygon Edge ใช้โปรโตคอล GRPC หลายอย่าง
ซึ่งมีวัตถุประสงค์เพื่อการยกระดับ UX โดยรวมสำหรับตัวดำเนินการโหนด ซึ่งมักจะช้ากว่าไคลเอ็นต์ต่างๆ เช่น GETH และ Parity + +ตัวดำเนินการโหนดมีข้อมูลภาพรวมของสิ่งที่เกิดขึ้นกับระบบที่ดียิ่งกว่า ด้วยการเรียกใช้บริการ GRPC แทนการค้นหาข้อมูลที่ต้องการผ่านการตรวจสอบบันทึก + +### GRPC สำหรับตัวดำเนินการโหนด {#grpc-for-node-operators} + +ส่วนดังต่อไปนี้อาจประกอบด้วยข้อมูลที่คุณทราบแล้ว เนื่องจากเราได้กล่าวถึงข้อมูลนั้นแล้วในส่วน[คำสั่ง CLI](/docs/edge/get-started/cli-commands) + +มีการนิยามบริการ GRPC ที่มีวัตถุประสงค์ให้**ตัวดำเนินการโหนด**ใช้งานไว้ดังนี้ +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip + +คำสั่ง CLI สามารถเรียกการนำเมธอด service เหล่านี้ไปใช้งานได้จริง + +เมธอดเหล่านี้ได้รับการนำไปใช้ใน ***minimal/system_service.go*** +::: + +### GRPC สำหรับโหนดอื่นๆ {#grpc-for-other-nodes} + +Polygon Edge ยังนำเมธอด service บางรายการไปใช้กับโหนดอื่นๆ ในเครือข่าย
เกี่ยวกับบริการที่เราได้กล่าวถึง มีการอธิบายในส่วน**[โปรโตคอล](docs/edge/architecture/modules/consensus)** + +## 📜 ทรัพยากร {#resources} +* **[Protocol Buffers](https://developers.google.com/protocol-buffers)** +* **[libp2p](https://libp2p.io/)** +* **[gRPC](https://grpc.io/)** diff --git a/archive/edge/th-edge/architecture/modules/other-modules.md b/archive/edge/th-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..565b82a385 --- /dev/null +++ b/archive/edge/th-edge/architecture/modules/other-modules.md @@ -0,0 +1,36 @@ +--- +id: other-modules +title: โมดูลอื่นๆ +description: คำอธิบายเกี่ยวกับโมดูลบางอย่างของ Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## Crypto {#crypto} + +โมดูล **Crypto** ประกอบด้วยฟังก์ชันซึ่งใช้เพื่อประโยชน์ของคริปโต + +## Chain {#chain} + +โมดูล **Chain** ประกอบด้วยพารามิเตอร์ chain (Fork ต่างๆ ที่ใช้งานอยู่ กลไกฉันทามติ ฯลฯ) + +* **chains** - ค่ากำหนดเกี่ยวกับเชนที่กำหนดไว้ล่วงหน้า (mainnet, goerli, ibft) + +## Helper {#helper} + +โมดูล **Helper** ประกอบด้วยแพ็กเกจ helper + +* **dao** - โปรแกรมอรรถประโยชน์ Dao +* **enode** - ฟังก์ชันเข้ารหัส/ถอดรหัสของ Enode +* **hex** - ฟังก์ชันเข้ารหัส/ถอดรหัสของ Hex +* **ipc** - ฟังก์ชันการเชื่อมต่อของ IPC +* **keccak** - ฟังก์ชันของ Keccak +* **rlputil** - ฟังก์ชัน helper เกี่ยวกับการเข้ารหัส/ถอดรหัสของ Rlp + +## Command {#command} + +โมดูล **Command** ประกอบด้วยอินเทอร์เฟซต่างๆ สำหรับคำสั่ง CLI \ No newline at end of file diff --git a/archive/edge/th-edge/architecture/modules/sealer.md b/archive/edge/th-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..89db2cbefb --- /dev/null +++ b/archive/edge/th-edge/architecture/modules/sealer.md @@ -0,0 +1,70 @@ +--- +id: sealer +title: Sealer +description: คำอธิบายเกี่ยวกับโมดูล sealer ของ Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## ภาพรวม {#overview} + +**Sealer** เป็นเอนทิตีที่รวบรวมธุรกรรม และสร้างบล็อกใหม่
จากนั้น จะส่งบล็อกดังกล่าวไปยังโมดูล **Consensus** เพื่อทำการซีล + +ลอจิกการซีลขั้นสุดท้ายอยู่ในโมดูล **Consensus** + +## เรียกใช้งานเมธอด {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution งานที่ดำเนินการอยู่ +โมดูล **Sealer** และ **Consensus** จะได้รับการรวมเข้าเป็นเอนทิตีเดียวในอนาคตอันใกล้นี้ + +โมดูลใหม่จะรวมลอจิกแบบโมดูลาร์ไว้สำหรับกลไกฉันทามติประเภทต่างๆ ซึ่งต้องมีการนำการซีลต่างๆ ไปใช้: +* **PoS** (Proof of Stake) +* **PoA** (Proof of Authority) + +ปัจจุบัน โมดูล **Sealer** และ **Consensus** ใช้งานได้กับ PoW (Proof of Work) +::: \ No newline at end of file diff --git a/archive/edge/th-edge/architecture/modules/state.md b/archive/edge/th-edge/architecture/modules/state.md new file mode 100644 index 0000000000..41b76a46a1 --- /dev/null +++ b/archive/edge/th-edge/architecture/modules/state.md @@ -0,0 +1,242 @@ +--- +id: state +title: State +description: คำอธิบายเกี่ยวกับโมดูล state ของ Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +เพื่อทำความเข้าใจอย่างถ่องแท้เกี่ยวกับการทำงานของ **State** คุณต้องเข้าใจแนวคิดหลักบางประการของ Ethereum
+ +เราขอแนะนำให้คุณอ่านบทความ **[State ในคู่มือของ Ethereum](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)** + +## ภาพรวม {#overview} + +ตอนนี้ เมื่อเรามีความเข้าใจเกี่ยวกับแนวคิดหลักของ Ethereum แล้ว คุณก็จะเข้าใจภาพรวมต่อไปได้ง่ายกว่า + +เราได้กล่าวว่า **World State Trie** มีบัญชี Ethereum ทั้งหมดที่มีอยู่
บัญชีเหล่านี้เป็นโหนดของ Merkle trieโดยแต่ละโหนดนั้นประกอบด้วยข้อมูล**สถานะบัญชี**ที่มีการเข้ารหัส + +ซึ่งทำให้ Polygon Edge สามารถรับ Merkle trie เฉพาะสำหรับช่วงเวลาใดเวลาหนึ่งโดยเฉพาะได้
ตัวอย่างเช่น เราสามารถรับแฮชของสถานะที่บล็อก 10 + +ในทุกช่วงเวลา เราเรียก Merkle trie ว่า ***Snapshot*** + +เราสามารถใช้ ***Snapshot*** กับ **state trie** หรือกับ **storage trie** ก็ได้ ซึ่งโดยทั่วไปแล้ว ถือว่าเหมือนกัน
ความแตกต่างเพียงอย่างเดียวคือสิ่งที่โหนดต่างๆ แสดงถึง : + +* ในกรณีของ storage trie โหนดต่างๆ จะประกอบด้วยสถานะแบบกำหนดเอง โดยเราไม่สามารถประมวลผลหรือรู้ว่ามีข้อมูลใดอยู่ +* ในกรณีของ state trie โหนดต่างๆ แสดงถึงบัญชี + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + +อินเทอร์เฟซ **Snapshot** ได้รับการนิยามไว้ดังต่อไปนี้: + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +*Object struct* เป็นตัวนิยามข้อมูลซึ่งสามารถกำหนดไว้ได้: + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +การนำ Merkle trie ไปใช้อยู่ในโฟลเดอร์ *state/immutable-trie*
*state/immutable-trie/state.go* จะนำอินเทอร์เฟซ **State** ไปใช้ + +*state/immutable-trie/trie.go* เป็นอ็อบเจ็กต์หลักของ Merkle trieซึ่งเป็นเวอร์ชันฉบับแก้ไขของ Merkle trieซึ่งใช้หน่วยความจำซ้ำมากที่สุดเท่าที่เป็นไปได้ + +## Executor {#executor} + +*state/executor.go* จะรวมข้อมูลทั้งหมดซึ่ง Polygon Edge ต้องใช้เพื่อตัดสินวิธีการซึ่งบล็อกใช้ในการเปลี่ยน +สถานะปัจจุบันการนำไปใช้ของ *ProcessBlock* อยู่ที่นี่ + +เมธอด *apply* จะทำการเปลี่ยนสถานะจริงexecutor จะเรียก EVM + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## Runtime {#runtime} + +เมื่อมีการดำเนินการเปลี่ยนสถานะ โมดูลหลักซึ่งดำเนินการเปลี่ยนสถานะ คือ EVM (อยู่ใน +state/runtime/evm) + + **dispatch table** ดำเนินการจับคู่ระหว่าง **opcode** กับคำสั่ง + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +ลอจิกหลักที่ EVM ใช้ คือลูป *Run*
+ +นี่คือจุดเริ่มต้นหลักสำหรับ EVMซึ่งสร้างลูปและตรวจสอบ opcode ปัจจุบัน นำคำสั่งมาใช้ ตรวจสอบว่าสามารถดำเนินการได้หรือไม่ ใช้แก๊ส และดำเนินการตามคำสั่งจนกว่าจะล้มเหลวหรือสิ้นสุด + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/th-edge/architecture/modules/storage.md b/archive/edge/th-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..a97256dad7 --- /dev/null +++ b/archive/edge/th-edge/architecture/modules/storage.md @@ -0,0 +1,116 @@ +--- +id: storage +title: Storage +description: คำอธิบายเกี่ยวกับโมดูล storage ของ Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## ภาพรวม {#overview} + +ปัจจุบัน Polygon Edge ใช้ **LevelDB** สำหรับการจัดเก็บข้อมูล และพื้นที่จัดเก็บข้อมูล**ในหน่วยความจำ** + +ทั่วทั้ง Polygon Edge เมื่อโมดูลจำเป็นต้องโต้ตอบกับที่เก็บข้อมูลที่รองรับโมดูลไม่จำเป็นต้องรู้ว่ากำลังสื่อสารกับเอนจิ้นหรือบริการ DB ใดอยู่ + +เลเยอร์ DB ได้รับการแยกออกมาระหว่างโมดูลที่ชื่อ **Storage** ซึ่งส่งออกอินเทอร์เฟซต่างๆ ที่โมดูลสืบค้น + +เฉพาะในตอนนี้ แต่ละเลเยอร์ DB **LevelDB** จะนำเมธอดเหล่านี้ไปใช้แยกกัน เพื่อให้แน่ใจว่าเหมาะกับการนำไปใช้ของตัวเอง + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### ส่วนนำหน้า {#prefixes} + +ในการทำให้การสืบค้นการจัดเก็บ LevelDB เป็นแบบ Deterministic และเพื่อหลีกเลี่ยงการขัดแย้งกันของการจัดเก็บคีย์ Polygon Edge ใช้ประโยชน์จากส่วนนำหน้าและส่วนนำหน้าย่อยเมื่อจัดเก็บข้อมูล + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## แผนสำหรับอนาคต {#future-plans} + +แผนสำหรับอนาคตอันใกล้นี้ประกอบด้วย การเพิ่มโซลูชัน DB ที่ได้รับความนิยมมากที่สุด เช่น: +* PostgreSQL +* MySQL + + +## 📜 ทรัพยากร {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/th-edge/architecture/modules/syncer.md b/archive/edge/th-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..691b36564e --- /dev/null +++ b/archive/edge/th-edge/architecture/modules/syncer.md @@ -0,0 +1,64 @@ +--- +id: syncer +title: Syncer +description: คำอธิบายเกี่ยวกับโมดูล Syncer ของ Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## ภาพรวม {#overview} + +โมดูลนี้มีลอจิกสำหรับโปรโตคอลการซิงค์ใช้สำหรับซิงค์โหนดใหม่กับเครือข่ายที่ทำงานอยู่ หรือตรวจสอบความถูกต้อง/แทรกบล็อกใหม่สำหรับโหนดที่ไม่เข้าร่วมในฉันทามติ (ไม่ใช่ตัวตรวจสอบความถูกต้อง) + +Polygon Edge ใช้ **libp2p** เป็นเลเยอร์เครือข่าย และเรียกใช้ **gRPC** + +โดยหลักแล้ว Polygon Edge มีการซิงค์ 2 ประเภท: +* ซิงค์เป็นกลุ่ม - ซิงค์บล็อกจำนวนมากพร้อมกัน +* ซิงค์แบบเฝ้าดู - ซิงค์แบบบล็อกต่อบล็อก + +### ซิงค์เป็นกลุ่ม {#bulk-sync} + +ขั้นตอนสำหรับการซิงค์เป็นกลุ่มค่อนข้างตรงไปตรงมาในด้านการรองรับเป้าหมายของการซิงค์เป็นกลุ่ม นั่นคือการซิงค์บล็อกให้มากที่สุด (เท่าที่มี) จากเพียร์อื่นเพื่อให้ตามทันโดยเร็วที่สุด + +นี่คือขั้นตอนการประมวลผลของการซิงค์เป็นกลุ่ม: + +1. ** กำหนดว่าโหนดต้องซิงค์เป็นกลุ่มหรือไม่ ** - ในขั้นตอนนี้ โหนดจะตรวจสอบเพียร์แมปเพื่อดูว่า มีใครที่มีจำนวนบล็อกมากกว่าที่โหนดมีอยู่ภายในหรือไม่ +2. ** หาเพียร์ที่ดีที่สุด (โดยใช้เพียร์แมปสำหรับการซิงค์) ** - ในขั้นตอนนี้ โหนดจะค้นหาเพียร์ที่ดีที่สุดที่จะซิงค์ด้วยตามเกณฑ์ที่กล่าวถึงในตัวอย่างข้างต้น +3. ** เปิดสตรีมการซิงค์เป็นกลุ่ม ** - ในขั้นตอนนี้ โหนดจะเปิดสตรีม gRPC ไปยังเพียร์ที่ดีที่สุดเพื่อทำการซิงค์บล็อกจำนวนมากจากหมายเลขบล็อกทั่วไป +4. ** เพียร์ที่ดีที่สุดปิดสตรีมเมื่อทำการส่งจำนวนมากเสร็จแล้ว ** - ในขั้นตอนนี้ เพียร์ที่ดีที่สุดที่โหนดกำลังซิงค์ด้วยจะปิดสตรีมทันทีที่ส่งบล็อกที่มีอยู่ทั้งหมดที่มี +5. ** เมื่อทำการซิงค์เป็นกลุ่มเสร็จแล้ว จะตรวจสอบว่าโหนดเป็นตัวตรวจสอบความถูกต้องหรือไม่ ** - ในขั้นตอนนี้ เพียร์ที่ดีที่สุดจะทำการปิดสตรีม และโหนดต้องตรวจสอบว่าโหนดเป็นตัวตรวจสอบความถูกต้องหรือไม่หลังจากการซิงค์เป็นกลุ่ม + * หากเป็นเช่นนั้น โหนดจะโดดออกจากสถานะซิงค์ และเริ่มเข้าร่วมในฉันทามติ + * หากไม่เป็นเช่นนั้น โหนดจะไปต่อที่ ** ซิงค์แบบเฝ้าดู ** + +### ซิงค์แบบเฝ้าดู {#watch-sync} + +:::info +ขั้นตอนสำหรับการซิงค์แบบเฝ้าดูจะได้รับการดำเนินการก็ต่อเมื่อโหนดไม่ใช่ตัวตรวจสอบความถูกต้อง แต่เป็นโหนดที่ไม่ใช่ตัวตรวจสอบปกติในเครือข่ายที่รอรับบล็อกขาเข้า +::: + +ลักษณะการทำงานของการซิงค์แบบเฝ้าดูค่อนข้างตรงไปตรงมา โหนดได้รับการซิงค์กับส่วนที่เหลือของเครือข่ายแล้ว และจำเป็นต้องแยกวิเคราะห์เฉพาะบล็อกใหม่ที่กำลังจะเข้ามา + +นี่คือขั้นตอนการประมวลผลของการซิงค์แบบเฝ้าดู: + +1. ** เพิ่มบล็อกใหม่เมื่อมีการอัปเดตสถานะของเพียร์ ** - ในขั้นตอนนี้ โหนดจะรอรับอีเวนต์บล็อกใหม่ และเมื่อมีบล็อกใหม่ จะมีการเรียกใช้ฟังก์ชัน gRPC รับบล็อก และอัปเดตสถานะภายใน +2. ** ตรวจสอบว่าโหนดเป็นตัวตรวจสอบความถูกต้องหรือไม่หลังจากซิงค์บล็อกล่าสุด ** + * ถ้าเป็น จะออกจากสถานะซิงค์ + * ถ้าไม่เป็น จะรอรับอีเวนต์บล็อกใหม่ๆ ต่อไป + +## รายงานประสิทธิภาพ {#perfomance-report} + +:::info +วัดประสิทธิภาพในเครื่องภายในโดยการซิงค์บล็อก ** 1 ล้านบล็อก ** +::: + +| ชื่อ | ผล | +|----------------------|----------------| +| การซิงค์ 1 ล้านบล็อก | ประมาณ 25 นาที | +| การโอน 1 ล้านบล็อก | ประมาณ 1 นาที | +| จำนวนการเรียก GRPC | 2 | +| การครอบคลุมของการทดสอบ | ประมาณ 93% | \ No newline at end of file diff --git a/archive/edge/th-edge/architecture/modules/txpool.md b/archive/edge/th-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..5dfa4129dd --- /dev/null +++ b/archive/edge/th-edge/architecture/modules/txpool.md @@ -0,0 +1,224 @@ +--- +id: txpool +title: TxPool +description: คำอธิบายเกี่ยวกับโมดูล TxPool ของ Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## ภาพรวม {#overview} + +โมดูล TxPool แสดงให้เห็นถึงการนำพูลธุรกรรมไปใช้ โดยมีการเพิ่มธุรกรรมจากส่วนต่างๆ ของระบบโมดูลนี้ยังประกอบด้วยคุณสมบัติบางอย่างที่มีประโยชน์ต่อตัวดำเนินการโหนด ซึ่งระบุไว้ด้านล่าง + +## คำสั่งสำหรับตัวดำเนินการ {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +ตัวดำเนินการโหนดสามารถค้นหา GRPC Endpoint เหล่านี้ได้ ตามรายละเอียดที่ปรากฏตามส่วน**[คำสั่ง CLI](/docs/edge/get-started/cli-commands#transaction-pool-commands)** + +## การประมวลผลธุรกรรม {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +***addImpl*** เป็นเมธอดที่ใช้กับโมดูล **TxPool** เป็นหลักโดยถือเป็นศูนย์กลางที่มีการเพิ่มธุรกรรมลงในระบบ โดยมีการเรียกใช้จากบริการ GRPC, JSON RPC Endpointและเมื่อไคลเอ็นต์ได้รับธุรกรรมผ่านโปรโตคอล **Gossip** + +ธุรกรรมนั้นกลายเป็นอาร์กิวเมนต์ **ctx** ซึ่งกำหนดบริบทที่เป็นแหล่งที่มาของธุรกรรม (เช่น GRPC, JSON RPC เป็นต้น)
พารามิเตอร์อื่นคือรายการธุรกรรมซึ่งได้รับการเพิ่มลงในพูล + +ประเด็นหลักที่ต้องจำไว้ในส่วนนี้ คือการตรวจสอบฟิลด์ **From** ในธุรกรรม: +* หากฟิลด์ **From** **ไม่ปรากฏข้อมูล** จะถือว่าเป็นธุรกรรมที่ยังไม่เข้ารหัส/ลงนามธุรกรรมประเภทเหล่านี้รับได้เฉพาะในโหมดการพัฒนา +* หากฟิลด์ **From** ** ปรากฏข้อมูล ** จะถือว่าเป็นธุรกรรมที่ลงนามแล้ว จึงมีการดำเนินการตรวจสอบความถูกต้องของลายเซ็นนั้น + +หลังจากมีการดำเนินการตรวจสอบความถูกต้องนั้นแล้ว ถือว่าธุรกรรมมีผลสมบูรณ์ + +## โครงสร้างข้อมูล {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +ฟิลด์ต่างๆ ในอ็อบเจ็กต์ TxPool ซึ่งอาจทำให้เกิดความสับสนได้ คือ รายการ **queue** และ **sorted** +* **queue** - การนำรายการธุรกรรมบัญชีแบบเรียงลำดับไปใช้เป็นจำนวนมาก (โดยใช้ nonce) +* **sorted** - รายการธุรกรรมที่ปรับให้เผยแพร่ได้ในปัจจุบันทั้งหมดแบบเรียงลำดับ (ธุรกรรมทั้งหมดที่สามารถดำเนินการได้)โดยเรียงลำดับตามราคาแก๊ส + +## การจัดการข้อผิดพลาดเกี่ยวกับขีดจำกัดค่าแก๊ส {#gas-limit-error-management} + +เมื่อคุณส่งธุรกรรม TxPool จะสามารถประมวลผลธุรกรรมนั้นได้ 3 รูปแบบ + +1. ธุรกรรมที่ค้างอยู่ทั้งหมดสามารถใส่ลงในบล็อกได้ +2. ธุรกรรมที่ค้างอยู่อย่างน้อยหนึ่งรายการไม่สามารถใส่ลงในบล็อกได้ +3. ธุรกรรมที่ค้างอยู่อย่างน้อยหนึ่งรายการจะไม่สามารถใส่ลงในบล็อกได้เลย + +ในที่นี้ คำว่า **_ใส่ได้_** หมายถึง ธุรกรรมมีขีดจำกัดค่าแก๊ส (Gas Limit) ที่ต่ำกว่าค่าแก๊ส (Gas) ที่เหลืออยู่ใน TxPool + +สถานการณ์แรกไม่ได้สร้างข้อผิดพลาดใด + +### สถานการณ์ที่สอง {#second-scenario} + +- กำหนดค่าแก๊สที่เหลืออยู่ใน TxPool เป็นขีดจำกัดค่าแก๊สของบล็อกล่าสุด เช่น **5000** หน่วย +- ประมวลผลธุรกรรมแรก และใช้ค่าแก๊สของ TxPool **3000** หน่วย + - ตอนนี้ TxPool มีค่าแก๊สคงเหลือ **2000** หน่วย +- ส่งธุรกรรมที่สอง ซึ่งมีค่าเท่ากันกับธุรกรรมแรก กล่าวคือ ธุรกรรมทั้งสองต่างใช้ค่าแก๊ส 3000 หน่วย +- เนื่องจากค่าแก๊สที่เหลืออยู่ใน TxPool **ต่ำกว่า**ค่าแก๊สสำหรับธุรกรรม จึงไม่สามารถประมวลผลได้ในบล็อกปัจจุบัน + - จึงมีการนำกลับไปไว้ในคิวธุรกรรมที่ค้างอยู่ เพื่อสามารถประมวลผลได้ในบล็อกถัดไป +- เขียนบล็อกแรก และเรียกบล็อกนั้นว่า **block #1** +- กำหนดค่าแก๊สที่เหลืออยู่ใน TxPool ให้กับบล็อกหลัก ซึ่งเป็นขีดจำกัดค่าแก๊สของ **block #1** +- คราวนี้ก็จะมาประมวลผลธุรกรรมซึ่งได้รับการนำกลับไปไว้ในคิวธุรกรรมที่ค้างอยู่ของ TxPool และเขียนลงในบล็อก + - ขณะนี้ ค่าแก๊สที่เหลืออยู่ใน TxPool คือ **2000** หน่วย +- เขียนบล็อกที่สอง +- ... + +![สถานการณ์ที่เกิดข้อผิดพลาดของ TxPool แบบที่ 1](/img/edge/txpool-error-1.png) + +### สถานการณ์ที่สาม {#third-scenario} +- กำหนดค่าแก๊สที่เหลืออยู่ใน TxPool เป็นขีดจำกัดค่าแก๊สของบล็อกล่าสุด เช่น **5000** หน่วย +- ประมวลผลธุรกรรมแรก และใช้ค่าแก๊สของ TxPool **3000** หน่วย + - ตอนนี้ TxPool มีค่าแก๊สคงเหลือ **2000** หน่วย +- ส่งธุรกรรมที่สอง ซึ่งมีการกำหนดค่าแก๊สไว้ที่ **6000** หน่วย +- เนื่องจากขีดจำกัดค่าแก๊สต่อบล็อก**ต่ำกว่า**ค่าแก๊สสำหรับธุรกรรม จึงมีการปฏิเสธธุรกรรมนั้น + - ซึ่งไม่สามารถใส่ลงในบล็อกได้เลย +- เขียนบล็อกแรก +- ... + + +![สถานการณ์ที่เกิดข้อผิดพลาดของ TxPool แบบที่ 2](/img/edge/txpool-error-2.png) + +> สถานการณ์นี้เกิดขึ้นเมื่อคุณได้รับข้อความแสดงข้อผิดพลาดต่อไปนี้: +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## เป้าหมายค่าแก๊สต่อบล็อก {#block-gas-target} + +อาจมีสถานการณ์ต่างๆ ที่โหนดต้องการคงขีดจำกัดค่าแก๊สต่อบล็อกให้ต่ำกว่าหรืออยู่ที่ค่าเป้าหมายที่เจาะจงในเชนที่ใช้งานอยู่ + +ตัวดำเนินการโหนดสามารถกำหนดขีดจำกัดค่าแก๊สเป้าหมายได้ในโหนดใดโหนดหนึ่ง ซึ่งจะพยายามนำขีดจำกัดนี้มาใช้กับบล็อกที่สร้างขึ้นมาใหม่ +หากโหนดอื่นๆ ส่วนใหญ่ก็มีการกำหนดขีดจำกัดค่าแก๊สเป้าหมายที่คล้ายกัน (หรือเท่ากัน) ไว้แล้ว ขีดจำกัดค่าแก๊สต่อบล็อกจะอยู่ใกล้เคียงกับ +เป้าหมายค่าแก๊สต่อบล็อกเสมอ ซึ่งจะค่อยๆ เข้าใกล้ค่าดังกล่าว (สูงสุดที่ `1/1024 * parent block gas limit`) เมื่อมีการสร้างบล็อกใหม่ๆ + +### สถานการณ์ตัวอย่าง {#example-scenario} + +* ตัวดำเนินการโหนดจะกำหนดขีดจำกัดค่าแก๊สต่อบล็อกสำหรับโหนดหนึ่งเป็น `5000` +* ส่วนโหนดอื่นๆ มีการกำหนดค่า `5000` เช่นเดียวกัน นอกเหนือจากโหนดเดี่ยว ซึ่งกำหนดค่าเป็น `7000` +* เมื่อบรรดาโหนดซึ่งกำหนดเป้าหมายค่าแก๊สเป็น `5000` กลายเป็นผู้เสนอ พวกเขาจะตรวจสอบว่าขีดจำกัดค่าแก๊สถึงค่าเป้าหมายหรือยัง +* หากขีดจำกัดค่าแก๊สยังไม่ได้เท่ากับเป้าหมาย (สูงกว่า / ต่ำกว่าเป้าหมาย) โหนดผู้เสนอจะกำหนดเป้าหมายค่าแก๊สต่อบล็อกเป็นค่าสูงที่สุด (1/1024 * ขีดจำกัดค่าแก๊สหลัก) ในคำสั่งของเป้าหมาย + 1. ตัวอย่าง `parentGasLimit = 4500` และ `blockGasTarget = 5000`ผู้เสนอจะคำนวณขีดจำกัดค่าแก๊สสำหรับบล็อกใหม่เป็น `4504.39453125` (`4500/1024 + 4500`) + 2. ตัวอย่าง `parentGasLimit = 5500` และ `blockGasTarget = 5000`ผู้เสนอจะคำนวณขีดจำกัดค่าแก๊สสำหรับบล็อกใหม่เป็น `5494.62890625` (`5500 - 5500/1024`) +* ซึ่งจะทำให้มั่นใจว่าขีดจำกัดค่าแก๊สต่อบล็อกของเชนจะคงอยู่ที่ค่าเป้าหมาย เนื่องจากผู้เสนอรายเดี่ยวซึ่งได้กำหนดค่าเป้าหมายเป็น `7000` ไม่สามารถเพิ่มขีดจำกัดได้มากนัก และส่วนใหญ่ของโหนดซึ่งกำหนดค่าไว้เป็น `5000` จะพยายามคงค่าไว้ที่เท่านั้นเสมอ \ No newline at end of file diff --git a/archive/edge/th-edge/architecture/modules/types.md b/archive/edge/th-edge/architecture/modules/types.md new file mode 100644 index 0000000000..a65c2d4937 --- /dev/null +++ b/archive/edge/th-edge/architecture/modules/types.md @@ -0,0 +1,39 @@ +--- +id: types +title: Types +description: คำอธิบายเกี่ยวกับโมดูล types ของ Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## ภาพรวม {#overview} + +โมดูล **Types** จะนำประเภทอ็อบเจ็กต์หลักต่างๆ ไปใช้ เช่น: + +* **Address** +* **Hash** +* **Header** +* ฟังก์ชันตัวช่วยอีกมากมาย + +## การเข้ารหัส / การถอดรหัส RLP {#rlp-encoding-decoding} + +Polygon Edge ต่างจากไคลเอ็นต์อย่าง GETH ตรงที่ไม่ใช้การสะท้อนในการเข้ารหัส
ถ้าให้ดีไม่ควรใช้การสะท้อนเพราะทำให้เกิดปัญหาใหม่ๆ เช่น ประสิทธิภาพการเสื่อมสภาพ และการปรับขนาดที่ยากขึ้น + +โมดูล **Types** จัดเตรียมอินเทอร์เฟซที่ใช้งานง่ายสำหรับกระบวนการ Marshall และ Unmarshall ตัว RLP โดยใช้แพ็คเกจ FastRLP + +ทำกระบวนการ Marshall ผ่านเมธอด *MarshalRLPWith* และ *MarshalRLPTo*เมธอดที่คล้ายคลึงกันมีไว้สำหรับกระบวนการ Unmarshall + +การกำหนดเมธอดเหล่านี้ด้วยตนเองทำให้ Polygon Edge ไม่จำเป็นต้องใช้การสะท้อนใน *rlp_marshal.go* คุณสามารถพบเมธอดสำหรับกระบวนการ Marshall + +* **Bodies** +* **Blocks** +* **Headers** +* **Receipts** +* **Logs** +* **Transactions** \ No newline at end of file diff --git a/archive/edge/th-edge/architecture/overview.md b/archive/edge/th-edge/architecture/overview.md new file mode 100644 index 0000000000..277a97c446 --- /dev/null +++ b/archive/edge/th-edge/architecture/overview.md @@ -0,0 +1,59 @@ +--- +id: overview +title: ภาพรวมสถาปัตยกรรม +sidebar_label: Overview +description: ข้อมูลเบื้องต้นเกี่ยวกับสถาปัตยกรรมของ Polygon Edge +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +เราเริ่มต้นด้วยแนวคิดในการสร้างซอฟต์แวร์ที่เป็น*แบบโมดูลาร์* + +นี่คือสิ่งที่มีอยู่ในเกือบทุกส่วนของ Polygon Edgeด้านล่างนี้ คุณจะพบภาพรวมคร่าวๆ ของสถาปัตยกรรมที่สร้างขึ้นและการจัดเรียงเลเยอร์ + +## การจัดเรียงเลเยอร์ของ Polygon Edge {#polygon-edge-layering} + +![สถาปัตยกรรม Polygon Edge](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +ทุกอย่างเริ่มต้นที่เลเยอร์เครือข่ายพื้นฐาน ซึ่งใช้ **libp2p**เราตัดสินใจเลือกเทคโนโลยีนี้เพราะเทคโนโลยีเข้ากับปรัชญาการออกแบบของ Polygon EdgeLibp2p เป็นแบบ: + +- โมดูลาร์ +- ขยายได้ +- รวดเร็ว + +สิ่งสำคัญที่สุดคือ เป็นพื้นฐานที่ดีสำหรับคุณสมบัติอันล้ำสมัยเพิ่มเติม ซึ่งเราจะกล่าวถึงในภายหลัง + + +## การซิงค์และฉันทามติ {#synchronization-consensus} +การแยกโปรโตคอลการซิงค์และฉันทามติช่วยให้เกิด Modularity และการนำกลไกการซิงค์และฉันทามติ**ที่กำหนดเอง**ไปใช้งาน ทั้งนี้ขึ้นอยู่กับวิธีการรันไคลเอ็นต์ + +เราออกแบบ Polygon Edge มาเพื่อนำเสนออัลกอริธึมฉันทามติแบบ Pluggable ที่พร้อมใช้งาน + +รายการปัจจุบันของอัลกอริธึมฉันทามติที่รองรับ + +* IBFT PoA +* IBFT PoS + +## บล็อกเชน {#blockchain} +เลเยอร์บล็อกเชนเป็นเลเยอร์กลางที่ประสานทุกอย่างไว้ในระบบ Polygon Edgeเราจะกล่าวถึงอย่างละเอียดในส่วน*โมดูล*ที่เกี่ยวข้อง + +## สถานะ {#state} +เลเยอร์ด้านใน "สถานะ" ประกอบด้วยลอจิกการเปลี่ยนสถานะสถานะจัดการกับวิธีการเปลี่ยนแปลงสถานะ เมื่อมีการรวมบล็อกใหม่เราจะกล่าวถึงอย่างละเอียดในส่วน*โมดูล*ที่เกี่ยวข้อง + +## JSON RPC {#json-rpc} +เลเยอร์ JSON RPC เป็นเลเยอร์ API ที่นักพัฒนา dApp ใช้เพื่อโต้ตอบกับบล็อกเชนเราจะกล่าวถึงอย่างละเอียดในส่วน*โมดูล*ที่เกี่ยวข้อง + +## TxPool {#txpool} +เลเยอร์ TxPool แสดงถึงกลุ่มธุรกรรม และเชื่อมโยงอย่างใกล้ชิดกับโมดูลอื่นๆ ในระบบ เนื่องจากสามารถเพิ่มธุรกรรมจากจุดเริ่มต้นได้หลายจุด + +## GRPC {#grpc} +gRPC หรือเรียกการดำเนินการทางไกลของ Google คือกรอบ RPC แบบเปิดซอร์สที่แข็งแกร่งซึ่งมี Google สร้างขึ้นเพื่อสร้างเอพีไอที่สามารถปรับขนาดได้และรวดเร็วเลเยอร์ GRPC สำคัญยิ่งต่อการโต้ตอบของตัวดำเนินการตัวดำเนินการโหนดสามารถโต้ตอบกับไคลเอ็นต์ได้อย่างง่ายดาย โดยมอบ UX ที่น่าพึงพอใจ diff --git a/archive/edge/th-edge/community/propose-new-feature.md b/archive/edge/th-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..c5739c763a --- /dev/null +++ b/archive/edge/th-edge/community/propose-new-feature.md @@ -0,0 +1,59 @@ +--- +id: propose-new-feature +title: เสนอคุณสมบัติใหม่ +description: "เทมเพลต PR และคำแนะนำสำหรับการเสนอคุณสมบัติใหม่" +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## ภาพรวม {#overview} + +หากคุณต้องการเพิ่มการแก้ไขหรืออยากมีส่วนร่วมในโค้ด เราขอแนะนำเป็นอย่างยิ่งให้คุณติดต่อทีมของเราก่อน
Polygon Edge ใช้เทมเพลตการเสนอคุณสมบัติที่ค่อนข้างธรรมดา ซึ่งกระชับและตรงประเด็น + +## เทมเพลต PR {#pr-template} + +### รายละเอียด {#description} + +โปรดให้คำอธิบายโดยรายละเอียดเกี่ยวกับสิ่งที่ทำใน PR นี้ + +### การเปลี่ยนแปลงต่างๆ ได้แก่ {#changes-include} + +- [ ] การแก้ไขบั๊ก (การเปลี่ยนแปลงที่ไม่ส่งผลกระทบเพื่อแก้ไขปัญหา) +- [ ] Hotfix (การเปลี่ยนแปลงเพื่อแก้ไขปัญหาเร่งด่วนและต้องให้ความสำคัญทันที) +- [ ] คุณสมบัติใหม่ (การเปลี่ยนแปลงที่ไม่ส่งผลกระทบเพื่อเพิ่มฟังก์ชัน) +- [ ] การเปลี่ยนแปลงที่ส่งผลกระทบ (การเปลี่ยนแปลงที่เข้ากันไม่ได้กับเวอร์ชันเก่าและ/หรือการเปลี่ยนแปลงฟังก์ชันปัจจุบัน) + +### การเปลี่ยนแปลงที่ส่งผลกระทบ {#breaking-changes} + +โปรดทำส่วนนี้หากมีการดำเนินการเปลี่ยนแปลงที่ส่งผลกระทบใดๆ หากไม่มี ให้ลบออก + +### รายการตรวจสอบ {#checklist} + +- [ ] ฉันได้มอบหมาย PR นี้ให้ตัวเองแล้ว +- [ ] ฉันได้เพิ่มตัวตรวจสอบความถูกต้องอย่างน้อย 1 คนแล้ว +- [ ] ฉันได้เพิ่มป้ายกำกับที่เกี่ยวข้องแล้ว +- [ ] ฉันได้อัปเดตเอกสารอย่างเป็นทางการแล้ว +- [ ] ฉันได้ใส่คำอธิบายโค้ดที่เพียงพอแล้ว + +### การทดสอบ {#testing} + +- [ ] ฉันได้ทดสอบโค้ดนี้ด้วยชุดทดสอบอย่างเป็นทางการแล้ว +- [ ] ฉันได้ทดสอบโค้ดนี้แบบ Manual Test แล้ว + +## Manual Test {#manual-tests} + +โปรดทำส่วนนี้ หากคุณทดสอบแบบ Manual Test กับฟังก์ชันนี้ หากไม่ได้ทำ ให้ลบออก + +### การอัปเดตเอกสาร {#documentation-update} + +โปรดลิงก์ PR การอัปเดตเอกสารไว้ในส่วนนี้ถ้ามี หากไม่มีให้ ให้ลบออก + +### ความคิดเห็นเพิ่มเติม {#additional-comments} + +โปรดเพิ่มความคิดเห็นเพิ่มเติมในส่วนนี้ถ้ามี หากไม่มี ให้ลบออก \ No newline at end of file diff --git a/archive/edge/th-edge/community/report-bug.md b/archive/edge/th-edge/community/report-bug.md new file mode 100644 index 0000000000..00f3474349 --- /dev/null +++ b/archive/edge/th-edge/community/report-bug.md @@ -0,0 +1,53 @@ +--- +id: report-bug +title: รายงานปัญหา +description: เทมเพลตและคำแนะนำในการรายงานปัญหา Polygon Edge +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## ภาพรวม {#overview} + +บางครั้งสิ่งของก็เสียหาย
เป็นการดีกว่าเสมอที่จะแจ้งให้ทีมทราบเกี่ยวกับปัญหาที่คุณอาจพบ
ในหน้า Polygon Edge GitHub คุณสามารถแจ้งปัญหาใหม่และเริ่มพูดคุยกับทีม + +## เทมเพลตปัญหา {#issue-template} + +## [หัวเรื่องปัญหา] + +### คำอธิบาย {#description} + +อธิบายปัญหาของคุณอย่างละเอียดที่สุดที่นี่ + +### สภาพแวดล้อมของคุณ {#your-environment} + +* OS และเวอร์ชัน +* เวอร์ชันของ Polygon Edge +* สาขาที่ทำให้เกิดปัญหานี้ + +### ขั้นตอนในการทำซ้ำ {#steps-to-reproduce} + +* บอกเราถึงวิธีการทำซ้ำปัญหานี้
+* ปัญหานี้อยู่ที่ไหน ถ้าคุณรู้
+* คำสั่งใดที่ก่อให้เกิดปัญหา หากมี + +### รูปแบบการทำงานที่ควรจะเป็น {#expected-behaviour} + +บอกเราว่าควรเกิดอะไรขึ้น + +### รูปแบบการทำงานที่เกิดขึ้นจริง {#actual-behaviour} + +บอกเราว่าเกิดอะไรขึ้นแทน + +### บันทึก {#logs} + +โปรดวางบันทึกใดๆ ที่แสดงให้เห็นปัญหาไว้ที่นี่ หากมี + +### วิธีแก้ไขปัญหาที่เสนอแนะ {#proposed-solution} + +หากคุณมีแนวคิดในการแก้ไขปัญหานี้ โปรดเขียนไว้ที่นี่ เพื่อเราจะได้เริ่มพูดคุยกัน \ No newline at end of file diff --git a/archive/edge/th-edge/configuration/manage-private-keys.md b/archive/edge/th-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..1e09a359cf --- /dev/null +++ b/archive/edge/th-edge/configuration/manage-private-keys.md @@ -0,0 +1,72 @@ +--- +id: manage-private-keys +title: การจัดการคีย์ส่วนตัว +description: "วิธีการจัดการคีย์ส่วนตัวและประเภทคีย์ที่มีอยู่" +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## ภาพรวม {#overview} + +Polygon Edge มีคีย์ส่วนตัวสองประเภท ซึ่งระบบจะจัดการโดยตรงกับ: + +* **คีย์ส่วนตัวที่ใช้สำหรับกลไกฉันทามติ** +* **คีย์ส่วนตัวที่ libp2p ใช้สำหรับการดำเนินการในเครือข่าย** +* **(ไม่บังคับ) คีย์ส่วนตัว BLS ที่ใช้สำหรับกลไกฉันทามติเพื่อรวบรวมลายเซ็นของตัวตรวจสอบความถูกต้อง** + +ปัจจุบันนี้ Polygon Edge ยังไม่ให้การรองรับการจัดการบัญชีโดยตรง + +ตามโครงสร้างไดเรกทอรีที่อธิบายไว้ใน[คู่มือเกี่ยวกับการสำรองและคืนค่าข้อมูล](/docs/edge/working-with-node/backup-restore)Polygon Edge จะจัดเก็บไฟล์ของคีย์ที่กล่าวถึงไว้เหล่านี้ใน 2 ไดเรกทอรี - **consensus** และ **keystore** + +## รูปแบบคีย์ {#key-format} + +คีย์ส่วนตัวได้รับการจัดเก็บไว้ในรูปแบบอย่างง่าย คือ **รูปแบบ Base64** จึงทำให้มนุษย์สามารถอ่านได้และใช้งานได้หลายระบบ + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info ประเภทคีย์ + +ไฟล์ของคีย์ส่วนตัวทั้งหมดที่สร้างและใช้ใน Polygon Edge ใช้ ECDSA ซึ่งมีส่วนโค้ง [secp256k1](https://en.bitcoin.it/wiki/Secp256k1) เป็นหลัก + +เนื่องจากส่วนโค้งไม่ได้เป็นไปตามมาตรฐาน จึงไม่สามารถเข้ารหัสและเก็บข้อมูลส่วนโค้งนั้นในรูปแบบ PEM มาตรฐานใดๆ ได้ไม่รองรับการนำเข้าคีย์ที่ไม่สอดคล้องกับประเภทคีย์นี้ + +::: +## คีย์ส่วนตัวฉันทามติ {#consensus-private-key} + +อาจเรียกไฟล์ของคีย์ส่วนตัวที่เรียกว่า*คีย์ส่วนตัวฉันทามติ* ว่า**คีย์ส่วนตัวของตัวตรวจสอบความถูกต้อง**ก็ได้ +ใช้คีย์ส่วนตัวนี้เมื่อโหนดดำเนินการในฐานะตัวตรวจสอบความถูกต้องในเครือข่ายและจำเป็นต้องลงนามในข้อมูลใหม่ + +ไฟล์ของคีย์ส่วนตัวอยู่ใน `consensus/validator.key` และเป็นไปตาม[รูปแบบคีย์](/docs/edge/configuration/manage-private-keys#key-format)ที่อ้างถึง + +:::warning +คีย์ส่วนตัวของตัวตรวจสอบความถูกต้องเป็นคีย์เฉพาะสำหรับโหนดตัวตรวจสอบความถูกต้องแต่ละโหนดจะไม่มีการแชร์คีย์เดียวกันให้กับตัวตรวจสอบความถูกต้องทั้งหมด เนื่องจากอาจส่งผลต่อความปลอดภัยของเชนของคุณ + +::: + +## คีย์ส่วนตัวสำหรับการดำเนินการในเครือข่าย {#networking-private-key} + +ไฟล์ของคีย์ส่วนตัวที่ใช้เพื่อดำเนินการในเครือข่ายที่ libp2p ใช้เพื่อสร้าง PeerID ที่เกี่ยวข้อง และทำให้โหนดสามารถเข้าร่วมเครือข่ายได้ + +ซึ่งอยู่ใน `keystore/libp2p.key` และเป็นไปตาม[รูปแบบคีย์](/docs/edge/configuration/manage-private-keys#key-format)ที่อ้างถึง + +## คีย์ลับ BLS {#bls-secret-key} + +ใช้ไฟล์ของคีย์ลับ BLS ในการรวบรวมซีลในเลเยอร์ฉันทามติขนาดของซีลที่คอมมิตซึ่งรวบรวมมาโดย BLS นั้น น้อยกว่าลายเซ็นใน ECDSA ที่คอมมิตซึ่งใช้ในการซีเรียลไลซ์ + +คุณสมบัติ BLS เป็นคุณสมบัติที่ไม่บังคับ และคุณยังสามารถเลือกว่าจะใช้ BLS หรือไม่ดูรายละเอียดเพิ่มเติมที่ [BLS](/docs/edge/consensus/bls) + +## การนำเข้า / ส่งออก {#import-export} + +เนื่องจากเก็บไฟล์ของคีย์ไว้ในดิสก์ในรูปแบบ Base64 อย่างง่าย จึงสามารถสำรองข้อมูลหรือนำเข้าได้ง่าย + +:::caution การเปลี่ยนไฟล์ของคีย์ +การเปลี่ยนแปลงประเภทใดๆ ที่ทำกับไฟล์ของคีย์ในเครือข่ายที่ตั้งค่าไว้แล้ว / กำลังใช้งานอยู่ อาจทำให้เกิดการขัดข้องของเครือข่าย/ฉันทามติอย่างรุนแรงเนื่องจากกลไกการค้นหาเพียร์และฉันทามติจะจัดเก็บข้อมูลที่เกิดมาจากบรรดาคีย์นั้นในพื้นที่เก็บข้อมูลเฉพาะโหนด และใช้ข้อมูลนี้เพื่อเริ่มการเชื่อมต่อและใช้ลอจิกฉันทามติ +::: \ No newline at end of file diff --git a/archive/edge/th-edge/configuration/prometheus-metrics.md b/archive/edge/th-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..f2888eb202 --- /dev/null +++ b/archive/edge/th-edge/configuration/prometheus-metrics.md @@ -0,0 +1,35 @@ +--- +id: prometheus-metrics +title: เมตริก Prometheus +description: "วิธีการเปิดใช้งานเมตริก Prometheus สำหรับ Polygon Edge" +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## ภาพรวม {#overview} + +Polygon Edge สามารถรายงานและรับใช้เมตริก Prometheus โดยเมตริกนั้นก็สามารถรับใช้ระบบรวบรวมข้อมูลของ Prometheus ได้ด้วย + +ตัวเมเยอร์ Prometheus ถูกปิดการทำงานโดยค่าปริยายสามารถเปิดใช้งานได้โดยระบุที่อยู่ผู้ฟังโดยใช้`--prometheus`[แฟล็ก](/docs/edge/get-started/cli-commands#prometheus)หรือ`Telemetry.prometheus`ฟิลด์ในไฟล์การปรับแต่งจะมีการใช้เมตริกภายใต้ `/metrics` บนที่อยู่ที่กำหนดไว้ + +## เมตริกที่สามารถใช้ได้ {#available-metrics} + +เมตริกดังต่อไปนี้สามารถใช้ได้: + +| **ชื่อ** | **ประเภท** | **คำอธิบาย** | +|-------------------------------------------------|----------|---------------------------------------------| +| ed_txsurior pending_transformation | ตัววัด | จำนวนธุรกรรมที่อยู่ในระหว่างการดำเนินการที่ TxPool | +| ตัวตรวจสอบความถูกต้องของ ede_consensus_ | ตัววัด | จำนวนตัวตรวจสอบความถูกต้อง | +| ed_consensus_rout | ตัววัด | จำนวนรอบ | +| ed_consensus_num_txs | ตัววัด | จำนวนธุรกรรมในบล็อกล่าสุด | +| ed_consensus_block_ช่วงเวลาการผลิต | ตัววัด | ระยะเวลาระหว่างบล็อกนี้และบล็อกล่าสุด หน่วยเป็นวินาที | +| Eed_networkers | ตัววัด | จำนวนเพียร์ที่เชื่อมต่อ | +| ed_networwork_outbedded การเชื่อมต่อ_count | ตัววัด | จำนวนการเชื่อมต่อขาออก | +| ed_network_inbed_newset | ตัววัด | จำนวนการเชื่อมต่อขาเข้า | +| ed_network_nworksworkset | ตัววัด | จำนวนการเชื่อมต่อขาออกที่ค้างอยู่ | +| ed_networwork_nworksworkset pending_outbalecount | ตัววัด | จำนวนการเชื่อมต่อขาเข้าที่ค้างอยู่ | +| ed_consensus_eepch_bent | ตัววัด | หมายเลข ePoint ปัจจุบัน | \ No newline at end of file diff --git a/archive/edge/th-edge/configuration/sample-config.md b/archive/edge/th-edge/configuration/sample-config.md new file mode 100644 index 0000000000..4b878295f1 --- /dev/null +++ b/archive/edge/th-edge/configuration/sample-config.md @@ -0,0 +1,149 @@ +--- +id: sample-config +title: ไฟล์กำหนดค่าเซิร์ฟเวอร์ +description: "เริ่มใช้เซิร์ฟเวอร์ของ Polygon Edge โดยใช้ไฟล์กำหนดค่า" +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# ไฟล์กำหนดค่าเซิร์ฟเวอร์ {#server-configuration-file} +เริ่มใช้งานเซิร์ฟเวอร์ด้วยตัวเลือกการกำหนดค่าต่างๆ ได้โดยใช้ไฟล์กำหนดค่าแทนการใช้เฉพาะค่าสถานะเท่านั้นคำสั่งที่ใช้เพื่อเริ่มใช้งานเซิร์ฟเวอร์ด้วยไฟล์กำหนดค่า `polygon-edge server --config ` + +## ส่งออกไฟล์กำหนดค่าด้วยการกำหนดค่าเริ่มต้น {#export-config-file-with-default-configuration} +ส่งออกการกำหนดค่าเซิร์ฟเวอร์ Polygon Edge ด้วยการตั้งค่าเริ่มต้นในไฟล์กำหนดค่าในรูปแบบไฟล์ `yaml` หรือ `json` ได้ใช้ไฟล์นี้เป็นเทมเพลตในการใช้งานเซิร์ฟเวอร์โดยใช้ไฟล์กำหนดค่าได้ + +### YAML {#yaml} +เพื่อสร้างไฟล์กำหนดค่าในรูปแบบ `yaml`: +```bash +polygon-edge server export --type yaml +``` +หรือเพียงแต่ +```bash +polygon-edge server export +``` +จะมีการสร้างไฟล์กำหนดค่าซึ่งมีชื่อว่า `default-config.yaml` ในไดเรกทอรีที่เป็นแหล่งที่มาของการเรียกใช้คำสั่ง + +ตัวอย่างไฟล์: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +เพื่อสร้างไฟล์กำหนดค่าในรูปแบบ `json`: +```bash +polygon-edge server export --type json +``` +จะมีการสร้างไฟล์กำหนดค่าซึ่งมีชื่อว่า `default-config.json` ในไดเรกทอรีที่เป็นแหล่งที่มาของการเรียกใช้คำสั่ง + +ตัวอย่างไฟล์: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +ดูข้อมูลเกี่ยวกับแนวทางการใช้พารามิเตอร์เหล่านี้ได้ในส่วน [คำสั่ง CLI](/docs/edge/get-started/cli-commands) + +### โครงสร้าง Typescript {#typescript-schema} + +รูปแบบดังต่อไปนี้เป็นรูปแบบตัวอย่างสำหรับไฟล์กำหนดค่าซึ่งเขียนไว้ใน TypeScript เพื่อแสดงประเภทคุณสมบัติต่างๆ (`string`, `number`, `boolean`) และคุณสามารถกำหนดค่าของตนเองได้ด้วยการใช้ไฟล์นั้นเราเห็นสมควรแจ้งด้วยว่าประเภท `PartialDeep` จาก `type-fest` มีการใช้เพื่อแสดงให้เห็นว่าคุณสมบัติทั้งหมดเป็นแบบไม่บังคับ + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/th-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/th-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..e49fa73038 --- /dev/null +++ b/archive/edge/th-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,122 @@ +--- +id: set-up-aws-ssm +title: ตั้งค่า AWS SSM (Systems Manager) +description: "ตั้งค่า AWS SSM (Systems Manager) สำหรับ Polygon Edge" +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## ภาพรวม {#overview} + +ปัจจุบันนี้ Polygon Edge มีความเชื่อมโยงกับการเก็บรักษาข้อมูลลับเกี่ยวกับรันไทม์ที่สำคัญอยู่ 2 ส่วน: +* **คีย์ส่วนตัวของตัวตรวจสอบความถูกต้อง**ที่โหนดใช้งาน หากโหนดนั้นเป็นตัวตรวจสอบความถูกต้อง +* **คีย์ส่วนตัวสำหรับการดำเนินการในเครือข่าย**ที่ libp2p ใช้งาน เพื่อเข้าร่วมและสื่อสารกับเพียร์อื่นๆ + +โปรดอ่านข้อมูลเพิ่มเติมที่คู่มือเกี่ยวกับ[การจัดการคีย์ส่วนตัว](/docs/edge/configuration/manage-private-keys) + +บรรดาโมดูลของ Polygon Edge **ไม่จำเป็นต้องรู้ถึงวิธีการเก็บรักษาข้อมูลลับ**และในท้ายที่สุด โมดูลไม่จำเป็นต้องสนใจว่ามีการเก็บข้อมูลลับไว้ในเซิร์ฟเวอร์ที่ตั้งอยู่ไกลออกไปหรือภายในดิสก์ของโหนด + +สิ่งเดียวที่โมดูลต้องทราบเกี่ยวกับการเก็บข้อมูลลับก็คือ **ความรู้เกี่ยวกับการใช้ข้อมูลลับ** กล่าวคือ **ทราบว่าข้อมูลลับใดที่ต้องรับหรือบันทึก**รายละเอียดเกี่ยวกับการนำไปใช้อย่างละเอียดกับการดำเนินการเหล่านี้ต้องได้รับการ Delegate ไปยัง `SecretsManager` ซึ่งแน่นอนว่าคือ Abstraction + +ตอนนี้ตัวดำเนินการโหนดที่เริ่มใช้ Polygon Edge สามารถระบุตัวจัดการข้อมูลลับที่ต้องการและเมื่อ +มีการสร้างอินสแตนซ์ของตัวจัดการข้อมูลลับที่ถูกต้อง โมดูลต่างๆ สามารถดำเนินการกับข้อมูลลับนั้นผ่านอินเทอร์เฟซที่กล่าวถึงโดยไม่ใส่ใจว่า มีการเก็บข้อมูลลับไว้ในดิสก์หรือเซิร์ฟเวอร์ + +บทความนี้ให้รายละเอียดขั้นตอนที่จำเป็นในการศึกษาเกี่ยวกับ Polygon Edge และใช้งานกับ[AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) + +:::info คู่มือก่อนหน้านี้ +ก่อนอ่านบทความนี้ เรา**ขอแนะนำ**ให้คุณอ่านบทความต่างๆ ใน[**การตั้งค่าภายใน**](/docs/edge/get-started/set-up-ibft-locally)ตลอดจนบทความ[**การตั้งค่าในระบบคลาวด์**](/docs/edge/get-started/set-up-ibft-on-the-cloud) +::: + + +## ข้อกำหนดเบื้องต้น {#prerequisites} +### นโยบาย IAM {#iam-policy} +ผู้ใช้จำเป็นต้องสร้างนโยบาย IAM ที่อนุญาตให้ดำเนินการอ่าน/เขียนสำหรับ AWS Systems Manager Parameter Storeหลังจากสร้างนโยบาย IAM สำเร็จแล้ว ผู้ใช้จำเป็นต้องแนบไปกับอินสแตนซ์ EC2 ที่กำลังเรียกใช้เซิร์ฟเวอร์ Polygon Edgeนโยบาย IAM ควรมีลักษณะเช่นนี้: +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +ดูข้อมูลเพิ่มเติมเกี่ยวกับบทบาทของ AWS SSM IAM ได้ใน [เอกสาร AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html) + +ข้อมูลที่จำเป็นต้องมีก่อนดำเนินการต่อไป มีดังต่อไปนี้: +* **ภูมิภาค** (ภูมิภาคที่มีโหนดและตัวจัดการระบบอยู่) +* **พาธของพารามิเตอร์ ** (พาธแบบกำหนดเองที่จะเก็บข้อมูลลับไว้ ตัวอย่างเช่น `/polygon-edge/nodes`) + +## ขั้นตอนที่ 1 - สร้างค่าตัวจัดการข้อมูลลับ {#step-1-generate-the-secrets-manager-configuration} + +เพื่อให้ Polygon Edge สามารถสื่อสารกับ AWS SSM ได้อย่างราบรื่นไม่มีสะดุด จำเป็นต้องแยกวิเคราะห์ไฟล์กำหนดค่าที่สร้างมาแล้ว ที่มีข้อมูลที่จำเป็นทั้งหมดสำหรับพื้นที่จัดเก็บข้อมูลลับใน AWS SSM + +เพื่อสร้างค่ากำหนดนั้น ให้เรียกใช้คำสั่งดังต่อไปนี้: + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +พารามิเตอร์แสดงถึง: +* `PATH` เป็นพาธซึ่งเป็นปลายทางในการส่งออกไฟล์กำหนดค่า`./secretsManagerConfig.json` ที่เป็นค่าเริ่มต้น +* `NODE_NAME` คือชื่อของโหนดปัจจุบันที่มีการตั้งค่าการกำหนดค่า AWS SSM ให้ซึ่งสามารถมีค่าแบบกำหนดเอง`polygon-edge-node` ที่เป็นค่าเริ่มต้น +* `REGION` เป็นภูมิภาคที่ AWS SSM อยู่ซึ่งต้องเป็นภูมิภาคเดียวกับโหนดที่ใช้ AWS SSM +* `SSM_PARAM_PATH` เป็นชื่อของพาธที่จะเก็บข้อมูลลับไว้ตัวอย่างเช่น หาก `--name node1` และ `ssm-parameter-path=/polygon-edge/nodes`มีการระบุไว้ จะจัดเก็บข้อมูลลับไว้ในรูปแบบ `/polygon-edge/nodes/node1/` + +:::caution ชื่อโหนด + +โปรดระวังเมื่อระบุชื่อโหนด + +Polygon Edge ใช้ชื่อโหนดเฉพาะเพื่อติดตามข้อมูลลับที่สร้างและใช้ใน AWS SSMการระบุชื่อโหนดที่มีอยู่อาจส่งผลทำให้การเขียนข้อมูลลับไปยัง AWS SSM ล้มเหลว + +เก็บข้อมูลลับไว้ในพาธหลักนี้: `SSM_PARAM_PATH/NODE_NAME` + +::: + +## ขั้นตอนที่ 2 - เริ่มใช้คีย์ลับโดยใช้ค่ากำหนด {#step-2-initialize-secret-keys-using-the-configuration} + +ตอนนี้ เมื่อเรามีไฟล์กำหนดค่าแล้ว เราสามารถเริ่มใช้คีย์ลับที่จำเป็นกับไฟล์กำหนดค่าที่ตั้งค่าไว้ในขั้นตอนที่ 1 โดยใช้ `--config`: + +```bash +polygon-edge secrets init --config +``` + +พารามิเตอร์ `PATH` เป็นที่ตั้งของพารามิเตอร์ตัวจัดการข้อมูลลับที่สร้างขึ้นก่อนหน้านี้ในขั้นตอนที่ 1 + +:::info นโยบาย IAM +ขั้นตอนนี้จะล้มเหลวหากไม่ได้กำหนดค่านโยบาย IAM ที่อนุญาตให้ดำเนินการอ่าน/เขียนอย่างถูกต้องและ/หรือไม่ได้แนบไปกับอินสแตนซ์ EC2 ที่เรียกใช้คำสั่งนี้ +::: + +## ขั้นตอนที่ 3 - สร้างไฟล์ Genesis {#step-3-generate-the-genesis-file} + +ควรสร้างไฟล์ Genesis ในลักษณะเดียวกันกับคู่มือ[**การตั้งค่าภายใน**](/docs/edge/get-started/set-up-ibft-locally)และ[**การตั้งค่าในระบบคลาวด์**](/docs/edge/get-started/set-up-ibft-on-the-cloud) พร้อมกับการแก้ไขเพิ่มเติมเล็กน้อย + +เนื่องจากมีการใช้ AWS SSM แทนระบบไฟล์ภายใน จึงควรเพิ่มที่อยู่ของตัวตรวจสอบความถูกต้องผ่านค่าสถานะ `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## ขั้นตอนที่ 4 - เริ่มใช้ไคลเอ็นต์ของ Polygon Edge {#step-4-start-the-polygon-edge-client} + +ตอนนี้ เมื่อมีการกำหนดคีย์และสร้างไฟล์ Genesis แล้ว ขั้นตอนสุดท้ายของกระบวนการนี้คือ การเริ่มต้นPolygon Edge โดยใช้คำสั่ง `server` + +ใช้คำสั่ง`server` ในลักษณะเดียวกันกับที่ได้ระบุไว้ในคู่มือที่กล่าวถึงก่อนหน้านี้ โดยมีการเพิ่มเติมเล็กน้อย ได้แก่ ค่าสถานะ `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +พารามิเตอร์ `PATH` เป็นที่ตั้งของพารามิเตอร์ตัวจัดการข้อมูลลับที่สร้างขึ้นก่อนหน้านี้ในขั้นตอนที่ 1 \ No newline at end of file diff --git a/archive/edge/th-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/th-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..0d1df5696b --- /dev/null +++ b/archive/edge/th-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,110 @@ +--- +id: set-up-gcp-secrets-manager +title: ตั้งค่าตัวจัดการข้อมูลลับ GCP +description: "ตั้งค่าตัวจัดการข้อมูลลับ GCP ให้กับ Polygon Edge" +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## ภาพรวม {#overview} + +ปัจจุบันนี้ Polygon Edge มีความเชื่อมโยงกับการเก็บรักษาข้อมูลลับเกี่ยวกับรันไทม์ที่สำคัญอยู่ 2 ส่วน: +* **คีย์ส่วนตัวของตัวตรวจสอบความถูกต้อง**ที่โหนดใช้งาน หากโหนดนั้นเป็นตัวตรวจสอบความถูกต้อง +* **คีย์ส่วนตัวสำหรับการดำเนินการในเครือข่าย**ที่ libp2p ใช้งาน เพื่อเข้าร่วมและสื่อสารกับเพียร์อื่นๆ + +โปรดอ่านข้อมูลเพิ่มเติมที่คู่มือเกี่ยวกับ[การจัดการคีย์ส่วนตัว](/docs/edge/configuration/manage-private-keys) + +บรรดาโมดูลของ Polygon Edge **ไม่จำเป็นต้องรู้ถึงวิธีการเก็บรักษาข้อมูลลับ**และในท้ายที่สุด โมดูลไม่จำเป็นต้องสนใจว่ามีการเก็บข้อมูลลับไว้ในเซิร์ฟเวอร์ที่ตั้งอยู่ไกลออกไปหรือภายในดิสก์ของโหนด + +สิ่งเดียวที่โมดูลต้องทราบเกี่ยวกับการเก็บข้อมูลลับก็คือ **ความรู้เกี่ยวกับการใช้ข้อมูลลับ** กล่าวคือ **ทราบว่าข้อมูลลับใดที่ต้องรับหรือบันทึก**รายละเอียดเกี่ยวกับการนำไปใช้อย่างละเอียดกับการดำเนินการเหล่านี้ต้องได้รับการ Delegate ไปยัง `SecretsManager` ซึ่งแน่นอนว่าคือ Abstraction + +ตอนนี้ตัวดำเนินการโหนดที่เริ่มใช้ Polygon Edge สามารถระบุตัวจัดการข้อมูลลับที่ต้องการและเมื่อ +มีการสร้างอินสแตนซ์ของตัวจัดการข้อมูลลับที่ถูกต้อง โมดูลต่างๆ สามารถดำเนินการกับข้อมูลลับนั้นผ่านอินเทอร์เฟซที่กล่าวถึงโดยไม่ใส่ใจว่า มีการเก็บข้อมูลลับไว้ในดิสก์หรือเซิร์ฟเวอร์ + +บทความนี้ให้รายละเอียดขั้นตอนที่จำเป็นในการศึกษาเกี่ยวกับ Polygon Edge และใช้งานกับ[ตัวจัดการข้อมูลลับ GCP](https://cloud.google.com/secret-manager) + +:::info คู่มือก่อนหน้านี้ +ก่อนอ่านบทความนี้ เรา**ขอแนะนำ**ให้คุณอ่านบทความต่างๆ ใน[**การตั้งค่าภายใน**](/docs/edge/get-started/set-up-ibft-locally)ตลอดจนบทความ[**การตั้งค่าในระบบคลาวด์**](/docs/edge/get-started/set-up-ibft-on-the-cloud) +::: + + +## ข้อกำหนดเบื้องต้น {#prerequisites} +### บัญชีรับวางบิล GCP {#gcp-billing-account} +เพื่อใช้ตัวจัดการข้อมูลลับ GCP ผู้ใช้จำเป็นต้องมี[บัญชีรับวางบิล](https://console.cloud.google.com/)ที่เปิดใช้งานอยู่ในพอร์ทัล GCP +มีการจัดเตรียมบัญชี Google ใหม่ในแพลตฟอร์ม GCP ให้มาพร้อมกับเงินทุนซึ่งสามารถใช้ได้ในขณะเริ่มต้น เพื่อเป็นการทดลองใช้งานฟรีรูปแบบหนึ่ง +ข้อมูลเพิ่มเติม [เอกสาร GCP](https://cloud.google.com/free) + +### API ตัวจัดการข้อมูลลับ {#secrets-manager-api} +ผู้ใช้จะต้องเปิดใช้งาน API ตัวจัดการข้อมูลลับ GCP ก่อนจึงจะสามารถใช้งานได้ +โดยสามารถดำเนินการได้ผ่าน[พอร์ทัล API ตัวจัดการข้อมูลลับ](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com) +ข้อมูลเพิ่มเติม: [การกำหนดค่าตัวจัดการข้อมูลลับ](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + +### ข้อมูลส่วนบุคคล GCP {#gcp-credentials} +ในขั้นตอนสุดท้าย ผู้ใช้จำเป็นต้องสร้างข้อมูลส่วนบุคคลใหม่ที่จะนำมาใช้ในการรับรองความถูกต้อง +ซึ่งสามารถทำได้โดยดำเนินการตามคำแนะนำที่ระบุไว้[ที่นี่](https://cloud.google.com/secret-manager/docs/reference/libraries) คุณต้องส่งไฟล์ json ที่สร้างขึ้น ซึ่งประกอบด้วยข้อมูลส่วนบุคคล ไปยังโหนดแต่ละโหนดที่ต้องใช้ตัวจัดการข้อมูลลับ GCP + +ข้อมูลที่จำเป็นต้องมีก่อนดำเนินการต่อไป มีดังต่อไปนี้: +* **ID โครงการ** (ID โครงการที่นิยามไว้ในแพลตฟอร์ม GCP) +* **ตำแหน่งไฟล์ข้อมูลส่วนบุคคล** (พาธไปยังไฟล์ json ซึ่งประกอบข้อมูลส่วนบุคคลนั้น) + +## ขั้นตอนที่ 1 - สร้างค่ากำหนดของตัวจัดการข้อมูลลับ {#step-1-generate-the-secrets-manager-configuration} + +เพื่อให้ Polygon Edge สามารถสื่อสารกับ GCP SM ได้อย่างราบรื่นไม่มีสะดุด จำเป็นต้องแยกวิเคราะห์ +ไฟล์กำหนดค่าที่สร้างมาแล้ว ที่ประกอบข้อมูลที่จำเป็นทั้งหมดสำหรับพื้นที่จัดเก็บข้อมูลลับใน GCP SM + +เพื่อสร้างค่ากำหนดนั้น ให้เรียกใช้คำสั่งดังต่อไปนี้: + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +พารามิเตอร์แสดงถึง: +* `PATH` เป็นพาธซึ่งเป็นปลายทางในการส่งออกไฟล์กำหนดค่า`./secretsManagerConfig.json` ที่เป็นค่าเริ่มต้น +* `NODE_NAME` คือชื่อของโหนดปัจจุบันที่มีการตั้งค่าการกำหนดค่า GCP SM ให้ซึ่งสามารถมีค่าแบบกำหนดเอง`polygon-edge-node` ที่เป็นค่าเริ่มต้น +* `PROJECT_ID` เป็น ID ของโครงการซึ่งผู้ใช้ได้กำหนดไว้ในคอนโซล GCP ในขณะกำหนดค่าบัญชีและการเริ่มใช้งาน API ตัวจัดการข้อมูลลับ +* `GCP_CREDS_FILE`เป็นพาธไปยังไฟล์ json ซึ่งมีข้อมูลส่วนบุคคลที่จะอนุญาตให้อ่าน/เขียนสิทธิ์การเข้าใช้งานตัวจัดการข้อมูลลับ + +:::caution ชื่อโหนด + +โปรดระวังเมื่อระบุชื่อโหนด + +Polygon Edge ใช้ชื่อโหนดเฉพาะเพื่อติดตามข้อมูลลับซึ่งโหนดสร้างและใช้ใน GCP SM +การระบุชื่อโหนดที่มีอยู่อาจส่งผลทำให้การเขียนข้อมูลลับไปยัง GCP SM ล้มเหลว + +เก็บข้อมูลลับไว้ในพาธหลักนี้: `projects/PROJECT_ID/NODE_NAME` +::: + +## ขั้นตอนที่ 2 - เริ่มใช้คีย์ลับโดยใช้ค่ากำหนด {#step-2-initialize-secret-keys-using-the-configuration} + +ตอนนี้ เมื่อเรามีไฟล์กำหนดค่าแล้ว เราสามารถเริ่มใช้คีย์ลับที่จำเป็นกับไฟล์กำหนดค่าที่ตั้งค่าไว้ในขั้นตอนที่ 1 โดยใช้ `--config`: + +```bash +polygon-edge secrets init --config +``` + +พารามิเตอร์ `PATH` เป็นที่ตั้งของพารามิเตอร์ตัวจัดการข้อมูลลับที่สร้างขึ้นก่อนหน้านี้ในขั้นตอนที่ 1 + +## ขั้นตอนที่ 3 - สร้างไฟล์ Genesis {#step-3-generate-the-genesis-file} + +ควรสร้างไฟล์ Genesis ในลักษณะเดียวกันกับคู่มือ[**การตั้งค่าภายใน**](/docs/edge/get-started/set-up-ibft-locally)และ[**การตั้งค่าในระบบคลาวด์**](/docs/edge/get-started/set-up-ibft-on-the-cloud) พร้อมกับการแก้ไขเพิ่มเติมเล็กน้อย + +เนื่องจากมีการใช้ GCP SM แทนระบบไฟล์ภายใน จึงควรเพิ่มที่อยู่ของตัวตรวจสอบความถูกต้องผ่านค่าสถานะ `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## ขั้นตอนที่ 4 - เริ่มใช้ไคลเอ็นต์ของ Polygon Edge {#step-4-start-the-polygon-edge-client} + +ตอนนี้ เมื่อมีการกำหนดคีย์และสร้างไฟล์ Genesis แล้ว ขั้นตอนสุดท้ายของกระบวนการนี้คือ การเริ่มต้นPolygon Edge โดยใช้คำสั่ง `server` + +ใช้คำสั่ง`server` ในลักษณะเดียวกันกับที่ได้ระบุไว้ในคู่มือที่กล่าวถึงก่อนหน้านี้ โดยมีการเพิ่มเติมเล็กน้อย ได้แก่ ค่าสถานะ `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +พารามิเตอร์ `PATH` เป็นที่ตั้งของพารามิเตอร์ตัวจัดการข้อมูลลับที่สร้างขึ้นก่อนหน้านี้ในขั้นตอนที่ 1 \ No newline at end of file diff --git a/archive/edge/th-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/th-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..6f63b224b3 --- /dev/null +++ b/archive/edge/th-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,105 @@ +--- +id: set-up-hashicorp-vault +title: ตั้งค่า Hashicorp Vault +description: "ตั้งค่า Hashicorp Vault ให้กับ Polygon Edge" +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## ภาพรวม {#overview} + +ปัจจุบันนี้ Polygon Edge มีความเชื่อมโยงกับการเก็บรักษาข้อมูลลับเกี่ยวกับรันไทม์ที่สำคัญอยู่ 2 ส่วน: +* **คีย์ส่วนตัวของตัวตรวจสอบความถูกต้อง**ที่โหนดใช้งาน หากโหนดนั้นเป็นตัวตรวจสอบความถูกต้อง +* **คีย์ส่วนตัวสำหรับการดำเนินการในเครือข่าย**ที่ libp2p ใช้งาน เพื่อเข้าร่วมและสื่อสารกับเพียร์อื่นๆ + +:::warning +คีย์ส่วนตัวของตัวตรวจสอบความถูกต้องเป็นคีย์เฉพาะสำหรับโหนดตัวตรวจสอบความถูกต้องแต่ละโหนดจะไม่มีการแชร์คีย์เดียวกันให้กับตัวตรวจสอบความถูกต้องทั้งหมด เนื่องจากอาจส่งผลต่อความปลอดภัยของเชนของคุณ +::: + +โปรดอ่านข้อมูลเพิ่มเติมที่[คู่มือเกี่ยวกับการจัดการคีย์ส่วนตัว](/docs/edge/configuration/manage-private-keys) + +บรรดาโมดูลของ Polygon Edge **ไม่จำเป็นต้องรู้ถึงวิธีการเก็บรักษาข้อมูลลับ**และในท้ายที่สุด โมดูลไม่จำเป็นต้องสนใจว่ามีการเก็บข้อมูลลับไว้ในเซิร์ฟเวอร์ที่ตั้งอยู่ไกลออกไปหรือภายในดิสก์ของโหนด + +สิ่งเดียวที่โมดูลต้องทราบเกี่ยวกับการเก็บข้อมูลลับก็คือ **ความรู้เกี่ยวกับการใช้ข้อมูลลับ** กล่าวคือ **ทราบว่าข้อมูลลับใดที่ต้องรับหรือบันทึก**รายละเอียดเกี่ยวกับการนำไปใช้อย่างละเอียดกับการดำเนินการเหล่านี้ต้องได้รับการ Delegate ไปยัง `SecretsManager` ซึ่งแน่นอนว่าคือ Abstraction + +ตอนนี้ตัวดำเนินการโหนดที่เริ่มใช้ Polygon Edge สามารถระบุตัวจัดการข้อมูลลับที่ต้องการและเมื่อ +มีการสร้างอินสแตนซ์ของตัวจัดการข้อมูลลับที่ถูกต้อง โมดูลต่างๆ สามารถดำเนินการกับข้อมูลลับนั้นผ่านอินเทอร์เฟซที่กล่าวถึงโดยไม่ใส่ใจว่า มีการเก็บข้อมูลลับไว้ในดิสก์หรือเซิร์ฟเวอร์ + +บทความนี้ให้รายละเอียดขั้นตอนที่จำเป็นในการศึกษาเกี่ยวกับ Polygon Edge และใช้งานกับเซิร์ฟเวอร์ [Hashicorp Vault](https://www.vaultproject.io/) + +:::info คู่มือก่อนหน้านี้ +ก่อนอ่านบทความนี้ เรา**ขอแนะนำ**ให้คุณอ่านบทความต่างๆ ใน[**การตั้งค่าภายใน**](/docs/edge/get-started/set-up-ibft-locally)ตลอดจนบทความ[**การตั้งค่าในระบบคลาวด์**](/docs/edge/get-started/set-up-ibft-on-the-cloud) +::: + + +## ข้อกำหนดเบื้องต้น {#prerequisites} + +บทความนี้ถือว่า **มีการตั้งค่า**อินสแตนซ์ด้านฟังก์ชันการทำงานของเซิร์ฟเวอร์ Hashicorp Vault แล้ว + +นอกจากนี้ เซิร์ฟเวอร์ Hashicorp Vault ที่ใช้งานกับ Polygon Edge ต้อง**เปิดใช้งานที่เก็บข้อมูล KV** ก่อน + +ข้อมูลที่จำเป็นต้องมีก่อนดำเนินการต่อไป มีดังต่อไปนี้: +* **URL ของเซิร์ฟเวอร์** (API URL ของเซิร์ฟเวอร์ Hashicorp Vault) +* **โทเค็น** (โทเค็นที่ใช้ในการเข้าถึงเครื่องพื้นที่จัดเก็บ KV) + +## ขั้นตอนที่ 1 - สร้างค่ากำหนดของตัวจัดการข้อมูลลับ {#step-1-generate-the-secrets-manager-configuration} + +เพื่อให้ Polygon Edge สามารถสื่อสารกับเซิร์ฟเวอร์ Vault ได้อย่างราบรื่นไม่มีสะดุด จำเป็นต้องแยกวิเคราะห์ +ไฟล์กำหนดค่าที่สร้างมาแล้ว ที่มีข้อมูลที่จำเป็นทั้งหมดสำหรับพื้นที่จัดเก็บข้อมูลลับในเซิร์ฟเวอร์ Vault + +เพื่อสร้างค่ากำหนดนั้น ให้เรียกใช้คำสั่งดังต่อไปนี้: + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +พารามิเตอร์แสดงถึง: +* `PATH` เป็นพาธซึ่งเป็นปลายทางในการส่งออกไฟล์กำหนดค่า`./secretsManagerConfig.json` ที่เป็นค่าเริ่มต้น +* `TOKEN` เป็นโทเค็นซึ่งใช้ในการเข้าถึง ตามที่ระบุไว้แล้วในส่วน[ข้อกำหนดเบื้องต้น](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `SERVER_URL` เป็น URL ของ API สำหรับเซิร์ฟเวอร์ Vault ตามที่ระบุไว้ในส่วน[ข้อกำหนดเบื้องต้น](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites)ด้วย +* `NODE_NAME` คือชื่อของโหนดปัจจุบันที่มีการตั้งค่าการกำหนดค่า Vault ให้ซึ่งสามารถมีค่าแบบกำหนดเอง`polygon-edge-node` ที่เป็นค่าเริ่มต้น + +:::caution ชื่อโหนด + +โปรดระวังเมื่อระบุชื่อโหนด + +Polygon Edge ใช้ชื่อโหนดเฉพาะเพื่อติดตามข้อมูลลับซึ่งโหนดสร้างและใช้ในอินสแตนซ์ของ Vaultการระบุชื่อโหนดที่มีอยู่อาจส่งผลให้เกิดการเขียนทับข้อมูลในเซิร์ฟเวอร์ Vault + +เก็บข้อมูลลับไว้ในพาธหลักนี้: `secrets/node_name` +::: + +## ขั้นตอนที่ 2 - เริ่มใช้คีย์ลับโดยใช้ค่ากำหนด {#step-2-initialize-secret-keys-using-the-configuration} + +ตอนนี้ เมื่อเรามีไฟล์กำหนดค่าแล้ว เราสามารถเริ่มใช้คีย์ลับที่จำเป็นกับไฟล์กำหนดค่าที่ตั้งค่าไว้ในขั้นตอนที่ 1 โดยใช้ `--config`: + +```bash +polygon-edge secrets init --config +``` + +พารามิเตอร์ `PATH` เป็นที่ตั้งของพารามิเตอร์ตัวจัดการข้อมูลลับที่สร้างขึ้นก่อนหน้านี้ในขั้นตอนที่ 1 + +## ขั้นตอนที่ 3 - สร้างไฟล์ Genesis {#step-3-generate-the-genesis-file} + +ควรสร้างไฟล์ Genesis ในลักษณะเดียวกันกับคู่มือ[**การตั้งค่าภายใน**](/docs/edge/get-started/set-up-ibft-locally)และ[**การตั้งค่าในระบบคลาวด์**](/docs/edge/get-started/set-up-ibft-on-the-cloud) พร้อมกับการแก้ไขเพิ่มเติมเล็กน้อย + +เนื่องจากมีการใช้ Hashicorp Vault แทนระบบไฟล์ภายใน จึงควรเพิ่มที่อยู่ของตัวตรวจสอบความถูกต้องผ่านค่าสถานะ `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## ขั้นตอนที่ 4 - เริ่มใช้ไคลเอ็นต์ของ Polygon Edge {#step-4-start-the-polygon-edge-client} + +ตอนนี้ เมื่อมีการกำหนดคีย์และสร้างไฟล์ Genesis แล้ว ขั้นตอนสุดท้ายของกระบวนการนี้คือ การเริ่มต้นPolygon Edge โดยใช้คำสั่ง `server` + +ใช้คำสั่ง`server` ในลักษณะเดียวกันกับที่ได้ระบุไว้ในคู่มือที่กล่าวถึงก่อนหน้านี้ โดยมีการเพิ่มเติมเล็กน้อย ได้แก่ ค่าสถานะ `--secrets-config`: +```bash +polygon-edge server --secrets-config ... +``` + +พารามิเตอร์ `PATH` เป็นที่ตั้งของพารามิเตอร์ตัวจัดการข้อมูลลับที่สร้างขึ้นก่อนหน้านี้ในขั้นตอนที่ 1 \ No newline at end of file diff --git a/archive/edge/th-edge/consensus/bls.md b/archive/edge/th-edge/consensus/bls.md new file mode 100644 index 0000000000..23daac3e6a --- /dev/null +++ b/archive/edge/th-edge/consensus/bls.md @@ -0,0 +1,140 @@ +--- +id: bls +title: BLS +description: "คำอธิบายและคำแนะนำเกี่ยวกับโหมด BLS" +keywords: + - docs + - polygon + - edge + - bls +--- + +## ภาพรวม {#overview} + +BLS หรือที่รู้จักกันในชื่อ Boneh-Lynn-Shachm (BLS) คือรูปแบบลายเซ็นของ cryptoographic ซึ่งช่วยให้ผู้ใช้ตรวจสอบว่าตัวเซ็นเซอร์เป็นเรื่องจริงมันเป็นโครงการลายเซ็นที่สามารถรวมรวมลายเซ็นได้หลายฉบับใน Polygon Edge มีการใช้ BLS ตามค่าเริ่มต้นเพื่อให้การรักษาความปลอดภัยที่ดีขึ้นในโหมดฉันทามติ IBFTBLS สามารถรวมลายเซ็นเป็นอาร์เรย์ไบต์เดียวและลดขนาดส่วนหัวของบล็อกแต่ละเชนสามารถเลือกได้ว่าจะใช้ BLS หรือไม่ใช้คีย์ ECDSA โดยไม่คำนึงว่าโหมด BLS จะเปิดใช้งานหรือไม่ + +## นำเสนอวิดีโอ {#video-presentation} + +[![bls - วิดีโอ](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## วิธีตั้งค่าเชนใหม่โดยใช้ BLS {#how-to-setup-a-new-chain-using-bls} + +ดูคำแนะนำการตั้งค่าแบบละเอียดได้ในส่วน[การตั้งค่าภายใน](/docs/edge/get-started/set-up-ibft-locally) / [การตั้งค่าในระบบคลาวด์](/docs/edge/get-started/set-up-ibft-on-the-cloud) + +## วิธีย้ายจากเชน ECDSA PoA ที่มีอยู่ไปยังเชน BLS PoA {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +ส่วนนี้อธิบายวิธีใช้โหมด BLS ในเชน PoA ที่มีอยู่จำเป็นต้องมีขั้นตอนต่อไปนี้เพื่อเปิดใช้งาน BLS ในเชน PoA + +1. หยุดโหนดทั้งหมด +2. สร้างคีย์ BLS สำหรับตัวตรวจสอบความถูกต้อง +3. เพิ่มการตั้งค่า Fork ใน Genesis.json +4. รีสตาร์ทโหนดทั้งหมด + +### 1. หยุดโหนดทั้งหมด {#1-stop-all-nodes} + +ยุติกระบวนการทั้งหมดของตัวตรวจสอบความถูกต้องโดยกด Ctrl + c (Control + c)โปรดจำความสูงของบล็อกล่าสุด (หมายเลขลำดับสูงสุดในบันทึกการคอมมิตบล็อก) + +### 2. สร้างคีย์ BLS {#2-generate-the-bls-key} + +`secrets init` กับ `--bls` สร้างคีย์ BLSต้องปิดการใช้งาน `--ecdsa` และ `--network` เพื่อเก็บ ECDSA และคีย์เครือข่ายที่มีอยู่และเพิ่มคีย์ BLS ใหม่ + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. เพิ่มการตั้งค่า Fork {#3-add-fork-setting} + +คำสั่ง `ibft switch` เพิ่มการตั้งค่า Fork ซึ่งเปิดใช้งาน BLS ในเชนที่มีอยู่ เข้าใน `genesis.json` + +สำหรับเครือข่าย PoA ต้องให้ตัวตรวจสอบความถูกต้องในคำสั่งโดยใช้วิธีการของคำสั่ง `genesis` ในการระบุตัวตรวจสอบความถูกต้องด้วยค่าสถานะ `--ibft-validators-prefix-path` หรือ `--ibft-validator` ได้ + +ระบุความสูงที่เชนเริ่มโดยใช้ BLS ที่มีค่าสถานะ `--from` + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. รีสตาร์ทโหนดทั้งหมด {#4-restart-all-nodes} + +รีสตาร์ทโหนดทั้งหมดตามคำสั่ง `server`หลังจากสร้างบล็อกที่ `from` ที่ระบุในขั้นตอนก่อนหน้าแล้ว เชนจะเปิดใช้งาน BLS และแสดงบันทึกดังต่อไปนี้: + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +นอกจากนี้ บันทึกยังแสดงโหมดการตรวจสอบความถูกต้องที่ใช้ในการสร้างแต่ละบล็อกหลังจากสร้างบล็อกแล้ว + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## วิธีย้ายจากเชน ECDSA PoS ที่มีอยู่ไปยังเชน BLS PoS {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +ส่วนนี้อธิบายวิธีใช้โหมด BLS ในเชน PoS ที่มีอยู่จำเป็นต้องมีขั้นตอนต่อไปนี้เพื่อเปิดใช้งาน BLS ในเชน PoS + +1. หยุดโหนดทั้งหมด +2. สร้างคีย์ BLS สำหรับตัวตรวจสอบความถูกต้อง +3. เพิ่มการตั้งค่า Fork ใน Genesis.json +4. เรียกสัญญา Stake เพื่อลงทะเบียนคีย์สาธารณะ BLS +5. รีสตาร์ทโหนดทั้งหมด + +### 1. หยุดโหนดทั้งหมด {#1-stop-all-nodes-1} + +ยุติกระบวนการทั้งหมดของตัวตรวจสอบความถูกต้องโดยกด Ctrl + c (Control + c)โปรดจำความสูงของบล็อกล่าสุด (หมายเลขลำดับสูงสุดในบันทึกการคอมมิตบล็อก) + +### 2. สร้างคีย์ BLS {#2-generate-the-bls-key-1} + +`secrets init` พร้อมกับค่าสถานะ `--bls` จะสร้างคีย์ BLS ขึ้นต้องปิดการใช้งาน `--ecdsa` และ `--network` เพื่อเก็บ ECDSA และคีย์เครือข่ายที่มีอยู่และเพิ่มคีย์ BLS ใหม่ + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. เพิ่มการตั้งค่า Fork {#3-add-fork-setting-1} + +คำสั่ง `ibft switch` เพิ่มการตั้งค่า Fork ซึ่งเปิดใช้งาน BLS จากตรงกลางของเชน ลงใน `genesis.json` + +ระบุความสูงที่ที่เชนเริ่มโดยใช้โหมด BLS ที่มีค่าสถานะ `from` และความสูงที่อัปเดตสัญญาด้วยค่าสถานะ `development` + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. ลงทะเบียนคีย์สาธารณะ BLS ในสัญญา Stake {#4-register-bls-public-key-in-staking-contract} + +หลังเพิ่ม Fork และรีสตาร์ทตัวตรวจสอบความถูกต้องแล้ว ตัวตรวจสอบความถูกต้องแต่ละตัวต้องเรียก `registerBLSPublicKey` ในสัญญา Stake เพื่อลงทะเบียนคีย์สาธารณะ BLSต้องทำหลังจากความสูงที่ระบุใน `--deployment` ก่อนความสูงที่ระบุใน `--from` + +มีการนิยามสคริปต์ในการลงทะเบียนคีย์สาธารณะ BLS ไว้ใน[พื้นที่เก็บข้อมูลสัญญาอัจฉริยะการ Stake](https://github.com/0xPolygon/staking-contracts) + +ตั้งค่า `BLS_PUBLIC_KEY` ให้มีการลงทะเบียนในไฟล์ `.env`ดูรายละเอียดเพิ่มเติมเกี่ยวกับพารามิเตอร์อื่นๆ ได้ที่ [pos-Stake-unStake](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +คำสั่งต่อไปนี้ลงทะเบียนคีย์สาธารณะ BLS ที่ให้ไว้ใน `.env` กับสัญญา + +```bash +npm run register-blskey +``` + +:::warning ตัวตรวจสอบความถูกต้องต้องลงทะเบียนคีย์สาธารณะ BLS ด้วยตนเอง +ในโหมด BLS ตัวตรวจสอบความถูกต้องจะต้องมีที่อยู่ของตนเองและคีย์สาธารณะ BLSเลเยอร์ฉันทามติละเว้นตัวตรวจสอบความถูกต้องที่ไม่ได้ลงทะเบียนคีย์สาธารณะ BLS ในสัญญาเมื่อฉันทามติดึงข้อมูลตัวตรวจสอบความถูกต้องจากสัญญา +::: + +### 5. รีสตาร์ทโหนดทั้งหมด {#5-restart-all-nodes} + +รีสตาร์ทโหนดทั้งหมดตามคำสั่ง `server`เชนเปิดใช้งาน BLS หลังจากสร้างบล็อกที่ `from` ที่ระบุในขั้นตอนก่อนหน้า diff --git a/archive/edge/th-edge/consensus/migration-to-pos.md b/archive/edge/th-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..6e2cedb20a --- /dev/null +++ b/archive/edge/th-edge/consensus/migration-to-pos.md @@ -0,0 +1,39 @@ +--- +id: migration-to-pos +title: การย้ายจาก PoA ไปยัง PoS +description: "วิธีย้ายโหมด IBFT จาก PoA ไปยัง PoS และในทางตรงกันข้าม" +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## ภาพรวม {#overview} + +ส่วนนี้แนะนำคุณตลอดการย้ายโหมด IBFT จาก PoA เป็น PoS สำหรับคลัสเตอร์ที่ทำงานอยู่ และในทางกลับกัน โดยไม่จำเป็นต้องรีเซ็ตบล็อกเชน + +## วิธีย้ายไปยัง PoS {#how-to-migrate-to-pos} + +คุณจะต้องหยุดโหนดทั้งหมด เพิ่มการกำหนดค่า Fork เข้าใน genesis.json โดยคำสั่ง `ibft switch` และรีสตาร์ทโหนด + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution สลับขณะใช้ ECDSA +เมื่อใช้ ECDSA จะต้องเพิ่ม`--ibft-validator-type`ธงชาติลงในสวิตต์ โดยกล่าวถึงการใช้ ECDAหากไม่รวมด้วย Edge จะเปลี่ยนเป็น BS โดยอัตโนมัติ + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::เพื่อเปลี่ยนเป็น PoS คุณจะต้องกำหนดความสูงของบล็อก2 อัน `deployment``from``deployment`และความสูงคือค่าปรับในการปรับใช้สัญญาการเดิมพัน`from`และเป็นการปรับระดับความสูงของจุดเริ่มต้นของ PoSจะมีการปรับใช้สัญญาการ Stake ตามที่อยู่ `0x0000000000000000000000000000000000001001` ที่ `deployment` เช่นในกรณีสัญญาที่ปรับใช้ล่วงหน้า + +โปรดดูรายละเอียดเพิ่มเติมเกี่ยวกับสัญญาการ Stake ที่ [Proof of Stake](/docs/edge/consensus/pos-concepts) + +:::warning ตัวตรวจสอบความถูกต้องจำเป็นต้อง Stake ด้วยตนเอง +ตัวตรวจสอบความถูกต้องแต่ละตัวจำเป็นต้อง Stake หลังจากปรับใช้สัญญาที่ `deployment` และก่อน `from`เพื่อที่จะเป็นตัวตรวจสอบความถูกต้องที่จุดเริ่มต้นของ PoSตัวตรวจสอบความถูกต้องแต่ละตัวจะอัปเดตตัวตรวจสอบความถูกต้องของตัวเองตามที่กำหนดไว้ในสัญญาการ Stake ที่จุดเริ่มต้นของ PoS + +เพื่อค้นหาข้อมูลเพิ่มเติมเกี่ยวกับการปักกิ่ง เยี่ยมชม**[การตั้งค่าและ](/docs/edge/consensus/pos-stake-unstake)**ใช้Proof of Sake. +::: diff --git a/archive/edge/th-edge/consensus/poa.md b/archive/edge/th-edge/consensus/poa.md new file mode 100644 index 0000000000..a59d465e60 --- /dev/null +++ b/archive/edge/th-edge/consensus/poa.md @@ -0,0 +1,104 @@ +--- +id: poa +title: Proof of Authority (PoA) +description: "คำอธิบายและคำแนะนำเกี่ยวกับ Proof of Authority" +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## ภาพรวม {#overview} + +IBFT PoA เป็นกลไกฉันทามติเริ่มต้นใน Polygon Edgeใน PoA ตัวตรวจสอบความถูกต้องคือตัวที่รับผิดชอบต่อการสร้างและเพิ่มบล็อกเข้าในบล็อกเชนต่อกันเป็นชุด + +ตัวตรวจสอบความถูกต้องทั้งหมดประกอบขึ้นเป็นชุดตัวตรวจสอบความถูกต้องแบบไดนามิก ที่สามารถเพิ่มหรือลบตัวตรวจสอบความถูกต้องออกจากชุดได้โดยใช้กลไกการโหวตซึ่งหมายความว่าสามารถลงคะแนนตัวตรวจสอบความถูกต้องเข้า/ออกจากชุดตัวตรวจสอบความถูกต้องได้ หากโหนดตัวตรวจสอบความถูกต้องส่วนใหญ่ (51%) ลงคะแนนเพื่อเพิ่ม/ปลดตัวตรวจสอบความถูกต้องไปยัง/ออกจากชุด ด้วยวิธีนี้ เราจะสามารถรับรู้และลบตัวตรวจสอบความถูกต้องที่เป็นอันตรายออกจากเครือข่าย ในขณะที่สามารถเพิ่มตัวตรวจสอบความถูกต้องที่เชื่อถือได้ใหม่ลงในเครือข่าย + +ตัวตรวจสอบความถูกต้องทั้งหมดผลัดกันเสนอบล็อกถัดไป (Round-Robin) และสำหรับบล็อกที่จะตรวจสอบความถูกต้อง/แทรกในบล็อกเชน ตัวตรวจสอบความถูกต้องส่วนใหญ่ (มากกว่า 2 ใน 3) จะต้องอนุมัติบล็อกดังกล่าว + +นอกจากตัวตรวจสอบความถูกต้องแล้ว ยังมีสิ่งที่ไม่ใช่ตัวตรวจสอบความถูกต้องที่ไม่ได้มีส่วนร่วมในการสร้างบล็อก แต่มีส่วนร่วมในกระบวนการตรวจสอบความถูกต้องของบล็อก + +## การเพิ่มตัวตรวจสอบความถูกต้องไปยังชุดตัวตรวจสอบความถูกต้อง {#adding-a-validator-to-the-validator-set} + +คู่มือนี้อธิบายวิธีเพิ่มโหนดตัวตรวจสอบความถูกต้องใหม่ไปยังเครือข่าย IBFT ที่ใช้งานอยู่ พร้อมกับ 4 โหนดตัวตรวจสอบความถูกต้องหากคุณต้องการความช่วยเหลือในการตั้งค่าเครือข่ายโดยอ้างถึงส่วน[การตั้งค่า/ Cloud Setup ภายในระบบ](/edge/get-started/set-up-ibft-locally.md)[](/edge/get-started/set-up-ibft-on-the-cloud.md) + +### ขั้นตอนที่ 1: เริ่มต้นโฟลเดอร์ข้อมูลสำหรับ IBFT และสร้างคีย์ตัวตรวจสอบความถูกต้องสำหรับโหนดใหม่ {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +ในการเริ่มใช้งาน IBFT บนโหนดใหม่ คุณจำเป็นต้องเริ่มต้นโฟลเดอร์ข้อมูลและสร้างคีย์ก่อน: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +คำสั่งนี้จะพิมพ์คีย์ตัวตรวจสอบความถูกต้อง (ที่อยู่) และรหัสโหนดคุณจะต้องใช้คีย์ตัวตรวจสอบความถูกต้อง (ที่อยู่) สำหรับขั้นตอนต่อไป + +### ขั้นตอนที่ 2: เสนอผู้สมัครใหม่จากโหนดตัวตรวจสอบความถูกต้องอื่นๆ {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +ในการที่โหนดใหม่ที่จะกลายเป็นตัวตรวจสอบความถูกต้อง ตัวตรวจสอบความถูกต้องอย่างน้อย 51% จำเป็นต้องเป็นผู้เสนอ + +ตัวอย่างวิธีเสนอตัวตรวจสอบความถูกต้องใหม่ (`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`) จากโหนดตัวตรวจสอบความถูกต้องที่มีอยู่บนที่อยู่ grpc: 127.0.0.1:10000: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +เนื้อหาของโครงสร้างคำสั่ง IBFT มีอยู่ในส่วน[คำสั่ง CLI](/docs/edge/get-started/cli-commands) + +:::info คีย์สาธารณะ BLS +คีย์สาธารณะ BLS จะจำเป็นก็ต่อเมื่อเครือข่ายทำงานกับ BLS ซึ่งเครือข่ายที่ไม่ทำงานในโหมด BLS ไม่จำเป็นต้องมี `--bls` +::: + +### ขั้นตอนที่ 3: เรียกใช้โหนดไคลเอ็นต์ {#step-3-run-the-client-node} + +เนื่องจากในตัวอย่างนี้ เรากำลังพยายามเรียกใช้เครือข่ายโดยที่โหนดทั้งหมดอยู่ในเครื่องเดียวกัน เราจึงต้องระมัดระวังเพื่อหลีกเลี่ยงปัญหาพอร์ตขัดแย้งกัน + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +หลังจากดึงบล็อกทั้งหมดแล้ว ภายในคอนโซลของคุณ คุณจะสังเกตเห็นว่ามีโหนดใหม่เข้าร่วมในการตรวจสอบความถูกต้อง + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info การเลื่อนตำแหน่งสิ่งที่ไม่ใช่ตัวตรวจสอบความถูกต้องเป็นตัวตรวจสอบความถูกต้อง +โดยปกติ สิ่งที่ไม่ใช่ตัวตรวจสอบความถูกต้องสามารถกลายเป็นตัวตรวจสอบความถูกต้องได้โดยกระบวนการโหวต แต่การรวมสิ่งที่ไม่ใช่ตัวตรวจสอบความถูกต้องไว้ในชุดตัวตรวจสอบความถูกต้องจะเสร็จสิ้นหลังจากกระบวนการโหวต จึงจะต้องรีสตาร์ทโหนดด้วยค่าสถานะ `--seal` + +::: + +## การลบตัวตรวจสอบความถูกต้องออกจากชุดตัวตรวจสอบความถูกต้อง {#removing-a-validator-from-the-validator-set} + +การดำเนินการนี้ค่อนข้างเรียบง่ายในการลบโหนดตัวตรวจสอบความถูกต้องออกจากชุดตัวตรวจสอบความถูกต้อง จำเป็นต้องดำเนินการคำสั่งนี้สำหรับโหนดตัวตรวจสอบความถูกต้องส่วนใหญ่ + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info คีย์สาธารณะ BLS +คีย์สาธารณะ BLS จะจำเป็นก็ต่อเมื่อเครือข่ายทำงานกับ BLS ซึ่งเครือข่ายที่ไม่ทำงานในโหมด BLS ไม่จำเป็นต้องมี `--bls` +::: + +หลังจากดำเนินการคำสั่งแล้ว ให้สังเกตว่าจำนวนตัวตรวจสอบความถูกต้องลดลง (ในตัวอย่างบันทึกนี้ลดลงจาก 4 เหลือ 3) + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/th-edge/consensus/pos-concepts.md b/archive/edge/th-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..fc1b236dc4 --- /dev/null +++ b/archive/edge/th-edge/consensus/pos-concepts.md @@ -0,0 +1,99 @@ +--- +id: pos-concepts +title: Proof of Stake +description: "คำอธิบายและคำแนะนำเกี่ยวกับ Proof of Stake" +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## ภาพรวม {#overview} + +ส่วนนี้มีจุดมุ่งหมายเพื่อให้ภาพรวมที่ดีขึ้นของแนวคิดบางอย่างที่ปัจจุบันมีอยู่ใน Proof of Stake (PoS) นี้การนำ Polygon Edge ไปใช้ + +การนำ Polygon Edge Proof of Stake (PoS) ไปใช้มีไว้เพื่อเป็นอีกหนึ่งทางเลือกของการนำ PoA IBFT ที่มีอยู่ไปใช้ทำให้ตัวดำเนินการโหนดสามารถเลือกระหว่างสองทางเลือกอย่างได้อย่างง่ายดายเมื่อเริ่มต้นเชน + +## คุณสมบัติ PoS {#pos-features} + +ลอจิกหลักที่อยู่เบื้องหลังการนำ Proof of Stake ไปใช้นั้นอยู่ภายใน**[คอนเซ็ต](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)** + +สัญญานี้จะมีการปรับใช้ล่วงหน้า เมื่อใดก็ตามที่มีการเริ่มต้นเชน Polygon Edge ที่ใช้ PoS และพร้อมใช้งานในที่อยู่ `0x0000000000000000000000000000000000001001`จากบล็อก `0` + +### Epoch {#epochs} + +Epoch เป็นแนวคิดที่นำเสนอการเพิ่ม PoS ไปยัง Polygon Edge + +Epoch ถือเป็นกรอบเวลาพิเศษ (ในบล็อก) ที่ตัวตรวจสอบความถูกต้องชุดหนึ่งๆ สามารถสร้างบล็อกได้ความยาวของ Epoch สามารถแก้ไขได้ ซึ่งหมายความว่าตัวดำเนินการโหนดสามารถกำหนดค่าความยาวของ Epoch ระหว่างการสร้าง Genesis ได้ + +ในตอนท้ายของแต่ละ Epoch จะมีการสร้าง_บล็อก Epoch_ และหลังจากอีเวนต์นั้น Epoch ใหม่จะเริ่มต้นขึ้นในการเรียนรู้เพิ่มเติมเกี่ยวกับบล็อก Epoch ดูส่วน[บล็อก Epoch](/docs/edge/consensus/pos-concepts#epoch-blocks) + +อัปเดตชุดตัวตรวจสอบความถูกต้องเมื่อสิ้นสุดแต่ละ Epochโหนดค้นหาชุดตัวตรวจสอบความถูกต้องจากสัญญาอัจฉริยะการ Stakeระหว่างการสร้างบล็อก Epoch และบันทึกข้อมูลที่ได้รับไปยังพื้นที่เก็บข้อมูลภายในรอบการบันทึกและค้นหานี้จะมีการทำซ้ำในตอนท้ายของแต่ละ Epoch + +โดยพื้นฐานแล้ว การดำเนินการนี้ทำให้มั่นใจว่าสัญญาอัจฉริยะการ Stake สามารถควบคุมที่อยู่ในชุดตัวตรวจสอบความถูกต้องได้อย่างสมบูรณ์และทำให้โหนดมีความรับผิดชอบเพียง 1 อย่าง ซึ่งก็คือค้นหาสัญญาครั้งหนึ่งในระหว่าง Epoch หนึ่งเพื่อดึงข้อมูลชุดตัวตรวจสอบความถูกต้องล่าสุดซึ่งเป็นการช่วยลดความรับผิดชอบจากโหนดแต่ละตัวในการดูแลชุดตัวตรวจสอบความถูกต้อง + +### การ Stake {#staking} + +ที่อยู่สามารถ Stake ทุนในสัญญาอัจฉริยะการ Stake โดยเรียกใช้เมธอด `stake` และโดยการระบุค่าสำหรับจำนวนที่ Stake ในธุรกรรม: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +เมื่อทำการ Stake ทุนในสัญญาอัจฉริยะการ Stake ที่อยู่สามารถป้อนชุดตัวตรวจสอบความถูกต้อง แล้วสามารถเข้าร่วมในกระบวนการสร้างบล็อก + +:::info เกณฑ์การ Stake +ปัจจุบันเกณฑ์ขั้นต่ำสำหรับการเข้าร่วมชุดตัวตรวจสอบความถูกต้องคือการ Stake `1 ETH` +::: + +### การยกเลิกการ Stake {#unstaking} + +ที่อยู่ที่มีทุนที่ Stake สามารถ**ยกเลิกการ Stake ทุนที่ Stake ทั้งหมดได้ครั้งเดียว**เท่านั้น + +ร้องขอการยกเลิกการ Stake โดยเรียกเมธอด `unstake` บนสัญญาอัจฉริยะการ Stake: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +หลังจากยกเลิกการ Stake ทุนแล้ว ที่อยู่จะได้รับการลบออกจากชุดตัวตรวจสอบความถูกต้องที่ตั้งค่าไว้ในสัญญาอัจฉริยะการ Stake และจะไม่ถือว่าเป็นตัวตรวจสอบความถูกต้องใน Epoch ถัดไป + +## บล็อก Epoch {#epoch-blocks} + +**บล็อก Epoch** เป็นแนวคิดที่นำเสนอในการนำ PoS ไปใช้ของ IBFT ใน Polygon Edge + +โดยพื้นฐานแล้ว บล็อก Epoch เป็นบล็อกพิเศษที่**ไม่มีธุรกรรม** และเกิดขึ้นเฉพาะที่**ตอนท้ายของ Epoch**ยกตัวอย่างเช่น หากตั้ง**ขนาด ePoch** ไว้สำหรับ`50`บล็อก อีโพชจะ`50`ถือว่าบล็อก `100``150`และต่อไปอีก + +ซึ่งใช้เพื่อดำเนินการลอจิกเพิ่มเติมที่ไม่ควรเกิดขึ้นระหว่างการสร้างบล็อกปกติ + +ที่สำคัญที่สุดคือ ถือเป็นตัวบ่งชี้ต่อโหนดว่า**โหนดต้องดึงข้อมูลชุดตัวตรวจสอบความถูกต้องล่าสุด**จากสัญญาอัจฉริยะการ Stake + +หลังอัปเดตชุดเครื่องมือตรวจสอบความถูกต้องที่บล็อก Epoch ชุดตัวตรวจสอบความถูกต้อง (เปลี่ยนแปลงหรือไม่เปลี่ยนแปลง)จะได้รับการนำมาใช้กับบล็อก `epochSize - 1` ที่ตามมา จนกว่าจะได้รับการอัปเดตอีกครั้งโดยดึงข้อมูลล่าสุดจากสัญญาอัจฉริยะการ Stake + +ความยาว Epoch (หน่วยเป็นบล็อก) สามารถแก้ไขได้เมื่อสร้างไฟล์ Genesis โดยใช้ค่าสถานะพิเศษ `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +ขนาดเริ่มต้นของ Epoch คือ `100000` บล็อกใน Polygon Edge + +## การปรับใช้สัญญาล่วงหน้า {#contract-pre-deployment} + +Polygon Edge _ปรับใช้ล่วงหน้า_กับ[สัญญาอัจฉริยะการ Stake](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)ระหว่าง**การสร้าง Genesis** ไปยังที่อยู่ `0x0000000000000000000000000000000000001001` + +ทำได้โดยไม่ต้องเรียกใช้ EVM เพียงแค่ปรับเปลี่ยนสถานะบล็อกเชนของสัญญาอัจฉริยะโดยตรง โดยใช้ค่าการกำหนดค่าที่ส่งผ่านไปยังคำสั่ง Genesis diff --git a/archive/edge/th-edge/consensus/pos-stake-unstake.md b/archive/edge/th-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..313fe48811 --- /dev/null +++ b/archive/edge/th-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,150 @@ +--- +id: pos-stake-unstake +title: ตั้งค่าและใช้ Proof of Stake (PoS) +description: "Stake, ยกเลิกการ Stake และคำแนะนำที่เกี่ยวกับการ Stake อื่นๆ" +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## ภาพรวม {#overview} + +คู่มือนี้มีรายละเอียดเกี่ยวกับวิธีการตั้งค่าเครือข่าย Proof of Stake กับ Polygon Edge, วิธี Stake ทุนเพื่อให้โหนดกลายเป็นตัวตรวจสอบความถูกต้อง และวิธียกเลิกการ Stake ทุน + +เป็นการ**สนับสนุนอย่างยิ่ง**ในการอ่านและผ่าน[การตั้งค่าภายใน](/docs/edge/get-started/set-up-ibft-locally)/ ส่วน [การตั้งค่าในระบบคลาวด์](/docs/edge/get-started/set-up-ibft-on-the-cloud) ก่อนไปต่อในคู่มือ PoS นี้ส่วนเหล่านี้สรุปขั้นตอนที่จำเป็นในการเริ่มต้นคลัสเตอร์ Proof of Authority (PoA) กับPolygon Edge + +ในปัจจุบัน ไม่มีการจำกัดจำนวนตัวตรวจสอบความถูกต้องที่สามารถ Stake ทุนบนสัญญาอัจฉริยะการ Stake + +## สัญญาอัจฉริยะการ Stake {#staking-smart-contract} + +พื้นที่เก็บข้อมูลสำหรับสัญญาอัจฉริยะการ Stake อยู่[ที่นี่](https://github.com/0xPolygon/staking-contracts) + +พื้นที่เก็บข้อมูลมีสคริปต์ทดสอบที่จำเป็น, ไฟล์ ABI และที่สำคัญที่สุดคือสัญญาอัจฉริยะการ Stake นั่นเอง + +## การตั้งค่าคลัสเตอร์โหนด N {#setting-up-an-n-node-cluster} + +เนื้อหาเกี่ยวกับการตั้งค่าเครือข่ายกับ Polygon Edge อยู่ในส่วน[การตั้งค่าภายใน](/docs/edge/get-started/set-up-ibft-locally)/ [การตั้งค่าในระบบคลาวด์](/docs/edge/get-started/set-up-ibft-on-the-cloud) + +**ความแตกต่างเดียว**ระหว่างการตั้งค่าคลัสเตอร์ PoS และ PoA อยู่ในส่วนการสร้าง Genesis + +**เมื่อสร้างไฟล์ Genesis สำหรับคลัสเตอร์ PoS จำเป็นต้องมีค่าสถานะเพิ่มเติม `--pos`** : + +```bash +polygon-edge genesis --pos ... +``` + +## การตั้งค่าความยาวของ Epoch {#setting-the-length-of-an-epoch} + +เนื้อหาเกี่ยวกับ Epoch อย่างละเอียดอยู่ในส่วน[บล็อก Epoch](/docs/edge/consensus/pos-concepts#epoch-blocks) + +ในการกำหนดขนาดของ Epoch สำหรับคลัสเตอร์ (หน่วยเป็นบล็อก) เมื่อสร้างไฟล์ Genesis ค่าสถานะเพิ่มเติมจะได้รับการระบุ `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +ค่านี้ระบุไว้ในไฟล์ Genesis ว่าขนาด Epoch ควรเป็น `50` บล็อก + +ค่าเริ่มต้นสำหรับขนาดของ Epoch (หน่วยเป็นบล็อก) คือ `100000` + +:::info การลดความยาว Epoch +ตามที่ระบุไว้ในส่วน[บล็อก Epoch](/docs/edge/consensus/pos-concepts#epoch-blocks)จะมีการใช้บล็อก Epoch เพื่ออัปเดตชุดตัวตรวจสอบความถูกต้องสำหรับโหนดต่างๆ + +ความยาว Epoch เริ่มต้นที่มีหน่วยเป็นบล็อก (`100000`) อาจใช้เวลานานในการอัปเดตชุดตัวตรวจสอบความถูกต้องเมื่อพิจารณาว่าการเพิ่มบล็อกใหม่ใช้เวลาประมาณ 2 วินาที อาจใช้เวลาประมาณ 55.5 ชั่วโมงในการเปลี่ยนแปลงชุดตัวตรวจสอบความถูกต้องที่อาจเกิดขึ้น + +การตั้งค่าที่ต่ำกว่าให้กับความยาว Epoch ช่วยให้มั่นใจได้ว่าชุดตัวตรวจสอบความถูกต้องได้รับการอัปเดตบ่อยขึ้น +::: + +## การใช้สคริปต์สัญญาอัจฉริยะการ Stake {#using-the-staking-smart-contract-scripts} + +### ข้อกำหนดเบื้องต้น {#prerequisites} + +พื้นที่เก็บข้อมูลสัญญาอัจฉริยะการ Stake เป็นโปรเจ็กต์ Hardhat ที่ต้องมี NPM + +ในการเริ่มต้นอย่างถูกต้อง ในไดเรกทอรีหลัก ให้เรียกใช้: + +```bash +npm install +```` + +### การตั้งค่าสคริปต์ตัวช่วยที่ให้ไว้ {#setting-up-the-provided-helper-scripts} + +สคริปต์สำหรับโต้ตอบกับสัญญาอัจฉริยะการ Stake ที่ปรับใช้มีอยู่ใน[พื้นที่เก็บข้อมูลสัญญาอัจฉริยะการ Stake](https://github.com/0xPolygon/staking-contracts) + +สร้างไฟล์ `.env` ด้วยพารามิเตอร์ต่อไปนี้ในตำแหน่งพื้นที่เก็บข้อมูลสัญญาอัจฉริยะ: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +โดยที่พารามิเตอร์ต่างๆ คือ: + +* **JSONRPC_URL** - JSON-RPC Endpoint สำหรับโหนดที่เรียกใช้ +* **PRIVATE_KEYS** - คีย์ส่วนตัวของที่อยู่ของผู้วาง Stake +* **STAKING_CONTRACT_ADDRESS** - ที่อยู่ของสัญญาอัจฉริยะการ Stake ( +ค่าเริ่มต้น `0x0000000000000000000000000000000000001001`) +* **BLS_PUBLIC_KEY** - คีย์สาธารณะ BLS ของผู้วาง Stakeจำเป็นเฉพาะเมื่อเครือข่ายทำงานกับ BLS + +### ทุนการ Stake {#staking-funds} + +:::info ที่อยู่การ Stake +ปรับใช้สัญญาอัจฉริยะการ Stake ล่วงหน้าที่ที่อยู่ `0x0000000000000000000000000000000000001001` + +การโต้ตอบประเภทใดก็ตามกับกลไกการ Stake จะทำผ่านสัญญาอัจฉริยะการ Stake ตามที่อยู่ที่ระบุ + +ดูเพิ่มเติมเกี่ยวกับสัญญาอัจฉริยะการ Stake ได้ที่**[สัญญาแบบ Stake](/docs/edge/consensus/pos-concepts#contract-pre-deployment)** +::: + +เพื่อเป็นส่วนหนึ่งของชุดตัวตรวจสอบความถูกต้อง ที่อยู่ต้อง Stake ยอดทุนที่มากกว่าเกณฑ์ที่กำหนด + +ตอนนี้ เกณฑ์เริ่มต้นสำหรับการเป็นส่วนหนึ่งของชุดตัวตรวจสอบความถูกต้องคือ `1 ETH` + +เริ่มต้นการ Stake ได้โดยเรียกเมธอด `stake` ของสัญญาอัจฉริยะการ Stake และระบุค่า `>= 1 ETH` + +หลังจากไฟล์ `.env` ที่กล่าวถึงใน[ส่วนก่อนหน้า](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) ได้รับการตั้งค่า และเริ่มต้นเชนในโหมด PoS แล้ว จะสามารถทำการ Stake ได้ด้วยคำสั่งต่อไปนี้ในพื้นที่เก็บข้อมูลสัญญาอัจฉริยะการ Stake: + +```bash +npm run stake +``` + +`stake`สคริปต์ Hardhat ทำการ Stake จำนวนเงินเริ่มต้นของ `1 ETH` ซึ่งสามารถเปลี่ยนแปลงได้โดยการแก้ไขไฟล์ `scripts/stake.ts` + +หากทุนที่ Stake อยู่ `>= 1 ETH` จะมีการอัปเดตชุดตัวตรวจสอบความถูกต้องในสัญญาอัจฉริยะการ Stake และที่อยู่จะเป็นส่วนหนึ่งของชุดตัวตรวจสอบความถูกต้องตั้งแต่ Epoch ถัดไป + +:::info การลงทะเบียนคีย์ BLS +หากเครือข่ายทำงานในโหมด BLS เพื่อให้โหนดกลายเป็นตัวตรวจสอบความถูกต้อง จะต้องลงทะเบียนคีย์สาธารณะ BLS หลังการ Stake + +ซึ่งสามารถทำได้ด้วยคำสั่งต่อไปนี้: + +```bash +npm run register-blskey +``` +::: + +### การยกเลิกการ Stake ทุน {#unstaking-funds} + +ที่อยู่ที่มี Stake สามารถ**ยกเลิกการ Stake ทุนทั้งหมดของที่อยู่**ได้ครั้งเดียว + +หลังจากไฟล์ `.env` ที่กล่าวถึงใน[ส่วนก่อนหน้านี้](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts)ได้รับการตั้งค่าและเริ่มต้นเชนในโหมด PoS แล้ว จะสามารถทำการยกเลิกการ Stake ได้ด้วยคำสั่งต่อไปนี้ในพื้นที่เก็บข้อมูลสัญญาอัจฉริยะการ Stake: + +```bash +npm run unstake +``` + +### การดึงรายการผู้วาง Stake {#fetching-the-list-of-stakers} + +ที่อยู่ทั้งหมดที่ Stake ทุนจะได้รับการบันทึกไว้ในสัญญาอัจฉริยะการ Stake + +หลังจากไฟล์ `.env` ที่กล่าวถึงใน[ส่วนก่อนหน้านี้](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts)ได้รับการตั้งค่าและเริ่มต้นเชนในโหมด PoS แล้ว จะสามารถทำการดึงรายการตัวตรวจสอบความถูกต้องได้ด้วยคำสั่งต่อไปนี้ในพื้นที่เก็บข้อมูลสัญญาอัจฉริยะการ Stake: + +```bash +npm run info +``` diff --git a/archive/edge/th-edge/faq/Contracts.md b/archive/edge/th-edge/faq/Contracts.md new file mode 100644 index 0000000000..b0fac18848 --- /dev/null +++ b/archive/edge/th-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: คำถามที่พบบ่อยเกี่ยวกับสัญญาอัจฉริยะ +description: "คำถามที่พบบ่อยเกี่ยวกับสัญญาอัจฉริยะ Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## Polygon Edge รองรับสัญญาอัจฉริยะหรือไม่ {#does-polygon-edge-support-smart-contracts} + +รองรับเครือข่าย Polygon Edge เป็นบล็อกเชนที่เข้ากันได้กับ Ethereum ดังนั้นสัญญาอัจฉริยะที่ปรับใช้ได้บน Ethereum จึงปรับใช้ได้เช่นกันบนเชน Polygon Edge + +## คุณอัปเดตลอจิกสัญญาการ Stake สำหรับ PoS หลังการปรับใช้ได้หรือไม่ {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +สำหรับตอนนี้ หลังจากที่คุณได้เริ่มต้นเครือข่าย PoS แล้ว คุณจะไม่สามารถเปลี่ยนลอจิกสัญญาการ Stake เนื่องจากเป็นส่วนหนึ่งของไฟล์ Genesisดังนั้น คุณจึงไม่สามารถทำสิ่งต่างๆ เช่น เปลี่ยนจำนวนตัวตรวจสอบความถูกต้องต่ำสุด/สูงสุดได้สิ่งที่คุณทำได้คือ Stake หรือยกเลิกการ Stake เพิ่มหรือลบตัวตรวจสอบความถูกต้อง + + + diff --git a/archive/edge/th-edge/faq/Gas.md b/archive/edge/th-edge/faq/Gas.md new file mode 100644 index 0000000000..b6ae0dfb6c --- /dev/null +++ b/archive/edge/th-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: คำถามที่พบบ่อยเกี่ยวกับแก๊ส +description: "คำถามที่พบบ่อยเกี่ยวกับแก๊สสำหรับ Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## วิธีการบังคับใช้ราคาแก๊สขั้นต่ำ {#how-to-enforce-a-minimum-gas-price} +คุณสามารถใช้ค่าสถานะ `--price-limit` ที่ให้ไว้ในคำสั่งเซิร์ฟเวอร์การดำเนินการนี้จะบังคับให้โหนดของคุณยอมรับเฉพาะธุรกรรมที่มีค่าแก๊สสูงกว่าหรือเท่ากับราคาที่คุณตั้งไว้ เพื่อให้แน่ใจว่ามีการบังคับใช้กับทั้งเครือข่าย คุณต้องตรวจสอบให้แน่ใจว่าโหนดทั้งหมดมีขีดจำกัดราคาเท่ากัน + + +## คุณสามารถทำธุรกรรมด้วยค่าแก๊สเป็น 0 ได้หรือไม่ {#can-you-have-transactions-with-0-gas-fees} +ใช่ คุณทำได้ขีดจำกัดราคาเริ่มต้นที่โหนดบังคับใช้คือ `0` ซึ่งหมายความว่า โหนดจะยอมรับธุรกรรมที่มีการตั้งค่าราคาแก๊สเป็น `0` + +## วิธีตั้งค่าจำนวนทั้งหมดของโทเค็นสำหรับจ่ายค่าแก๊ส (ดั้งเดิม) {#how-to-set-the-gas-native-token-total-supply} + +คุณสามารถกำหนดยอดคงเหลือที่วางไว้ล่วงหน้าให้กับบัญชี (ที่อยู่) ต่างๆ โดยใช้ `--premine flag`โปรดทราบว่านี่เป็นการกำหนดค่าจากไฟล์ Genesis และไม่สามารถเปลี่ยนแปลงได้ในภายหลัง + +ตัวอย่างวิธีใช้ `--premine flag`: + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +คำสั่งนี้จะกำหนดยอดคงเหลือที่วางไว้ล่วงหน้าที่ 1000 ETH ไปยัง 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862 (ยอดจากอาร์กิวเมนต์มีหน่วยเป็น wei) + +ยอดคงเหลือที่วางไว้ล่วงหน้าของโทเค็นสำหรับจ่ายค่าแก๊สจะเป็นจำนวนทั้งหมดไม่สามารถสร้างสกุลเงินดั้งเดิม (โทเค็นสำหรับจ่ายค่าแก๊ส) ในยอดอื่นๆ ได้ภายหลัง + +## Edge รองรับ ERC-20 เป็นโทเค็นสำหรับจ่ายค่าแก๊สหรือไม่ {#does-edge-support-erc-20-as-a-gas-token} + +Edge ไม่รองรับโทเค็น ERC-20 เป็นโทเค็นสำหรับจ่ายค่าแก๊สรองรับเฉพาะสกุลเงิน Edge ดั้งเดิมสำหรับแก๊ส + +## วิธีเพิ่มขีด จำกัด ของแก๊สอย่างไร {#how-to-increase-the-gas-limit} + +มีสองตัวเลือกสำหรับการเพิ่มขีดจำกัดของแก๊สใน Polygon Edge: +1. การเชื่อมต่อเชน และเพิ่ม`block-gas-limit`ค่ายูเอ็นที64 สูงสุดในไฟล์ Genesis +2. ใช้`--block-gas-target`แฟล็กกับค่าสูงเพื่อเพิ่มขีดจำกัดของโหนดทั้งหมดนี้ต้องใช้รีบูต์โหนดคำอธิบายโดยละเอียด[ที่นี่](/docs/edge/architecture/modules/txpool/#block-gas-target) \ No newline at end of file diff --git a/archive/edge/th-edge/faq/Tokens.md b/archive/edge/th-edge/faq/Tokens.md new file mode 100644 index 0000000000..4d39ad0226 --- /dev/null +++ b/archive/edge/th-edge/faq/Tokens.md @@ -0,0 +1,22 @@ +--- +id: tokens +title: คำถามที่พบบ่อยเกี่ยวกับโทเค็น +description: "คำถามที่พบบ่อยสำหรับโทเค็น Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## Polygon Edge รองรับ EIP-1559 หรือไม่ {#does-polygon-edge-support-eip-1559} +ในขณะนี้ Polygon Edge ไม่รองรับ EIP-1559 + +## วิธีกำหนดสัญลักษณ์สกุลเงิน (โทเค็น) {#how-to-set-the-currency-token-symbol} + +สัญลักษณ์โทเค็นเป็นเพียง UI ดังนั้นจึงไม่สามารถกำหนดค่าหรือฮาร์ดโค้ดได้ในเครือข่ายแต่คุณเปลี่ยนได้ เมื่อคุณเพิ่มเครือข่ายลงในวอลเล็ต เช่น Metamask + +## จะเกิดอะไรขึ้นกับการดำเนินการเมื่อปุ่มสำหรับโซ่? {#what-happens-to-transactions-when-a-chain-halts} + +ธุรกรรมทั้งหมดที่ยังไม่ผ่านการประมวลผลจะอยู่ในระบบ Txsool (เข้าสู่คิวหรือเลื่อนขั้น)หากครึ่งเชน (หยุดการผลิตบล็อกทั้งหมด) ธุรกรรมเหล่านี้จะไม่เข้าสู่บล็อก
นี่ไม่ใช่แค่กรณีเมื่อปุ่มสำหรับเชนหากโหนดถูกหยุดหรือรีสตาร์ทใหม่ ธุรกรรมทั้งหมดที่ยังไม่ได้รับการดำเนินการและจะยังอยู่ใน Txpool จะถูกลบออกอย่างเงียบสนิท
สิ่งเดียวกันจะเกิดขึ้นกับธุรกรรมเมื่อมีการเปลี่ยนแปลงการเปลี่ยนแปลงแล้ว เนื่องจากจำเป็นสำหรับโหนดเพื่อเริ่มการทำงานใหม่ diff --git a/archive/edge/th-edge/faq/Validators.md b/archive/edge/th-edge/faq/Validators.md new file mode 100644 index 0000000000..4305c75b66 --- /dev/null +++ b/archive/edge/th-edge/faq/Validators.md @@ -0,0 +1,85 @@ +--- +id: validators +title: คำถามที่พบบ่อยเกี่ยวกับตัวตรวจสอบความถูกต้อง +description: "คำถามที่พบบ่อยสำหรับตัวตรวจสอบความถูกต้องของ Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## วิธีการเพิ่ม/ถอนตัวตรวจสอบความถูกต้องมีอะไรบ้าง {#how-to-add-remove-a-validator} + +### PoA {#poa} +มีการเพิ่ม/ถอนตัวตรวจสอบความถูกต้องด้วยการโหวต คุณสามารถค้นหาคู่มือฉบับเต็มที่เกี่ยวกับเรื่องนี้ได้[ที่นี่](/docs/edge/consensus/poa) + +### PoS {#pos} +คุณสามารถค้นหาคู่มือเกี่ยวกับวิธีการ Stake ทุนได้[ที่นี่](/docs/edge/consensus/pos-stake-unstake) เพื่อให้โหนดสามารถกลายเป็นตัวตรวจสอบความถูกต้อง และวิธียกเลิกการ Stake (ถอนตัวตรวจสอบความถูกต้อง) + +หมายเหตุ: +- คุณสามารถใช้ค่าสถานะ Genesis `--max-validator-count` เพื่อตั้งค่าจำนวนสูงสุดของผู้วาง Stake ที่สามารถเข้าร่วมในชุดตัวตรวจสอบความถูกต้องได้ +- คุณสามารถใช้ค่าสถานะ Genesis `--min-validator-count ` เพื่อตั้งค่าจำนวนขั้นต่ำของผู้วาง Stake ที่จำเป็นต้องเข้าร่วมชุดตัวตรวจสอบความถูกต้อง (`1` เป็นค่าเริ่มต้น) +- เมื่อตัวตรวจสอบความถูกต้องถึงจำนวนสูงสุดแล้ว คุณจะไม่สามารถเพิ่มตัวตรวจสอบความถูกต้องอื่นได้ จนกว่าคุณจะถอนตัวตรวจสอบความถูกต้องที่มีอยู่ในชุดออก (โดยไม่สนใจว่า ยอดที่ Stake ของตัวตรวจสอบความถูกต้องใหม่นั้นสูงกว่าหรือไม่)หากคุณถอนตัวตรวจสอบความถูกต้อง จำนวนตัวตรวจสอบความถูกต้องที่เหลือต้องไม่น้อยกว่า `--min-validator-count` +- มีขีดจำกัดเริ่มต้นของหน่วยสกุลเงินในเครือข่ายดั้งเดิม (ค่าแก๊ส) ซึ่งใช้ในการกลายเป็นตัวตรวจสอบความถูกต้องอยู่ที่ `1` + + + +## คุณแนะนำให้ตัวตรวจสอบความถูกต้องต้องมีพื้นที่ในดิสก์เท่าใด {#how-much-disk-space-is-recommended-for-a-validator} + +เราแนะนำให้เริ่มด้วย 100G ซึ่งเป็น Runway โดยประมาณที่ใช้เป็นหลัก และทำให้มั่นใจว่าเรายังสามารถปรับขนาดดิสก์ในภายหลังได้ + + +## มีขีดจำกัดเกี่ยวกับจำนวนตัวตรวจสอบความถูกต้องหรือไม่ {#is-there-a-limit-to-the-number-of-validators} + +หากเราพูดถึงข้อจำกัดทางเทคนิค Polygon Edge ไม่มีขีดจำกัดอย่างแน่นอนในส่วนจำนวนโหนดที่คุณสามารถมีได้ในเครือข่ายคุณสามารถตั้งค่าขีดจำกัด (จำนวนการเชื่อมต่อภายใน / ภายนอก) โดยใช้จำนวนต่อโหนดเป็นหลัก + +หากเราพูดถึงข้อจำกัดทางการปฏิบัติ คุณจะพบว่าประสิทธิภาพลดลงในกรณีคุณมีกลุ่มโหนดจำนวน 100 โหนด ถ้าเปรียบเทียบกับกลุ่มโหนดจำนวน 10 โหนดการเพิ่มจำนวนโหนดในกลุ่ม จะเป็นการเพิ่มความซับซ้อนในการสื่อสาร และโดยทั่วไปแล้ว เป็นการทำให้เครือข่ายทำงานเกินความสามารถเท่านั้นทั้งนี้ขึ้นอยู่กับประเภทเครือข่ายที่คุณเรียกใช้และรูปแบบการเชื่อมต่อของเครือข่ายนั้น + +## วิธีการเปลี่ยน PoA เป็น PoS มีอะไรบ้าง {#how-to-switch-from-poa-to-pos} + +PoA เป็นกลไกฉันทามติเริ่มต้น เพื่อให้คลัสเตอร์ใหม่สามารถเปลี่ยนไปใช้ PoS ได้ คุณจะต้องเพิ่มค่าสถานะ `--pos` ในขณะสร้างไฟล์ Genesisหากคุณมีคลัสเตอร์ซึ่งอยู่ในระหว่างการใช้งาน คุณสามารถค้นหาวิธีการเปลี่ยนได้[ที่นี่](/docs/edge/consensus/migration-to-pos)คุณสามารถดูข้อมูลทั้งหมดที่คุณต้องรู้เกี่ยวกับกลไกฉันทามติของเราและการกำหนดค่าได้ในส่วน[ฉันทามติ](/docs/edge/consensus/poa) + +## ฉันสามารถอัปเดตโหนดของฉันได้อย่างไร เมื่อมีการเปลี่ยนแปลงที่ส่งผลกระทบ {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +คุณสามารถค้นหาคู่มืออย่างละเอียดเกี่ยวกับวิธีการนี้ได้[ที่นี่](/docs/edge/validator-hosting#update) + +## PoS Edge อนุญาตให้กำหนดค่าการ Stake ขั้นต่ำได้หรือไม่ {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +ค่าเริ่มต้นสำหรับยอดการ Stake ขั้นต่ำอยู่ที่ `1 ETH` โดยไม่สามารถกำหนดค่านั้นเองได้ + +## ทำไมคำสั่ง JSON RPC `eth_getBlockByNumber` และ `eth_getBlockByHash` ไม่ส่งกลับที่อยู่ของผู้ขุด {#not-return-the-miner-s-address} + +ฉันทามติ ซึ่ง Polygon Edge ใช้ในปัจจุบัน คือ IBFT 2.0 ซึ่งวางอยู่บนกลไกการโหวตซึ่งระบุไว้ใน Clique PoA: [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225) + +เมื่อเราตรวจสอบ EIP-225 (Clique PoA) เห็นว่าเป็นส่วนที่เกี่ยวข้องซึ่งอธิบายเป้าหมายในการใช้ `miner` (หรือ `beneficiary`) + +
+เราเปลี่ยนวัตถุประสงค์ในฟิลด์หัวข้อ Ethash ดังต่อไปนี้: +
    +
  • beneficiary / miner: ที่อยู่ซึ่งใช้ในการเสนอการแก้ไขรายการผู้ลงนามซึ่งได้รับอนุญาต
  • +
      +
    • ควรทำการเขียนทับด้วยค่าศูนย์ตามปกติ โดยแก้ไขได้เฉพาะในขณะการโหวตเท่านั้น
    • +
    • อย่างไรก็ตาม สามารถใช้ค่าแบบกำหนดเอง (แม้แต่ค่าที่ไม่มีความหมายก็ตาม เช่น voting out non signers) เพื่อป้องกันไม่ให้เกิดความสับสนเพิ่มเติมในการนำไปใช้ส่วนที่เกี่ยวกับกลไกการโหวต
    • +
    • ต้องทำการเขียนทับด้วยค่าศูนย์ในบล็อกเช็คพอยต์ (เช่น การย้าย Epoch)
    • +
    + +
+ +
+ +ดังนั้น ฟิลด์ `miner` จะได้รับการนำไปใช้เพื่อเสนอการโหวตสำหรับที่อยู่เฉพาะ โดยไม่ต้องแสดงผู้เสนอบล็อก + +ค้นหาข้อมูลเกี่ยวกับผู้เสนอบล็อกได้โดยการกู้คืน pubkey จากฟิลด์ Seal ของฟิลด์สำหรับข้อมูลเพิ่มเติมของ Istanbul ซึ่งใช้การเข้ารหัส RLP ในหัวข้อของบล็อก + +## ส่วนไหนและค่าของ Genesis สามารถแก้ไขได้อย่างปลอดภัยได้ {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +โปรดตรวจสอบให้แน่ใจว่าสร้างสำเนาด้วยตนเองของแฟ้ม Genesis.json ที่มีอยู่ก่อนที่จะพยายามแก้ไขมัน นอกจากนี้ จึงต้องหยุดอีกก่อนที่จะแก้ไขไฟล์ Genesis.jsonเมื่อมีการแก้ไขไฟล์ Genesis รุ่นใหม่ของ จึงต้องแจกจ่ายทั่วโหนดตัวตรวจสอบความถูกต้องและโหนดตัวตรวจสอบความถูกต้องทั้งหมด + +::: + +**เฉพาะส่วนโหนด ของแฟ้ม Genesis ที่สามารถแก้ไขได้อย่างปลอดภัยโดยเฉพาะ** ซึ่งคุณสามารถเพิ่มหรือลบโหนดออกจากรายการ \ No newline at end of file diff --git a/archive/edge/th-edge/get-started/cli-commands.md b/archive/edge/th-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..0ec53ae0c5 --- /dev/null +++ b/archive/edge/th-edge/get-started/cli-commands.md @@ -0,0 +1,2204 @@ +--- +id: cli-commands +title: คำสั่ง CLI +description: "รายการคำสั่ง CLI และค่าสถานะคำสั่งสำหรับ Polygon Edge" +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +ส่วนนี้ให้รายละเอียดคำสั่งปัจจุบัน ค่าสถานะคำสั่งใน Polygon Edge และวิธีใช้งาน + +:::tip การรองรับเอาต์พุต JSON + +รองรับค่าสถานะ `--json` บนบางคำสั่งค่าสถานะนี้สั่งให้คำสั่งพิมพ์เอาต์พุตในรูปแบบ JSON + +::: + +## คำสั่งเริ่มต้น {#startup-commands} + +| **คำสั่ง** | **คำอธิบาย** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| server | คำสั่งเริ่มต้นที่เริ่มต้นไคลเอ็นต์บล็อกเชน โดยการเริ่มต้นโมดูลทั้งหมดพร้อมกัน | +| genesis | สร้างไฟล์ *genesis.json* ซึ่งใช้ในการตั้งค่าสถานะเชนที่กำหนดไว้ล่วงหน้าก่อนเริ่มไคลเอ็นต์มีคำอธิบายโครงสร้างของไฟล์ Genesis ด้านล่าง | +| genesis | นำสัญญาอัจฉริยะสำหรับเครือข่ายใหม่ | + +### แฟล็กเซิร์ฟเวอร์ {#server-flags} + + +| **แฟล็ก ของเซิร์ฟเวอร์** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [Prometheus](/docs/edge/get-started/cli-commands#prometheus) | [block-gas-target](/docs/edge/get-started/cli-commands#block-gas-target) | +| [max-peers](/docs/edge/get-started/cli-commands#max-peers) | [max-inbound-peers](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [max-outbound-peers](/docs/edge/get-started/cli-commands#max-outbound-peers) | [max-enqueued](/docs/edge/get-started/cli-commands#max-enqueued) | +| [log-level](/docs/edge/get-started/cli-commands#log-level) | [log-to](/docs/edge/get-started/cli-commands#log-to) | +| [เชน](/docs/edge/get-started/cli-commands#chain) | [เข้าร่วม](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [ขีดจำกัดราคา](/docs/edge/get-started/cli-commands#price-limit) | [สล็อตสูงสุด](/docs/edge/get-started/cli-commands#max-slots) | +| [การกำหนดค่า](/docs/edge/get-started/cli-commands#config) | [secrets-config](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-interval](/docs/edge/get-started/cli-commands#dev-interval) | +| [no-discover](/docs/edge/get-started/cli-commands#no-discover) | [กู้คืน](/docs/edge/get-started/cli-commands#restore) | +| [block-time](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +ใช้เพื่อระบุไดเรกทอรีข้อมูลที่ใช้สำหรับจัดเก็บข้อมูลไคลเอ็นต์ Polygon Edge ค่าเริ่มต้น: `./test-chain` + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +ตั้งค่าที่อยู่และพอร์ตสำหรับบริการ JSON-RPC `address:port` หากมีการกำหนดเฉพาะพอร์ต `:10001` บริการจะผูกกับอินเทอร์เฟซทั้งหมด `0.0.0.0:10001` +หากไม่ระบุ บริการจะผูกกับ `address:port` ที่เป็นค่าเริ่มต้น ที่อยู่ตามค่าเริ่มต้น: `0.0.0.0:8545` + +--- + +####

json-rpc-block-range-limit + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +ตั้งค่าช่วงบล็อกสูงสุดเพื่อพิจารณาเมื่อทำการประมวลผลคำขอของ json-rpc ซึ่งรวมจากค่า Bock/toBlock (เช่น eth_getLogs) ขีดจำกัดนี้สามารถปิดการทำงานได้อย่างสมบูรณ์ได้โดยตั้งค่าค่า`0`ไปยังค่าเริ่มต้น: `1000` + +--- + +####

json-rpc-batch-request-limit + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +ตั้งค่าความยาวสูงสุดที่จะถูกพิจารณาเมื่อจัดการการร้องขอชุดของ json - rpcขีดจำกัดนี้สามารถปิดการทำงานได้อย่างสมบูรณ์ได้โดยตั้งค่าค่า`0`ไปยังค่าเริ่มต้น: `20` + +--- + +####

grpc + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +ตั้งค่าที่อยู่และพอร์ตสำหรับบริการ gRPC `address:port`ที่อยู่ตามค่าเริ่มต้น: `127.0.0.1:9632` + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +ตั้งค่าที่อยู่และพอร์ตสำหรับบริการ libp2p `address:port`ที่อยู่ตามค่าเริ่มต้น: `127.0.0.1:1478` + +--- + +####

prometheus + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +ตั้งค่าที่อยู่และพอร์ตสำหรับเซิร์ฟเวอร์ Prometheus `address:port` +หากมีการกำหนดเฉพาะพอร์ต `:5001` บริการจะผูกกับอินเทอร์เฟซทั้งหมด `0.0.0.0:5001` หากไม่ระบุ บริการจะไม่เริ่มทำงาน + +--- + +####

block-gas-target + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +ตั้งค่าขีดจำกัดค่าแก๊สต่อบล็อกเป้าหมายสำหรับเชนค่าเริ่มต้น (ไม่บังคับ): `0` + +ดูคำอธิบายโดยละเอียดเพิ่มเติมเกี่ยวกับเป้าหมายค่าแก๊สต่อบล็อกได้ใน[ส่วน TxPool](/docs/edge/architecture/modules/txpool#block-gas-target) + +--- + +####

max-peers + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +ตั้งค่าจำนวนเพียร์สูงสุดของไคลเอ็นต์ค่าเริ่มต้น: `40` + +ควรระบุขีดจำกัดเพียร์โดยใช้ค่าสถานะ `max-peers` หรือ `max-inbound/outbound-peers` + +--- + +####

max-inbound-peers + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +ตั้งค่าจำนวนเพียร์ขาเข้าสูงสุดของไคลเอ็นต์หากตั้งค่า `max-peers` ขีดจำกัด max-inbound-peer จะได้รับการคำนวณโดยใช้สูตรต่อไปนี้ + +`max-inbound-peer = InboundRatio * max-peers` โดย `InboundRatio` คือ `0.8` + +--- + +####

max-outbound-peers + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +ตั้งค่าจำนวนเพียร์ขาออกสูงสุดของไคลเอ็นต์หากตั้งค่า `max-peers` จำนวน max-outbound-peer จะได้รับการคำนวณโดยใช้สูตรต่อไปนี้ + +`max-outbound-peer = OutboundRatio * max-peers` โดย `OutboundRatio` คือ `0.2` + +--- + +####

max-enqueued + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +ตั้งค่าจำนวนสูงสุดของธุรกรรมในคิวต่อหนึ่งบัญชีค่าเริ่มต้น: `128` + +--- + +####

log-level + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +ตั้งค่าระดับบันทึกสำหรับคอนโซลเอาต์พุตค่าเริ่มต้น: `INFO` + +--- + +####

log-to + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +กำหนดชื่อไฟล์บันทึกที่จะเก็บเอาต์พุตบันทึกทั้งหมดจากคำสั่งเซิร์ฟเวอร์ตามค่าเริ่มต้น จะมีการส่งข้อมูลบันทึกเซิร์ฟเวอร์ทั้งหมดไปยังคอนโซล (stdout)แต่ถ้าตั้งค่าสถานะไว้ จะไม่มีเอาต์พุตไปยังคอนโซลเมื่อเรียกใช้คำสั่งเซิร์ฟเวอร์ + +--- + +####

chain + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +ระบุไฟล์ Genesis ที่ใช้สำหรับเริ่มเชนค่าเริ่มต้น: `./genesis.json` + +--- + +####

join + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +ระบุที่อยู่ของเพียร์ที่ควรเข้าร่วม + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +ตั้งค่าที่อยู่ IP ภายนอกโดยไม่มีพอร์ตตามที่เพียร์สามารถเห็น + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +ตั้งค่าที่อยู่ DNS โฮสต์ซึ่งสามารถใช้เพื่อโฆษณา DNS ภายนอกรองรับ `dns`,`dns4`,`dns6` + +--- + +####

ขีดจำกัดราคา + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +ตั้งค่าขีดจำกัดราคาแก๊สขั้นต่ำเพื่อบังคับใช้สำหรับการยอมรับในพูลเริ่มต้น: `1` + +--- + +####

สล็อตสูงสุด + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +ตั้งสล็อตสูงสุดในพูลค่าเริ่มต้น: `4096` + +--- + +####

การกำหนดค่า + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +ระบุพาธไปยังการกำหนดค่า CLIรองรับ `.json` + +--- + +####

secrets-config + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +ตั้งค่าพาธไปยังไฟล์กำหนดค่า SecretsManagerใช้สำหรับ Hashicorp Vaul, AWS SSM และ GCP Secrets Managerหากไม่ระบุ จะมีการใช้ตัวจัดการข้อมูลลับ FS ภายใน + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +ตั้งค่าไคลเอ็นต์เป็นโหมด devค่าปริยาย`false`:ในโหมด dev การค้นพบ Peer จะถูกปิดการทำงานโดยค่าปริยาย + +--- + +####

dev-interval + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +ตั้งค่าช่วงแจ้งเตือน dev ของไคลเอ็นต์ หน่วยเป็นวินาทีค่าเริ่มต้น: `0` + +--- + +####

no-discover + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +ป้องกันไคลเอ็นต์ไม่ให้ค้นพบเพียร์อื่นๆค่าเริ่มต้น: `false` + +--- + +####

restore + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +กู้คืนบล็อกจากไฟล์เก็บถาวรที่ระบุ + +--- + +####

block-time + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +ตั้งค่าเวลาในการสร้างบล็อก หน่วยเป็นวินาทีค่าเริ่มต้น: `2` + +--- + +####

access-control-allow-origins + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +ตั้งค่าโดเมนที่ได้รับอนุญาตให้สามารถแชร์การตอบสนองจากคำขอ JSON-RPC +เพิ่มหลายค่าสถานะ `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"` เพื่ออนุญาตหลายโดเมน +หากไม่ระบุ จะกำหนดส่วนหัว Access-Control-Allow-Origins เป็น `*` และโดเมนทั้งหมดจะได้รับอนุญาต + +--- + +### แฟล็ก Genesis {#genesis-flags} +| **แฟล็ก Genesis** | +|---------------------------------------|---------------------------------------------| +| [dir](/docs/edge/get-started/cli-commands#dir) | [ชื่อ](/docs/edge/get-started/cli-commands#name) | +| [pos](/docs/edge/get-started/cli-commands#pos) | [epoch-size](/docs/edge/get-started/cli-commands#epoch-size) | +| [วางล่วงหน้า](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [ibft-validator-type](/docs/edge/get-started/cli-commands#ibft-validator-type) | [ibft-validators-prefix-path](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [ibft-validator](/docs/edge/get-started/cli-commands#ibft-validator) | [block-gas-limit](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [ฉันทามติ](/docs/edge/get-started/cli-commands#consensus) | [bootnode](/docs/edge/get-started/cli-commands#bootnode) | +| [max-validator-count](/docs/edge/get-started/cli-commands#max-validator-count) | [min-validator-count](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

dir + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +ตั้งค่าไดเรกทอรีสำหรับข้อมูล Genesis บน Polygon Edge ค่าเริ่มต้น: `./genesis.json` + +--- + +####

ชื่อ + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +ตั้งชื่อให้กับเชนค่าเริ่มต้น: `polygon-edge` + +--- + +####

pos + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +ตั้งค่าค่าสถานะที่ระบุว่าไคลเอ็นต์ควรใช้ IBFT แบบ Proof of Stakeตั้งค่าเริ่มต้นเป็น Proof of Authority หากไม่ได้ให้ค่าสถานะไว้หรือมีค่าเป็น `false` + +--- + +####

epoch-size + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +ตั้งค่าขนาด Epoch สำหรับเชนค่าเริ่มต้น `100000` + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +ตั้งค่าบัญชีและยอดคงเหลือที่วางไว้ล่วงหน้าในรูปแบบ `address:amount`จำนวนสามารถเป็นทศนิยมหรือฐานสิบหกสมดุลที่กำหนดล่วงหน้า: (โทเค็นแบบดั้งเดิม`0xD3C21BCECCEDA1000000`1 ล้าน) + +--- + +####

chainid + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +ตั้งค่า ID ของเชนค่าเริ่มต้น: `100` + +--- + +####

ibft-validator-type + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +ระบุโหมดการตรวจสอบความถูกต้องของส่วนหัวบล็อกค่าที่เป็นไปได้: `[ecdsa, bls]`ค่าเริ่มต้น: `bls` + +--- + +####

ibft-validators-prefix-path + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +พาธนำหน้าสำหรับไดเรกทอรีโฟลเดอร์ตัวตรวจสอบความถูกต้องจำเป็นต้องมี หากเว้นค่าสถานะ `ibft-validator` ไว้ + +--- + +####

ibft-validator + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +ตั้งค่าที่อยู่ที่ส่งผ่านเป็นตัวตรวจสอบความถูกต้อง IBFTจำเป็นต้องมี หากเว้นค่าสถานะ `ibft-validators-prefix-path` ไว้ +1. หากเครือข่ายทำงานด้วย ECDSA รูปแบบจะเป็น `--ibft-validator [ADDRESS]` +2. หากเครือข่ายทำงานด้วย BLS รูปแบบจะเป็น `--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]` + +--- + +####

block-gas-limit + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +หมายถึงปริมาณแก๊สสูงสุดที่การดำเนินการทั้งหมดในบล็อกใช้ค่าเริ่มต้น: `5242880` + +--- + +####

consensus + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +ตั้งค่าโปรโตคอลฉันทามติค่าเริ่มต้น: `pow` + +--- + +####

bootnode + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Multiaddr URL สำหรับการเริ่มต้นระบบการค้นพบ p2pใช้ค่าสถานะนี้ได้หลายครั้งคุณสามารถระบุที่อยู่ DNS ของบูตโหนด แทนที่อยู่ IP ได้ + +--- + +####

max-validator-count + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +จำนวนผู้วาง Stake สูงสุดที่สามารถเข้าร่วมชุดตัวตรวจสอบความถูกต้องตามฉันทามติ PoSตัวเลขนี้ต้องไม่เกินค่า MAX_SAFE_INTEGER (2^53 - 2) + +--- + +####

min-validator-count + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +จำนวนผู้วาง Stake ขั้นต่ำที่จำเป็นในการเข้าร่วมชุดตัวตรวจสอบความถูกต้องตามฉันทามติ PoSจำนวนนี้ต้องไม่เกินค่าของ max-validator-countค่าเริ่มต้นเป็น 1. + +--- + +### genesis ปรับใช้เบื้องต้นแฟล็ก {#genesis-predeploy-flags} + +

เส้นทางของวัตถุ

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +ตั้งค่าพาธไปยังวัตถุสำหรับสัญญา`abi`ที่มีค่า JSON `bytecode`และ`deployedBytecode` + +--- + +

chain

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +ตั้งค่าพาธไปยัง`genesis.json`แฟ้มที่ควรจะมีการอัปเดตค่าเริ่มต้น `./genesis.json` + +--- + +

ตัวสร้างอาร์ตเตอร์

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +ตั้งค่าอาร์กิวเมนต์ตัวสร้างสัญญาแบบ Smart หากมีสำหรับคู่มือโดยละเอียดเกี่ยวกับวิธีการอาร์กิวเมนต์เหล่านี้ควรมีลักษณะอย่างไร โปรดอ้างอิง[บทความการเคลื่อนไหว](/docs/edge/additional-features/predeployment) + +--- + +

ที่อยู่ก่อนการใช้

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +ตั้งค่าที่อยู่เพื่อปรับใช้ไปยังการตั้งค่าดั้งเดิมค่าเริ่มต้น `0x0000000000000000000000000000000000001100` + +--- + + +## คำสั่งของผู้ดำเนินการ {#operator-commands} + +### คำสั่งของเพียร์ {#peer-commands} + +| **คำสั่ง** | **คำอธิบาย** | +|------------------------|-------------------------------------------------------------------------------------| +| peers add | เพิ่มเพียร์ใหม่โดยใช้ที่อยู่ libp2p ของพวกเขา | +| peers list | รายการเพียร์ทั้งหมดที่เชื่อมต่อกับไคลเอ็นต์ผ่าน libp2p | +| peers status | ส่งกลับสถานะของเพียร์เฉพาะจากรายการเพียร์ โดยใช้ที่อยู่ libp2p | + +

ค่าสถานะ peers add

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +ที่อยู่ libp2p ของเพียร์ในรูปแบบ multiaddr + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +ที่อยู่ของ gRPC APIค่าเริ่มต้น: `127.0.0.1:9632` + +

ค่าสถานะ peers list

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +ที่อยู่ของ gRPC APIค่าเริ่มต้น: `127.0.0.1:9632` + +

ค่าสถานะ peers status

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +ID โหนด Libp2p ของเพียร์เฉพาะภายในเครือข่าย p2p + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +ที่อยู่ของ gRPC APIค่าเริ่มต้น: `127.0.0.1:9632` + +### คำสั่ง IBFT {#ibft-commands} + +| **คำสั่ง** | **คำอธิบาย** | +|------------------------|-------------------------------------------------------------------------------------| +| ibft snapshot | ส่งกลับสแนปชอต IBFT | +| ibft candidates | ค้นหาชุดผู้สมัครที่เสนอปัจจุบัน เช่นเดียวกับผู้สมัครที่ยังไม่ได้รวม | +| ibft propose | เสนอผู้สมัครใหม่ที่จะเพิ่ม/ลบออกจากชุดตัวตรวจสอบความถูกต้อง | +| ibft status | ส่งกลับสถานะโดยรวมของไคลเอ็นต์ IBFT | +| ibft switch | เพิ่มการกำหนดค่า Fork ไปยังไฟล์ genesis.json เพื่อสลับประเภท IBFT | +| ibft quorum | ระบุหมายเลขบล็อกที่จะใช้เมธอด optimal quorum size เพื่อให้ได้ฉันทามติหลังหลังจากนั้น | + + +

ค่าสถานะ ibft snapshot

+ +

number

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +ความสูงของบล็อก (ตัวเลข) สำหรับสแนปชอต + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +ที่อยู่ของ gRPC APIค่าเริ่มต้น: `127.0.0.1:9632` + +

ค่าสถานะ ibft candidates

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +ที่อยู่ของ gRPC APIค่าเริ่มต้น: `127.0.0.1:9632` + +

ค่าสถานะ ibft propose

+ +

vote

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +เสนอการเปลี่ยนแปลงชุดตัวตรวจสอบความถูกต้อง ค่าที่เป็นไปได้: `[auth, drop]` + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +ที่อยู่ของบัญชีที่จะลงคะแนนให้ + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +คีย์สาธารณะ BLS ของบัญชีที่จะลงคะแนนให้ ซึ่งจำเป็นเฉพาะในโหมด BLS + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +ที่อยู่ของ gRPC APIค่าเริ่มต้น: `127.0.0.1:9632` + +

ค่าสถานะ ibft status

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +ที่อยู่ของ gRPC APIค่าเริ่มต้น: `127.0.0.1:9632` + +

ibft switch flags

+ +

chain

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +ระบุไฟล์ Genesis เพื่ออัปเดตค่าเริ่มต้น: `./genesis.json` + +--- + +

ประเภท

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +ระบุประเภท IBFT เพื่อสลับค่าที่เป็นไปได้: `[PoA, PoS]` + +--- + +

deployment

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +ระบุความสูงของการปรับใช้สัญญาพร้อมใช้งานกับ PoS เท่านั้น + +--- + +

from

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +ระบุโหมดการตรวจสอบความถูกต้องของส่วนหัวบล็อกค่าที่เป็นไปได้: `[ecdsa, bls]`ค่าเริ่มต้น: `bls` + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +พาธนำหน้าสำหรับไดเรกทอรีของตัวตรวจสอบความถูกต้องใหม่จำเป็นต้องมี หากเว้นค่าสถานะ `ibft-validator` ไว้ใช้ได้เฉพาะเมื่อโหมด IBFT เป็น PoA (เว้นค่าสถานะ `--pos` ไว้) + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +ชุดที่ส่งผ่านในที่อยู่เป็นตัวตรวจสอบความถูกต้อง IBFT ที่ใช้หลัง Forkจำเป็นต้องมี หากเว้นค่าสถานะ `ibft-validators-prefix-path` ไว้พร้อมใช้งานในโหมด PoA เท่านั้น +1. หากเครือข่ายทำงานด้วย ECDSA รูปแบบจะเป็น `--ibft-validator [ADDRESS]` +2. หากเครือข่ายทำงานด้วย BLS รูปแบบจะเป็น `--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]` + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +จำนวนผู้วาง Stake สูงสุดที่สามารถเข้าร่วมชุดตัวตรวจสอบความถูกต้องตามฉันทามติ PoSตัวเลขนี้ต้องไม่เกินค่า MAX_SAFE_INTEGER (2^53 - 2) + +--- + +

min-validator-count

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +จำนวนผู้วาง Stake ขั้นต่ำที่จำเป็นในการเข้าร่วมชุดตัวตรวจสอบความถูกต้องตามฉันทามติ PoSจำนวนนี้ต้องไม่เกินค่าของ max-validator-countค่าเริ่มต้นเป็น 1 + +ระบุความสูงเริ่มต้นของ Fork + +--- + +

ค่าสถานะ ibft quorum

+ +

from

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +ความสูงที่จะสลับการคำนวณ Quorum เป็น QuorumOptimal ซึ่งใช้สูตร `(2/3 * N)` โดยที่ `N` เป็นจำนวนโหนดตัวตรวจสอบความถูกต้องโปรดทราบว่าสิ่งนี้มีไว้สำหรับความเข้ากันได้แบบย้อนหลัง กล่าวคือ มีไว้สำหรับเชนที่ใช้การคำนวณแบบเดิมของ Quorum จนถึงความสูงบล็อกที่แน่นอนเท่านั้น + +--- + +

chain

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +ระบุไฟล์ Genesis เพื่ออัปเดตค่าเริ่มต้น: `./genesis.json` + +### คำสั่งพูลธุรกรรม {#transaction-pool-commands} + +| **คำสั่ง** | **คำอธิบาย** | +|------------------------|--------------------------------------------------------------------------------------| +| txpool status | ส่งกลับจำนวนธุรกรรมในพูล | +| txpool subscribe | สมัครติดตามอีเวนต์ในพูลธุรกรรม | + +

ค่าสถานะ txpool status

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +ที่อยู่ของ gRPC APIค่าเริ่มต้น: `127.0.0.1:9632` + +

ค่าสถานะ txpool subscribe

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +ที่อยู่ของ gRPC APIค่าเริ่มต้น: `127.0.0.1:9632` + +--- + +

promoted

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +สมัครติดตามอีเวนต์ธุรกรรมที่ปรับให้เผยแพร่ได้ใน TxPool + +--- + +

dropped

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +สมัครติดตามอีเวนต์ธุรกรรมที่ดรอปใน TxPool + +--- + +

demoted

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +สมัครติดตามอีเวนต์ธุรกรรมที่ปรับกลับไปเป็นธุรกรรมภายในของ TxPool + +--- + +

added

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +สมัครติดตามอีเวนต์ธุรกรรมที่เพิ่มไปยัง TxPool + +--- + +

enqueued

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +สมัครติดตามอีเวนต์ธุรกรรมที่เข้าคิวในคิวบัญชี + +--- + +### คำสั่งบล็อกเชน {#blockchain-commands} + +| **คำสั่ง** | **คำอธิบาย** | +|------------------------|-------------------------------------------------------------------------------------| +| status | ส่งกลับสถานะของไคลเอ็นต์ดูการตอบกลับโดยละเอียดได้ที่ด้านล่าง | +| monitor | สมัครติดตามอีเวนต์สตรีมของบล็อกเชนดูการตอบกลับโดยละเอียดได้ที่ด้านล่าง | +| version | ส่งกลับเวอร์ชันปัจจุบันของไคลเอ็นต์ | + +

ค่าสถานะ status

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +ที่อยู่ของ gRPC APIค่าเริ่มต้น: `127.0.0.1:9632` + +

ค่าสถานะ monitor

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +ที่อยู่ของ gRPC APIค่าเริ่มต้น: `127.0.0.1:9632` + +--- +

คำสั่งของเวอร์ชัน

+ + + + + + version + + + + +แสดงเวอร์ชั่นปล่อย, แบรนช์ git , count and building + +## คำสั่ง Secrets {#secrets-commands} + +| **คำสั่ง** | **คำอธิบาย** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| secrets init | เริ่มต้นคีย์ส่วนตัวไปยังตัวจัดการข้อมูลลับที่เกี่ยวข้อง | +| secrets generate | สร้างไฟล์การกำหนดค่าตัวจัดการความลับ ซึ่งสามารถแยกวิเคราะห์โดย Polygon Edge | +| ออกข้อมูลลับ | พิมพ์ที่อยู่ของคีย์สาธารณะ BS ที่อยู่ของตัวตรวจสอบความถูกต้องและโหนดสำหรับการอ้างอิง | + +### แฟล็ก secrets init {#secrets-init-flags} + +

การกำหนดค่า

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +ตั้งค่าพาธไปยังไฟล์กำหนดค่า SecretsManagerใช้สำหรับ Hashicorp Vaultหากไม่ระบุ จะมีการใช้ตัวจัดการข้อมูลลับ FS ภายใน + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +ตั้งค่าไดเรกทอรีสำหรับข้อมูล Polygon Edge หากใช้ FS ภายใน + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +ตั้งค่าค่าสถานะที่ระบุว่าจะสร้างคีย์ ECDSA หรือไม่ค่าเริ่มต้น: `true` + +--- + +

network

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +ตั้งค่าค่าสถานะที่ระบุว่าจะสร้างคีย์เครือข่าย Libp2p หรือไม่ค่าเริ่มต้น: `true` + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +ตั้งค่าค่าสถานะที่ระบุว่าจะสร้างคีย์ BLS หรือไม่ค่าเริ่มต้น: `true` + +### ค่าสถานะ secrets generate {#secrets-generate-flags} + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +ตั้งค่าไดเรกทอรีสำหรับไฟล์การกำหนดค่าตัวจัดการข้อมูลลับ ค่าเริ่มต้น: `./secretsManagerConfig.json` + +--- + +

ประเภท

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +ระบุประเภทตัวจัดการข้อมูลลับ [`hashicorp-vault`]ค่าเริ่มต้น: `hashicorp-vault` + +--- + +

token

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +ระบุโทเค็นเข้าถึงบริการ + +--- + +

server-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +ระบุ URL เซิร์ฟเวอร์สำหรับบริการ + +--- + +

name

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +ระบุชื่อของโหนดสำหรับการเก็บบันทึกบนบริการค่าเริ่มต้น: `polygon-edge-node` + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +ระบุเนมสเปซที่ใช้สำหรับตัวจัดการข้อมูลลับของ Hashicorp Vaultค่าเริ่มต้น: `admin` + +### แฟล็กของลับ {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +ตั้งค่าแฟล็กที่ระบุว่าจะส่งคีย์สาธารณะของ BS เท่านั้นค่าเริ่มต้น: `true` + +--- + +

การกำหนดค่า

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +ตั้งค่าพาธไปยังไฟล์กำหนดค่า SecretsManagerหากไม่ระบุ ตัวจัดการความลับ FS ในเครื่องจะถูกใช้ + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +ตั้งค่าไดเรกทอรีสำหรับข้อมูล Polygon Edge หากใช้ FS ภายใน + +--- + +

node-id

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +ตั้งค่าสถานะที่ระบุว่าจะส่งหมายเลขโหนดของเครือข่ายค่าเริ่มต้น: `true` + +--- + +

ตัวตรวจสอบความถูกต้อง

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +ตั้งค่าสถานะที่ระบุว่าจะส่งเพียงที่อยู่ตัวตรวจสอบความถูกต้องหรือไม่ค่าเริ่มต้น: `true` + +--- + +## การตอบกลับ {#responses} + +### การตอบกลับสถานะ {#status-response} + +นิยามอ็อบเจ็กต์การตอบกลับโดยใช้ Protocol Buffers +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### การตอบกลับการติดตาม {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## ยูทิลิตี้ {#utilities} + +### คำสั่ง whitelist {#whitelist-commands} + +| **คำสั่ง** | **คำอธิบาย** | +|------------------------|-------------------------------------------------------------------------------------| +| whitelist show | แสดงข้อมูลไวท์ลิสต์ | +| whitelist deployment | อัปเดตไวท์ลิสต์การปรับใช้สัญญาอัจฉริยะ | + +

whitelist show

+ + + + + whitelist show + + + + +แสดงข้อมูลไวท์ลิสต์ + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +ระบุไฟล์ Genesis เพื่ออัปเดตค่าเริ่มต้น: `./genesis.json` + +--- + +

whitelist deployment

+ +

chain

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +ระบุไฟล์ Genesis เพื่ออัปเดตค่าเริ่มต้น: `./genesis.json` + +--- + +

เพิ่ม

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +เพิ่มที่อยู่ใหม่ไปยังไวท์ลิสต์การปรับใช้สัญญาเฉพาะที่อยู่ในไวท์ลิสต์การปรับใช้สัญญาเท่านั้นที่ปรับใช้สัญญาได้หากว่างเปล่า ที่อยู่ใดๆ สามารถดำเนินการปรับใช้สัญญาได้ + +--- + +

remove

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +ลบที่อยู่ออกจากไวท์ลิสต์การปรับใช้สัญญาเฉพาะที่อยู่ในไวท์ลิสต์การปรับใช้สัญญาเท่านั้นที่ปรับใช้สัญญาได้หากว่างเปล่า ที่อยู่ใดๆ สามารถดำเนินการปรับใช้สัญญาได้ + +--- + +### ค่าสถานะ backup {#backup-flags} + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +ที่อยู่ของ gRPC APIค่าเริ่มต้น: `127.0.0.1:9632` + +--- + +

out

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +พาธของไฟล์เก็บถาวรที่จะบันทึก + +--- + +

from

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +ความสูงเริ่มต้นของบล็อกในหน่วยเก็บถาวรค่าเริ่มต้น: 0 + +--- + +

to

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +ความสูงสิ้นสุดของบล็อกในหน่วยเก็บถาวร + +--- + +## เทมเพลต Genesis {#genesis-template} +ต้องใช้ไฟล์ Genesis เพื่อกำหนดสถานะเริ่มต้นของบล็อกเชน (เช่น บางบัญชีควรมียอดคงเหลือเริ่มต้นหรือไม่) + +ไฟล์ *./genesis.json* ต่อไปนี้จะได้รับการสร้างขึ้น: +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### ไดเรกทอรีข้อมูล {#data-directory} + +เมื่อดำเนินการค่าสถานะ *data-dir* จะมีการสร้างโฟลเดอร์ **test-chain** ขึ้นโครงสร้างโฟลเดอร์ประกอบด้วยโฟลเดอร์ย่อยต่อไปนี้: +* **blockchain** - จัดเก็บ LevelDB ให้กับอ็อบเจ็กต์บล็อกเชน +* **trie** - จัดเก็บ LevelDB ให้กับ Merkle Trie +* **keystore** - จัดเก็บคีย์ส่วนตัวให้กับไคลเอ็นต์รวมถึงคีย์ส่วนตัว libp2p และคีย์ส่วนตัวการซีล/ตัวตรวจสอบความถูกต้อง +* **consensus** - จัดเก็บข้อมูลฉันทามติที่ไคลเอ็นต์อาจต้องใช้ในการดำเนินงาน + +## แหล่งข้อมูล {#resources} +* **[Protocol Buffers](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/th-edge/get-started/installation.md b/archive/edge/th-edge/get-started/installation.md new file mode 100644 index 0000000000..6b9b590563 --- /dev/null +++ b/archive/edge/th-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: การติดตั้ง +description: "วิธีการติดตั้ง Polygon Edge" +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +โปรดเลือกวิธีการติดตั้งที่คุณสามารถใช้ได้อย่างสะดวก + +เราขอแนะนำให้คุณใช้รุ่นที่สร้างไว้ล่วงหน้าและตรวจสอบ checksum ต่างๆ ที่ให้ไว้ + +## รุ่นที่สร้างไว้ล่วงหน้า {#pre-built-releases} + +โปรดดูรายการเวอร์ชันที่หน้า[รุ่นต่างๆ ของ GitHub](https://github.com/0xPolygon/polygon-edge/releases) + +Polygon Edge ประกอบด้วยไบนารี AMD64/ARM64 แบบข้ามสถาปัตยกรรมซึ่งสามารถใช้ได้ทั้งกับ Darwin และ Linux + +--- + +## อิมเมจ Docker {#docker-image} + +มีอิมเมจ Docker อย่างเป็นทางการอยู่ใน[รีจิสทรี hub.docker.com](https://hub.docker.com/r/0xpolygon/polygon-edge) + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## สร้างจากต้นฉบับ {#building-from-source} + +ก่อนใช้ `go install` ตรวจสอบให้แน่ใจว่าคุณได้ติดตั้ง Go `>=1.18` และกำหนดค่าอย่างถูกต้องแล้ว + +สาขาที่มั่นคงคือสาขาของรุ่นล่าสุด + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## การใช้ `go install` + +ก่อนใช้ `go install` ตรวจสอบให้แน่ใจว่าคุณได้ติดตั้ง Go `>=1.17` และกำหนดค่าอย่างถูกต้องแล้ว + +`go install github.com/0xPolygon/polygon-edge@release/` + +จะมีไบนารีใน`GOBIN`ตัวแปรแวดล้อม ของคุณ และจะรวมการเปลี่ยนแปลงจากรุ่นล่าสุดคุณสามารถเช็คเอาท์แบบ [GitHub ได้ Release Release](https://github.com/0xPolygon/polygon-edge/releases) เพื่อค้นหาว่าอันไหนเป็นตัวเลือกที่ช้าที่สุด diff --git a/archive/edge/th-edge/get-started/set-up-ibft-locally.md b/archive/edge/th-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..d1d7641658 --- /dev/null +++ b/archive/edge/th-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,335 @@ +--- +id: set-up-ibft-locally +title: การตั้งค่าภายใน +description: "คู่มือการตั้งค่าภายในแบบเป็นขั้นตอน" +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution คู่มือนี้มีไว้สำหรับวัตถุประสงค์ในการทดสอบเท่านั้น + +คู่มือด้านล่างจะแนะนำวิธีตั้งค่าเครือข่าย Polygon Edge ในอุปกรณ์ภายในของคุณเพื่อวัตถุประสงค์ในการทดสอบและพัฒนา + +กระบวนการแตกต่างอย่างมากจากวิธีที่คุณต้องการตั้งค่าเครือข่าย Polygon Edge สำหรับสถานการณ์การใช้งานจริงบนผู้ให้บริการคลาวด์: **[การตั้งค่า Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud)** + +::: + + +## ข้อกำหนด {#requirements} + +ดู[การติดตั้ง](/docs/edge/get-started/installation)เพื่อติดตั้ง Polygon Edge + +## ภาพรวม {#overview} + +![การตั้งค่าภายใน](/img/edge/ibft-setup/local.svg) + +ในคู่มือนี้ เป้าหมายของเราคือการสร้างเครือข่ายบล็อกเชน `polygon-edge` ที่ใช้งานได้และใช้ได้กับ[โปรโตคอลฉันทามติ IBFT](https://github.com/ethereum/EIPs/issues/650)เครือข่ายบล็อกเชนจะประกอบด้วยโหนดจำนวน 4 โหนด ซึ่งเป็นโหนดตัวตรวจสอบความถูกต้องทั้งหมด จึงสามารถคัดเลือกได้ทั้งเพื่อเสนอบล็อกและตรวจสอบความถูกต้องของบล็อกซึ่งรับมาจากผู้เสนออื่นๆทั้ง 4 โหนดจะทำงานบนเครื่องเดียวกัน เนื่องจากแนวคิดของคู่มือนี้คือเพื่อให้คุณมีคลัสเตอร์ IBFT ที่ทำงานได้อย่างสมบูรณ์ในระยะเวลาน้อยที่สุด + +เพื่อให้บรรลุเป้าหมายนั้น เราจะให้คำแนะนำกับคุณผ่าน 4 ขั้นตอนง่ายๆ ดังต่อไปนี้: + +1. การเริ่มต้นไดเรกทอรีข้อมูลจะสร้างคีย์ตัวตรวจสอบความถูกต้องทั้งสองคีย์ให้กับแต่ละโหนดจาก 4 โหนด และเริ่มต้นไดเรกทอรีข้อมูลบล็อกเชนที่ว่างเปล่าคีย์ตัวตรวจสอบความถูกต้องมีความสำคัญ เนื่องจากเราจำเป็นต้องเริ่มต้นระบบบล็อก Genesis ด้วยชุดตัวตรวจสอบความถูกต้องเริ่มต้น โดยใช้คีย์เหล่านี้ +2. การเตรียมสตริงการเชื่อมต่อสำหรับบูตโหนดจะเป็นข้อมูลที่สำคัญสำหรับทุกโหนดที่เราจะเรียกใช้ ในส่วนที่ว่าจะเชื่อมต่อกับโหนดใดเมื่อเริ่มต้นครั้งแรก +3. การสร้างไฟล์ `genesis.json` จะต้องมีการใช้ทั้งคีย์ตัวตรวจสอบความถูกต้องที่สร้างขึ้นใน**ขั้นตอนที่ 1** ที่ใช้สำหรับการตั้งค่าตัวตรวจสอบความถูกต้องเริ่มต้นของเครือข่ายในบล็อก Genesis และสตริงการเชื่อมต่อบูตโหนดจาก**ขั้นตอนที่ 2** เป็นอินพุต +4. การเรียกใช้โหนดทั้งหมดเป็นเป้าหมายสุดท้ายของคู่มือนี้ และจะเป็นขั้นตอนสุดท้ายที่เราทำ เราจะแนะนำโหนดว่าจะใช้ไดเรกทอรีข้อมูลใด และตำแหน่งที่จะค้นหา `genesis.json` ซึ่งเริ่มต้นสถานะเครือข่ายเบื้องต้น + +เนื่องจากทั้งสี่โหนดจะทำงานบน localhost จึงคาดว่า ในระหว่างกระบวนการตั้งค่า ไดเรกทอรีข้อมูลทั้งหมดสำหรับแต่ละโหนดจะอยู่ในไดเรกทอรีหลักเดียวกัน + +:::info จำนวนตัวตรวจสอบความถูกต้อง + +ไม่มีขั้นต่ำของจำนวนโหนดในคลัสเตอร์ กล่าวคือ คุณสามารถใช้คลัสเตอร์ที่ประกอบด้วยโหนดตัวตรวจสอบความถูกต้องเพียงโหนดเดียวได้โปรดจำไว้ว่า หากคุณใช้คลัสเตอร์ที่ประกอบด้วยโหนด_เดียว_ จะ**ไม่มีการทนทานต่อการหยุดทำงาน**และ**ไม่มีการรับประกัน BFT** + +จำนวนโหนดขั้นต่ำที่แนะนำเพื่อให้ได้รับการรับประกันจาก BFT อยู่ที่ 4 โหนด เนื่องจากในคลัสเตอร์ที่ประกอบด้วย 4 โหนด การขัดข้องของโหนด 1 โหนดยังสามารถยอมให้เกิดขึ้นได้ โดยมีโหนดอีก 3 โหนดซึ่งใช้งานโดยปกติ + +::: + +## ขั้นตอนที่ 1: เริ่มต้นโฟลเดอร์ข้อมูลสำหรับ IBFT และสร้างคีย์ตัวตรวจสอบความถูกต้อง {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +ในการเริ่มต้นใช้งาน IBFT คุณต้องเริ่มต้นโฟลเดอร์ข้อมูลหนึ่งโฟลเดอร์สำหรับแต่ละโหนด: + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +คำสั่งเหล่านี้แต่ละคำสั่งจะพิมพ์คีย์ตัวตรวจสอบความถูกต้อง คีย์สาธารณะ bls และ [ID โหนด](https://docs.libp2p.io/concepts/peer-id/) คุณจะต้องใช้ ID โหนดสำหรับโหนดรายแรกเพื่อสามารถดำเนินตามขั้นตอนถัดไป + +### เอารหัสออก {#outputting-secrets} +สามารถเรียกเก็บเอาต์พุตของลับได้อีกหากจำเป็น + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## ขั้นตอนที่ 2: เตรียมสตริงการเชื่อมต่อ multiaddr สำหรับบูตโหนด {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +เพื่อให้โหนดสร้างการเชื่อมต่อได้สำเร็จ จะต้องรู้ว่าจะเชื่อมต่อกับเซิร์ฟเวอร์ `bootnode` ใดเพื่อให้ได้ให้ได้ข้อมูลเกี่ยวกับโหนดทั้งหมดที่เหลืออยู่ในเครือข่าย `bootnode` ซึ่งบางที่เรียกว่าเซิร์ฟเวอร์ `rendezvous` ตามคำศัพท์พิเศษของ p2p + +`bootnode`ไม่ใช่ตัวสำรองของ โหนด Polygon - edgeโหนด Polygon-edge ทุกโหนด สามารถใช้เป็น`bootnode`โหนด แต่ทุกโหนด Polygon Edge ต้องมีชุดบูตโหนดที่ระบุ ซึ่งจะได้รับการติดต่อเพื่อให้ข้อมูลเกี่ยวกับวิธีเชื่อมต่อโหนดทั้งหมดที่เหลืออยู่ในเครือข่าย + +เพื่อสร้างสตริงการเชื่อมต่อเพื่อระบุบูตโหนด เราจะต้องใช้[รูปแบบ multaddr](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +ในคู่มือนี้ เราจะใช้โหนดแรกและโหนดที่สองเป็นบูตโหนดสำหรับโหนดที่เหลือทั้งหมดสิ่งที่เกิดขึ้นในสถานการณ์นี้คือบรรดาโหนดที่เชื่อมต่อกับ `node 1` หรือ `node 2` จะได้รับข้อมูลเกี่ยวกับวิธีการเชื่อมต่อกันและกันผ่านการใช้บูตโหนดที่ได้ติดต่อร่วมกัน + +:::info คุณต้องระบุบูตโหนดอย่างน้อยหนึ่งโหนดเพื่อเริ่มใช้โหนด + +ต้องมีบูตโหนดอย่างน้อย**หนึ่ง**โหนด เพื่อทำให้โหนดอื่นๆ ในเครือข่ายสามารถค้นหากันได้แนะนำให้ใช้บูตโหนดมากขึ้น เนื่องจากให้ความสามารถในการฟื้นฟูกับเครือข่ายในกรณีที่เกิดการขัดข้องในคู่มือนี้ เราจะระบุสองโหนด แต่คุณสามารถทำการเปลี่ยนแปลงได้ในระหว่างการดำเนินการ โดยจะไม่ส่งผลกระทบต่อความสมบูรณ์ของไฟล์ `genesis.json` + +::: + +เนื่องจากเราทำงานบน localhost เราจึงคาดเดาได้ว่า `` คือ `127.0.0.1` + +สำหรับ `` เราจะใช้ `10001` เนื่องจากเราจะกำหนดค่าเซิร์ฟเวอร์ libp2p สำหรับ `node 1` เพื่อรอรับคำสั่งในพอร์ตนี้ในภายหลัง + +สุดท้ายแล้ว เราต้องการ `` ซึ่งเราสามารถได้รับจากเอาต์พุตคำสั่งที่เรียกใช้มาก่อน ได้แก่ คำสั่ง `polygon-edge secrets init --data-dir test-chain-1` (ซึ่งเราได้ใช้เพื่อสร้างคีย์และไดเรกทอรีข้อมูลสำหรับ `node1`) + +หลังจากมีการประกอบแล้ว สตริงการเชื่อมต่อ multiaddr ซึ่งใช้กับ `node 1` ที่เราจะใช้เป็นบูตโหนด จะมีลักษณะเช่นนี้ (เพียงแต่ `` ในปลายทางต้องมีค่าอื่น): +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +ในทางเดียวกัน เราสร้าง multiaddr สำหรับบูตโหนดที่สอง ตามที่ระบุไว้ด้านล่าง +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info ชื่อโฮสต์ DNS ที่ใช้แทน IP + +Polygon Edge รองรับการใช้ชื่อโฮสต์ DNS สำหรับการกำหนดค่าโหนดนี่เป็นคุณสมบัติที่มีประโยชน์มากสำหรับการปรับใช้ในระบบคลาวด์ เนื่องจาก IP ของโหนดอาจเปลี่ยนได้ด้วยหลายสาเหตุ + +รูปแบบ multiaddr ซึ่งใช้สำหรับสตริงการเชื่อมต่อในระหว่างการใช้ชื่อโฮสต์ DNS ตามที่ปรากฏไว้ดังต่อไปนี้:`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## ขั้นตอนที่ 3: สร้างไฟล์ genesis ที่มีโหนดจำนวน 4 โหนดเป็นตัวตรวจสอบความถูกต้อง {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +สิ่งที่คำสั่งนี้ทำ: + +* `--ibft-validators-prefix-path` กำหนดพาธโฟลเดอร์นำหน้าไปยังพาธที่ระบุ ซึ่ง IBFT ใน Polygon Edge สามารถใช้งานได้ใช้ไดเรกทอรีนี้เพื่อสร้างโฟลเดอร์ `consensus/` ซึ่งเก็บคีย์ส่วนตัวของตัวตรวจสอบความถูกต้องไว้ ต้องใช้คีย์สาธารณะของตัวตรวจสอบความถูกต้องเพื่อสร้างไฟล์ Genesis ซึ่งเป็นรายการเริ่มต้นของโหนดการเริ่มต้นระบบค่าสถานะนี้ใช้ได้ก็ต่อเมื่อตั้งค่าเครือข่ายบน localhost เนื่องจากในสถานการณ์จริง เราไม่สามารถคาดหวังว่าไดเรกทอรีข้อมูลทั้งหมดของโหนดจะอยู่ในระบบไฟล์เดียวกัน ซึ่งเราสามารถอ่านคีย์สาธารณะได้อย่างง่ายดาย +* `--bootnode` กำหนดที่อยู่ของบูตโหนด ซึ่งจะทำให้โหนดสามารถค้นหากันเองได้ +เราจะใช้สตริง multiaddr ของ `node 1` ตามที่กล่าวถึงใน**ขั้นตอนที่ 2** + +ผลลัพธ์ของคำสั่งนี้คือไฟล์ `genesis.json` ซึ่งมีบล็อก Genesis ของบล็อกเชนใหม่ของเรา พร้อมด้วยชุดตัวตรวจสอบความถูกต้องที่กำหนดไว้ล่วงหน้า และการกำหนดค่าสำหรับโหนดที่จะติดต่อก่อนเพื่อสร้างการเชื่อมต่อ + +:::info สลับไปยัง ECDSA + +BLS คือโหมดการตรวจสอบความถูกต้องเริ่มต้นของตัวต่อเนื่องของบล็อกหากคุณต้องการให้เชนของคุณทำงานในโหมด ECDSA คุณสามารถใช้`—ibft-validator-type`แฟล็ก ด้วยอาร์กิวเมนต์`ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info บัญชียอดคงเหลือแบบ Premining + +คุณอาจต้องการตั้งค่าเครือข่ายบล็อกเชนของคุณโดยให้ที่อยู่บางส่วนมียอดคงเหลือ "ที่วางไว้ล่วงหน้า" + +ในการดำเนินการนี้ ให้ส่งผ่านค่าสถานะ `--premine` ต่างๆ ตามที่คุณต้องการไปยังแต่ละที่อยู่ที่คุณต้องการให้เริ่มต้นด้วยยอดคงเหลือที่กำหนดในบล็อกเชน + +ตัวอย่างเช่น หากเราต้องการวาง 1000 ETH ไว้ล่วงหน้าให้กับที่อยู่ `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` ในบล็อก genesis ของเรา เราจึงต้องเสนออาร์กิวเมนต์ดังต่อไปนี้: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**โปรดทราบว่าจำนวนที่วางไว้ล่วงหน้า มีหน่วยเป็น WEI ไม่ใช่ ETH** + +::: + +:::info กำหนดขีดจำกัดค่าแก๊สต่อบล็อก + +ขีดจำกัดค่าแก๊สเริ่มต้นในแต่ละบล็อกอยู่ที่ `5242880`มีการเขียนค่านี้เขียนไว้ในไฟล์ genesis แต่คุณอาจต้องการเพิ่ม / ลดค่านั้น + +เพื่อดำเนินการเช่นนั้น คุณสามารถใช้ค่าสถานะ `--block-gas-limit` ตามด้วยค่าที่จำเป็นต้องใช้ ตามที่ระบุไว้ด้านล่าง : + +```shell +--block-gas-limit 1000000000 +``` +::: + +:::info กำหนดขีดจำกัดของ File Descriptor ของระบบ + +ขีดจำกัดตัวอธิบายของไฟล์ปริยาย (จำนวนสูงสุดของไฟล์ที่เปิด) สามารถใช้ได้ต่ำและบน Linux ทุกอย่างคือไฟล์หากคาดว่าจะมีโหนดที่มีแบบผ่านมาตรฐาน คุณสามารถพิจารณาเพิ่มขีดจำกัดนี้ได้ตรวจสอบเอกสารอย่างเป็นทางการของเลเวโดของคุณเพื่อหารายละเอียดเพิ่มเติม + +#### ตรวจสอบขีดจำกัดปัจจุบันของระบบปฏิบัติการ (ไฟล์ที่เปิดอยู่) {#check-current-os-limits-open-files} +```shell title="ulimit -n" +1024 # Ubuntu default +``` + +#### เพิ่มขีดจำกัดสำหรับไฟล์ที่เปิดอยู่ {#increase-open-files-limit} +- วิ่ง`polygon-edge`บนหน้าผา (shel) + ```shell title="Set FD limit for the current session" + ulimit -n 65535 # affects only current session, limit won't persist after logging out + ``` + + ```shell title="Edit /etc/security/limits.conf" + # add the following lines to the end of the file to modify FD limits + * soft nofile 65535 # sets FD soft limit for all users + * hard nofile 65535 # sets FD hard limit for all users + + # End of file + ``` +บันทึกไฟล์และรีสตาร์ทระบบด้วย + +- การใช้งาน`polygon-edge`ในพื้นหลังเป็นบริการ + +หาก`polygon-edge`ทำงานเป็นบริการระบบโดยใช้เครื่องมือเช่น ขีดจำกัดตัวอธิบาย`systemd`ไฟล์Nameควรมีการจัดการโดยใช้`systemd`ระบบ + ```shell title="Edit /etc/systemd/system/polygon-edge.service" + [Service] + ... + LimitNOFILE=65535 + ``` + +### การแก้ไขปัญหา {#troubleshooting} +```shell title="Watch FD limits of polygon edge running process" +watch -n 1 "ls /proc/$(pidof polygon-edge)/fd | wc -l" +``` + +```shell title="Check max FD limits for polygon-edge running process" +cat /proc/$(pidof polygon-edge)/limits +``` +::: + + +## ขั้นตอนที่ 4: เรียกใช้ไคลเอ็นต์ทั้งหมด {#step-4-run-all-the-clients} + +เนื่องจากเรากำลังพยายามเรียกใช้เครือข่าย Polygon Edge ที่ประกอบด้วยโหนด 4 โหนดที่ต่างอยู่ในเครื่องเดียวกัน เราจึงต้องระมัดระวังเพื่อหลีกเลี่ยงปัญหาพอร์ตที่ขัดแย้งกันนี่คือเหตุผลที่เราจะใช้การให้เหตุผลต่อไปนี้ในการกำหนดพอร์ตรอรับการสื่อสารของแต่ละเซิร์ฟเวอร์ของโหนด: + +- `10000` สำหรับเซิร์ฟเวอร์ gRPC ของ `node 1`, `20000` สำหรับเซิร์ฟเวอร์ GRPC ของ `node 2` เป็นต้น +- `10001` สำหรับเซิร์ฟเวอร์ libp2p ของ `node 1`, `20001` สำหรับเซิร์ฟเวอร์ libp2p ของ `node 2` เป็นต้น +- `10002` สำหรับเซิร์ฟเวอร์ JSON-RPC ของ `node 1`, `20002` สำหรับเซิร์ฟเวอร์ JSON-RPC ของ `node 2` เป็นต้น + +ในการเรียกใช้ไคลเอ็นต์**แรก** (บันทึกพอร์ต `10001` ไว้ เนื่องจากจะมีการใช้เป็นส่วนหนึ่งของ libp2p multiaddr ใน**ขั้นตอนที่ 2** ควบคู่ไปกับ ID โหนดของ node 1: + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +ในการเรียกใช้ไคลเอ็นต์**ที่สอง**: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +ในการเรียกใช้ไคลเอ็นต์**ที่สาม**: + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +ในการเรียกใช้ไคลเอ็นต์**ที่สี่**: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +เพื่อสรุปสิ่งที่ได้ทำไปแล้วโดยสังเขป: + +* ไดเรกทอรีสำหรับข้อมูลไคลเอ็นต์ได้รับการระบุเป็น **./test-chain-\*** +* เซิร์ฟเวอร์ GRPC เริ่มทำงานบนพอร์ต **10000**, **20000**, **30000** และ **40000** สำหรับแต่ละโหนดตามลำดับ +* เซิร์ฟเวอร์ libp2p เริ่มทำงานบนพอร์ต **10001**, **20001**, **30001** และ **40001** สำหรับแต่ละโหนดตามลำดับ +* เซิร์ฟเวอร์ JSON-RPC เริ่มทำงานบนพอร์ต **10002**, **20002**, **30002** และ **40002** สำหรับแต่ละโหนดตามลำดับ +* ค่าสถานะ *seal* หมายความว่าโหนดที่กำลังเริ่มต้นกำลังจะเข้าร่วมในการซีลบล็อก +* ค่าสถานะ *chain* ระบุว่าควรใช้ไฟล์ Genesis ใดสำหรับการกำหนดค่าเชน + +เนื้อหาเกี่ยวกับโครงสร้างของไฟล์ genesis อยู่ในส่วน[คำสั่ง CLI](/docs/edge/get-started/cli-commands) + +หลังจากเรียกใช้คำสั่งก่อนหน้าหน้า คุณได้กำหนดเครือข่าย Polygon Edge ซึ่งประกอบด้วย 4 โหนด ที่สามารถซีลบล็อกและคืนค่า +จากกรณีโหนดล้มเหลว + +:::info เริ่มใช้ไคลเอ็นต์โดยใช้ไฟล์กำหนดค่า + +แทนที่จะระบุพารามิเตอร์การกำหนดค่าทั้งหมดเป็นอาร์กิวเมนต์ CLI เรายังสามารถเริ่มต้นไคลเอ็นต์ผ่านการใช้ไฟล์กำหนดค่า โดยให้เรียกใช้คำสั่งดังต่อไปนี้: + +````bash +polygon-edge server --config +```` +ตัวอย่าง: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +ปัจจุบัน เรารองรับ`yaml`และไฟล์การตั้งค่า`json`ตามฐาน สามารถค้นหาไฟล์การตั้งค่าตัวอย่าง **[ได้ที่นี่](/docs/edge/configuration/sample-config)** + +::: + +:::info ขั้นต่างๆ ในการเรียกใช้โหนดที่ไม่ใช่โหนดผู้ตรวจสอบ + +โหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้องจะซิงค์บรรดาบล็อกล่าสุดที่ได้รับมาจากโหนดตัวตรวจสอบความถูกต้อง คุณสามารถเริ่มโหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้องโดยเรียกใช้คำสั่งดังต่อไปนี้ + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +ตัวอย่างเช่น คุณสามารถเพิ่มไคลเอ็นต์ที่ไม่ใช่ไคลเอ็นต์ตัวตรวจสอบความถูกต้องตัว**ที่ห้า**ได้ โดยการเรียกใช้คำสั่งดังต่อไปนี้ : + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info กำหนดขีดจำกัดราคา +เริ่มต้นโหนด Polygon Edge ได้ด้วย**ขีดจำกัดราคา**ที่กำหนดค่าไว้สำหรับธุรกรรมที่เข้ามา + +หน่วยที่ใช้สำหรับขีดจำกัดราคาคือ `wei` + +การกำหนดขีดจำกัดราคาหมายความว่า ธุรกรรมใดๆ ที่ดำเนินการโดยโหนดปัจจุบันจะต้องมีราคาแก๊ส**สูงกว่า**ขีดจำกัดราคาที่กำหนดไว้ มิฉะนั้นจะไม่รวมอยู่ในบล็อก + +การที่โหนดส่วนใหญ่ยอมรับขีดจำกัดราคาที่กำหนดจะทำให้เกิดบังคับใช้กฎที่ระบุว่าธุรกรรมในเครือข่ายต้องไม่ต่ำกว่าขีดจำกัดราคาที่กำหนด + +ค่าเริ่มต้นสำหรับขีดจำกัดราคาคือ `0` หมายความว่า ตามค่าเริ่มต้น จะไม่มีการบังคับใช้เลย + +ตัวอย่างการใช้ค่าสถานะ `--price-limit`: +````bash +polygon-edge server --price-limit 100000 ... +```` + +โปรดจำไว้ว่า ขีดจำกัดราคาจะ**ได้รับการบังคับใช้กับธุรกรรมที่ไม่ใช่ธุรกรรมภายในเท่านั้น** หมายความว่าขีดจำกัดราคาจะไม่นำมาใช้กับธุรกรรมที่เพิ่มเป็นการภายในกับโหนด +::: + +:::info WebSocket URL +ตามค่าเริ่มต้น เมื่อคุณเรียกใช้ Polygon Edge จะมีการสร้าง WebSocket URL โดยใช้ที่ตั้งของเชนเป็นหลักใช้โครงสร้าง URL `wss://` ใช้กับลิงก์ HTTPS และ `ws://` สำหรับ HTTP + +Localhost WebSocket URL: +````bash +ws://localhost:10002/ws +```` +โปรดจำไว้ว่าหมายเลขพอร์ตขึ้นอยู่กับพอร์ต JSON-RPC ที่คุณได้เลือกไว้สำหรับโหนดดังกล่าว + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## ขั้นตอนที่ 5: โต้ตอบกับเครือข่าย polygon-edge {#step-5-interact-with-the-polygon-edge-network} + +คุณได้ตั้งค่าไคลเอ็นต์ที่ทำงานอยู่ไว้อย่างน้อย 1 ไคลเอ็นต์ ตอนนี้คุณสามารถดำเนินการต่อและโต้ตอบกับบล็อกเชนโดยใช้บัญชีที่คุณวางไว้ล่วงหน้าข้างต้นและโดยระบุ JSON-RPC URL ไปยังโหนดใดโหนดหนึ่งจาก 4 โหนด: +- Node 1: `http://localhost:10002` +- Node 2: `http://localhost:20002` +- Node 3: `http://localhost:30002` +- Node 4: `http://localhost:40002` + +ปฏิบัติตามคู่มือนี้เพื่อออกคำสั่งสำหรับตัวดำเนินการไปยังคลัสเตอร์ที่สร้างขึ้นใหม่: [วิธีค้นหาข้อมูลตัวดำเนินการ](/docs/edge/working-with-node/query-operator-info) (พอร์ต GRPC สำหรับคลัสเตอร์ที่เราสร้างคือ `10000`/`20000`/`30000`/`40000` สำหรับแต่ละโหนด ตามลำดับ) diff --git a/archive/edge/th-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/th-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..775ad86029 --- /dev/null +++ b/archive/edge/th-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,364 @@ +--- +id: set-up-ibft-on-the-cloud +title: การตั้งค่าในระบบคลาวด์ +description: "คู่มือการตั้งค่าในระบบคลาวด์แบบทีละขั้นตอน" +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info คู่มือฉบับนี้ใช้ได้สำหรับการตั้งค่า Mainnet หรือ Testnet + +คู่มือดังต่อไปนี้จะให้คำแนะนำกับคุณเกี่ยวกับวิธีการตั้งค่าเครือข่าย Polygon Edge ในผู้ให้บริการคลาวด์ เพื่อตั้งค่า Testnet หรือ Mainnet ของคุณไว้สำหรับการใช้งานจริง + +หากคุณต้องการตั้งค่าเครือข่าย Polygon Edge ภายในเพื่อทดสอบ `polygon-edge` อย่างรวดเร็ว ก่อนดำเนินการตั้งค่าแบบใช้งานจริง โปรดไปยัง +**[ตั้งค่าแบบท้องถิ่น](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## ข้อกำหนด {#requirements} + +โปรดดู[การติดตั้ง](/docs/edge/get-started/installation)เพื่อติดตั้ง Polygon Edge + +### การตั้งการเชื่อมต่อ VM {#setting-up-the-vm-connectivity} + +ตามผู้ให้บริการคลาวด์ที่คุณเลือก คุณอาจตั้งค่าการเชื่อมต่อและกฎระหว่าง VM ต่างๆ โดยใช้ไฟร์วอลล์ +กลุ่มความปลอดภัย หรือรายการควบคุมการเข้าถึง + +เนื่องจากส่วนของ `polygon-edge` ที่ต้องแสดงต่อ VM อื่นๆ มีเพียงแค่เซิร์ฟเวอร์ libp2p เพียงเท่านั้น ดังนั้น เพียงอนุญาตให้ +มีการสื่อสารระหว่าง VM ต่างๆ ในพอร์ตเริ่มต้น libp2p `1478` ก็พอแล้ว + +## ภาพรวม {#overview} + +![การตั้งค่าในระบบคลาวด์](/img/edge/ibft-setup/cloud.svg) + +ในคู่มือนี้ เป้าหมายของเราคือการสร้างเครือข่ายบล็อกเชน `polygon-edge` ที่ใช้งานได้และใช้ได้กับ[โปรโตคอลฉันทามติ IBFT](https://github.com/ethereum/EIPs/issues/650) +เครือข่ายบล็อกเชนจะประกอบด้วยโหนดจำนวน 4 โหนด ซึ่งเป็นโหนดตัวตรวจสอบความถูกต้องทั้งหมด จึงสามารถคัดเลือกได้ทั้งเพื่อเสนอบล็อกและตรวจสอบความถูกต้องของบล็อกซึ่งรับมาจากผู้เสนออื่นๆโหนดแต่ละโหนดจากทั้งหมด 4 โหนดจะเรียกใช้ VM ของตัวเอง เนื่องจากวัตถุประสงค์ของคู่มือฉบับนี้คือ การให้เครือข่าย Polygon Edge ที่สามารถใช้งานได้เต็มรูปแบบกับคุณ ไปพร้อมๆ กับการรักษาความเป็นส่วนตัวของคีย์ตัวตรวจสอบความถูกต้อง เพื่อทำให้มั่นใจได้ถึงการตั้งค่าเครือข่ายที่ไม่ต้องใช้ความไว้วางใจ + +เพื่อให้บรรลุเป้าหมายนั้น เราจะให้คำแนะนำกับคุณผ่าน 4 ขั้นตอนง่ายๆ ดังต่อไปนี้: + +0. โปรดดูรายการ**ข้อกำหนด**ด้านบน +1. สร้างคีย์ส่วนตัวสำหรับตัวตรวจสอบความถูกต้องแต่ละตัว และเริ่มต้นใช้งานไดเรกทอรีข้อมูล +2. เตรียมสตริงเชื่อมต่อสำหรับบูตโหนดเพื่อให้ทำการเพิ่มลงใน `genesis.json` ที่ใช้ร่วมกัน +3. สร้าง `genesis.json` ในเครื่องของคุณและส่ง/โอนไปยังโหนดแต่ละโหนด +4. เริ่มใช้งานโหนดทั้งหมด + +:::info จำนวนตัวตรวจสอบความถูกต้อง + +ไม่มีขั้นต่ำของจำนวนโหนดในคลัสเตอร์ กล่าวคือ คุณสามารถใช้คลัสเตอร์ที่ประกอบด้วยโหนดตัวตรวจสอบความถูกต้องเพียงโหนดเดียวได้โปรดจำไว้ว่า หากคุณใช้คลัสเตอร์ที่ประกอบด้วยโหนด_เดียว_ จะ**ไม่มีการทนทานต่อการหยุดทำงาน**และ**ไม่มีการรับประกัน BFT** + +จำนวนโหนดขั้นต่ำที่แนะนำเพื่อให้ได้รับการรับประกันจาก BFT อยู่ที่ 4 โหนด เนื่องจากในคลัสเตอร์ที่ประกอบด้วย 4 โหนด การขัดข้องของโหนด 1 โหนดยังสามารถยอมให้เกิดขึ้นได้ โดยมีโหนดอีก 3 โหนดซึ่งใช้งานโดยปกติ + +::: + +## ขั้นตอนที่ 1: เริ่มใช้งานโฟลเดอร์ข้อมูลและสร้างคีย์ตัวตรวจสอบความถูกต้อง {#step-1-initialize-data-folders-and-generate-validator-keys} + +เพื่อเริ่มและเรียกใช้งานกับ Polygon Edge คุณต้องเริ่มใช้งานโฟลเดอร์ข้อมูลสำหรับแต่ละโหนด: + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +คำสั่งเหล่านี้แต่ละคำสั่งจะพิมพ์คีย์ตัวตรวจสอบความถูกต้อง คีย์สาธารณะ bls และ [ID โหนด](https://docs.libp2p.io/concepts/peer-id/)คุณจะต้องใช้ ID โหนดสำหรับโหนดรายแรกเพื่อสามารถดำเนินตามขั้นตอนถัดไป + +### เอารหัสออก {#outputting-secrets} +สามารถเรียกเก็บเอาต์พุตของลับได้อีกหากจำเป็น + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning โปรดรักษาความเป็นส่วนตัวของไดเรกทอรีข้อมูลของคุณ + +นอกจากเริ่มใช้งานไดเรกทอรีเพื่อรักษาสถานะของบล็อกเชน บรรดาไดเรกทอรีข้อมูลที่สร้างมาตามคำแนะนำด้านบนจะสร้างบรรดาคีย์ส่วนตัวของตัวตรวจสอบความถูกต้องของคุณ**คุณต้องเก็บคีย์นี้เป็นข้อมูลลับ เนื่องจากการขโมยคีย์นั้นไปได้ จะทำให้บางคนสามารถแสดงตนว่าเป็นคุณ ในขณะทำหน้าที่เป็นตัวตรวจสอบความถูกต้องในเครือข่าย** + +::: + +## ขั้นตอนที่ 2: เตรียมสตริงการเชื่อมต่อ multiaddr สำหรับบูตโหนด {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +เพื่อให้โหนดประสบความสำเร็จในการเชื่อมต่อ โหนดนั้นต้องทราบว่า ต้องเชื่อมต่อกับเซิร์ฟเวอร์ไหนของ `bootnode` เพื่อ +ให้ได้ข้อมูลเกี่ยวกับโหนดทั้งหมดที่เหลืออยู่ในเครือข่าย บางครั้ง เราก็เรียก `bootnode` ว่าเซิร์ฟเวอร์ `rendezvous` ตามคำศัพท์พิเศษของ p2p + + `bootnode` ไม่ถือว่าเป็นอินสแตนซ์ของโหนด Polygon Edgeโหนด Polygon Edge ทั้งหมดสามารถทำหน้าที่เป็น `bootnode` และ +โหนด Polygon Edge ทั้งหมดต้องมีการะบุชุดบูตโหนดไว้แล้ว โดยมีการติดต่อบูตโหนดดังกล่าวเพื่อส่งมอบข้อมูลเกี่ยวกับการเชื่อมต่อกับ +โหนดทั้งหมดที่เหลืออยู่ในเครือข่าย + +เพื่อสร้างสตริงการเชื่อมต่อเพื่อระบุบูตโหนด เราจะต้องใช้[รูปแบบ multaddr](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +ในคู่มือนี้ เราจะใช้โหนดแรกและโหนดที่สองเป็นบูตโหนดสำหรับโหนดที่เหลือทั้งหมดสิ่งที่เกิดขึ้นในสถานการณ์นี้คือบรรดาโหนดที่เชื่อมต่อกับ `node 1` หรือ `node 2` จะได้รับข้อมูลเกี่ยวกับวิธีการเชื่อมต่อกันและกันผ่านการใช้บูตโหนดที่ได้ติดต่อร่วมกัน + +:::info คุณต้องระบุบูตโหนดอย่างน้อยหนึ่งโหนดเพื่อเริ่มใช้โหนด + +ต้องมีบูตโหนดอย่างน้อย**หนึ่ง**โหนด เพื่อทำให้โหนดอื่นๆ ในเครือข่ายสามารถค้นหากันได้แนะนำให้ใช้บูตโหนดมากขึ้น เนื่องจากให้ความสามารถในการฟื้นฟูกับเครือข่ายในกรณีที่เกิดการขัดข้องในคู่มือนี้ เราจะระบุสองโหนด แต่คุณสามารถทำการเปลี่ยนแปลงได้ในระหว่างการดำเนินการ โดยจะไม่ส่งผลกระทบต่อความสมบูรณ์ของไฟล์ `genesis.json` +::: + +เนื่องจากส่วนแรกของสตริงการเชื่อมต่อ multiaddr คือ `` คุณจะต้องใส่ที่อยู่ IP เป็นที่อยู่ที่เข้าถึงได้จากโหนดอื่นๆ ที่นี่ ซึ่งอาจเป็นที่อยู่ IP ส่วนตัวหรือ IP สาธารณะตามการตั้งค่าของคุณ โดยที่ไม่ใช่ `127.0.0.1` + +สำหรับ `` เราจะใช้ `1478` เนื่องจากเป็นพอร์ต libp2p เริ่มต้น + +สุดท้ายแล้ว เราต้องการ `` ซึ่งเราสามารถได้รับจากเอาต์พุตคำสั่งที่เรียกใช้มาก่อน ได้แก่ คำสั่ง `polygon-edge secrets init --data-dir data-dir` (ซึ่งเราได้ใช้เพื่อสร้างคีย์และไดเรกทอรีข้อมูลสำหรับ `node 1`) + +หลังจากมีการประกอบแล้ว สตริงการเชื่อมต่อ multiaddr ซึ่งใช้กับ `node 1` ที่เราจะใช้เป็นบูตโหนด จะมีลักษณะเช่นนี้ (เพียงแต่ `` ในปลายทางต้องมีค่าอื่น): +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +ในทำนองเดียวกัน เราสร้าง multiaddr สำหรับบูตโหนดที่สองตามที่แสดงไว้ด้านล่าง +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info ชื่อโฮสต์ DNS ที่ใช้แทน IP + +Polygon Edge รองรับการใช้ชื่อโฮสต์ DNS สำหรับการกำหนดค่าโหนดนี่เป็นคุณสมบัติที่มีประโยชน์มากสำหรับการปรับใช้ในระบบคลาวด์ เนื่องจาก IP ของโหนดอาจเปลี่ยนได้ด้วยหลายสาเหตุ + +รูปแบบ multiaddr ซึ่งใช้สำหรับสตริงการเชื่อมต่อในระหว่างการใช้ชื่อโฮสต์ DNS ตามที่ปรากฏไว้ดังต่อไปนี้:`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## ขั้นตอนที่ 3: สร้างไฟล์ genesis ที่มีโหนดจำนวน 4 โหนดเป็นตัวตรวจสอบความถูกต้อง {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +ทำขั้นตอนนี้ได้ในเครื่องของคุณ แต่คุณยังต้องใช้คีย์สาธารณะของตัวตรวจสอบความถูกต้องทั้ง 4 ตัว + +ตัวตรวจสอบความถูกต้องต่างๆ สามารถแชร์ `Public key (address)` ตามที่แสดงไว้ด้านล่างได้อย่างปลอดภัยในเอาต์พุตของคำสั่ง `secrets init` ของตน เพื่อให้ +คุณสามารถสร้าง genesis.json ได้อย่างปลอดภัยด้วยตัวตรวจสอบความถูกต้องในชุดตัวตรวจสอบความถูกต้องเริ่มต้นตามที่คีย์สาธารณะของตนระบุไว้: + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +เมื่อคุณได้รับคีย์สาธารณะของตัวตรวจสอบความถูกต้องครบทั้ง 4 ตัวแล้ว คุณจะสามารถเรียกใช้คำสั่งดังต่อไปนี้เพื่อสร้าง `genesis.json` + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +สิ่งที่คำสั่งนี้ทำ: + +* `--ibft-validator` กำหนดคีย์สาธารณะของตัวตรวจสอบความถูกต้อง ซึ่งจะรวมอยู่ในชุดตัวตรวจสอบความถูกต้องเริ่มต้นในบล็อก genesisอาจมีตัวตรวจสอบความถูกต้องเริ่มต้นเป็นจำนวนมากก็ได้ +* `--bootnode` กำหนดที่อยู่ของบูตโหนด ซึ่งจะทำให้โหนดสามารถค้นหากันเองได้เราจะใช้สตริง multiaddr ของ `node 1` ตามที่ระบุไว้ใน **ขั้น 2** แต่คุณสามารถเพิ่มบูตโหนดตามจำนวนที่คุณต้องการ ตามที่ระบุไว้ด้านบน + +:::info สลับไปยัง ECDSA + +BLS คือโหมดการตรวจสอบความถูกต้องเริ่มต้นของตัวต่อเนื่องของบล็อกหากคุณต้องการให้เชนของคุณทำงานในโหมด ECDSA คุณสามารถใช้`—ibft-validator-type`แฟล็ก ด้วยอาร์กิวเมนต์`ecdsa`: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info บัญชียอดคงเหลือแบบ Premining + +คุณอาจต้องการตั้งค่าเครือข่ายบล็อกเชนของคุณโดยให้ที่อยู่บางส่วนมียอดคงเหลือ "ที่วางไว้ล่วงหน้า" + +ในการดำเนินการนี้ ให้ส่งผ่านค่าสถานะ `--premine` ต่างๆ ตามที่คุณต้องการไปยังแต่ละที่อยู่ที่คุณต้องการให้เริ่มต้นด้วยยอดคงเหลือที่กำหนดในบล็อกเชน + +ตัวอย่างเช่น หากเราต้องการวาง 1000 ETH ไว้ล่วงหน้าให้กับที่อยู่ `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` ในบล็อก genesis ของเรา เราจึงต้องเสนออาร์กิวเมนต์ดังต่อไปนี้: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**โปรดทราบว่าจำนวนที่วางไว้ล่วงหน้า มีหน่วยเป็น WEI ไม่ใช่ ETH** + +::: + +:::info กำหนดขีดจำกัดค่าแก๊สต่อบล็อก + +ขีดจำกัดค่าแก๊สเริ่มต้นในแต่ละบล็อกอยู่ที่ `5242880`มีการเขียนค่านี้เขียนไว้ในไฟล์ genesis แต่คุณอาจต้องการเพิ่ม / ลดค่านั้น + +เพื่อดำเนินการเช่นนั้น คุณสามารถใช้ค่าสถานะ `--block-gas-limit` ตามด้วยค่าที่จำเป็นต้องใช้ ตามที่ระบุไว้ด้านล่าง : + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info กำหนดขีดจำกัดของ File Descriptor ของระบบ + +ขีดจำกัดตัวอธิบายของไฟล์ปริยาย (จำนวนสูงสุดของไฟล์ที่เปิด) สามารถใช้ได้ต่ำและบน Linux ทุกอย่างคือไฟล์หากคาดว่าจะมีโหนดที่มีแบบผ่านมาตรฐาน คุณสามารถพิจารณาเพิ่มขีดจำกัดนี้ได้ตรวจสอบเอกสารอย่างเป็นทางการของเลเวโดของคุณเพื่อหารายละเอียดเพิ่มเติม + +#### ตรวจสอบขีดจำกัดปัจจุบันของระบบปฏิบัติการ (ไฟล์ที่เปิดอยู่) {#check-current-os-limits-open-files} +```shell title="ulimit -n" +1024 # Ubuntu default +``` + +#### เพิ่มขีดจำกัดสำหรับไฟล์ที่เปิดอยู่ {#increase-open-files-limit} +- วิ่ง`polygon-edge`บนหน้าผา (shel) + ```shell title="Set FD limit for the current session" + ulimit -n 65535 # affects only current session, limit won't persist after logging out + ``` + + ```shell title="Edit /etc/security/limits.conf" + # add the following lines to the end of the file to modify FD limits + * soft nofile 65535 # sets FD soft limit for all users + * hard nofile 65535 # sets FD hard limit for all users + + # End of file + ``` +บันทึกไฟล์และรีสตาร์ทระบบด้วย + +- การใช้งาน`polygon-edge`ในพื้นหลังเป็นบริการ + +หาก`polygon-edge`ทำงานเป็นบริการระบบโดยใช้เครื่องมือเช่น ขีดจำกัดตัวอธิบาย`systemd`ไฟล์Nameควรมีการจัดการโดยใช้`systemd`ระบบ + ```shell title="Edit /etc/systemd/system/polygon-edge.service" + [Service] + ... + LimitNOFILE=65535 + ``` + +### การแก้ไขปัญหา {#troubleshooting} +```shell title="Watch FD limits of polygon edge running process" +watch -n 1 "ls /proc/$(pidof polygon-edge)/fd | wc -l" +``` + +```shell title="Check max FD limits for polygon-edge running process" +cat /proc/$(pidof polygon-edge)/limits +``` +::: + +หลังจากระบุ: +1. คีย์สาธารณะของตัวตรวจสอบความถูกต้องที่จะรวมไว้ในบล็อก genesis ในฐานะชุดตัวตรวจสอบความถูกต้อง +2. สตริงการเชื่อมต่อ multiaddr ของบูตโหนด +3. บัญชีและยอดคงเหลือที่วางไว้ล่วงหน้าที่จะรวมไว้ในบล็อก genesis + +และสร้าง `genesis.json` คุณต้องคัดลอกสิ่งเหล้านั้นไปยัง VM ทั้งหมดในเครือข่ายขึ้นอยู่กับการกำหนดค่าของคุณ คุณสามารถคัดลอก/วาง ส่งไปยังตัวดำเนินการโหนด หรือใช้วิธีการ SCP/FTP + +เนื้อหาเกี่ยวกับโครงสร้างของไฟล์ genesis อยู่ในส่วน[คำสั่ง CLI](/docs/edge/get-started/cli-commands) + +## ขั้นตอนที่ 4: เรียกใช้ไคลเอ็นต์ทั้งหมด {#step-4-run-all-the-clients} + +:::note การใช้เครือข่ายกับผู้ให้บริการคลาวด์ + +ผู้ให้บริการคลาวด์ส่วนใหญ่จะไม่แสดงที่อยู่ IP (โดยเฉพาะที่อยู่สาธารณะ) เป็นอินเทอร์เฟซของเครือข่ายโดยตรงใน VM ของคุณ แต่จะตั้งค่าพร็อกซี NAT ที่ไม่สามารถมองเห็นได้ + + +เพื่อให้โหนดเชื่อมต่อซึ่งกันและกันในกรณีนี้ คุณจะต้องรอรับคำสั่งในที่อยู่ IP `0.0.0.0` เพื่อผูกกับอินเทอร์เฟซทั้งหมด แต่คุณยังคงต้องระบุที่อยู่ IP หรือที่อยู่ DNS ซึ่งโหนดอื่นๆ สามารถใช้เพื่อเชื่อมต่อกับอินสแตนซ์ของคุณได้คุณสามารถดำเนินการเช่นนั้นได้โดยใช้อาร์กิวเมนท์ `--nat` หรือ `--dns` ที่คุณสามารถระบุที่อยู่ IP หรือ DNS ภายนอกของคุณตามลำดับ + +#### ตัวอย่าง {#example} + +ที่อยู่ IP ที่เกี่ยวข้องที่คุณต้องรอรับคำสั่งคือ `192.0.2.1` ซึ่งไม่ได้ผูกกับอินเทอร์เฟซเครือข่ายต่างๆ ของคุณโดยตรงเลย + +เพื่อให้โหนดเชื่อมต่อได้ คุณจะต้องส่งผ่านพารามิเตอร์ดังต่อไปนี้: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +หรือหากคุณต้องการระบุที่อยู่ DNS `dns/example.io` ให้ส่งผ่านพารามิเตอร์ดังต่อไปนี้: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +การดำเนินการเช่นนั้นจะทำให้โหนดของคุณรอรับคำสั่งในอินเทอร์เฟซทั้งหมด แต่ยังทำให้รู้ว่าไคลเอ็นต์กำลังเชื่อมต่อกับโหนดผ่านที่อยู่ `--dns` หรือ `--nat` ที่ระบุไว้ + +::: + +ในการเรียกใช้ไคลเอ็นต์**แรก**: + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +ในการเรียกใช้ไคลเอ็นต์**ที่สอง**: + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +ในการเรียกใช้ไคลเอ็นต์**ที่สาม**: + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +ในการเรียกใช้ไคลเอ็นต์**ที่สี่**: + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +หลังจากเรียกใช้คำสั่งก่อนหน้าหน้า คุณได้กำหนดเครือข่าย Polygon Edge ซึ่งประกอบด้วย 4 โหนด ที่สามารถซีลบล็อกและคืนค่าจากกรณีโหนดล้มเหลว + +:::info เริ่มใช้ไคลเอ็นต์โดยใช้ไฟล์กำหนดค่า + +แทนที่จะระบุพารามิเตอร์การกำหนดค่าทั้งหมดเป็นอาร์กิวเมนต์ CLI เรายังสามารถเริ่มต้นไคลเอ็นต์ผ่านการใช้ไฟล์กำหนดค่า โดยให้เรียกใช้คำสั่งดังต่อไปนี้: + +````bash +polygon-edge server --config +```` +ตัวอย่าง : + +````bash +polygon-edge server --config ./test/config-node1.json +```` +ปัจจุบัน เรารองรับไฟล์การปรับแต่งแบบ`json`พื้นฐานเท่านั้น จึงสามารถพบแฟ้มปรับแต่งตัวอย่าง **[ได้ที่นี่](/docs/edge/configuration/sample-config)** + +::: + +:::info ขั้นตอนต่างๆ ในการเรียกใช้โหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้อง + +โหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้องจะซิงค์บรรดาบล็อกล่าสุดที่ได้รับมาจากโหนดตัวตรวจสอบความถูกต้อง คุณสามารถเริ่มโหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้องโดยเรียกใช้คำสั่งดังต่อไปนี้ + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +ตัวอย่างเช่น คุณสามารถเพิ่มไคลเอ็นต์ที่ไม่ใช่ไคลเอ็นต์ตัวตรวจสอบความถูกต้องตัว**ที่ห้า**ได้ โดยการเรียกใช้คำสั่งดังต่อไปนี้ : + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info กำหนดขีดจำกัดราคา +เริ่มต้นโหนด Polygon Edge ได้ด้วย**ขีดจำกัดราคา**ที่กำหนดค่าไว้สำหรับธุรกรรมที่เข้ามา + +หน่วยที่ใช้สำหรับขีดจำกัดราคาคือ `wei` + +การกำหนดขีดจำกัดราคาหมายความว่า ธุรกรรมใดๆ ที่ดำเนินการโดยโหนดปัจจุบันจะต้องมีราคาแก๊ส**สูงกว่า**ขีดจำกัดราคาที่กำหนดไว้ มิฉะนั้น จะไม่สามารถรวมลงในบล็อกได้ + +การที่โหนดส่วนใหญ่ยอมรับขีดจำกัดราคาที่กำหนดจะทำให้เกิดบังคับใช้กฎที่ระบุว่าธุรกรรมในเครือข่ายต้องไม่ต่ำกว่าขีดจำกัดราคาที่กำหนด + +ค่าเริ่มต้นสำหรับขีดจำกัดราคาคือ `0` หมายความว่า ตามค่าเริ่มต้น จะไม่มีการบังคับใช้เลย + +ตัวอย่างการใช้ค่าสถานะ `--price-limit`: +````bash +polygon-edge server --price-limit 100000 ... +```` + +โปรดจำไว้ว่า ขีดจำกัดราคาจะ**ได้รับการบังคับใช้กับธุรกรรมที่ไม่ใช่ธุรกรรมภายในเท่านั้น** หมายความว่าขีดจำกัดราคาจะไม่นำมาใช้กับธุรกรรมที่เพิ่มเป็นการภายในกับโหนด +::: + +:::info WebSocket URL +ตามค่าเริ่มต้น เมื่อคุณเรียกใช้ Polygon Edge จะมีการสร้าง WebSocket URL โดยใช้ที่ตั้งของเชนเป็นหลักใช้โครงสร้าง URL `wss://` ใช้กับลิงก์ HTTPS และ `ws://` สำหรับ HTTP + +Localhost WebSocket URL: +````bash +ws://localhost:10002/ws +```` +โปรดจำไว้ว่าหมายเลขพอร์ตขึ้นอยู่กับพอร์ต JSON-RPC ที่คุณได้เลือกไว้สำหรับโหนดดังกล่าว + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/th-edge/get-started/terraform-aws-deployment.md b/archive/edge/th-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..f9900af7d6 --- /dev/null +++ b/archive/edge/th-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,171 @@ +--- +id: terraform-aws-deployment +title: การปรับใช้ Terraform AWS +description: "ปรับใช้เครือข่าย Polygon Edge กับผู้ให้บริการคลาวด์ AWS โดยใช้ Terraform" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info คู่มือเกี่ยวกับการปรับใช้ผลิตภัณฑ์ + +คำแนะนำนี้เป็นคำแนะนำเกี่ยวกับการปรับใช้ AWS แบบอัตโนมัติเต็มรูปแบบที่พร้อมสำหรับการใช้งานจริงอย่างทางการ + +แนะนำการปรับใช้งานด้วยตนเองกับ***[คลาวด์](set-up-ibft-on-the-cloud)***หรือ***[ภายใน](set-up-ibft-locally)***สำหรับการทดสอบและ/หรือในกรณีที่ผู้ให้บริการคลาวด์ของคุณไม่ใช่ AWS +::: + +:::info + +การปรับใช้งานนี้เป็นแบบ PoA เท่านั้น +หากจำเป็นต้องใช้กลไก PoS ก็เพียงแค่ทำตามวิธีการย้ายจาก PoA ไปยัง PoS ใน***[คู่มือ](/docs/edge/consensus/migration-to-pos)***ฉบับนี้ +::: + +คู่มือนี้จะอธิบายกระบวนการปรับใช้เครือข่ายบล็อกเชน Polygon Edge กับผู้ให้บริการคลาวด์ AWS โดยละเอียด +ซึ่งพร้อมสำหรับการใช้งานจริงเมื่อขยายโหนดตัวตรวจสอบความถูกต้องออกไปใน Availability Zone จำนวนมาก + +## ข้อกำหนดเบื้องต้น {#prerequisites} + +### เครื่องมือของระบบ {#system-tools} +* [Terraform](https://www.terraform.io/) +* [AWS cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [ID ของคีย์การเข้าใช้งาน AWS และคีย์การเข้าใช้งานข้อมูลลับ](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### ตัวแปรของ Terraform {#terraform-variables} +ตัวแปรที่ต้องให้สองตัวที่กำหนด ก่อนที่จะเรียกใช้การใช้งาน: + +* `alb_ssl_certificate` - ARN ของใบรับรองจาก AWS Certificate Manager ซึ่ง ALB จะใช้สำหรับโปรโตคอล https + ให้สร้างใบรับรองก่อนเริ่มการปรับใช้งาน และใบรับรองต้องมีสถานะ**ออกให้แล้ว** +* `premine` - บัญชีที่จะรับสกุลเงินดั้งเดิมที่วางไว้ล่วงหน้า +ค่าต้องเป็นไปตามข้อมูลค่าสถานะ [CLI](/docs/edge/get-started/cli-commands#genesis-flags) อย่างเป็นทางการ + +## ข้อมูลเกี่ยวกับการปรับใช้ {#deployment-information} +### ทรัพยากรที่ปรับใช้ {#deployed-resources} +ภาพรวมระดับสูงของทรัพยากรที่จะปรับใช้: + +* VPC แบบเฉพาะ +* โหนดตัวตรวจสอบความถูกต้องจำนวน 4 โหนด (ซึ่งเป็นบูตโหนดในขณะเดียวกัน) +* เกตเวย์ NAT จำนวน 4 รายการ ซึ่งอนุญาตการใช้งานอินเตอร์เน็ตภายนอกให้กับโหนด +* ฟังก์ชัน Lambda ซึ่งใช้สำหรับสร้างบล็อกแรก (บล็อก Genesis) และเริ่มต้นเชน +* บทบาท IAM และกลุ่มความปลอดภัยแบบเฉพาะ +* S3 Bucket ที่ใช้เพื่อจัดเก็บไฟล์ genesis.json +* Application Load Balancer ที่ใช้ในการแสดง JSON-RPC Endpoint + +### ความทนทานต่อความผิดพลาด {#fault-tolerance} + +สำหรับการปรับใช้นี้ ให้ใช้เฉพาะ Region ที่มี Availability Zone จำนวน 4 โซนปรับใช้งานแต่ละโหนดใน AZ เดียว + +โดยการวางโหนดแต่ละโหนดใน AZ เดี่ยว คลัสเตอร์ของบล็อกเชนทั้งหมดจะมีความทนทานต่อความผิดพลาดกับการขัดข้องในโหนดเดี่ยว (AZ) เมื่อ Polygon Edge ปรับใช้ฉันทามติ IBFT +ซึ่งยอมให้โหนดขัดข้องได้ 1 โหนด ในคลัสเตอร์โหนดตัวตรวจสอบความถูกต้องแบบ 4 โหนด + +### การเข้าถึงบรรทัดคำสั่ง {#command-line-access} + +ไม่มีการแสดงโหนดตัวตรวจสอบความถูกต้องต่อเครือข่ายอินเทอร์เน็ตสาธารณะแต่อย่างใด (เข้าใช้งาน JSON-PRC ผ่าน ALB เท่านั้น) +และบรรดาโหนดนั้นไม่มี IP สาธารณะแนบท้ายด้วย +บรรทัดคำสั่งโหนดสามารถเข้าถึงได้เฉพาะผ่าน [AWS Systems Manager - Session Manager](https://aws.amazon.com/systems-manager/features/) + +### การอัปเกรด Base AMI {#base-ami-upgrade} + +การปรับใช้นี้ใช้ `ubuntu-focal-20.04-amd64-server` AWS AMIโดย**ไม่มี**การทริกเกอร์*การปรับใช้ใหม่*กับ EC2 หากมีการอัปเดต AWS AMI + +หากจำเป็นต้องอัปเดต Base AMI ด้วยเหตุผลบางอย่างจะสามารถทำได้โดยเรียกใช้คำสั่ง `terraform taint` สำหรับอินสแตนซ์แต่ละรายการ ก่อน `terraform apply` +คุณสามารถดำเนินการกับอินสแตนซ์ได้โดยเรียกใช้คำสั่ง +`terraform taint module.instances[].aws_instance.polygon_edge_instance` + +ตัวอย่าง: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info + +ในสภาพแวดล้อมการใช้งานจริง ควรเรียกใช้ `terraform taint` ทีละรายการเพื่อรักษาการทำงานของเครือข่ายบล็อกเชน + +::: + +## ขั้นตอนการปรับใช้ {#deployment-procedure} + +### ขั้นตอนที่ต้องดำเนินการก่อนการปรับใช้ {#pre-deployment-steps} +* อ่านไฟล์ Readme ของ Terraform Registry [polygon-technology-edge](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) +* เพิ่มโมดูล `polygon-technology-edge` ลงในไฟล์ `main.tf` ของคุณโดยใช้*คำแนะนำเกี่ยวกับข้อกำหนด*ในหน้า Readme ของโมดูล +* เรียกใช้คำสั่ง `terraform init` เพื่อติดตั้งรูปแบบการขึ้นต่อกันของ Terraform ที่จำเป็นทั้งหมด +* จัดเตรียมใบรับรองใหม่ใน [AWS Certificate Manager](https://aws.amazon.com/certificate-manager/) +* ตรวจสอบว่าใบรับรองที่ให้ไว้อยู่ในสถานะ **ออกให้แล้ว** และบันทึก **ARN** ของใบรับรองไว้ +* ตั้งค่าชุดคำสั่งเอาต์พุตของคุณ เพื่อให้ได้ค่าเอาต์พุตของโมดูลใน cli + +#### ตัวอย่าง `main.tf` {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### ตัวอย่าง `terraform.tfvars` {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### ขั้นตอนการปรับใช้ {#deployment-steps} +* สร้างไฟล์ `terraform.tfvars` +* กำหนดตัวแปรของ terraform ที่จำเป็นต้องใช้กับไฟล์นี้ (ตามที่อธิบายไว้ด้านบน) +:::info + +มีตัวแปรที่ไม่จำเป็นอื่นๆ ที่สามารถปรับเปลี่ยนการปรับใช้นี้ได้อย่างเต็มรูปแบบ +คุณสามารถแทนที่ค่าเริ่มต้นได้โดยการเพิ่มค่าของตัวคุณเองในไฟล์ `terraform.tfvars` + + ค้นหาข้อมูลจำเพาะของตัวแปรที่มีอยู่ทั้งหมดได้ใน***[รีจิสทรี](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)*** Terraform ของโมดูลต่างๆ + +::: +* ทำให้มั่นใว่าคุณได้กำหนดค่าการรับรองความถูกต้อง aws cli อย่างถูกต้องโดยเรียกใช้ `aws s3 ls` - ต้องไม่ปรากฏข้อผิดพลาด +* ปรับใช้โครงสร้างพื้นฐาน `terraform apply` + +### ขั้นตอนที่ต้องดำเนินการหลังการปรับใช้ {#post-deployment-steps} +* เมื่อเสร็จสิ้นการปรับใช้แล้ว ให้บันทึกค่าตัวแปร `json_rpc_dns_name` ที่พิมพ์ไว้ใน cli +* สร้างบันทึก dns cname สาธารณะ ซึ่งระบุชื่อโดเมนของคุณแก่ค่า `json_rpc_dns_name` ที่กำหนดไว้ตัวอย่าง: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* เมื่อบันทึก cname เผยแพร่ ให้ตรวจสอบว่าเชนทำงานอย่างถูกต้องหรือไม่ โดยเรียกใช้ JSON-PRC Endpoint ของคุณ + จากตัวอย่างด้านบน: + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## ขั้นตอนการทำลาย {#destroy-procedure} +:::warning +กระบวนการต่อไปนี้จะลบโครงสร้างพื้นฐานทั้งหมดของคุณที่ปรับใช้ด้วยการใช้สคริปต์ terraform เหล่านี้อย่างถาวร ตรวจสอบให้แน่ใจว่าคุณมี[ข้อมูลสำรองของข้อมูลบล็อกเชน](docs/edge/working-with-node/backup-restore) และ/หรือคุณกำลังดำเนินการในสภาพแวดล้อมทดสอบ + +::: + +หากคุณจำเป็นต้องลบโครงสร้างพื้นฐานทั้งหมด ให้เรียกใช้คำสั่งดังต่อไปนี้ `terraform destroy` +นอกจากนี้ คุณต้องลบข้อมูลลับที่เก็บไว้ใน AWS [Parameter Store](https://aws.amazon.com/systems-manager/features/) ด้วยตนเอง +สำหรับ Region ที่ได้ดำเนินการปรับใช้ diff --git a/archive/edge/th-edge/overview.md b/archive/edge/th-edge/overview.md new file mode 100644 index 0000000000..d151346e4d --- /dev/null +++ b/archive/edge/th-edge/overview.md @@ -0,0 +1,35 @@ +--- +id: overview +title: Polygon Edge +sidebar_label: What is Edge +description: "ข้อมูลเบื้องต้นเกี่ยวกับ Polygon Edge" +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +Polygon Edge โครงสร้างแบบโมดูลาร์ที่ขยายได้ ซึ่งใช้ในการสร้างเครือข่ายบล็อกเชน ไซด์เชน และโซลูชันการปรับขนาดทั่วไปที่ Ethereum รองรับ + +วัตถุประสงค์หลักในการใช้คือการเริ่มต้นระบบเครือข่ายบล็อกเชนใหม่ พร้อมกับให้ความเข้าใจได้อย่างเต็มรูปแบบกับสัญญาอัจฉริยะและธุรกรรมของ Ethereumซึ่งใช้กลไกฉันทามติ IBFT (Istanbul Byzantine Fault Tolerant) ที่รองรับสองรูปแบบ ได้แก่ [PoA (Proof of Authority)](/docs/edge/consensus/poa) และ [PoS (Proof of Stake)](/docs/edge/consensus/pos-stake-unstake) + +นอกจากนั้น Polygon Edge รองรับการสื่อสารกับเครือข่ายบล็อกเชนจำนวนมาก ทำให้สามารถใช้ทั้งโทเค็น [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) และ [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) ผ่านการใช้[โซลูชันบริดจ์แบบมีตัวกลาง](/docs/edge/additional-features/chainbridge/overview) + +ใช้วอลเล็ตมาตรฐานอุตสาหกรรมเพื่อโต้ตอบกับ Polygon Edge ผ่าน [JSON-RPC](/docs/edge/working-with-node/query-json-rpc) Endpoint และตัวตรวจสอบความถูกต้องโหนดสามารถดำเนินการต่างๆ ผ่านการใช้โปรโตคอล [gRPC](/docs/edge/working-with-node/query-operator-info) + +ดูข้อมูลเพิ่มเติมเกี่ยวกับ Polygon ได้ที่[เว็บไซต์อย่างเป็นทางการ](https://polygon.technology) + +**[พื้นที่เก็บข้อมูล GitHub](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +ส่วนนี้อยู่ในระหว่างการสร้าง จึงอาจมีการเปลี่ยนแปลงทางสถาปัตยกรรมในอนาคตยังไม่มีการตรวจสอบโค้ดโปรดติดต่อทีม Polygon หากคุณประสงค์ใช้ส่วนนี้ในการใช้งานจริง + +::: + + + +ในการเริ่มต้นใช้งานโดยการเรียกใช้เครือข่าย `polygon-edge` ภายใน โปรดอ่าน[การติดตั้ง](/docs/edge/get-started/installation)และ[การตั้งค่าในเครื่อง](/docs/edge/get-started/set-up-ibft-locally) diff --git a/archive/edge/th-edge/performance-reports/overview.md b/archive/edge/th-edge/performance-reports/overview.md new file mode 100644 index 0000000000..b65a1a740a --- /dev/null +++ b/archive/edge/th-edge/performance-reports/overview.md @@ -0,0 +1,32 @@ +--- +id: overview +title: ภาพรวม +description: "ข้อมูลเบื้องต้นเกี่ยวกับการทดสอบ Polygon Edge" +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +โปรดทราบว่าเราใช้สำหรับการดำเนินการการทดสอบเหล่านี้`loadbot`จะถูกนำไปใช้เพื่อทำการตั้งค่าดังกล่าว ตอนนี้มีการตั้งค่าที่อ่อนค่าลง +::: + +| ประเภท | ค่า | ลิงก์ไปที่ผลการทดสอบ | +| ---- | ----- | ------------ | +| การโอนตามปกติ | 1428 tps | [4 กรกฎาคม 2022](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| การโอน ERC-20 | 1111 tps | [4 กรกฎาคม 2022](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| การสร้าง NFT | 714 tps | [4 กรกฎาคม 2022](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +เป้าหมายของเราคือการสร้างซอฟท์แวร์ไคลเอ็นต์บล็อกเชนซึ่งมีประสิทธิภาพสูง ประกอบด้วยคุณสมบัติหลายอย่าง และสามารถติดตั้งและดูแลได้ง่าย +ได้มีการดำเนินการทดสอบทั้งหมดโดยใช้ Polygon Edge Loadbot +รายงานประสิทธิภาพทั้งหมดที่คุณจะพบในส่วนนี้มีการระบุวันที่อย่างเหมาะสม อธิบายสภาพแวดล้อมอย่างชัดเจน และอธิบายวิธีการทดสอบอย่างชัดเจน + +เป้าหมายในการทดสอบประสิทธิภาพเหล่านี้คือ การแสดงให้เห็นถึงประสิทธิภาพของเครือข่ายบล็อกเชน Polygon Edge ในการใช้งานจริง +โดยการใช้ loadbot ของเราในสภาพแวดล้อมเดียวกัน ทุกคนจะได้ผลลัพธ์เดียวกันตามที่ระบุไว้ในที่นี่ + +ได้มีการดำเนินการทดสอบทั้งหมดในแพลตฟอร์ม AWS โดยใช้เชนประกอบด้วยโหนดอินสแตนซ์จำนวน 2 โหนด \ No newline at end of file diff --git a/archive/edge/th-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/th-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..b2cfa0e2ca --- /dev/null +++ b/archive/edge/th-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,130 @@ +--- +id: test-2022-01-21 +title: 21 มกราคม 2022 +description: "การทดสอบประสิทธิภาพจากวันที่ 21 มกราคม" +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## 21 มกราคม 2022 {#january-21st-2022} + +### สรุป {#summary} + +:::caution +โปรดทราบว่าเราใช้สำหรับการดำเนินการการทดสอบเหล่านี้`loadbot`จะถูกนำไปใช้เพื่อทำการตั้งค่าดังกล่าว ตอนนี้มีการตั้งค่าที่อ่อนค่าลง +::: + +ทำการทดสอบนี้หลังจากรีแฟกเตอร์ TxPool ซึ่งปรับปรุงประสิทธิภาพอย่างมีนัยสำคัญ (เผยแพร่ใน [v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0)) + +เป้าหมายคือเพื่อตั้งค่าเครือข่ายขนาดใหญ่ที่ประกอบด้วยตัวตรวจสอบความถูกต้องที่เข้าร่วมอย่างจริงจัง 30 ตัวเพื่อทดสอบความเครียดของฉันทามติและการกระจายข้อมูล (Gossip) ธุรกรรม TxPool อย่างเหมาะสม เมื่อส่งธุรกรรมทั้งหมดไปยัง JSON-RPC ของโหนดเดียว + +เป้าหมายของเราไม่ใช่การพยายามทำให้ได้ค่า TPS สูงสุดเท่าที่เป็นไปได้ เนื่องจากขนาดเครือข่ายจะส่งผลเสียต่อประสิทธิภาพการทำงานและเนื่องจากมีการตั้งค่าขีดจำกัดค่าแก๊สต่อบล็อกและเวลาในการสร้างบล็อกเป็นค่าปกติ ที่ไม่ใช้ทรัพยากรของระบบมากนัก จึงทำให้ทำงานได้บนฮาร์ดแวร์ที่ใช้งานกันทั่วไป + +### ผลลัพธ์ {#results} + +| เมตริก | ค่า | +| ------ | ----- | +| ธุรกรรมต่อวินาที | 344 | +| ธุรกรรมล้มเหลว | 0 | +| ธุรกรรมประสบความสำเร็จ | 10000 | +| เวลาเรียกใช้ทั้งหมด | 30 วินาที | + +### สภาพแวดล้อม {#environment} + +
+ ค่ากำหนดโฮสต์ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ผู้ให้บริการคลาวด์AWS
ขนาดอินสแตนซ์t2.xlarge
ระบบเครือข่ายเครือข่ายย่อยส่วนตัว
ระบบการปฏิบัติการLinux Ubuntu 20.04 LTS - Focal Fossa
ขีดจำกัดของ File Descriptor65535
การประมวลผลสูงสุดของผู้ใช้65535
+
+
+
+
+ +
+ ค่ากำหนดของบล็อกเชน +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
เวอร์ชัน Polygon EdgeCommit 8377162281d1a2e4342ae27cd4e5367c4364aee2 ใน Develop Branch
โหนดตัวตรวจสอบความถูกต้อง30
โหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้อง0
ฉันทามติIBFT PoA
เวลาในการสร้างบล็อก2000ms
ขีดจำกัดค่าแก๊สต่อบล็อก5242880
+
+
+
+
+ +
+ การกำหนดค่า Loadbot +
+
+ + + + + + + + + + + + + +
ธุรกรรมทั้งหมด10000
ธุรกรรมที่ส่งต่อวินาที400
ประเภทธุรกรรมการโอนประเภท EOA ถึง EOA
+
+
+
+
diff --git a/archive/edge/th-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/th-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..b53b46d1c4 --- /dev/null +++ b/archive/edge/th-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,389 @@ +--- +id: test-2022-03-02 +title: 2 มีนาคม 2022 +description: "การทดสอบประสิทธิภาพจากวันที่ 2 มีนาคม" +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### สรุป {#summary} + +:::caution +โปรดทราบว่าเราใช้สำหรับการดำเนินการการทดสอบเหล่านี้`loadbot`จะถูกนำไปใช้เพื่อทำการตั้งค่าดังกล่าว ตอนนี้มีการตั้งค่าที่อ่อนค่าลง +::: + +ทำการทดสอบนี้เพื่อวัดค่าการโอนโทเค็น SC ERC20 และฟังก์ชันการสร้างโทเค็น SC ERC721 ที่มีโหลดจำนวนมาก และความเร็วของธุรกรรม + +เป้าหมายคือเพื่อตรวจสอบว่าทุกอย่างทำงานตามที่คาดไว้หรือไม่ในระหว่างที่มีโหลดจำนวนมากนั่นคือเหตุผลที่เราแนะนำเมตริกค่าแก๊สในเอาต์พุต Loadbot ซึ่งแสดงให้เราเห็นว่ามีการบรรจุธุรกรรมต่างๆ ลงในบล็อกนั้นอย่างถูกต้องหรือไม่ + +ส่งธุรกรรมทั้งหมดไปไปยังโหนดเดี่ยวผ่าน GRPC API และรับธุรกรรมผ่าน JSON-RPC APIหลังจากดำเนินการกับธุรกรรมทั้งหมดแล้ว จะมีการอ่านข้อมูลค่าแก๊สจากแต่ละบล็อกโดยใช้เมธอด eth_getBlockByNumber JSON-RPC + +เป้าหมายของเราไม่ใช่การพยายามทำให้ได้ค่า TPS สูงสุดเท่าที่เป็นไปได้เนื่องจากมีการตั้งค่าขีดจำกัดค่าแก๊สต่อบล็อกและเวลาในการสร้างบล็อกเป็นค่าปกติ ที่ไม่ใช้ทรัพยากรของระบบมากนัก จึงทำให้ทำงานได้บนฮาร์ดแวร์ที่ใช้งานกันทั่วไป + +### ผลลัพธ์ ERC20 {#results-erc20} + +| เมตริก | ค่า | +| ------ | ----- | +| ประเภทธุรกรรม | ERC20 | +| ธุรกรรมต่อวินาที | 65 | +| ธุรกรรมล้มเหลว | 0 | +| ธุรกรรมประสบความสำเร็จ | 5000 | +| เวลาเรียกใช้ธุรกรรม ERC20 | 76.681690 วินาที | +| เวลาปรับใช้ SC | 4.048250 วินาที | + +### ผลลัพธ์ ERC721 {#results-erc721} + +| เมตริก | ค่า | +| ------ | ----- | +| ประเภทธุรกรรม | ERC721 | +| ธุรกรรมต่อวินาที | 20 | +| ธุรกรรมล้มเหลว | 0 | +| ธุรกรรมประสบความสำเร็จ | 2000 | +| เวลาเรียกใช้ธุรกรรม ERC721 | 97.239920 วินาที | +| เวลาปรับใช้ SC | 3.048970 วินาที | + +### สภาพแวดล้อม ERC20 {#environment-erc20} + +
+ ค่ากำหนดโฮสต์ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ผู้ให้บริการคลาวด์AWS
ขนาดอินสแตนซ์t2.micro
ระบบเครือข่ายเครือข่ายย่อยส่วนตัว
ระบบการปฏิบัติการLinux Ubuntu 20.04 LTS - Focal Fossa
ขีดจำกัดของ File Descriptor65535
การประมวลผลสูงสุดของผู้ใช้65535
+
+
+
+
+ +
+ ค่ากำหนดของบล็อกเชน +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
เวอร์ชัน Polygon Edgeคอมมิต 8a033aa1afb191abdac04636d318f83f32511f3c ใน Develop Branch
โหนดตัวตรวจสอบความถูกต้อง6
โหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้อง0
ฉันทามติIBFT PoA
เวลาในการสร้างบล็อก2 วินาที
ขีดจำกัดค่าแก๊สต่อบล็อก5242880
การใช้บล็อกโดยเฉลี่ย95%
+
+
+
+
+ +
+ การกำหนดค่า Loadbot +
+
+ + + + + + + + + + + + + +
ธุรกรรมทั้งหมด5000
ธุรกรรมที่ส่งต่อวินาที200
ประเภทธุรกรรมการโอน ERC20 ถึง ERC20
+
+
+
+
+ +
+ บันทึก Loadbot + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### สภาพแวดล้อม ERC721 {#environment-erc721} + +
+ ค่ากำหนดโฮสต์ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ผู้ให้บริการคลาวด์AWS
ขนาดอินสแตนซ์t2.micro
ระบบเครือข่ายเครือข่ายย่อยส่วนตัว
ระบบการปฏิบัติการLinux Ubuntu 20.04 LTS - Focal Fossa
ขีดจำกัดของ File Descriptor65535
การประมวลผลสูงสุดของผู้ใช้65535
+
+
+
+
+ +
+ ค่ากำหนดของบล็อกเชน +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
เวอร์ชัน Polygon Edgeคอมมิต 8a033aa1afb191abdac04636d318f83f32511f3c ใน Develop Branch
โหนดตัวตรวจสอบความถูกต้อง6
โหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้อง0
ฉันทามติIBFT PoA
เวลาในการสร้างบล็อก2 วินาที
ขีดจำกัดค่าแก๊สต่อบล็อก5242880
การใช้บล็อกโดยเฉลี่ย94%
+
+
+
+
+ +
+ การกำหนดค่า Loadbot +
+
+ + + + + + + + + + + + + +
ธุรกรรมทั้งหมด2000
ธุรกรรมที่ส่งต่อวินาที200
ประเภทธุรกรรมการสร้างโทเค็น ERC721
+
+
+
+
+ +
+ บันทึก Loadbot + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/th-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/th-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..21d0decea6 --- /dev/null +++ b/archive/edge/th-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,951 @@ +--- +id: test-2022-03-23 +title: 23 มีนาคม 2022 +description: "การทดสอบประสิทธิภาพจากวันที่ 23 มีนาคม" +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### สรุป {#summary} + +:::caution +โปรดทราบว่าเราใช้สำหรับการดำเนินการการทดสอบเหล่านี้`loadbot`จะถูกนำไปใช้เพื่อทำการตั้งค่าดังกล่าว ตอนนี้มีการตั้งค่าที่อ่อนค่าลง +::: + +ทำการทดสอบนี้เพื่อวัดค่าการโอนโทเค็น SC ERC20 และฟังก์ชันการสร้างโทเค็น SC ERC721 ที่มีโหลดจำนวนมาก และความเร็วของธุรกรรมบนโหนดที่มีทรัพยากรฮาร์ดแวร์ที่สูงขึ้น + +เป้าหมายคือเพื่อตรวจสอบว่าทุกอย่างทำงานตามที่คาดไว้หรือไม่ในระหว่างที่มีโหลดจำนวนมากนั่นคือเหตุผลที่เราแนะนำเมตริกค่าแก๊สในเอาต์พุต Loadbot ซึ่งแสดงให้เราเห็นว่ามีการบรรจุธุรกรรมต่างๆ ลงในบล็อกนั้นอย่างถูกต้องหรือไม่ + +ส่งธุรกรรมทั้งหมดไปไปยังโหนดเดี่ยวผ่าน GRPC API และรับธุรกรรมผ่าน JSON-RPC APIหลังจากดำเนินการกับธุรกรรมทั้งหมดแล้ว จะมีการอ่านข้อมูลค่าแก๊สจากแต่ละบล็อกโดยใช้เมธอด eth_getBlockByNumber JSON-RPC + +เป้าหมายของเราคือการพยายามทำให้ได้ค่า TPS สูงสุดเท่าที่เป็นไปได้ โดยใช้ทรัพย์การฮาร์ดแวร์ที่มีอยู่เพื่อเป้าหมายนี้ เราได้ปรับเปลี่ยนพารามิเตอร์ขีดจำกัดค่าแก๊สต่อบล็อกและเวลาในการสร้างบล็อก เพื่อให้เราได้ผลลัพธ์เป็นค่า TPS ที่ดีที่สุดเท่าที่ทำได้ ตลอดจนรักษาความสมบูรณ์และความมั่นคงของระบบ + +:::info ขีดจำกัดค่าแก๊สต่อบล็อก +เพิ่มขีดจำกัดค่าแก๊สต่อบล็อกเป็นจำนวนที่ค่อนข้างสูงได้ หากธุรกรรมกำลังใช้ค่าแก๊สจำนวนมากในการดำเนินการในตัวอย่างด้านล่าง การสร้างโทเค็น ERC721 ทำงานเร็วขึ้นมากเมื่อตั้งค่าขีดจำกัดค่าแก๊สต่อบล็อกเป็น 80 000 000 (แทนที่จะเป็น 20 ล้าน) แต่ด้วยการโอนโทเค็น ERC20 ที่มีขีดจำกัดค่าแก๊สต่อบล็อก 80 ล้าน เซิร์ฟเวอร์จะขัดข้อง +::: + +:::info สภาพแวดล้อมการใช้งานจริง +เมื่อกำหนดค่าสภาพแวดล้อมของการใช้งานจริง คุณต้องใช้ความระมัดระวังหากคุณพยายามทำให้ได้มาซึ่งประสิทธิภาพระดับสูงของเชนหากกำหนดพารามิเตอร์ขีดจำกัดของแก๊สต่อบล็อกไว้เป็นค่าสูง กำหนดเวลาในการสร้างบล็อกไว้เป็น 1 วินาที และมีโหลดธุรกรรมจำนวนมากในโหนดเดี่ยว โหนดนั้นจะใช้ RAM จำนวนมาก (หรือ RAM ทั้งหมดที่สามารถใช้ได้) และอาจทำให้เซิร์ฟเวอร์ขัดข้องโปรดใช้ loadbot เพื่อทดสอบทุกอย่างโดยละเอียด ติดตามการใช้ทรัพยากรระบบ และกำหนดค่าพารามิเตอร์ต่างๆ ของคุอย่างสอดคล้อง + +::: + +:::info ข้อผิดพลาดด้านหน่วยความจำเต็ม (Out of Memory) +แพ็คเกจ Linux บางส่วนจะยุติกระบวนการที่มีการใช้ RAM สูงมากโดยอัตโนมัติ (ข้อผิดพลาด OOM) เพื่อรักษาเสถียรภาพของระบบเอาต์พุตบันทึกของข้อผิดพลาด OOM นี้จะมีลักษณะเหมือนด้านล่าง +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### ผลการโอนประเภท EOA ถึง EOA {#results-of-eoa-to-eoa-transfers} +| เมตริก | ค่า | +| ------ | ----- | +| ประเภทธุรกรรม | EOA ถึง EOA | +| ธุรกรรมต่อวินาที | 689 | +| ธุรกรรมล้มเหลว | 0 | +| ธุรกรรมประสบความสำเร็จ | 20000 | +| บล็อกทั้งหมดที่ใช้ | 25 | +| เวลาเรียกใช้ทั้งหมด | 29.921110 วินาที | + +### ผลการโอนโทเค็น ERC20 {#results-of-erc20-token-transfers} + +| เมตริก | ค่า | +| ------ | ----- | +| ประเภทธุรกรรม | ERC20 | +| ธุรกรรมต่อวินาที | 500 | +| ธุรกรรมล้มเหลว | 0 | +| ธุรกรรมประสบความสำเร็จ | 20000 | +| บล็อกทั้งหมดที่ใช้ | 33 | +| เวลาเรียกใช้ธุรกรรม ERC20 | 40.402900 วินาที | +| เวลาปรับใช้ SC | 2.004140 วินาที | + +### ผลการสร้างโทเค็น ERC721 {#results-of-erc721-token-minting} + +| เมตริก | ค่า | +| ------ | ----- | +| ประเภทธุรกรรม | ERC721 | +| ธุรกรรมต่อวินาที | 157 | +| ธุรกรรมล้มเหลว | 0 | +| ธุรกรรมประสบความสำเร็จ | 20000 | +| บล็อกทั้งหมดที่ใช้ | 124 | +| เวลาเรียกใช้ธุรกรรม ERC721 | 127.537340 วินาที | +| เวลาปรับใช้ SC | 2.004420 วินาที | + + +### ผลของการสร้างโทเค็น ERC721 ที่มีขีดจำกัดค่าแก๊สต่อบล็อกสูงมาก (80 ล้าน) {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| เมตริก | ค่า | +| ------ | ----- | +| ประเภทธุรกรรม | ERC721 | +| ธุรกรรมต่อวินาที | 487 | +| ธุรกรรมล้มเหลว | 0 | +| ธุรกรรมประสบความสำเร็จ | 20000 | +| บล็อกทั้งหมดที่ใช้ | 34 | +| เวลาเรียกใช้ธุรกรรม ERC721 | 41.098410 วินาที | +| เวลาปรับใช้ SC | 2.004300 วินาที | + + +### สภาพแวดล้อม EOA ถึง EOA {#environment-eoa-to-eoa} +
+ ค่ากำหนดโฮสต์ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ผู้ให้บริการคลาวด์AWS
ขนาดอินสแตนซ์c5.2xlarge
ระบบเครือข่ายเครือข่ายย่อยส่วนตัว
ระบบการปฏิบัติการAmazon Linux 2 AMI (HVM) - Kernel 5.10
ขีดจำกัดของ File Descriptor65535
การประมวลผลสูงสุดของผู้ใช้65535
+
+
+
+
+ +
+ ค่ากำหนดของบล็อกเชน +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
เวอร์ชัน Polygon Edgeคอมมิต 06e11eac8da98c79c938fc53dda2da3318cfbe04 ใน Develop Branch
โหนดตัวตรวจสอบความถูกต้อง4
โหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้อง0
ฉันทามติIBFT PoA
เวลาในการสร้างบล็อก1 วินาที
ขีดจำกัดค่าแก๊สต่อบล็อก20000000
ช่องสูงสุด1000000
การใช้บล็อกโดยเฉลี่ย84.00%
+
+
+
+
+ +
+ การกำหนดค่า Loadbot +
+
+ + + + + + + + + + + + + +
ธุรกรรมทั้งหมด20000
ธุรกรรมที่ส่งต่อวินาที689
ประเภทธุรกรรมการโอนประเภท EOA ถึง EOA
+
+
+
+
+ +
+ บันทึก Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### สภาพแวดล้อม ERC20 {#environment-erc20} +
+ ค่ากำหนดโฮสต์ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ผู้ให้บริการคลาวด์AWS
ขนาดอินสแตนซ์c5.2xlarge
ระบบเครือข่ายเครือข่ายย่อยส่วนตัว
ระบบการปฏิบัติการAmazon Linux 2 AMI (HVM) - Kernel 5.10
ขีดจำกัดของ File Descriptor65535
การประมวลผลสูงสุดของผู้ใช้65535
+
+
+
+
+ +
+ ค่ากำหนดของบล็อกเชน +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
เวอร์ชัน Polygon Edgeคอมมิต 06e11eac8da98c79c938fc53dda2da3318cfbe04 ใน Develop Branch
โหนดตัวตรวจสอบความถูกต้อง4
โหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้อง0
ฉันทามติIBFT PoA
เวลาในการสร้างบล็อก1 วินาที
ขีดจำกัดค่าแก๊สต่อบล็อก20000000
ช่องสูงสุด1000000
การใช้บล็อกโดยเฉลี่ย88.38%
+
+
+
+
+ +
+ การกำหนดค่า Loadbot +
+
+ + + + + + + + + + + + + +
ธุรกรรมทั้งหมด20000
ธุรกรรมที่ส่งต่อวินาที500
ประเภทธุรกรรมการโอน ERC20 ถึง ERC20
+
+
+
+
+ +
+ บันทึก Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### สภาพแวดล้อม ERC721 {#environment-erc721} +
+ ค่ากำหนดโฮสต์ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ผู้ให้บริการคลาวด์AWS
ขนาดอินสแตนซ์c5.2xlarge
ระบบเครือข่ายเครือข่ายย่อยส่วนตัว
ระบบการปฏิบัติการAmazon Linux 2 AMI (HVM) - Kernel 5.10
ขีดจำกัดของ File Descriptor65535
การประมวลผลสูงสุดของผู้ใช้65535
+
+
+
+
+ +
+ ค่ากำหนดของบล็อกเชน +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
เวอร์ชัน Polygon Edgeคอมมิต 06e11eac8da98c79c938fc53dda2da3318cfbe04 ใน Develop Branch
โหนดตัวตรวจสอบความถูกต้อง4
โหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้อง0
ฉันทามติIBFT PoA
เวลาในการสร้างบล็อก1 วินาที
ขีดจำกัดค่าแก๊สต่อบล็อก20000000
ช่องสูงสุด1000000
การใช้บล็อกโดยเฉลี่ย92.90%
+
+
+
+
+ +
+ การกำหนดค่า Loadbot +
+
+ + + + + + + + + + + + + +
ธุรกรรมทั้งหมด20000
ธุรกรรมที่ส่งต่อวินาที157
ประเภทธุรกรรมการสร้างโทเค็น ERC721
+
+
+
+
+ +
+ บันทึก Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### สภาพแวดล้อม ERC20 - ขีดจำกัดค่าแก๊สต่อบล็อกสูงมาก {#environment-erc20-very-high-block-gas-limit} +
+ ค่ากำหนดโฮสต์ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ผู้ให้บริการคลาวด์AWS
ขนาดอินสแตนซ์c5.2xlarge
ระบบเครือข่ายเครือข่ายย่อยส่วนตัว
ระบบการปฏิบัติการAmazon Linux 2 AMI (HVM) - Kernel 5.10
ขีดจำกัดของ File Descriptor65535
การประมวลผลสูงสุดของผู้ใช้65535
+
+
+
+
+ +
+ ค่ากำหนดของบล็อกเชน +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
เวอร์ชัน Polygon Edgeคอมมิต 06e11eac8da98c79c938fc53dda2da3318cfbe04 ใน Develop Branch
โหนดตัวตรวจสอบความถูกต้อง4
โหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้อง0
ฉันทามติIBFT PoA
เวลาในการสร้างบล็อก1 วินาที
ขีดจำกัดค่าแก๊สต่อบล็อก80000000
ช่องสูงสุด1000000
การใช้บล็อกโดยเฉลี่ย---
+
+
+
+
+ +
+ การกำหนดค่า Loadbot +
+
+ + + + + + + + + + + + + +
ธุรกรรมทั้งหมด20000
ธุรกรรมที่ส่งต่อวินาที---
ประเภทธุรกรรมการโอน ERC20 ถึง ERC20
+
+
+
+
+ +
+ บันทึกข้อผิดพลาด OOM + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### สภาพแวดล้อม ERC721 - ขีดจำกัดค่าแก๊สต่อบล็อกสูงมาก {#environment-erc721-very-high-block-gas-limit} +
+ ค่ากำหนดโฮสต์ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ผู้ให้บริการคลาวด์AWS
ขนาดอินสแตนซ์c5.2xlarge
ระบบเครือข่ายเครือข่ายย่อยส่วนตัว
ระบบการปฏิบัติการAmazon Linux 2 AMI (HVM) - Kernel 5.10
ขีดจำกัดของ File Descriptor65535
การประมวลผลสูงสุดของผู้ใช้65535
+
+
+
+
+ +
+ ค่ากำหนดของบล็อกเชน +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
เวอร์ชัน Polygon Edgeคอมมิต 06e11eac8da98c79c938fc53dda2da3318cfbe04 ใน Develop Branch
โหนดตัวตรวจสอบความถูกต้อง4
โหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้อง0
ฉันทามติIBFT PoA
เวลาในการสร้างบล็อก1 วินาที
ขีดจำกัดค่าแก๊สต่อบล็อก80000000
ช่องสูงสุด1000000
การใช้บล็อกโดยเฉลี่ย84.68%
+
+
+
+
+ +
+ การกำหนดค่า Loadbot +
+
+ + + + + + + + + + + + + +
ธุรกรรมทั้งหมด20000
ธุรกรรมที่ส่งต่อวินาที487
ประเภทธุรกรรมการสร้างโทเค็น ERC721
+
+
+
+
+ +
+ บันทึก Loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/th-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/th-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..88fdcf5328 --- /dev/null +++ b/archive/edge/th-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,563 @@ +--- +id: test-2022-07-04 +title: 4 กรกฎาคม 2022 +description: "การทดสอบประสิทธิภาพจากวันที่ 4 กรกฎาคม" +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### สรุป {#summary} + +:::caution +โปรดทราบว่าเราใช้สำหรับการดำเนินการการทดสอบเหล่านี้`loadbot`จะถูกนำไปใช้เพื่อทำการตั้งค่าดังกล่าว ตอนนี้มีการตั้งค่าที่อ่อนค่าลง +::: + +ทำการทดสอบนี้เพื่อวัดค่าการโอนโทเค็น SC ERC20 และฟังก์ชันการสร้างโทเค็น SC ERC721 ที่มีโหลดจำนวนมาก และความเร็วของธุรกรรมบนโหนดที่มีทรัพยากรฮาร์ดแวร์ที่สูงขึ้น + +เป้าหมายคือเพื่อตรวจสอบว่าทุกอย่างทำงานตามที่คาดไว้หรือไม่ในระหว่างที่มีโหลดจำนวนมากนั่นคือเหตุผลที่เราแนะนำเมตริกค่าแก๊สในเอาต์พุต Loadbot ซึ่งแสดงให้เราเห็นว่ามีการบรรจุธุรกรรมต่างๆ ลงในบล็อกนั้นอย่างถูกต้องหรือไม่ + +ส่งธุรกรรมทั้งหมดไปไปยังโหนดเดี่ยวผ่าน GRPC API และรับธุรกรรมผ่าน JSON-RPC APIหลังจากดำเนินการกับธุรกรรมทั้งหมดแล้ว จะมีการอ่านข้อมูลค่าแก๊สจากแต่ละบล็อกโดยใช้เมธอด eth_getBlockByNumber JSON-RPC + +เป้าหมายของเราคือการพยายามทำให้ได้ค่า TPS สูงสุดเท่าที่เป็นไปได้ โดยใช้ทรัพย์การฮาร์ดแวร์ที่มีอยู่เพื่อเป้าหมายนี้ เราได้ปรับเปลี่ยนพารามิเตอร์ขีดจำกัดค่าแก๊สต่อบล็อกและเวลาในการสร้างบล็อก เพื่อให้เราได้ผลลัพธ์เป็นค่า TPS ที่ดีที่สุดเท่าที่ทำได้ ตลอดจนรักษาความสมบูรณ์และความมั่นคงของระบบ + + +:::info สภาพแวดล้อมของการใช้งานจริง +เมื่อกำหนดค่าสภาพแวดล้อมของการใช้งานจริง คุณต้องใช้ความระมัดระวังหากคุณพยายามทำให้ได้มาซึ่งประสิทธิภาพระดับสูงของเชนหากกำหนดพารามิเตอร์ขีดจำกัดของแก๊สต่อบล็อกไว้เป็นค่าสูง กำหนดเวลาในการสร้างบล็อกไว้เป็น 1 วินาที และมีโหลดธุรกรรมจำนวนมากในโหนดเดี่ยว โหนดนั้นจะใช้ RAM จำนวนมาก (หรือ RAM ทั้งหมดที่สามารถใช้ได้) และอาจทำให้เซิร์ฟเวอร์ขัดข้องโปรดใช้ loadbot เพื่อทดสอบทุกอย่างโดยละเอียด ติดตามการใช้ทรัพยากรระบบ และกำหนดค่าพารามิเตอร์ต่างๆ ของคุอย่างสอดคล้อง +::: + + + +### ผลการโอนประเภท EOA ถึง EOA {#results-of-eoa-to-eoa-transfers} +| เมตริก | ค่า | +| ------ | ----- | +| ประเภทธุรกรรม | EOA ถึง EOA | +| ธุรกรรมต่อวินาที | 1428 | +| ธุรกรรมล้มเหลว | 0 | +| ธุรกรรมประสบความสำเร็จ | 30000 | +| บล็อกทั้งหมดที่ใช้ | 15 | +| เวลาเรียกใช้ทั้งหมด | 21.374620 วินาที | + +### ผลการโอนโทเค็น ERC20 {#results-of-erc20-token-transfers} + +| เมตริก | ค่า | +| ------ | ----- | +| ประเภทธุรกรรม | ERC20 | +| ธุรกรรมต่อวินาที | 1111 | +| ธุรกรรมล้มเหลว | 0 | +| ธุรกรรมประสบความสำเร็จ | 50000 | +| บล็อกทั้งหมดที่ใช้ | 38 | +| เวลาเรียกใช้ธุรกรรม ERC20 | 45.906450 วินาที | +| เวลาปรับใช้ SC | 2.006580 วินาที | + +### ผลการสร้างโทเค็น ERC721 {#results-of-erc721-token-minting} + +| เมตริก | ค่า | +| ------ | ----- | +| ประเภทธุรกรรม | ERC721 | +| ธุรกรรมต่อวินาที | 714 | +| ธุรกรรมล้มเหลว | 0 | +| ธุรกรรมประสบความสำเร็จ | 30000 | +| บล็อกทั้งหมดที่ใช้ | 39 | +| เวลาเรียกใช้ธุรกรรม ERC721 | 42.864140 วินาที | +| เวลาปรับใช้ SC | 2.005500 วินาที | + + + + +### สภาพแวดล้อม EOA ถึง EOA {#environment-eoa-to-eoa} +
+ ค่ากำหนดโฮสต์ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ผู้ให้บริการคลาวด์AWS EC2
ขนาดอินสแตนซ์c6a.48xlarge
ระบบเครือข่ายเครือข่ายย่อยส่วนตัว
ระบบการปฏิบัติการLinux Ubuntu 20.04 LTS - Focal Fossa
ขีดจำกัดของ File Descriptor65535
การประมวลผลสูงสุดของผู้ใช้65535
+
+
+
+
+ +
+ ค่ากำหนดของบล็อกเชน +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
เวอร์ชัน Polygon Edgeรุ่น v0.4.1
โหนดตัวตรวจสอบความถูกต้อง4
โหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้อง0
ฉันทามติIBFT PoA
เวลาในการสร้างบล็อก1 วินาที
ขีดจำกัดค่าแก๊สต่อบล็อก70778880
ช่องสูงสุด276480
การใช้บล็อกโดยเฉลี่ย59.34%
+
+
+
+
+ +
+ การกำหนดค่า Loadbot +
+
+ + + + + + + + + + + + + +
ธุรกรรมทั้งหมด30000
ธุรกรรมที่ส่งต่อวินาที1428
ประเภทธุรกรรมการโอนประเภท EOA ถึง EOA
+
+
+
+
+ +
+ บันทึก Loadbot + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### สภาพแวดล้อม ERC20 {#environment-erc20} +
+ ค่ากำหนดโฮสต์ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ผู้ให้บริการคลาวด์AWS EC2
ขนาดอินสแตนซ์c6a.48xlarge
ระบบเครือข่ายเครือข่ายย่อยส่วนตัว
ระบบการปฏิบัติการLinux Ubuntu 20.04 LTS - Focal Fossa
ขีดจำกัดของ File Descriptor65535
การประมวลผลสูงสุดของผู้ใช้65535
+
+
+
+
+ +
+ ค่ากำหนดของบล็อกเชน +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
เวอร์ชัน Polygon Edgeรุ่น v0.4.1
โหนดตัวตรวจสอบความถูกต้อง4
โหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้อง0
ฉันทามติIBFT PoA
เวลาในการสร้างบล็อก1 วินาที
ขีดจำกัดค่าแก๊สต่อบล็อก47185920
ช่องสูงสุด184320
การใช้บล็อกโดยเฉลี่ย81.29%
+
+
+
+
+ +
+ การกำหนดค่า Loadbot +
+
+ + + + + + + + + + + + + +
ธุรกรรมทั้งหมด50000
ธุรกรรมที่ส่งต่อวินาที1111
ประเภทธุรกรรมการโอน ERC20 ถึง ERC20
+
+
+
+
+ +
+ บันทึก Loadbot + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### สภาพแวดล้อม ERC721 {#environment-erc721} +
+ ค่ากำหนดโฮสต์ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ผู้ให้บริการคลาวด์AWS EC2
ขนาดอินสแตนซ์c6a.48xlarge
ระบบเครือข่ายเครือข่ายย่อยส่วนตัว
ระบบการปฏิบัติการLinux Ubuntu 20.04 LTS - Focal Fossa
ขีดจำกัดของ File Descriptor65535
การประมวลผลสูงสุดของผู้ใช้65535
+
+
+
+
+ +
+ ค่ากำหนดของบล็อกเชน +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
เวอร์ชัน Polygon Edgeรุ่น v0.4.1
โหนดตัวตรวจสอบความถูกต้อง4
โหนดที่ไม่ใช่โหนดตัวตรวจสอบความถูกต้อง0
ฉันทามติIBFT PoA
เวลาในการสร้างบล็อก1 วินาที
ขีดจำกัดค่าแก๊สต่อบล็อก94371840
ช่องสูงสุด1000000
การใช้บล็อกโดยเฉลี่ย93.88%
+
+
+
+
+ +
+ การกำหนดค่า Loadbot +
+
+ + + + + + + + + + + + + +
ธุรกรรมทั้งหมด30000
ธุรกรรมที่ส่งต่อวินาที714
ประเภทธุรกรรมการสร้างโทเค็น ERC721
+
+
+
+
+ +
+ บันทึก Loadbot + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/th-edge/troubleshooting.md b/archive/edge/th-edge/troubleshooting.md new file mode 100644 index 0000000000..0c43123aaf --- /dev/null +++ b/archive/edge/th-edge/troubleshooting.md @@ -0,0 +1,67 @@ +--- +id: troubleshooting +title: การแก้ไขปัญหา +description: "ส่วนการแก้ไขปัญหาสำหรับ Polygon Edge" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# การแก้ไขปัญหา {#troubleshooting} + +## ข้อผิดพลาด `method=eth_call err="invalid signature"` {#error} + +เมื่อคุณใช้วอลเล็ตเพื่อทำธุรกรรมกับ Polygon Edge โปรดตรวจสอบให้แน่ใจว่า ในการตั้งค่าเครือข่ายภายในของวอลเล็ตของคุณ: + +1. `chainID` นั้นถูกต้อง`chainID` เริ่มต้นสำหรับ Edge คือ `100` แต่สามารถปรับแต่งได้โดยใช้ค่าสถานะ Genesis`--chain-id` + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. ตรวจสอบให้แน่ใจว่าในฟิลด์ "RPC URL" คุณใช้พอร์ต JSON RPC ของโหนดที่คุณกำลังเชื่อมต่ออยู่ + + +## วิธีรับ WebSocket URL {#how-to-get-a-websocket-url} + +ตามค่าเริ่มต้น เมื่อคุณเรียกใช้ Polygon Edge จะมีการแสดง WebSocket Endpoint โดยใช้ที่ตั้งของเชนเป็นหลักใช้โครงสร้าง URL `wss://` กับลิงก์ HTTPS และ `ws://` สำหรับ HTTP + +Localhost WebSocket URL: +````bash +ws://:/ws +```` +โปรดจำไว้ว่าหมายเลขพอร์ตขึ้นอยู่กับพอร์ต JSON-RPC ที่คุณได้เลือกไว้สำหรับโหนดดังกล่าว + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## ข้อผิดพลาด `insufficient funds` เมื่อพยายามปรับใช้สัญญา {#error-when-trying-to-deploy-a-contract} + +หากคุณได้รับข้อผิดพลาดนี้ โปรดตรวจสอบให้แน่ใจว่าคุณมีทุนเพียงพอในที่อยู่ที่ต้องการ และที่อยู่ที่ใช้คือที่อยู่ที่ถูกต้อง
ในการตั้งค่ายอดคงเหลือที่วางไว้ล่วงหน้า คุณสามารถใช้ค่าสถานะ Genesis `genesis [--premine ADDRESS:VALUE]` ในขณะที่สร้างไฟล์ Genesisตัวอย่างการใช้ค่าสถานะนี้: +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +ซึ่งวางล่วงหน้า 1000000000000000000000 WEI ใน 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862 + + +## โทเค็น ERC20 ไม่ได้ถูกปล่อยขณะใช้ Chainbridge {#erc20-tokens-not-released-while-using-chainbridge} + +หากคุณพยายามโอนโทเค็น ERC20 ระหว่าง Polygon POS และเครือข่าย Edge ภายใน และมีการฝากโทเค็น ERC20 ของคุณพร้อมกับดำเนินการกับข้อเสนอที่ตัวรีเลย์ แต่ไม่มีการปล่อยโทเค็นในเครือข่าย Edge ของคุณ โปรดตรวจสอบให้แน่ใจว่า ERC20 Handler ในเชน Polygon Edge มีโทเค็นเพียงพอที่จะปล่อย
+สัญญา Handler ในเชนปลายทางต้องมีโทเค็นเพียงพอที่จะปล่อยสำหรับโหมดปลดล็อกหากคุณไม่มีโทเค็น ERC20 ใน ERC20 Handler ของเครือข่าย Edge ภายในของคุณ โปรดสร้างโทเค็นใหม่และโอนไปยัง ERC20 Handler + +## `Incorrect fee supplied` ข้อผิดพลาดเมื่อใช้ Chainbridge {#error-when-using-chainbridge} + +คุณอาจได้รับข้อผิดพลาดนี้เมื่อพยายามโอนโทเค็น ERC20 ระหว่างเชน Mumbai Polygon POS และการตั้งค่า Polygon Edge ภายในข้อผิดพลาดนี้ปรากฏขึ้นเมื่อคุณตั้งค่าค่าธรรมเนียมในการปรับใช้โดยใช้แฟล็ก `--fee` แต่คุณไม่ได้ตั้งค่าเดียวกันในธุรกรรมการฝากเงินคุณสามารถใช้คำสั่งด้านล่างเพื่อเปลี่ยนค่าธรรมเนียม: +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +คุณสามารถค้นหาข้อมูลเพิ่มเติมเกี่ยวกับแฟล็กนี้[ได้ที่](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md)นี่ + + + + + diff --git a/archive/edge/th-edge/validator-hosting.md b/archive/edge/th-edge/validator-hosting.md new file mode 100644 index 0000000000..e28c0b6abc --- /dev/null +++ b/archive/edge/th-edge/validator-hosting.md @@ -0,0 +1,261 @@ +--- +id: validator-hosting +title: การโฮสต์ตัวตรวจสอบความถูกต้อง +description: "ข้อกำหนดเกี่ยวกับการโฮสต์สำหรับ Polygon Edge" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +ด้านล่างเป็นคำแนะนำเกี่ยวกับการโฮสต์โหนดตัวตรวจสอบความถูกต้องในเครือข่าย Polygon Edge อย่างถูกต้องโปรดให้ความสำคัญกับรายการทั้งหมดที่ระบุไว้ด้านล่าง เพื่อคุณสามารถมั่นใจ +ว่ามีการกำหนดค่าตัวตรวจสอบความถูกต้องของคุณอย่างถูกต้อง เพื่อให้ทำงานได้อย่างปลอดภัย เสถียร และมีประสิทธิภาพ + +## พื้นฐานความรู้ {#knowledge-base} + +ก่อนคุณลองเรียกใช้โหนดตัวตรวจสอบความถูกต้อง โปรดอ่านเอกสารนี้อย่างละเอียด +เอกสารเพิ่มเติมที่อาจเป็นประโยชน์คือ: + +- [การติดตั้ง](get-started/installation) +- [การตั้งค่าในระบบคลาวด์](get-started/set-up-ibft-on-the-cloud) +- [คำสั่ง CLI](get-started/cli-commands) +- [ไฟล์กำหนดค่าของเซิร์ฟเวอร์](configuration/sample-config) +- [คีย์ส่วนตัว](configuration/manage-private-keys) +- [เมตริก Prometheus](configuration/prometheus-metrics) +- [ตัวจัดการข้อมูลลับ](/docs/category/secret-managers) +- [สำรอง/กู้คืนข้อมูล](working-with-node/backup-restore) + +## ข้อกำหนดของระบบขั้นต่ำ {#minimum-system-requirements} + +| ประเภท | ค่า | กำหนดตาม | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 2 คอร์ |
  • จำนวนการสืบค้น JSON-RPC
  • ขนาดของสถานะบล็อกเชน
  • ขีดจำกัดค่าแก๊สต่อบล็อก
  • เวลาในการสร้างบล็อก
| +| RAM | 2 GB |
  • จำนวนการสืบค้น JSON-RPC
  • ขนาดของสถานะบล็อกเชน
  • ขีดจำกัดค่าแก๊สต่อบล็อก
| +| ดิสก์ |
  • พาร์ติชั่นรูทขนาด 10 GB
  • พาร์ติชั่นรูทขนาด 30 GB โดยใช้ LVM ในการขยายดิสก์
|
  • ขนาดของสถานะบล็อกเชน
| + + +## การกำหนดค่าบริการ {#service-configuration} + +คุณจำเป็นต้องเรียกใช้ไบนารี `polygon-edge` เป็นบริการของระบบโดยอัตโนมัติ เมื่อทำการเชื่อมต่อเครือข่าย และมีฟังก์ชันเริ่ม / หยุด / รีสตาร์ทเราแนะนำให้ใช้ตัวจัดการบริการ เช่น `systemd.` + +ตัวอย่าง ไฟล์กำหนดค่าระบบ `systemd`: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### ไบนารี {#binary} + +ในเวิร์กโหลดด้านการใช้งานจริง ควรปรับใช้ไบนารี `polygon-edge` จากไบนารีของรุ่น GitHub ที่สร้างไว้ล่วงหน้า ไม่ใช่การคอมไพล์ไบนารีด้วยตนเอง +:::info + +เมื่อคอมไพล์สาขา GitHub `develop` ด้วยตนเอง คุณอาจนำการเปลี่ยนแปลงที่ส่งผลกระทบเข้ามาในสภาพแวดล้อมของคุณได้ +ด้วยเหตุนี้ เราจึงแนะนำให้ปรับใช้ไบนารีของ Polygon Edge เฉพาะจากรุ่นต่างๆ เพราะว่าจะมี +ข้อมูลเกี่ยวกับการเปลี่ยนแปลงที่ส่งผลกระทบและวิธีการแก้ไขปัญหานั้น + +::: + +โปรดดูภาพรวมของวิธีการติดตั้งอย่างละเอียดได้ใน[การติดตั้ง](/docs/edge/get-started/installation) + +### การจัดเก็บข้อมูล {#data-storage} + +คุณต้องติดตั้งโฟลเดอร์ `data/` ที่ปรากฏสถานะบล็อกเชนทั้งหมดลงในดิสก์ / ไดรฟ์ข้อมูลเฉพาะ ซึ่งทำให้ดำเนิน +การสำรองข้อมูลดิสก์โดยอัตโนมัติ การเพิ่มไดรฟ์ข้อมูล และ (ไม่บังคับ) การติดตั้งดิสก์ไดรฟ์ข้อมูลกับอินสแตนซ์อื่น ในกรณีเกิดเหตุขัดข้อง + + +### ไฟล์บันทึก {#log-files} + +คุณต้องสับเปลี่ยนไฟล์บันทึกเป็นแบบรายวัน (โดยใช้เครื่องมือ เช่น `logrotate`) +:::warning + +หากมีการกำหนดค่าโดยไม่มีการสับเปลี่ยนบันทึก ไฟล์บันทึกอาจจะใช้พื้นที่ดิสก์ที่มีอยู่ทั้งหมด ซึ่งอาจส่งผลกระทบต่อช่วงเวลาการดำเนินงานของตัวตรวจสอบความถูกต้อง + +::: + +ตัวอย่าง การกำหนค่า `logrotate`: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +ดูคำแนะนำเกี่ยวกับการจัดเก็บบันทึกได้ที่ส่วน[การทำบันทึก](#logging)ด้านล่าง + +### รูปแบบการขึ้นต่อกันเพิ่มเติม {#additional-dependencies} + +`polygon-edge` ได้รับการคอมไพล์แบบคงที่ โดยไม่ต้องมีรูปแบบการขึ้นต่อกันของระบบปฏิบัติการที่โฮสต์เพิ่มเติม + +## การบำรุงรักษา {#maintenance} + +ด้านล่างนี้เป็นหลักปฏิบัติที่ดีที่สุดซึ่งใช้ในการบำรุงรักษาโหนดตัวตรวจสอบความถูกต้องที่อยู่ในระหว่างการเรียกใช้งานในเครือข่าย Polygon Edge + +### การสำรองข้อมูล {#backup} + +วิธีการสำรองข้อมูลที่แนะนำใช้กับโหนดของ Polygon Edge มีสองแบบ + +หากทำได้ เราขอแนะนำให้คุณใช้ทั้งสองวิธีการนั้นกับการสำรองข้อมูลใน Polygon Edge ซึ่งเป็นตัวเลือกที่ใช้งานได้อยู่เสมอ + +* ***การสำรองข้อมูลไดรฟ์ข้อมูล***: + การสำรองข้อมูลที่เพิ่มขึ้นทุกวันในไดรฟ์ข้อมูล `data/` ของโหนด Polygon Edge หรือการสำรองข้อมูลทั้งหมดใน VM หากสามารถทำเช่นนั้นได้ + + +* ***การสำรองข้อมูลใน Polygon Edge***: แนะนำงาน CRON รายวัน ซึ่งสำรองข้อมูลของ Polygon Edge เป็นประจำ และย้ายไฟล์ `.dat` ไปพื้นที่ภายนอกหรือไปยังที่เก็บข้อมูลอ็อบเจ็กต์ในคลาวด์ที่ปลอดภัย + +ในทางที่ดีที่สุด การสำรองข้อมูลของ Polygon Edge ต้องไม่ทับซ้อนกับการสำรองข้อมูลในไดรฟ์ข้อมูลซึ่งระบุไว้ด้านบน + +ดูคำแนะนำเกี่ยวกับวิธีการสำรองข้อมูลของ Polygon Edge ได้ที่[การสำรอง/กู้คืนข้อมูลอินสแตนซ์ของโหนด](working-with-node/backup-restore) + +### การทำบันทึก {#logging} + +ในบันทึกต่างๆ ที่โหนด Polygon Edge แสดงข้อมูลควร: +- ได้รับการส่งไปยังพื้นที่จัดเก็บข้อมูลภายในที่มีความสามารถในการจัดทำดัชนีและการค้นหา +- มีระยะเวลาเก็บรักษาบันทึก 30 วัน + +หากคุณตั้งค่าตัวตรวจสอบความถูกต้องของ Polygon Edge ครั้งนี้เป็นครั้งแรก เราแนะนำให้เริ่มโหนด +พร้อมกับตัวเลือก `--log-level=DEBUG` เพื่อให้สามารถดีบักปัญหาต่างๆ ที่คุณอาจพบได้อย่างรวดเร็ว + +:::info + + `--log-level=DEBUG` จะสร้างเอาต์พุตบันทึกของโหนดมีความละเอียดที่สุดเท่าที่ทำได้ +บันทึกเกี่ยวกับดีบักจะเพิ่มขนาดของไฟล์บันทึกขึ้นเป็นอย่างมาก ซึ่งต้องพิจารณาถึงเมื่อตั้งค่าโซลูชันเกี่ยวกับการสับเปลี่ยนบันทึก + +::: +### แพทช์ความปลอดภัยของระบบปฏิบัติการ {#os-security-patches} + +ผู้ดูแลต้องตรวจสอบให้แน่ใจว่ามีการอัปเดตระบบปฏิบัติการของอินสแตนซ์ตัวตรวจสอบความถูกต้องอย่างสม่ำเสมอโดยใช้แพทช์ล่าสุด และให้ดำเนินการเช่นนั้นอย่างน้อยหนึ่งครั้งต่อเดือน + +## เมตริก {#metrics} + +### เมตริกของระบบ {#system-metrics} + +ผู้ดูแลต้องตั้งค่าวิธีการติดตามเมตริกบางส่วนของระบบ (เช่น Telegraf + InfluxDB + Grafana หรือ SaaS ของบุคคลภายนอก) + +เมตริกที่ต้องอยู่ภายใต้การติดตามและต้องมีการตั้งค่าการแจ้งเตือนสัญญาณอันตราย: + +| ชื่อเมตริก | ค่าเกณฑ์การแจ้งเตือน | +|-----------------------|-------------------------------| +| การใช้ CPU (%) | มากกว่า 90% เป็นเวลานานกว่า 5 นาที | +| การใช้ RAM (%) | มากกว่า 90% เป็นเวลานานกว่า 5 นาที | +| การใช้รูทดิสก์ | มากกว่า 90% | +| การใช้ดิสก์ข้อมูล | มากกว่า 90% | + +### เมตริกของตัวตรวจสอบความถูกต้อง {#validator-metrics} + +ผู้ดูแลต้องกำหนดค่าชุดเมตริกจาก Prometheus API ของ Polygon Edge เพื่อให้สามารถ +ติดตามการดำเนินการของบล็อกเชน + +โปรดดู[เมตริก Prometheus](configuration/prometheus-metrics) เพื่อทำความเข้าใจว่ามีการแสดงเมตริกใดบ้าง ตลอดจนวิธีการกำหนดค่าชุด เมตริก Prometheus + + +คุณต้องให้ความสำคัญเป็นพิเศษกับบรรดาเมตริกดังต่อไปนี้: +- ***เวลาในการสร้างบล็อก*** - หากเวลาในการสร้างบล็อกนานกว่าปกติ อาจมีปัญหาเกิดขึ้นกับเครือข่าย +- ***จำนวนรอบฉันทามติ*** - หากมีมากกว่า 1 รอบ อาจมีปัญหาเกี่ยวกับชุดตัวตรวจสอบความถูกต้องในเครือข่าย +- ***จำนวนเพียร์*** - หากจำนวนเพียร์ลดลง แสดงว่ามีปัญหาเกี่ยวกับการเชื่อมต่อในระบบ + +## การรักษาความปลอดภัย {#security} + +ด้านล่างนี้เป็นหลักปฏิบัติที่ดีที่สุดซึ่งใช้ในการรักษาความปลอดภัยของโหนดตัวตรวจสอบความถูกต้องที่อยู่ในระหว่างการเรียกใช้งานในเครือข่าย Polygon Edge + +### บริการ API {#api-services} + +- ***JSON-RPC*** - +มีแต่บริการ API ที่ต้องแสดงต่อสาธารณะ (ผ่าน Load Balancer หรือโดยตรง) +ให้เรียกใช้ API นี้กับอินเทอร์เฟซทั้งหมดหรือกับที่อยู่ IP เฉพาะ ( ตัวอย่าง: `--json-rpc 0.0.0.0:8545` หรือ `--json-prc 192.168.1.1:8545` ) +:::info +เนื่องจากเป็น API ที่แสดงต่อสาธารณะ เราแนะนำให้คุณมี Load Balancer / Reverse Proxy อยู่เบื้องหน้าเพื่อสร้างความปลอดภัยและจำกัดอัตรา + +::: + + +- ***LibP2P*** - +นี่เป็น API ระบบเครือข่ายที่โหนดใช้ในการสื่อสารกับเพียร์ต้องเรียกใช้กับอินเทอร์เฟซทั้งหมดหรือกับที่อยู่ IP เฉพาะ +( `--libp2p 0.0.0.0:1478` หรือ `--libp2p 192.168.1.1:1478` )ไม่ควรแสดง API นี้ต่อสาธารณะ +แต่โหนดอื่นทั้งหมดต้องสามารถเข้าถึง API นั้นได้ +:::info + +หากมีการใช้กับ localhost ( `--libp2p 127.0.0.1:1478` ) โหนดอื่นๆ จะไม่สามารถเชื่อมต่อได้ + +::: + + +- ***GRPC*** - +ใช้ API นี้เฉพาะสำหรับการเรียกใช้คำสั่งของตัวดำเนินการเท่านั้นดังนั้น ให้เรียกใช้ API นั้นกับ localhost เท่านั้น ( `--grpc-address 127.0.0.1:9632` ) + +### ข้อมูลลับของ Polygon Edge {#polygon-edge-secrets} + +ไม่ควรเก็บข้อมูลลับของ Polygon Edge (คีย์ `ibft` และ `libp2p` ) ไว้ในระบบไฟล์ของเครื่อง +ควรใช้[ตัวจัดการข้อมูลลับ](configuration/secret-managers/set-up-aws-ssm)ที่ระบบรองรับแทน +ควรใช้การจัดเก็บข้อมูลลับในระบบไฟล์ภายในเฉพาะในสภาพแวดล้อมที่ไม่มีส่วนได้เสียกับการใช้งานจริง + +## อัปเดต {#update} + +ต่อไปนี้ คือวิธีการอัปเดตที่ต้องการสำหรับโหนดตัวตรวจสอบความถูกต้อง ตามที่ระบุไว้ในคำแนะนำทีละขั้นตอน + +### กระบวนการอัปเดต {#update-procedure} + +- ให้ดาวน์โหลดไบนารี Polygon Edge ล่าสุดจาก GitHub อย่างเป็นทางการ[รุ่นต่างๆ](https://github.com/0xPolygon/polygon-edge/releases) +- ให้หยุดบริการ Polygon Edge ( ตัวอย่าง: `sudo systemctl stop polygon-edge.service` ) +- ให้แทนที่ไบนารี `polygon-edge` ที่มีอยู่ด้วยไบนารีที่ดาวน์โหลดมา ( ตัวอย่าง: `sudo mv polygon-edge /usr/local/bin/` ) +- โปรดตรวจสอบว่าคุณใช้เวอร์ชัน `polygon-edge` ที่ถูกต้อง โดยการเรียกใช้ `polygon-edge version` - ต้องสอดคล้องกับเวอร์ชันที่เผยแพร่ +- ก่อนเริ่มใช้งานบริการ `polygon-edge` ตรวจสอบเอกสารประกอบการเผยแพร่ว่า จำเป็นต้องมีการดำเนินขั้นเกี่ยวกับความเข้ากันได้แบบย้อนหลังหรือไม่ +- เริ่มบริการ `polygon-edge` ( ตัวอย่าง: `sudo systemctl start polygon-edge.service` ) +- สุดท้าย โปรดตรวจสอบเอาต์พุตบันทึก `polygon-edge` และทำให้มั่นใจว่า ทุกสิ่งทุกอย่างสามารถเรียกใช้ได้โดยไม่มีบันทึก `[ERROR]` + +:::warning + +เมื่อมีรุ่นที่ส่งผลกระทบ ให้ใช้กระบวนการอัปเดตนี้กับโหนดทั้งหมด เนื่องจาก +ไบนารีที่กำลังใช้งานอยู่จะไม่สามารถเข้ากันได้กับรุ่นใหม่ + +หมายความว่า ต้องหยุดการทำงานของเชนเป็นระยะเวลาสั้นๆ ( จนกว่าจะมีการแทนที่ไบนารี `polygon-edge` และรีสตาร์ทบริการ ) +ดังนั้น คุณต้องวางแผนให้สอดคล้องกัน + +คุณสามารถใช้เครื่องมือต่างๆ เช่น **[Ansible](https://www.ansible.com/)** หรือสคริปต์ที่กำหนดเองบางอย่างเพื่อทำการอัปเดตอย่างมีประสิทธิภาพ +และลดลงช่วงเวลาที่เชนไม่ทำงาน + +::: + +## กระบวนการเริ่มต้นระบบ {#startup-procedure} + +ต่อไปนี้เป็นขั้นตอนที่ต้องการสำหรับกระบวนการเริ่มต้นสำหรับตัวตรวจสอบความถูกต้อง Polygon Edge + +- อ่านเอกสารที่ระบุไว้ในส่วน[พื้นฐานความรู้](#knowledge-base) +- แพทช์ระบบปฏิบัติการล่าสุดกับโหนดตัวตรวจสอบความถูกต้อง +- ดาวน์โหลดไบนารี `polygon-edge` ล่าสุดจาก GitHub อย่างเป็นทางการ[รุ่นต่างๆ](https://github.com/0xPolygon/polygon-edge/releases) และวางไว้ในอินสแตนซ์ภายใน `PATH` +- เริ่มใช้งาน[ตัวจัดการข้อมูลลับ](/docs/category/secret-managers)ที่ระบบรองรับ โดยใช้คำสั่ง CLI `polygon-edge secrets generate` +- สร้างและเก็บข้อมูลลับโดยใช้ [คำสั่ง CLI](/docs/edge/get-started/cli-commands#secrets-init-flags) `polygon-edge secrets init` +- จดบันทึกค่า `NodeID` และ `Public key (address)` +- สร้างไฟล์ `genesis.json` ตามที่ระบุไว้ใน[การตั้งค่าคลาวด์](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators) โดยใช้ [คำสั่ง CLI](/docs/edge/get-started/cli-commands#genesis-flags) `polygon-edge genesis` +- สร้างไฟล์การกำหนดค่าเริ่มต้นโดยใช้ [คำสั่ง CLI](/docs/edge/configuration/sample-config) `polygon-edge server export` +- แก้ไขไฟล์ `default-config.yaml` เพื่อจัดลงในสภาพแวดล้อมโหนดตัวตรวจสอบความถูกต้องภายใน ( เช่น พาธไฟล์ เป็นต้น ) +- สร้างบริการ Polygon Edge ( `systemd` หรือคล้ายกัน ) โดยไบนารี `polygon-edge` จะเรียกใช้งานเซิร์ฟเวอร์จากไฟล์ `default-config.yaml` +- เริ่มเซิร์ฟเวอร์ Polygon Edge โดยเริ่มใช้งานบริการ ( ตัวอย่าง: `systemctl start polygon-edge` ) +- โปรดตรวจสอบเอาต์พุตบันทึก `polygon-edge` และทำให้มั่นใจว่ากำลังมีการสร้างบล็อกและไม่ปรากฏบันทึก `[ERROR]` +- โปรดตรวจสอบการใช้งานของเชนโดยการเรียกใช้เมธอด JSON-RPC เช่น [`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid) diff --git a/archive/edge/th-edge/working-with-node/backup-restore.md b/archive/edge/th-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..d600a67cc2 --- /dev/null +++ b/archive/edge/th-edge/working-with-node/backup-restore.md @@ -0,0 +1,93 @@ +--- +id: backup-restore +title: การสำรอง/กู้คืนข้อมูลอินสแตนซ์ของโหนด +description: "วิธีการสำรองและกู้คืนข้อมูลอินแสตนส์ของโหนด Polygon Edge" +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## ภาพรวม {#overview} + +คู่มือนี้อธิบายรายละเอียดเกี่ยวกับการสำรองข้อมูลและกู้คืนข้อมูลอินสแตนซ์ของโหนด Polygon Edge +โดยมีการระบุโฟลเดอร์พื้นฐานและเนื้อหา ตลอดจนการอธิบายว่า ไฟล์ไหนเป็นส่วนสำคัญในการดำเนินการสำรองและกู้คืนข้อมูลที่ประสบความสำเร็จ + +## โฟลเดอร์พื้นฐาน {#base-folders} + +Polygon Edge ใช้ LevelDB เป็นกลไกในการจัดเก็บ +เมื่อคุณเริ่มโหนด Polygon Edge จะมีการสร้างโฟลเดอร์ย่อยดังต่อไปนี้ในไดเรกทอรีการใช้งานที่กำหนดไว้: +* **blockchain** - จัดเก็บข้อมูลบล็อกเชน +* **trie** - จัดเก็บ Merkle trie (ข้อมูลสถานะทั้งระบบ) +* **keystore** - จัดเก็บคีย์ส่วนตัวให้กับไคลเอ็นต์รวมถึงคีย์ส่วนตัว libp2p และคีย์ส่วนตัวการซีล/ตัวตรวจสอบความถูกต้อง +* **consensus** - จัดเก็บข้อมูลฉันทามติที่ไคลเอ็นต์อาจต้องใช้ในการดำเนินงานตอนนี้ โฟลเดอร์นี้จะจัดเก็บ*คีย์ของตัวตรวจสอบความถูกต้องส่วนตัว*ของโหนด + +การเก็บรักษาโฟลเดอร์เหล่านี้เป็นสิ่งสำคัญในการทำให้อินสแตนซ์ Polygon Edge ทำงานได้อย่างงราบรื่น + +## สร้างการสำรองข้อมูลจากโหนดที่ใช้งานอยู่และกู้คืนข้อมูลสำหรับโหนดใหม่ {#create-backup-from-a-running-node-and-restore-for-new-node} + +ส่วนนี้จะแนะนำคุณตลอดการสร้างข้อมูลเก็บถาวรของบล็อกเชนในโหนดที่ใช้งานอยู่และกู้คืนข้อมูลนั้นในอินสแตนซ์อื่น + +### การสำรองข้อมูล {#backup} + +คำสั่ง `backup` จะดึงข้อมูลบล็อกจากโหนดที่ใช้งานอยู่โดยใช้ gRPC และสร้างไฟล์เก็บถาวรหากไม่มีการให้ `--from` และ `--to` ไว้ในคำสั่ง คำสั่งนี้จะดึงข้อมูลบล็อกตั้งแต่บล็อก genesis จนถึงบล็อกล่าสุด + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### การกู้คืน {#restore} + +เซิร์ฟเวอร์นำเข้าบล็อกจากพื้นที่เก็บถาวรตั้งแต่เริ่มต้น เมื่อมีการเริ่มด้วยค่าสถานะ `--restore`โปรดตรวจสอบว่ามีคีย์สำหรับโหนดใหม่ดูข้อมูลเพิ่มเติมเกี่ยวกับการนำเข้าหรือสร้างคีย์ได้ที่[ส่วนตัวจัดการข้อมูลลับ](/docs/edge/configuration/secret-managers/set-up-aws-ssm) + +```bash +$ polygon-edge server --restore archive.dat +``` + +## การสำรอง/กู้คืนข้อมูลทั้งหมด {#back-up-restore-whole-data} + +ส่วนนี้แนะนำคุณตลอดการสำรองข้อมูล รวมถึงคีย์และข้อมูลสถานะ และกู้คืนข้อมูลนั้นในอินสแตนซ์ใหม่ + +### ขั้นตอนที่ 1: หยุดไคลเอ็นต์ที่ใช้งานอยู่ {#step-1-stop-the-running-client} + +เนื่องจาก Polygon Edge ใช้ **LevelDB** เพื่อจัดเก็บข้อมูล ต้องหยุดการทำงานของโหนดในระหว่างการสำรองข้อมูล +เนื่องจาก **LevelDB** ไม่อนุญาตให้เข้าถึงไฟล์ฐานข้อมูลของตนพร้อมกัน + +นอกจากนี้ Polygon Edge ยังทำการ Flush ข้อมูลเมื่อมีการหยุดทำงาน + +ขั้นตอนแรกจะเกี่ยวข้องกับการหยุดการทำงานของไคลเอ็นต์ที่ใช้งานอยู่ (ผ่านการใช้ตัวจัดการบริการหรือผ่านการใช้กลไกอื่นใดที่ส่งสัญญาณ SIGINT แก่การประมวลผล) +เพื่อให้สามารถทริกเกอร์อีเวนต์ 2 อย่าง ในขณะที่กำลังค่อยๆ ปิดระบบ: +* การเรียกใช้การ Flush ข้อมูลกับดิสก์ +* การปล่อยไฟล์ DB ที่ LevelDB ล็อกไว้ + +### ขั้นตอนที่ 2: สำรองข้อมูลไดเรกทอรี {#step-2-backup-the-directory} + +ตอนนี้ไคลเอ็นต์ไม่ใช้งานอยู่แล้ว เราจึงสามารถสำรองไดเรกทอรีข้อมูลในเครื่องอื่น +โปรดจำไว้ว่า ไฟล์ที่มีนามสกุล `.key` จะประกอบด้วยข้อมูลเกี่ยวกับคีย์ส่วนตัว ซึ่งสามารถนำไปใช้เพื่อแสดงตัวเป็นโหนดปัจจุบันได้ +และห้ามมิให้แชร์ไฟล์นั้นกับบุคคลที่สาม/บุคคลที่ไม่ได้รู้จัก + +:::info + +โปรดสำรองและกู้คืนไฟล์ `genesis` ที่สร้างมาโดยตนเอง เพื่อให้โหนดที่กู้คืนมานั้นสามารถใช้งานได้อย่างเต็มที่ + +::: + +## การกู้คืน {#restore-1} + +### ขั้นตอนที่ 1: หยุดไคลเอ็นต์ที่ใช้งานอยู่ {#step-1-stop-the-running-client-1} + +หากมีอินสแตนซ์ใดของ Polygon Edge กำลังทำงานอยู่ ให้หยุดใช้งานเพื่อให้ดำเนินการตามขั้นตอนที่ 2 ประสบความสำเร็จ + +### ขั้นตอนที่ 2: คัดลอกไดเรกทอรีข้อมูลที่สำรองไว้ไปยังโฟลเดอร์ที่ต้องการ {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +เมื่อไคลเอ็นต์ไม่ได้ใช้งานอยู่ จะสามารถคัดลอกไดเรกทอรีข้อมูลซึ่งมีการสำรองไว้ก่อนหน้านี้ไปยังโฟลเดอร์ที่ต้องการได้ +นอกจากนี้ ให้กู้คืนไฟล์ `genesis` ที่คัดลอกไว้ก่อนหน้า + +### ขั้นตอนที่ 3: เรียกใช้ ไคลเอ็นต์ Polygon Edge ในขณะระบุไดเรกทอรีข้อมูลที่ถูกต้อง {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +เพื่อให้ Polygon Edge สามารถใช้ไดเรกทอรีข้อมูลที่กู้คืนมาได้ ในขณะเรียกใช้งาน ผู้ใช้ต้องระบุพาธไปยัง +ไดเรกทอรีข้อมูลโปรดดูข้อมูลเกี่ยวกับค่าสถานะ `data-dir` ในส่วน[คำสั่ง CLI](/docs/edge/get-started/cli-commands) diff --git a/archive/edge/th-edge/working-with-node/query-json-rpc.md b/archive/edge/th-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..7820ea0f17 --- /dev/null +++ b/archive/edge/th-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,87 @@ +--- +id: query-json-rpc +title: ค้นหา JSON RPC Endpoint +description: "ค้นหาข้อมูลและเริ่มต้นเชนด้วยบัญชีที่วางไว้ล่วงหน้า" +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## ภาพรวม {#overview} + +เลเยอร์ JSON-RPC ของ Polygon Edge ให้ฟังก์ชันในการโต้ตอบกับบล็อกเชนอันแสนง่ายดายกับนักพัฒนาผ่านคำขอ HTTP + +ตัวอย่างนี้ครอบคลุมการใช้เครื่องมือ เช่น **curl** เพื่อค้นหาข้อมูล และเริ่มต้นเชนด้วยบัญชีที่วางไว้ล่วงหน้าและส่งธุรกรรม + +## ขั้นตอนที่ 1: สร้างไฟล์ Genesis ด้วยบัญชีที่วางไว้ล่วงหน้า {#step-1-create-a-genesis-file-with-a-premined-account} + +ในการสร้างไฟล์ Genesis ให้เรียกใช้คำสั่งต่อไปนี้: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +ค่าสถานะ **Premine** กำหนดที่อยู่ที่ควรรวมอยู่กับยอดคงเหลือเริ่มต้นในไฟล์ **Genesis**
ในกรณีนี้ ที่อยู่ `0x1010101010101010101010101010101010101010` จะมี **ยอดคงเหลือตามค่าเริ่มต้น** ในการเริ่มต้นเป็น +`0xD3C21BCECCEDA1000000`(โทเค็นแบบดั้งเดิม1 ล้าน) + +หากเราต้องการระบุยอดคงเหลือ เราสามารถแยกยอดคงเหลือและที่อยู่ด้วย `:` ดังนี้: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +ยอดคงเหลือสามารถเป็นค่า `hex` หรือ `uint256` ก็ได้ + +:::warning วางบัญชีล่วงหน้าก็ต่อเมื่อคุณมีคีย์ส่วนตัวสำหรับบัญชีเท่านั้น! +หากคุณวางบัญชีล่วงหน้าและไม่มีคีย์ส่วนตัวในการเข้าถึง ยอดคงเหลือที่วางไว้ล่วงหน้าของคุณจะใช้งานไม่ได้ +::: + +## ขั้นตอนที่ 2: เริ่ม Polygon edge ในโหมด Dev {#step-2-start-the-polygon-edge-in-dev-mode} + +ในการเริ่ม Polygon Edge ในโหมดการพัฒนา ซึ่งอธิบายไว้ในส่วน[คำสั่ง CLI](/docs/edge/get-started/cli-commands) +ให้เรียกใช้ชุดคำสั่งต่อไปนี้: +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## ขั้นตอนที่ 3: ค้นหายอดคงเหลือในบัญชี {#step-3-query-the-account-balance} + +ตอนนี้ไคลเอ็นต์เริ่มทำงานในโหมด Dev โดยใช้ไฟล์ Genesis ที่สร้างใน**ขั้นตอนที่ 1** เราสามารถใช้เครื่องมือเช่น**curl** เพื่อค้นหายอดคงเหลือในบัญชี: +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +คำสั่งควรส่งกลับเอาต์พุตต่อไปนี้: +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## ขั้นตอนที่ 4: ส่งธุรกรรมการโอน {#step-4-send-a-transfer-transaction} + +ตอนนี้เราได้ยืนยันว่าบัญชีที่เราตั้งค่าไว้เป็นบัญชีที่วางล่วงหน้ามียอดคงเหลือที่ถูกต้องแล้ว เราสามารถโอน Ether บางส่วนได้: + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/th-edge/working-with-node/query-operator-info.md b/archive/edge/th-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..8dc8711e21 --- /dev/null +++ b/archive/edge/th-edge/working-with-node/query-operator-info.md @@ -0,0 +1,85 @@ +--- +id: query-operator-info +title: ค้นหาข้อมูลเกี่ยวกับตัวดำเนินการ +description: "วิธีการค้นหาข้อมูลของตัวดำเนินการ" +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## ข้อกำหนดเบื้องต้น {#prerequisites} + +คู่มือฉบับนี้ถือว่าคุณได้ปฏิบัติตามคำแนะนำว่าด้วย[การตั้งค่าภายใน](/docs/edge/get-started/set-up-ibft-locally) หรือ[คู่มือเกี่ยวกับการตั้งค่าคลัสเตอร์ IBFT ในคลาวด์](/docs/edge/get-started/set-up-ibft-on-the-cloud) + +คุณจำเป็นต้องมีโหนดที่สามารถใช้งานได้เพื่อให้สามารถค้นหาข้อมูลในตัวดำเนินการได้ทุกประเภท + +เมื่อใช้ Polygon Edge ตัวดำเนินการโหนดสามารถควบคุมและรับแจ้งข้อมูลเกี่ยวกับการดำเนินการของโหนดที่พวกเขาใช้งาน
+ตลอดระยะเวลาพวกเขาสามารถใช้เลเยอร์ข้อมูลของโหนดที่สร้างขึ้นบน gRPC และได้รับมาซึ่งข้อมูลสำคัญ โดยไม่ต้องค้นหาข้อมูลผ่านการตรวจสอบบันทึก + +:::note + +หากโหนดของคุณไม่สามารถเรียกใช้ได้กับ `127.0.0.1:8545` คุณต้องเพิ่มค่าสถานะ `--grpc-address ` ลงในรายการคำสั่งที่ระบุไว้ในเอกสารนี้ + +::: + +## ข้อมูลเกี่ยวกับเพียร์ {#peer-information} + +### รายการเพียร์ {#peers-list} + +หากต้องการรายการของเพียร์ที่เชื่อมต่ออยู่ทั้งหมด (รวมถึงตัวโหนดที่ใช้งานอยู่) ให้เรียกใช้คำสั่งดังต่อไปนี้: +````bash +polygon-edge peers list +```` + +คำสั่งนี้จะส่งกลับรายการที่อยู่ libp2p ซึ่งในตอนนี้เป็นเพียร์ของไคลเอ็นต์ที่เรียกใช้งานอยู่ + +### สถานะของเพียร์ {#peer-status} + +เพื่อได้มาซึ่งสถานะเพียร์รายใดรายหนึ่งโดยเฉพาะ ให้เรียกใช้: +````bash +polygon-edge peers status --peer-id
+```` +โดยพารามิเตอร์ *address* เป็นที่อยู่ libp2p ของเพียร์ + +## ข้อมูล IBFT {#ibft-info} + +หลายครั้งตัวดำเนินการอาจต้องการทราบข้อมูลเกี่ยวกับสถานะโหนดที่อยู่ในระหว่างการปฏิบัติการในฉันทามติ IBFT + +โชคดีที่ Polygon Edge มีวิธีการง่ายๆ ในการค้นหาข้อมูลนี้ + +### สแนปชอต {#snapshots} + +เมื่อคุณเรียกใช้คำสั่งดังต่อไปนี้ คำสั่งนั้นจะส่งกลับสแนปชอตล่าสุด +````bash +polygon-edge ibft snapshot +```` +เพื่อค้นหาแสนปชอตในส่วนสูงเฉพาะ (จำนวนบล็อก) ตัวดำเนินการสามารถเรียกใช้: +````bash +polygon-edge ibft snapshot --num +```` + +### ผู้สมัคร {#candidates} + +เพื่อได้รับข้อมูลล่าสุดของผู้สมัคร ตัวดำเนินการสามารถเรียกใช้: +````bash +polygon-edge ibft candidates +```` +คำสั่งดำเนินการค้นหาชุดผู้สมัครที่เสนอในปัจจุบัน เช่นเดียวกับผู้สมัครที่ยังไม่ได้รวม + +### สถานะ {#status} + +คำสั่งดังต่อไปนี้จะส่งกลับคีย์ตัวตรวจสอบความถูกต้องปัจจุบันของไคลเอ็นต์ IBFT ที่ใช้งานอยู่: +````bash +polygon-edge ibft status +```` + +## พูลธุรกรรม {#transaction-pool} + +เพื่อค้นหาจำนวนธุรกรรมปัจจุบันในพูลธุรกรรม ตัวดำเนินการสามารถเรียกใช้: +````bash +polygon-edge txpool status +```` diff --git a/archive/edge/tl-edge/additional-features/blockscout.md b/archive/edge/tl-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..10b969483f --- /dev/null +++ b/archive/edge/tl-edge/additional-features/blockscout.md @@ -0,0 +1,418 @@ +--- +id: blockscout +title: Blockscout +description: Paano mag-set up ng instance ng Blockscout na gagana sa Polygon Edge. +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## Pangkalahatang-ideya {#overview} +Idinedetalye sa gabay na ito kung paano mag-compile at mag-deploy ng instance ng Blockscout na gagana sa Polygon-Edge. +Ang Blockscout ay may sariling [dokumentasyon](https://docs.blockscout.com/for-developers/manual-deployment) ngunit gabay na ito ay nakatuon sa simple ngunit detalyadong step-by-step na tagubilin kung paano mag-set up ng instance ng Blockscout. + +## Kapaligiran {#environment} +* Operating System: Ubuntu Server 20.04 LTS [link sa pag-download](https://releases.ubuntu.com/20.04/) na may mga sudo permission +* Server Hardware: 8CPU / 16GB RAM / 50GB HDD (LVM) +* Database Server: Nakatalagang server na may 2 CPU / 4GB RAM / 100GB SSD / PostgreSQL 13.4 + +### DB Server {#db-server} +Ang kinakailangan para sa pagsunod sa gabay na ito ay magkaroon ng database server na handa na, at ng naka-configure na database at db user. +Hindi idedetalye sa gabay na ito kung paano i-deploy at i-configure ang PostgreSQL server. +Maraming gabay sa kung paano gawin ito, halimbawa ang [DigitalOcean Guide](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart) + +:::info DISCLAIMER + +Ang layunin lang ng gabay na ito ay tulungan kang patakbuhin ang Blockscout sa iisang instance na hindi magandang setup sa produksyon. +Para sa produksyon, maaari kang magpasok sa arkitektura ng reverse proxy, load balancer, mga pagpipilian sa kakayahang mai-scale at iba pa. + +::: + +# Pamamaraan sa Deployment ng Blockscout {#blockscout-deployment-procedure} + +## Bahagi 1 - i-install ang mga dependency {#part-1-install-dependencies} +Bago tayo magsimula, kailangan nating tiyakin na na-install natin ang lahat ng binary na ginagamit ng blockscout. + +### I-update at i-upgrade ang system {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### Idagdag ang mga erlang repo {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### Idagdag ang NodeJS repo {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### I-install ang Rust {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### i-install ang kinakailangang bersyon ng Erlang {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### I-install ang kinakailangang bersyon ng Elixir {#install-required-version-of-elixir} +Dapat ay `1.13` ang bersyon ng Elixir. Kung susubukan nating i-install ang bersyong ito mula sa opisyal na repo, +ang `erlang` ay mag-a-update sa `Erlang/OTP 25` at hindi natin gusto iyon. +Dahil dito, kailangan nating i-install ang partikular na precompiled na bersyon `elixir` mula sa page ng mga release ng GitHub. + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +Ngayon, kailangan nating maayos na mag-set up ng `exlixir` mga binary na sistema. +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +Tingnan kung maayos na naka-install ang `elixir` at `erlang` sa pamamagitan ng pagpapatakbo sa `elixir -v`. +Ito dapat ang maging output: +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning + +Ang `Erlang/OTP` ay dapat maging bersyon `24` at ang `Elixir` ay dapat maging bersyon `1.13.*`. +Kung hindi ganoon ang kaso, makakaranas ka ng mga isyu sa pag-compile ng Blockscout at/o sa pagpapatakbo nito. + +::: +:::info + +Tingnan ang opisyal na ***[page ng mga kinakailangan ng Blockscout](https://docs.blockscout.com/for-developers/information-and-settings/requirements)*** + +::: + +### I-install ang NodeJS {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### I-install ang Cargo {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### I-install ang iba pang dependency {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### Kung gusto mo, i-install ang postgresql client para matingnan ang iyong koneksyon sa db {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## Bahagi 2 - itakda ang mga environment variable {#part-2-set-environment-variables} +Kailangan nating itakda ang mga environment variable bago tayo magsimula sa pag-compile ng Blockscout. +Sa gabay na ito, itatakda lang natin ang minimum na kinakailangan para mapagana ito. +Makikita mo [rito](https://docs.blockscout.com/for-developers/information-and-settings/env-variables) ang kumpletong listahan ng mga variable na maaari mong itakda + +### Itakda ang koneksyon sa database bilang environment variable {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +Ngayon, subukan ang iyong koneksyon sa DB gamit ang mga ibinigay na parameter. +Dahil nagbigay ka ng mga PG env var, dapat ay nakakakonekta ka sa database sa pamamagitan lang ng pagpapatakbo sa: +```bash +psql +``` + +Kung naka-configure nang tama ang database, dapat kang makakita ng prompt ng psql: +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +Kung hindi, maaari kang makakakita ng error tulad nito: +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +Sa ganitong sitwasyon, maaaring makatulong sa iyo ang [mga dokumentong ito](https://ubuntu.com/server/docs/databases-postgresql). + +:::info Koneksyon sa DB + +Siguraduhing nalutas mo na ang lahat ng isyu sa koneksyon sa db bago magpatuloy sa susunod na bahagi. +Kakailanganin mong magbigay ng mga pribilehiyo ng superuser sa user ng blockscout. + +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## Bahagi 3 - i-clone at i-compile ang Blockscout {#part-3-clone-and-compile-blockscout} +Ngayon, masisimulan na natin sa wakas ang pag-install ng Blockscout. + +### I-clone ang Blockscout repo {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### Bumuo ng sikretong key base para maprotektahan ang build ng produksyon {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +Sa pinakahuling linya, dapat kang makakita ng mahabang string ng mga random na character. +Dapat itong itakda bilang iyong `SECRET_KEY_BASE` environment variable, bago ang susunod na hakbang. +Halimbawa: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### Itakda ang mode ng produksyon {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### I-compile {#compile} +ang Cd sa clone directory at simulang mag-compile + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info + +Kung nag-deploy ka dati, alisin ang mga static na asset sa dating build na ***mix phx.digest.clean***. + +::: + +### I-migrate ang mga database {#migrate-databases} +:::info + +Mabibigo ang bahaging ito kung hindi mo na-set up nang maayos ang iyong koneksyon sa DB, hindi ka nagbigay, +o mali ang mga tinukoy mong parameter sa DATABASE_URL environment variable. +Kailangang magkaroon ng mga pribilehiyo ng superuser ang user ng database. + +::: +```bash +mix do ecto.create, ecto.migrate +``` + +Kung kailangan mong i-drop muna ang database, patakbuhin +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### I-install ang mga npm dependency at i-compile ang mga frontend asset {#install-npm-dependencies-and-compile-frontend-assets} +Kailangan mong baguhin ang directory sa folder na naglalaman ng mga frontend asset. + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info Maghintay + +Maaaring abutin nang ilang minuto ang pag-compile ng mga asset na ito, at wala itong ipapakitang output. +Maaaring magmukhang hindi umuusad ang proseso, pero maghintay lang. +Kapag tapos na ang proseso ng pag-compile, dapat itong magkaroon ng output na tulad nito: `webpack 5.69.1 compiled with 3 warnings in 104942 ms` + +::: + +### Gumawa ng mga static na asset {#build-static-assets} +Para sa hakbang na ito, kailangan mong bumalik sa root ng clone folder ng iyong Blockscout. +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### Bumuo ng mga self-signed na certificate {#generate-self-signed-certificates} +:::info + +Maaari mong laktawan ang hakbang na ito kung hindi mo gagamitin ang `https`. + +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## Bahagi 4 - gumawa at magpatakbo ng serbisyo ng Blockscout {#part-4-create-and-run-blockscout-service} +Sa bahaging ito, kailangan nating mag-set up ng serbisyo sa sistema dahil gusto nating tumakbo ang Blockscout sa background at magpatuloy ito pagkatapos na mag-reboot ng sistema. + +### Gumawa ng file ng serbisyo {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### I-edit ang file ng serbisyo {#edit-service-file} +Gamitin ang paboritong linux text editor mo para i-edit ang file na ito at i-configure ang serbisyo. +```bash +sudo vi /etc/systemd/system/explorer.service +``` +Ganito dapat ang maging hitsura ng mga nilalaman ng explorer.service: file: +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### I-enable ang pagsisimula ng serbisyo sa boot ng sistema {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### Ilipat ang clone folder ng iyong Blockscout sa system-wide na lokasyon {#move-your-blockscout-clone-folder-to-system-wide-location} +Kinakailangan ng serbisyo ng Blockscout na magkaroon ng access sa folder na na-clone mo mula sa Blockscout repo at kailangan nitong ma-compile ang lahat ng asset. +```bash +sudo mv ~/blockscout /usr/local +``` + +### Gumawa ng mga file ng env var na gagamitin ng serbisyo ng Blockscout {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info + +Gamitin ang `SECRET_KEY_BASE` na binuo mo sa Bahagi 3. + +::: +I-save ang file at lumabas.. + +### Panghuli, simulan ang serbisyo ng Blockscout {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## Part 5 - subukan ang functionality ng instance ng Blockscout mo {#part-5-test-out-the-functionality-of-your-blockscout-instance} +Ngayon, ang kailangan na lang gawin ay tingnan kung tumatakbo ang serbisyo ng Blockscout. +Tingnan ang status ng serbisyo sa: +```bash +sudo systemctl status explorer.service +``` + +Para tingnan ang output ng serbisyo: +```bash +sudo journalctl -u explorer.service -f +``` + +Maaari mong tingnan kung mayroong ilang bagong port sa pakikinig: +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +Dapat kang makakuha ng listahan ng mga port sa pakikinig at sa listahan, mayroon dapat na ganito: +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +Pinapatakbo ng serbisyo sa web ng Blockscout ang port at protocol na tinukoy sa file ng env. Sa halimbawang ito, tumatakbo ito sa `4000`(http). +Kung ok ang lahat, dapat mong ma-access ang web portal ng Blockscout gamit ang `http://:4000`. + +## Mga Pagsasaalang-alang {#considerations} +Para sa pinakamahusay na performance, ipinapayo na magkaroon ng nakatalaga/lokal na non-validator node ng buong archive ng `polygon-edge` +na eksklusibong gagamitin para sa mga query sa Blockscout. +Ang `json-rpc` API ng node na ito ay hindi kailangang ipakita sa publiko dahil pinapatakbo ng Blockscout ang lahat ng query mula sa backend. + + +## Kongklusyon {#final-thoughts} +Katatapos lang nating mag-deploy ng isang instance ng Blockscout, na gumagana nang maayos, ngunit para sa produksyon, dapat mong pag-isipang ilagay ang instance na ito sa likod ng reverse proxy tulad ng Nginx. +Dapat mo ring pag-isipan ang kakayahang mai-scale ng database at instance, depende sa iyong kaso ng paggamit. + +Dapat mong tingnan ang opisyal na [dokumentasyon ng Blockscout](https://docs.blockscout.com/) dahil maraming opsyon doon para sa pag-customize. \ No newline at end of file diff --git a/archive/edge/tl-edge/additional-features/chainbridge/definitions.md b/archive/edge/tl-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..b1e10e930f --- /dev/null +++ b/archive/edge/tl-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,216 @@ +--- +id: definitions +title: Mga Pangkalahatang Kahulugan +description: Mga Pangkalahatang Kahulugan para sa mga terminong ginamit sa chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## Relayer {#relayer} +Isang relayer na uri ng bridge ang Chainbridge. Ang tungkulin ng isang relayer ay bumoto para sa pagpapatupad ng kahilingan (kung ilang token ang gagastusin/ilalabas, halimbawa). Sinusubaybayan nito ang mga kaganapan mula sa bawat chain, at bumuboto para sa isang panukala sa Bridge contract ng destination chain kapag nakatanggap ito ng `Deposit`event mula sa isang chain. Tumatawag ng paraan sa Bridge contract ang isang relayer para maisagawa ang panukala pagkatapos maisumite ang kailangang bilang ng mga boto. Itinatalaga ng bridge ang pagpapatupad sa Handler contract. + + +## Mga uri ng mga kontrata {#types-of-contracts} +Sa ChainBridge, may tatlong uri ng kontrata sa bawat chain, na tinatawag na Bridge/Handler/Target. + +| **Uri** | **Paglalarawan** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Bridge contract | Isang Bridge contract na namamahala sa mga kahilingan, boto, at pagpapatupad na kailangang i-deploy sa bawat chain. Tatawag ang mga user`deposit` sa Bridge para simulan ang paglipat, at itatalaga ni Bridge ang proseso sa Handler contract na naaayon sa Target contract. Kapag naging matagumpay ang Handler contract sa pagtawag sa Target contract, maglalabas ang Bridge contract ng `Deposit`na kaganapan para abisuhan ang mga relayer. | +| Handler contract | Nakikipag-ugnayan ang kontrata na ito sa Target contract para magsagawa ng deposito o panukala. Pinapatunayan nito ang kahilingan ng user, tinatawagan ang Target contract at tumutulong sa ilang setting para sa Target contract. May ilang partikular na Handler contract para tawagan ang bawat Target contract na may ibang interface. Nagiging bridge ang mga hindi direktang tawag ng Handler contract para i-enable ang paglipat ng anumang uri ng mga asset o data. Sa kasalukuyan, mayroong tatlong uri ng mga Handler contract na ipinapatupad ng ChainBridge: ERC20Handler, ERC721Handler, at GenericHandler. | +| Target contract | Isang kontrata na namamahala ng mga asset na ipapalit o ang mga mensaheng inililipat sa pagitan ng mga chain. Gagawin ang pakikipag-ugnayan sa kontratang ito mula sa bawat panig ng bridge. | + +
+ +![Arkitektura ng ChainBridge](/img/edge/chainbridge/architecture.svg) *Arkitektura ng ChainBridge* + +
+ +
+ +![Workflow ng paglilipat ng token ng ERC20](/img/edge/chainbridge/erc20-workflow.svg) *hal. Workflow ng paglilipat ng token ng ERC20* + +
+ +## Mga uri ng mga account {#types-of-accounts} + +Pakitiyak na may sapat na mga native token ang mga account para lumikha ng mga transaksyon bago magsimula. Maaari kang magtalaga ng mga premined na balanse sa mga account sa Polygon Edge kapag bumubuo ng genesis block. + +| **Uri** | **Paglalarawan** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Admin | Bilang default, bibigyan ng tungkulin ng admin ang account na ito. | +| User | Ang account ng nagpadala/tatanggap na nagpapadala/tumatanggap ng mga asset. Ang account ng nagpapadala ang magbabayad ng mga gas fee kapag inaaprubahan ang mga paglilipat ng token at tumatawag ng deposito sa Bridge contract para simulan ang isang paglipat. | + +:::info Ang tungkulin ng admin +Mayroong ilang pagkilos na maaari lang gawin ng account na may tungkulin ng admin. Bilang default, ang deployer ng Bridge contract ang may tungkulin ng admin. Makikita mo sa ibaba kung paano bigyan ng tungkulin ng admin ang ibang account o tanggalin ito. + +### Magdagdag ng tungkulin ng admin {#add-admin-role} + +Nagdaragdag ng isang admin + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### Bawiin ang tungkulin ng admin {#revoke-admin-role} + +Nag-aalis ng isang admin + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## Ang mga operasyon na pinapayagan ng `admin`account ay makikita sa ibaba. {#account-are-as-below} + +### Magtakda ng Resource {#set-resource} + +Magrehistro ng resource ID na may address ng kontrata para sa isang handler. + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Gawing nabu-burn/nami-mint ang kontrata {#make-contract-burnable-mintable} + +Magtakda ng token contract bilang nami-mint/nabu-burn sa isang handler. + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Kanselahin ang panukala {#cancel-proposal} + +Kanselahin ang panukala para sa pagpapatupad + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### I-pause/I-unpause {#pause-unpause} + +I-pause pansamantala ang mga pagpapatupad ng deposito, paggawa ng panukala, pagboto, at pagdeposito. + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### Baguhin ang Fee {#change-fee} + +Baguhin ang fee na ibabayad sa Bridge Contract + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### Magdagdag/Mag-alis ng isang relayer {#add-remove-a-relayer} + +Magdagdag ng isang account bilang bagong relayer o mag-alis ng isang account mula sa mga relayer + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### Baguhin ang relayer threshold {#change-relayer-threshold} + +Baguhin ang bilang ng mga kinakailangang boto para sa pagpapatupad ng panukala + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## Chain ID {#chain-id} + +Isang arbitrary value ang Chainbridge `chainId`na ginagamit sa bridge para makilala ang pagkakaiba ng mga blockchain network, at kailangan itong nasa saklaw ng uint8. Para hindi malito, magkaiba sila ng chain ID ng network. Kailangang maging natatangi ang value na ito, ngunit hindi nito kailangang maging pareho sa ID ng network. + +Sa halimbawang ito, itinakda natin ang `99`sa`chainId`, dahil ang chain ID ng Mumbai testnet ay`80001`, na hindi maaaring katawanin ng isang uint8. + +## Resource ID {#resource-id} + +Isang natatanging 32-bytes value ang resource ID sa cross-chain environment, na nauugnay sa isang tiyak na asset (resource) na inililipat sa pagitan ng mga network. + +Ang resource ID ay arbitrary, ngunit bilang kalakaran, kadalasan na naglalaman ng chain ID ang huling byte ng source chain (ang network kung saan nagmula ang asset na ito). + +## JSON-RPC URL para sa Polygon PoS {#json-rpc-url-for-polygon-pos} + +Para sa gabay na ito, gagamitin natin ang https://rpc-mumbai.matic.today, isang pampublikong JSON-RPC URL na inilaan ng Polygon, na maaaring mayroong mga limit sa trapiko o rate. Gagamitin lang ito para kumonekta sa Polygon Mumbai testnet. Pinapayuhan ka naming kunin ang JSON-RPC URL mo sa pamamagitan ng isang external service tulad ng Infura dahil magpapadala ng maraming katanungan/kahilingan sa JSON-RPC ang pag-deploy ng mga kontrata. + +## Mga paraan sa pagproseso ng paglipat ng mga token {#ways-of-processing-the-transfer-of-tokens} +Kapag inililipat ang mga ERC20 token sa pagitan ng mga chain, maaari silang maproseso sa dalawang magkaibang mode: + +### Lock/release na mode {#lock-release-mode} +Source chain : Maila-lock ang mga token na ipinapadala mo sa Handler Contract.
+Destination chain: Maa-unlock at maililipat ang kaparehong halaga ng mga token na ipinadala mo sa source chain mula sa Handler contract patungo sa account ng tatanggap sa destination chain. + +### Burn/mint mode {#burn-mint-mode} +Source chain: Mabu-burn ang mga token na ipinapadala mo...
Destination chain: Mami-mint sa destination chain at ipapadala sa account ng tatanggap ang kaparehong halaga ng mga token na ipinadala mo at na-burn sa source chain. + +Puwede kang gumamit ng iba't ibang mode sa bawat chain. Nangangahulugan ito na maaari mong i-lock ang isang token sa main chain habang nagmi-mint ng isang token sa subchain para ilipat. Halimbawa, maaaring maging makabuluhan na i-lock/pakawalan ang mga token kung kontrolado ang kabuuang supply o mint schedule. Maaaring ma-mint/ma-burn ang mga token kung ang kontrata sa subchain ay kailangang sumunod sa supply sa main chain. + +Ang default mode ay lock/release mode. Kung gusto mong gawing nami-mint/nabu-burn ang mga Token, kailangan mong tawagin ang`adminSetBurnable`na method. Kung gusto mong mag-mint ng mga token sa pagpapatupad, kailangan mong bigyan ng `minter`na tungkulin ang ERC20 Handler contract. + + diff --git a/archive/edge/tl-edge/additional-features/chainbridge/overview.md b/archive/edge/tl-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..298f50a83a --- /dev/null +++ b/archive/edge/tl-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Pangkalahatang-ideya +description: Pangkalahatang-ideya ng ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Ano ang ChainBridge? {#what-is-chainbridge} + +Isang modular multi-directional blockchain bridge ang Chainbridge na sumusuporta sa EVM at mga Substrate compatible chain, na binuo ng ChainSafe. Pinapahintulutan nito ang mga user na ilipat ang lahat ng uri ng mga asset o mensahe sa pagitan ng dalawang magkaibang chain. + +Para alamin pa ang tungkol sa ChainBridge, bisitahin muna ang [mga opisyal na dokumento](https://chainbridge.chainsafe.io/) na inilaan ng mga developer nito. + +Inilaan ang gabay na ito para tumulong sa pag-integrate ng Chainbridge sa Polygon Edge. Ipinapakita nito ang setup ng bridge sa pagitan ng gumaganang Polygon PoS (Mumbai testnet) at lokal na Polygon Edge network. + +## Mga Kinakailangan {#requirements} + +Sa gabay na ito, patatakbuhin mo ang mga Polygon Edge node, ChainBridge relayer (higit pa tungkol nito[ dito](/docs/edge/additional-features/chainbridge/definitions)), at ang cb-sol-cli tool, na isang CLI tool para lokal na mai-deploy ang mga kontrata, pagrerehistro ng resource, at pagbabago ng mga setting para sa bridge (maaari mo rin [itong](https://chainbridge.chainsafe.io/cli-options/#cli-options) tingnan). Kailangan ang sumusunod na mga enviroment bago simulan ang setup: + +* Go: >= 1.17 +* Node.js >= 16.13.0 +* Git + + +Bilang karagdagan, kailangan mong i-clone ang sumusunod na mga repository kasama ang mga bersyon para mapatakbo ang ilang application. + +* [Polygon Edge](https://github.com/0xPolygon/polygon-edge) : sa`develop` na branch +* [ChainBridge](https://github.com/ChainSafe/ChainBridge): v1.1.5 +* [Mga ChainBridge Deploy Tool](https://github.com/ChainSafe/chainbridge-deploy) : `f2aa093`sa`main` branch + + +Kailangan mong i-set up ang Polygon Edge network bago magpatuloy sa susunod na seksyon. Tingnan ang [Lokal na Setup](/docs/edge/get-started/set-up-ibft-locally) o [Cloud Setup](/docs/edge/get-started/set-up-ibft-on-the-cloud) para sa higit pang mga detalye. \ No newline at end of file diff --git a/archive/edge/tl-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/tl-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..6059f525e7 --- /dev/null +++ b/archive/edge/tl-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,142 @@ +--- +id: setup-erc20-transfer +title: Paglilipat ng ERC20 Token +description: Paano i-setup ang paglilipat ng ERC-20 sa chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Sa ngayon, nag set up kami ng bridge para magpalitan ng mga asset/data sa pagitan ng Polygon PoS at Polygon Edge chain. Ang seksyong ito ay gagabay sa iyo para i-set up ang ERC20 bridge at ipadala ang mga token sa pagitan ng iba't ibang blockchain. + +## Hakbang 1: Iparehistro ang resource ID {#step-1-register-resource-id} + +Una, ipaparehistro mo ang resource ID na nauugnay sa mga resource sa cross-chain environment. Isang 32-bytes na value ang Resource ID na dapat maging natatangi sa resource na inililipat natin sa pagitan ng mga blockchain na ito. Ang mga Resource ID ay arbitrary, ngunit maaaring mayroon silang chain ID ng home chain ng huling byte, bilang kalakaran (Tumutukoy ang home chain sa network kung saan nagmula ang mga resource na ito). + +Para maiparehistro ang resource ID, puwede mong gamitin ang `cb-sol-cli bridge register-resource` na command. Kakailanganin mong ibigay ang pribadong key ng `admin` account. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (Opsyonal) Gawing nami-mint/nabu-burn ang mga kontrata {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## Hakbang 2: Ilipat ang ERC20 Token {#step-2-transfer-erc20-token} + +Magpapadala kami ng mga ERC20 Token mula sa Polygon PoS chain patungo sa Polygon Edge chain. + +Una, makakakuha ka ng mga token sa pamamagitan ng pagmi-mint. Puwedeng mag-mint ng mga bagong token ang account na may `minter` na tungkulin. May `minter`na tungkulin bilang default ang account na nag-deploy ng ERC20 contract. Para tukuyin ang iba pang account bilang mga miyembro ng `minter` na tungkulin, kailangan mong patakbuhin ang `cb-sol-cli erc20 add-minter` na command. + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +Para tingnan ang kasalukuyang balanse, puwede mong gamitin ang `cb-sol-cli erc20 balance` na command. + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +Susunod, kailangan mong aprubahan ang paglilipat ng ERC20 token mula sa account sa pamamagitan ng ERC20 Handler + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +Para ilipat ang mga token patungo sa mga Polygon Edge chain, tatawag ka sa `deposit`. + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Pagkatapos maging matagumpay ng transaksyon sa pagdeposito, kukunin ng relayer ang event at boboto para sa panukala. Ipatutupad nito ang isang transaksyon para ipadala ang mga token sa account ng tatanggap sa Polygon Edge chain pagkatapos isumite ang kinakailangang bilang ng mga boto. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Kapag naging matagumpay ang pagsasagawa ng transaksyon, makukuha mo ang mga token sa Polygon Edge chain. + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/tl-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/tl-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..f22fa01ea4 --- /dev/null +++ b/archive/edge/tl-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,134 @@ +--- +id: setup-erc721-transfer +title: Paglilipat ng ERC721 NFT +description: Paano i-setup ang paglilipat ng ERC721 sa chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Ang seksyong ito ay gagabay sa iyo sa pagset up ng ERC721 bridge at pagpapadala ng mga NFT sa pagitan ng mga blockchain network. + +## Hakbang 1: Iparehistro ang resource ID {#step-1-register-resource-id} + +Kailangan mo munang iparehistro ang resource ID para sa ERC721 token sa mga Bridge contract sa parehong chain. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (Opsyonal) Gawing nami-mint/nabu-burn ang mga kontrata {#optional-make-contracts-mintable-burnable} + +Para gawing nami-mint/nabu-burn ang mga Token, kailangan mong gamitin ang sumusunod na mga command: + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## Hakbang 2: Ilipat ang NFT {#step-2-transfer-nft} + +Una, i-mint mo ang NFT kung kailangan mo ito. + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Para tingnan ang may-ari ng NFT, maaari mong gamitin ang `cb-sol-cli erc721 owner` + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Pagkatapos, aaprubahan mo ang paglipat ng NFT sa pamamagitan ng ERC721 Handler + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Panghuli, sisimulan mo ang paglipat + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +Kukunin ng relayer ang event at boboto para sa panukala. Ipinapatupad nito ang transaksyon para ipadala ang mga NFT sa account ng tatanggap sa Polygon Edge chain pagkatapos isumite ang kinakailangang bilang ng mga boto. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Maaari mong tingnan ang may-ari ng NFT sa Polygon Edge network pagkatapos makumpleto ang pagpapatupad. + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/tl-edge/additional-features/chainbridge/setup.md b/archive/edge/tl-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..aeb1783185 --- /dev/null +++ b/archive/edge/tl-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,198 @@ +--- +id: setup +title: Pag-setup +description: Paano i-set up ang chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Pag-deploy ng mga kontrata {#contracts-deployment} + +Sa seksyong ito, ide-deploy mo ang mga kinakailangang kontrata sa Polygon POS at Polygon Edge chain gamit ang `cb-sol-cli`. + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +Una, magde-deploy tayo ng mga kontrata sa Polygon PoS chain sa pamamagitan ng `cb-sol-cli deploy` na command. Sa pamamagitan ng `--all` flag, dine-deploy ng command ang lahat ng kontrata kabilang ang mga kontrata ng Bridge, ERC20 Handler, ERC721 Handler, Generic Handler, ERC20, at ERC721. Dagdag pa, itatakda nito ang default na relayer account address at ang threshold + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +Alamin ang tungkol sa chainID at JSON-RPC URL [dito](/docs/edge/additional-features/chainbridge/definitions) + +:::caution + +Ang default na gas price sa `cb-sol-cli` ay `20000000` (`0.02 Gwei`). Para itakda ang naaangkop na gas price sa transaksyon, itakda ang value gamit ang `--gasPrice` argument. + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +Gumagamit ang kontrata ng Bridge ng humigit-kumulang 0x3f97b8 (4167608) gas para ma-deploy. Tiyakin na ang mga block na binubuo ay may sapat na limitasyon sa gas kada block para maisama ang transaksyon sa paggawa ng kontrata. Para matuto pa tungkol sa pagbabago ng limitasyon sa gas kada block sa Polygon Edge, pumunta sa +[Local na Pag-set Up](/docs/edge/get-started/set-up-ibft-locally) + +::: + +Kapag na-deploy na ang mga kontrata, makukuha mo ang sumusunod na resulta: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +Maaari na natin ngayon i-deploy ang mga kontrata sa Polygon Edge chain. + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +I-save ang mga terminal output kasama ang mga na-deploy na address ng smart contract dahil kakailanganin natin ang mga ito para sa susunod na hakbang. + +## Pag-set up ng relayer {#relayer-setup} + +Sa seksyong ito, magsisimula ka ng relayer para makapagpalitan ng data sa pagitan ng 2 chain. + +Una, kailangan nating i-clone at gawin ang ChainBridge repository. + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +Susunod, kailangan mong gawin ang `config.json` at itakda ang mga JSON-RPC URL, address ng relayer, at address ng mga kontrata para sa bawat chain. + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +Para magsimula ng relayer, kailangan mong i-import ang pribadong key na nauugnay sa address ng relayer account. Kailangan mong i-input ang password kapag nag-import ka ng pribadong key. Kapag nagtagumpay ang pag-import, iso-store ang key sa ilalim ng `keys/
.key`. + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +Pagkatapos, masisimulan mo ang relayer. Kailangan mong i-input ang parehong password na pinili mo para sa pag-store ng key sa simula. + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +Kapag nag-umpisa na ang relayer, magsisimula itong magbantay ng mga bagong block sa bawat chain. diff --git a/archive/edge/tl-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/tl-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..6c37de45bd --- /dev/null +++ b/archive/edge/tl-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,255 @@ +--- +id: use-case-erc20-bridge +title: Gamitin ang case - ERC20 Bridge +description: Halimbawa para sa pag-bridge sa ERC20 contract +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +Layunin ng seksyong ito na magbigay sa iyo ng daloy ng pag-setup ng ERC20 Bridge para sa praktikal na paggamit ng case. + +Sa gabay na ito, gagamitin mo ang Mumbai Polygon PoS testnet at Polygon Edge local chain. Tiyakin na mayroon kang JSON-RPC endpoint para sa Mumbai at nai-set up mo ang Polygon Edge sa isang lokal na environment. Sumangguni sa [Lokal na Pag-Setup](/docs/edge/get-started/set-up-ibft-locally) o [Pag-Setup sa Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) para sa higit pang detalye. + +## Scenario {#scenario} + +Tumutukoy ang scenario na ito sa pag-setup ng Bridge para sa ERC20 token na na-deploy na sa pampublikong chain (Polygon PoS) para magbigay-daan sa mababang halaga ng paglipat sa pribadong chain (Polygon Edge) para sa mga user sa isang regular na case. Sa ganitong case, tinukoy sa pampublikong chain ang kabuuang supply ng token at ang halaga lang ng token na nailipat mula sa pampublikong chain patungo sa pribadong chain ang dapat umiral sa pribadong chain. Sa kadahilanang iyon, kailangan mong gamitin ang lock/release mode sa pampublikong chain at ang burn/mint mode sa pribadong chain. + +Kapag nagpapadala ng mga token mula sa pampublikong chain patungo sa pribadong chain, mala-lock sa ERC20 Handler contract ang token ng pampublikong chain at mami-mint sa pribadong chain ang parehong halaga ng token. Sa kabilang banda, sa kaso ng paglilipat mula sa pribadong chain patungo sa pampulikong chain, ibu-burn ang token sa pribadong chain at ang parehong halaga ng token ay ire-release mula sa ERC20 Handler contract sa pampublikong chain. + +## Mga Kontrata {#contracts} + +Pagpapaliwanag ng simpleng mga ERC20 contract sa halip na kontrata na ginawa ng ChainBridge. Para sa burn/mint mode, dapat may mga paraang `mint` at `burnFrom` ng ERC20 contract bukod pa sa mga paraan para sa ERC20 gaya nito: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +Ang lahat ng mga code at script ay nasa Github Repo [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Hakbang1: I-deploy ang Bridge at mga ERC20 Handler contract {#step1-deploy-bridge-and-erc20-handler-contracts} + +Una, ide-deploy mo ang Bridge at mga ERC20Handler contract gamit ang `cb-sol-cli` sa magkaparehong chain. + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Makakakuha ka ng mga address ng Bridge at ERC20 Handler contract gaya nito: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Hakbang2: I-deploy ang iyong ERC20 contract {#step2-deploy-your-erc20-contract} + +Ide-deploy mo ang iyong ERC20 contract. Ang halimbawang ito ay gumagabay sa iyo sa hardhat project [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Mangyaring gumawa ng `.env` file at i-set ang sumusunod na values. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Susunod, ide-deploy mo ang ERC20 contract sa magkaparehong chain. + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +Pagkatapos maging matagumpay ang pag-deploy, makakakuha ka ng address ng kontrata gaya nito: + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## Hakbang3: Irehistro ang resource ID sa Bridge {#step3-register-resource-id-in-bridge} + +Magrerehistro ka ng resource ID na mag-uugnay ng resource sa isang cross-chain environment. Kailangan mong itakda ang parehong resource ID sa magkaparehong chain. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## Hakbang4: Itakda ang Mint/Burn mode sa ERC20 bridge ng Edge {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +Inaasahang tatakbo ang bridge tulad ng burn/mint mode sa Polygon Edge. Itatakda mo ang burn/mint mode gamit ang `cb-sol-cli`. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +At kinakailangan mong magbigay ng minter at burner na tungkulin sa ERC20 Handler contract. + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Hakbang5: Mag-mint ng Token {#step5-mint-token} + +Magmi-mint ka ng mga bagong ERC20 token sa Mumbai chain. + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +Pagkatapos maging matagumpay ng transaksyon, magkakaroon ang account ng minted token. + +## Hakbang6: Simulan ang paglipat ng ERC20 {#step6-start-erc20-transfer} + +Bago simulan ang hakbang na ito, mangyaring tiyaking nakapagsimula ka na ng relayer. Mangyaring tingnan ang [Pag-Setup](/docs/edge/additional-features/chainbridge/setup) para sa higit pang detalye. + +Sa paglilipat ng token mula Mumbai patungong Edge, wini-withdraw ng ERC20 Handler contract sa Mumbai ang mga token mula sa iyong account. Aaprubahan mo muna bago gawin ang paglipat. + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +Panghuli, sisimulan mo ang paglipat ng token mula Mumbai patungong Edge gamit ang `cb-sol-cli`. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Pagkatapos maging matagumpay ng depositong transaksyon, kukunin ng relayer ang event at boboto para sa proposal. Isinasagawa nito ang isang transaksyon para ipadala ang mga token sa account ng tatanggap sa Polygon Edge chain pagkatapos maisumite ang kinakailangang bilang ng mga boto. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Kapag naging matagumpay ang pagsasagawa ng transaksyon, makakakuha ka ng mga token sa Polygon Edge chain. diff --git a/archive/edge/tl-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/tl-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..0755d7f44e --- /dev/null +++ b/archive/edge/tl-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,308 @@ +--- +id: use-case-erc721-bridge +title: Gamitin ang case - ERC721 Bridge +description: Halimbawa para i-bridge ang ERC721 contract +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +Layunin ng seksyong ito na magbigay sa iyo ng daloy ng pag-setup ng ERC721 Bridge para sa praktikal na paggamit ng case. + +Sa gabay na ito, gagamitin mo ang Mumbai Polygon PoS testnet at Polygon Edge local chain. Tiyakin na mayroon kang JSON-RPC endpoint para sa Mumbai at nai-set up mo ang Polygon Edge sa isang lokal na environment. Sumangguni sa [Lokal na Pag-Setup](/docs/edge/get-started/set-up-ibft-locally) o [Pag-Setup sa Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) para sa higit pang detalye. + +## Scenario {#scenario} + +Tumutukoy ang scenario na ito sa pag-setup ng Bridge para sa ERC721 NFT na na-deploy na sa pampublikong chain (Polygon PoS) para magbigay-daan sa mababang halaga ng paglipat sa pribadong chain (Polygon Edge) para sa mga user sa isang regular na case. Sa ganitong case, ang orihinal na metadata ay tinukoy sa pampublikong chain at ang mga NFT lang na inilipat mula sa Pampublikong chain ang maaaring umiral sa pribadong chain. Sa kadahilanang iyon, kailangan mong gamitin ang lock/release mode sa pampublikong chain at burn/mint mode sa pribadong chain. + +Kapag nagpapadala ng mga NFT mula sa pampublikong chain patungo sa pribadong chain, ang NFT ay malo-lock sa ERC721 Handler contract sa pampublikong chain at ang parehong NFT ay mami-mint sa pribadong chain. Sa kabilang banda, sa kaso ng paglilipat mula sa pribadong chain patungo sa pampulikong chain, ang NFT sa pribadong chain ay i-burn at ang parehong NFT ay ire-release mula sa ERC721 Handler contract sa pampublikong chain. + +## Mga Contract {#contracts} + +Pagpapaliwanag sa pamamagitan ng isang simpleng ERC721 contract sa halip na kontrata na binuo ng ChainBridge. Para sa burn/mint mode, ang ERC721 contract ay dapat magtaglay ng `mint` at `burn` na mga pamamaraan bilang karagdagan sa mga pamamaraang tinukoy sa ERC721 tulad nito: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +Ang lahat ng mga code at script ay nasa Github Repo [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Hakbang1: I-deploy ang Bridge at ang mga ERC721 Handler contract {#step1-deploy-bridge-and-erc721-handler-contracts} + +Una, ide-deploy mo ang Bridge at ang mga ERC721Handler contract gamit ang `cb-sol-cli` sa magkaparehong chain. + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Makakakuha ka ng Bridge at ng mga ERC721 Handler contract address tulad nito: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Hakbang2: I-deploy ang iyong ERC721 contract {#step2-deploy-your-erc721-contract} + +Ide-deploy mo ang iyong ERC721 contract. Ang halimbawang ito ay gumagabay sa iyo sa hardhat project [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Mangyaring gumawa ng `.env` file at i-set ang sumusunod na values. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Susunod ay ide-deploy mo ang ERC721 contract sa magkaparehong chain. + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +Pagkatapos maging matagumpay ng pag-deploy, makakakuha ka ng mga contract address tulad nito: + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## Hakbang3: Irehistro ang resource ID sa Bridge {#step3-register-resource-id-in-bridge} + +Irerehistro mo ang isang resource ID na nauugnay sa mga resources sa isang cross-chain environment. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## Hakbang4: I-set ang Mint/Burn mode sa ERC721 Bridge ng Edge {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +Inaasahang gagana ang Bridge bilang burn/mint mode sa Edge. Ise-set mo ang burn/mint mode. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +At kailangan mong magbigay ng tungkulin ng isang minter at burner sa ERC721 Handler contract. + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Hakbang5: Mag-mint ng NFT {#step5-mint-nft} + +Magmi-mint ka ng bagong ERC721 NFT sa Mumbai chain. + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +Pagkatapos maging matagumpay ang transaksyon, magkakaroon ang account ng minted NFT. + +## Hakbang6: Simulan ang paglipat ng ERC721 {#step6-start-erc721-transfer} + +Bago simulan ang hakbang na ito, mangyaring tiyakin na nasimulan mo ang relayer. Mangyaring tingnan ang [Pag-Setup](/docs/edge/additional-features/chainbridge/setup) para sa higit pang detalye. + +Sa paglilipat ng NFT mula Mumbai patungong Edge, iwi-withdraw ng ERC721 Handler contract sa Mumbai ang NFT mula sa iyong account. Aaprubahan mo muna bago gawin ang paglilipat. + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +Huli, sisimulan mo ang paglipat ng NFT mula Mumbai patungong Edge. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +Pagkatapos maging matagumpay ng depositong transaksyon, kukunin ng relayer ang event at boboto para sa proposal. +Isinasagawa nito ang isang transaksyon para ipadala ang NFT sa account ng tatanggap sa Polygon Edge chain pagkatapos maisumite ang kinakailangang bilang ng mga boto. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Kapag naging matagumpay na ang pagsasagawa ng transaksyon, makakakuha ka ng NFT sa Polygon Edge chain. diff --git a/archive/edge/tl-edge/additional-features/permission-contract-deployment.md b/archive/edge/tl-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..2396fcf3a3 --- /dev/null +++ b/archive/edge/tl-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,85 @@ +--- +id: permission-contract-deployment +title: Pahintulot ng pag-deploy ng smart na kontrata +description: Paano magdagdag ng pahintulot sa pag-deploy ng smart na kontrata. +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## Pangkalahatang-ideya {#overview} + +Idedetalye ng gabay na ito kung paano i-whitelist ang mga address na maaaring mag-deploy ng mga smart na kontrata. Kung minsan, nais hadlangan ng mga network operator ang mga user sa pag-deploy ng mga smart na kontrata na walang kaugnayan sa layunin ng network. Ang mga network operator ay maaaring: + +1. Mag-whitelist ng mga address para sa pag-deploy ng Smart na Kontrata +2. Mag-alis ng mga adres mula sa whitelist para sa pag-deploy ng Smart Contract + +## Video presentation {#video-presentation} + +[![pag-deploy ng kontrata - video](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## Paano gamitin ito? {#how-to-use-it} + + +Makikita mo ang lahat ng mga cli command na may kaugnayan sa deployment whitelist sa [CLI Commands](/docs/edge/get-started/cli-commands#whitelist-commands) page. + +* `whitelist show`: Ipinapakita ang impormasyon ng whitelist +* `whitelist deployment --add`: Nagdadagdag ng isang bagong address sa contract deployment whitelist +* `whitelist deployment --remove`: Inaalis ang isang bagong address mula sa whitelist ng pag-deploy ng kontrata + +#### Ipakita ang lahat ng mga address sa deployment whitelist {#show-all-addresses-in-the-deployment-whitelist} + +Mayroong 2 paraan para mahanap ang mga address mula sa deployment whitelist. +1. Pagtingin sa `genesis.json` kung saan naka-save ang mga whitelist +2. Pagsasagawa ng `whitelist show`, na nagpi-print ng impormasyon para sa lahat ng mga whitelist na sinusuportahan ng Polygon Edge + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### Magdagdag ng isang address sa deployment whitelist {#add-an-address-to-the-deployment-whitelist} + +Para magdagdag ng isang bagong address sa deployment whitelist, isagawa ang `whitelist deployment --add [ADDRESS]` CLI command. Walang limitasyon ang bilang ng mga address na nasa whitelist. Ang mga address lamang na umiiral sa contract deployment whitelist ang maaaring mag-deploy ng mga kontrata. Kung walang laman ang whitelist, maaaring mag-deploy ang kahit anong address + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### Alisin ang isang address mula sa deployment whitelist {#remove-an-address-from-the-deployment-whitelist} + +Para alisin isang address mula sa deployment whitelist, isagawa ang `whitelist deployment --remove [ADDRESS]` CLI command. Ang mga address lamang na umiiral sa contract deployment whitelist ang maaaring mag-deploy ng mga kontrata. Kung walang laman ang whitelist, maaaring mag-deploy ang kahit anong address + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/tl-edge/architecture/modules/blockchain.md b/archive/edge/tl-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..2f7e4f35bb --- /dev/null +++ b/archive/edge/tl-edge/architecture/modules/blockchain.md @@ -0,0 +1,160 @@ +--- +id: blockchain +title: Blockchain +description: Paliwanag para sa mga module ng blockchain at state ng Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## Pangkalahatang-ideya {#overview} + +Ang isa sa mga pangunahing module ng Polygon Edge ay ang **Blockchain** at **State**.
+ +Ang **Blockchain** ay ang powerhouse na nangangasiwa sa mga pagbabago ng organisasyon ng block. Ibig sabihin, ito ang nangangasiwa sa lahat ng logic na nangyayari kapag may bagong block na isinasama sa blockchain. + +Ang **State** ay kumakatawan sa object ng *state transition*. Pinapangasiwaan nito kung paano nagbabago ang state kapag nadagdag ang isang bagong block.
Kabilang din sa mga pinapangasiwaan ng **State** ang: +* Pagsasagawa ng mga transaksyon +* Pagsasagawa sa EVM +* Pagbabago sa Merkle tries +* Marami pa, na tinatalakay sa kaugnay na seksyong **State** 🙂 + +Ang key takeaway ay lubos na magkaugnay ang 2 bahaging ito, at nagtutulungan ang mga ito para gumana ang client.
Halimbawa, kapag nakatanggap ang **Blockchain** layer ng bagong block (at walang naganap na pagbabago ng organisasyon), tinatawag nito ang **State** para magsagawa ng state transition. + +Nangangasiwa din ang **Blockchain** ng ilang bahaging nauugnay sa consensus (hal. *tama ba ang ethHash na ito?*, *tama ba ang PoW na ito?*).
Sa madaling salita, **ito ang pangunahing core ng logic na ginagamit para maisama ang lahat ng block**. + +## *WriteBlocks* + +Ang isa sa pinakamahahalagang bahaging nauugnay sa **Blockchain** layer ay ang paraang *WriteBlocks*: + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +Ang paraang *WriteBlocks* ay ang entry point para magsulat ng mga block sa blockchain. Bilang isang parameter, nagpoproseso ito ng iba't ibang block.
+Una, bina-validate ang mga block. Pagkatapos nito, isinusulat ang mga ito sa chain. + +Isinasagawa ang aktwal na *state transition* sa pamamagitan ng pag-call sa paraang *processBlock* sa *WriteBlocks*. + +Mahalaga ring banggitin na dahil ito ay ang entry point para sa pagsusulat ng mga block sa blockchain, ginagamit ng iba pang module (gaya ng **Sealer**) ang paraang ito. + +## Mga Subscription sa Blockchain {#blockchain-subscriptions} + +Kailangang magkaroon ng paraan para masubaybayan ang mga pagbabagong may kaugnayan sa blockchain.
+Dito papasok ang mga **Subscription**. + +Ang mga Subscription ay isang paraan para mapakinabangan ang mga stream ng blockchain event at makatanggap kaagad ng makabuluhang data. + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +Ang mga **Blockchain Event** ay naglalaman ng impormasyon tungkol sa anumang pagbabagong ginagawa sa aktwal na chain. Kasama rito ang mga pagbabago sa organisasyon, pati na rin ang mga bagong block: + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip Refresher + +Naaalala mo ba noong binanggit namin ang command na ***monitor*** sa mga [CLI Command](/docs/edge/get-started/cli-commands)? + +Ang mga Blockchain Event ay ang mga orihinal na event na nangyayari sa Polygon Edge, at pagkatapos ay iminamapa ang mga ito sa isang format ng mensahe ng mga Buffer ng Protokol para sa madaling paglilipat. + +::: \ No newline at end of file diff --git a/archive/edge/tl-edge/architecture/modules/consensus.md b/archive/edge/tl-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..81faaaa44c --- /dev/null +++ b/archive/edge/tl-edge/architecture/modules/consensus.md @@ -0,0 +1,512 @@ +--- +id: consensus +title: Consensus +description: Paliwanag para sa consensus module ng Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## Pangkalahatang-ideya {#overview} + +Ang **Consensus** module ay nagbibigay ng interface para sa mga mekanismo ng consensus. + +Sa kasalukuyan, available ang mga sumusunod na consensus engine: +* **IBFT PoA** +* **IBFT PoS** + +Gusto ng Polygon Edge na mapanatili ang state ng modularity at pluggability nito.
+Ito ang dahilan kung bakit ang core na logic ng consensus ay nawala na bunsod ng abstraction nito, para makagawa ng mga bagong mekanismo ng consensus, nang hindi +nakokompromiso ang kakayahang magamit at kadalian ng paggamit. + +## Interface ng Consensus {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + +Ang interface ng ***Consensus*** ay ang core ng nabanggit na abstraction.
+* Ang paraang **VerifyHeader** ay kumakatawan sa isang helper na function na ipinapakita ng layer ng consensus sa layer ng **blockchain** +Tungkulin nito na pangasiwaan ang pag-verify ng header +* Sinisimulan lang ng paraang **Start** ang proseso ng consensus, at ang lahat ng bagay na nauugnay rito. Kabilang dito ang pag-synchronize, +pag-seal, at lahat ng kailangang gawin +* Ang paraang **Close** ay nagsasara sa koneksyon ng consensus + +## Configuration ng Consensus {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +Maaaring may mga pagkakataon kung kailan maaaring gusto mong mag-pass in ng custom na lokasyon para sa protokol ng consensus para mag-store ng data, o kaya +ng custom na key-value map na gusto mong gamitin ng mekanismo ng consensus. Maaari itong magawa sa pamamagitan ng ***Config*** struct, +na binabasa kapag may bagong nilikhang instance ng consensus. + +## IBFT {#ibft} + +### ExtraData {#extradata} + +Ang blockchain header object, bukod sa iba pang field, ay may field na tinatawag na **ExtraData**. + +Ginagamit ng IBFT ang karagdagang field na ito para mag-store ng impormasyon tungkol sa pagpapatakbo kaugnay sa block, sumagot ng mga tanong gaya ng: +* "Sino ang nag-sign sa block na ito?" +* "Sino ang mga validator para sa block na ito?" + +Ang mga karagdagang field na ito para sa IBFT ay tinutukoy ayon sa sumusunod: +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### Pag-sign ng Data {#signing-data} + +Para ma-sign ng node ang impormasyon sa IBFT, ginagamit nito ang paraang *signHash*: +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +Ang isa pang mahalagang paraan ay ang paraang *VerifyCommittedFields* na nagbe-verify na mula sa mga valid na validator ang mga na-commit na seal: +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### Mga Snapshot {#snapshots} + +Ang mga Snapshot, gaya ng ipinapahiwatig ng pangalan, ay nariyan para magbigay ng *snapshot*, o para ipaalam ang *state* ng system sa anumang block height (numero). + +Ang mga Snapshot ay naglalaman ng set ng mga node na mga validator, pati na rin ng impormasyon sa pagboto (maaaring bomoto ang mga validator para sa iba pang validator). +Isinasama ng mga validator ang impormasyon sa pagboto sa **Miner** header na inihahain, at binabago ng mga ito ang value ng **nonce**: +* Ang nonce ay **1s lahat** kung gusto ng node na mag-alis ng validator +* Ang nonce ay **0s lahat** kung gusto ng node na magdagdag ng validator + +Kinakalkula ang mga Snapshot gamit ang paraang ***processHeaders***: + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +Ang paraang ito ay karaniwang kinakailangan sa 1 header, ngunit pareho ang daloy kahit sa maramihang header.
+Para sa bawat na-pass in na header, kailangang i-verify ng IBFT na ang proposer ng header ay ang validator. Madali itong magagawa sa pamamagitan ng +pagkuha sa pinakabagong snapshot, at pagsuri kung ang node ay nasa validator set. + +Susunod, sinusuri ang nonce. Ang boto ay isinasama, at binibilang - at kung may sapat na bilang ng mga boto, idadagdag/aalisin ang node sa +validator set, at pagkatapos nito, sine-save ang bagong snapshot. + +#### Snapshot Store {#snapshot-store} + +Pinapamahalaan at ina-update ng serbisyo ng snapshot ang entity na tinatawag na **snapshotStore**, na nagi-store ng listahan ng lahat na available na snapshot. +Gamit ito, mabilis na natutukoy ng serbisyo kung aling snapshot ang nauugnay sa kaukulang block height. +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### Pag-start Up ng IBFT {#ibft-startup} + +Para i-start up ang IBFT, kailangan muna ng Polygon Edge na i-set up ang pag-transport ng IBFT: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +Pangunahing gumagawa ito ng bagong paksa gamit ang IBFT proto, na may bagong mensahe ng proto buff.
+Ang mga mensaheng ito ay nilalayon para gamitin ng mga validator. Pagkatapos, magsu-subscribe ang Polygon Edge sa paksa at pinapangasiwaan nito ang mga mensahe nang naaayon. + +#### MessageReq {#messagereq} + +Ang mensaheng ipinapadala ng mga validator sa bawat isa: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +Ang field na **View** sa **MessageReq** ay kumakatawan sa kasalukuyang posisyon ng node sa loob ng chain. +Ito ay may *round* at *sequence* na katangian. +* Ang **round** ay kumakatawan sa round ng proposer para sa height +* Ang **sequence** ay kumakatawan sa height ng blockchain + +Ang *msgQueue* na inihahain sa implementasyon ng IBFT ay may layunin na mag-store ng mga kahilingang mensahe. Inaayos nito ang mga mensahe ayon sa +*View* (una ayon sa sequence, pagkatapos ay ayon sa round). Ang implementasyon ng IBFT ay mayroon ding iba't ibang queue para sa iba't ibang state sa system. + +### Mga State ng IBFT {#ibft-states} + +Pagkatapos na simulan ang mekanismo ng consensus gamit ang paraang **Start**, tumatakbo ito sa walang hanggang loop na nagsi-simulate ng isang state machine: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### SyncState {#syncstate} + +Ang lahat ng node ay inisyal na nagsisimula sa state na **Sync**. + +Ito ay dahil ang fresh data ay kailangang i-fetch mula sa blockchain. Kinakailangan ng client na alamin kung ito ang validator, +hanapin ang kasalukuyang snapshot. Nilulutas ng state na ito ang anumang nakabinbing mga block. + +Pagkatapos ng sync, at matutukoy ng client na ito nga ay isang validator, kailangan nitong lumipat sa **AcceptState**. +Kung **hindi** validator ang client, ito ay patuloy na magsi-sync, at mananatili sa **SyncState** + +#### AcceptState {#acceptstate} + +Palaging sinusuri ng state na **Accept** ang snapshot at ang validator set. Kung ang kasalukuyang node ay wala sa validators set, +bumabalik ito sa state na **Sync**. + +Sa kabilang banda, kung ang node **ay** ay validator, kinakalkula nito ang proposer. Kung lalabas na ang kasalukuyang node ay ang +proposer, gumagawa ito ng block, at nagpapadala ito ng mga mensahe sa paunang paghahanda at pagkatapos ay mga mensahe sa paghahanda. + +* Mga mensahe sa preprepare o paunang paghahanda - mga mensaheng ipinapadala ng mga proposer sa mga validator, para ipaalam sa kanila ang tungkol sa proposal +* Mga mensahe sa paghahanda - mga mensahe kung saan ang mga validator ay sumasang-ayon sa isang proposal. Natatanggap ng lahat ng node ang lahat ng mensahe sa paghahanda +* Mga mensahe sa commit - mga mensaheng naglalaman ng impormasyon tungkol sa commit para sa proposal + +Kung **hindi** validator ang kasalukuyang node, ginagamit nito ang paraang *getNextMessage* para magbasa ng mensahe mula sa naunang ipinakitang queue.
+Hinihintay nito ang mga mensahe sa paunang paghahanda. Kapag nakumpirma na nitong tama ang lahat, lilipat ang node sa state na **Validate**. + +#### ValidateState {#validatestate} + +Ang state na **Validate** ay simple lamang - ang ginagawa ng lahat ng node sa state na ito ay magbasa ng mga mensahe at idagdag ang mga ito sa state ng kanilang lokal na snapshot. diff --git a/archive/edge/tl-edge/architecture/modules/json-rpc.md b/archive/edge/tl-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..bbbfeda56e --- /dev/null +++ b/archive/edge/tl-edge/architecture/modules/json-rpc.md @@ -0,0 +1,181 @@ +--- +id: json-rpc +title: JSON RPC +description: Paliwanag para sa JSON RPC module ng Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## Pangkalahatang-ideya {#overview} + +Ipinapatupad ng **JSON RPC** module ang **layer ng JSON RPC API**, isang bagay na ginagamit ng mga dApp developer para makipag-interaksyon sa +blockchain. + +Kasama rito ang suporta para sa mga standard na **[json-rpc endpoint](https://eth.wiki/json-rpc/API)**, at mga websocket +endpoint. + +## Interface ng Blockchain {#blockchain-interface} + +Ginagamit ng Polygon Edge ang ***interface ng blockchain*** para tukuyin ang lahat ng paraan na kinakailangang gamitin ng JSON RPC module, para +maihatid ang mga endpoint nito. + +Ang interface ng blockchain ay ipinapatupad ng **[Minimal](/docs/edge/architecture/modules/minimal)** server. Ito ang base ng pagpapatupad +na ipinapasa sa layer ng JSON RPC. + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## Mga ETH Endpoint {#eth-endpoints} + +Ang lahat ng standard na JSON RPC endpoint ay ipinapatupad sa: + +````bash +jsonrpc/eth_endpoint.go +```` + +## Filter Manager {#filter-manager} + +Ang **Filter Manager** ay isang serbisyo na tumatakbo kasama ng JSON RPC server. + +Nagbibigay ito ng suporta para sa pag-filter ng mga block sa blockchain.
+Sa partikular, may kasama itong **log** at isang **block** level filter. + +Lubos na ginagamit ng Filter Manager ang mga Event ng Subscription, na nabanggit sa +seksyong [Blockchain](blockchain#blockchain-subscriptions) + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +Dini-dispatch ang mga event ng Filter Manager sa paraang *Run*: + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## 📜 Mga Resource {#resources} +* **[Ethereum JSON-RPC](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/tl-edge/architecture/modules/minimal.md b/archive/edge/tl-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..cb36fa7c13 --- /dev/null +++ b/archive/edge/tl-edge/architecture/modules/minimal.md @@ -0,0 +1,118 @@ +--- +id: minimal +title: Minimal +description: Paliwanag para sa minimal na module ng Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## Pangkalahatang-ideya {#overview} + +Tulad ng nabanggit dati, ang Polygon Edge ay isang set ng iba't ibang mga module, na ang lahat ay konektado sa bawat isa.
+Ang **Blockchain** ay konektado sa **State**, o bilang halimbawa, ang **Synchronization**, na naghahatid ng mga bagong block sa **Blockchain**. + +Ang **Minimal** ay ang pundasyon para sa mga magkakakonektang mga module na ito.
Nagsisilbi itong isang central hub para sa lahat ng mga serbisyong tumatakbo sa Polygon Edge. + +## Startup Magic {#startup-magic} + +Maliban sa iba pang mga bagay, responsable ang Minimal sa: +* Pag-set up ng mga data directory +* Paglikha ng isang keystore para sa libp2p communication +* Paglikha ng storage +* Pag-set up ng consensus +* Pag-set up ng blockchain object na may GRPC, JSON RPC, at Synchronization + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/tl-edge/architecture/modules/networking.md b/archive/edge/tl-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..98a1e6e70d --- /dev/null +++ b/archive/edge/tl-edge/architecture/modules/networking.md @@ -0,0 +1,79 @@ +--- +id: networking +title: Networking +description: Paliwanag para sa networking module ng Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## Pangkalahatang-ideya {#overview} + +Ang isang node ay kailangang makipag-ugnayan sa iba pang mga node sa network, upang makipagpalitan ng kapaki-pakinabang na impormasyon.
+Para magawa ito, pinapakinabangan ng Polygon Edge ang subok nang **libp2p** framework. + +Ang pagpili para gamitin ang **libp2p** ay pangunahing nakapokus sa: +* **Bilis** - ang libp2p ay may higit na pagsulong sa performance kaysa sa devp2p (na ginagamit sa GETH at iba pang mga client) +* **Extensibility** - nagsisilbi itong isang mahusay na pundasyon para sa iba pang mga feature ng system +* **Modularity** - ang libp2p ay likas na modular, tulad ng Polygon Edge. Nagbibigay ito ng mas higit na flexibility, lalo na kapag ang mga bahagi ng Polygon Edge ay kailangang pagpalit-palitin + +## GRPC {#grpc} + +Dagdag pa sa **libp2p**, ginagamit ng Polygon Edge ang **GRPC** na protokol.
Sa teknikal, ginagamit ng Polygon Edge ang ilang mga GRPC na protokol, na tatalakayin sa susunod. + +Ang GRPC layer ay tumutulong para makuha ang lahat ng mga kahilingan/reply na protokol at pinapasimple ang mga kinakailangang streaming na protokol para gumana ang Polygon Edge. + +Umaasa ang GRPC sa mga **Protokol na Buffer** para tukuyin ang *mga serbisyo* at mga *istraktura ng mensahe*.
+Ang mga serbisyo at mga istruktura ay tinukoy sa mga *.proto* files, na pinagsama-sama at language-agnostic. + +Sa una, nabanggit naming pinapakinabangan ng Polygon Edge ang ilang mga GRPC na protokol.
+Ginawa ito para palakasin ang pangkalahatang UX para sa node operator, isang bagay na kadalasan nang nagpapabagal sa mga client tulad ng GETH at Parity. + +Ang node operator ay may mas mahusay na pangkalahatang-ideya kung ano ang nangyayari sa system sa pamamagitan ng pagtawag sa GRPC service, sa halip na suriin ang mga log para hanapin ang impormasyong hinahanap nila. + +### GRPC para sa mga Node Operator {#grpc-for-node-operators} + +Ang susunod na seksyon ay malamang na pamilyar dahil ito ay panandaliang tinalakay sa mga [CLI Commands](/docs/edge/get-started/cli-commands) na seksyon. + +Ang GRPC service na inilaan para gamitin ng mga **node operator** ay tinukoy bilang: +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip + +Ang totoo, ang mga CLI command ang tumatawag sa mga implementasyon ng mga pamamaraan ng serbisyong ito. + +Ang mga pamamaraang ito ay ipinatutupad sa ***minimal/system_service.go***. + +::: + +### GRPC para sa Iba Pang Node {#grpc-for-other-nodes} + +Ipinapatupad din ng Polygon Edge ang ilang mga pamamaraan ng serbisyo na ginagamit ng ibang mga node sa network.
+Ang serbisyong nabanggit ay inilarawan sa **[Protokol](docs/edge/architecture/modules/consensus)** na seksyon. + +## 📜 Mga Resource {#resources} +* **[Mga Protokol na Buffer](https://developers.google.com/protocol-buffers)** +* **[libp2p](https://libp2p.io/)** +* **[gRPC](https://grpc.io/)** diff --git a/archive/edge/tl-edge/architecture/modules/other-modules.md b/archive/edge/tl-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..248c70e789 --- /dev/null +++ b/archive/edge/tl-edge/architecture/modules/other-modules.md @@ -0,0 +1,36 @@ +--- +id: other-modules +title: Iba pang module +description: Paliwanag para sa ilang module ng Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## Crypto {#crypto} + +Ang **Crypto** module ay naglalaman ng mga crypto utility function. + +## Chain {#chain} + +Ang **Chain** module ay naglalaman ng mga chain parameter (mga aktibong fork, consensus engine, atbp.) + +* **mga chain** - Paunang natukoy na mga chain configuration (mainnet, goerli, ibft) + +## Helper {#helper} + +Ang **Helper** module ay naglalaman ng mga helper package. + +* **dao** - Dao utils +* **enode** - Enode encoding/decoding function +* **hex** - mga hex encoding/decoding function +* **ipc** - mga IPC connection function +* **keccak** - mga keccak function +* **rlputil** - Rlp encoding/decoding helper function + +## Command {#command} + +Ang **Command** module ay naglalaman ng mga interface para sa mga CLI command. \ No newline at end of file diff --git a/archive/edge/tl-edge/architecture/modules/sealer.md b/archive/edge/tl-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..06dd99a63d --- /dev/null +++ b/archive/edge/tl-edge/architecture/modules/sealer.md @@ -0,0 +1,73 @@ +--- +id: sealer +title: Sealer +description: Paliwanag para sa sealer module ng Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## Pangkalahatang-ideya {#overview} + +Ang **Sealer** ay isang entidad na nag-iipon ng mga transaksyon, at lumilikha ito ng bagong block.
+Pagkatapos, ang block na iyon ay ipinapadala sa **Consensus** module para i-seal ito. + +Ang huling logic ng pag-seal ay matatagpuan sa **Consensus** module. + +## Paraang Run {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution Ginagawa pa + +Malapit nang pagsamahin sa iisang entidad ang **Sealer** module at ang **Consensus** module. + +Ang bagong module ay magsasama ng modular logic para sa iba't ibang uri ng mekanismo ng consensus, na nangangailangan ng iba't ibang implementasyon ng pag-seal: +* **PoS** (Proof of Stake) +* **PoA** (Proof of Authority) + +Sa kasalukuyan, gumagana sa PoW (Proof of Work) ang **Sealer** module at ang **Consensus** module. + +::: \ No newline at end of file diff --git a/archive/edge/tl-edge/architecture/modules/state.md b/archive/edge/tl-edge/architecture/modules/state.md new file mode 100644 index 0000000000..6f62b3625a --- /dev/null +++ b/archive/edge/tl-edge/architecture/modules/state.md @@ -0,0 +1,248 @@ +--- +id: state +title: State +description: Paliwanag para sa state module ng Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +Para talagang maunawaan kung paano gumagana ang **State**, dapat mong maunawaan ang ilang mga basehang konsepto ng Ethereum.
+ +Lubos naming inirerekomenda ang pagbabasa sa **[State sa Ethereum guide](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)**. + +## Pangkalahatang-ideya {#overview} + +Ngayong pamilyar na tayo sa mga basehang konsepto ng Ethereum, ang susunod na pangkalahatang-ideya ay madali na. + +Binanggit namin na ang **World state trie** ay mayroon ng lahat ng umiiral na mga Ethereum account.
+Ang mga account na ito ay ang mga pahina ng Merkle trie. Ang bawat pahina ay may naka-encode ng impormasyon ng **Account State**. + +Pinapagana nito ang Polygon Edge na makakuha ng isang espesipikong Merkle trie, para sa isang espesikong punto ng panahon.
+Halimbawa, maaari naming makuha ang hash ng state sa block 10. + +Ang Merkle trie, sa anumang punto ng panahon, ay tinatawag na isang ***Snapshot***. + +Maaari kaming magkaroon ng mga ***Snapshot*** para sa **state trie**, o para sa **storage trie** - halos parehas lang sila.
+Ang pagkakaiba lamang ay kung ano ang kinakatawan ng mga pahina: + +* Sa kaso ng storage trie, ang mga pahina ay naglalaman ng isang arbitrary state, na hindi namin maaaring iproseso o malaman kung ano ang naroroon +* Sa kaso ng state trie, ang mga pahina ay kumakatawan sa mga account + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + +Ang **Snapshot** interface ay tinukoy bilang sumusunod: + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +Ang impormasyong maaaring magawa ay tinukoy ng *Object struct*: + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +Ang implementasyon para sa Merkle trie ay nasa *state/immutable-trie* na folder.
+Ang *state/immutable-trie/state.go* ay nagpapatupad ng **State** interface. + +Ang *state/immutable-trie/trie.go* ay ang pangunahing Merkle trie object. Ito ay kumakatawan sa isang optimized na bersyon ng Merkle trie, +na muling gumagamit ng maraming memory hangga't maaari. + +## Executor {#executor} + +Ang *state/executor.go* ay naglalaman ng lahat ng impormasyong kinakailangan para makapagpasya ang Polygon Edge kung paano binabago ng block ang kasalukuyang +state. Ang implementasyon ng *ProcessBlock* ay matatagpuan dito. + +Ang paraan ng *pag-apply* ang gumagawa ng aktuwal na state transition. Ang executor ay tumatawag sa EVM. + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## Runtime {#runtime} + +Kapag naisagawa ang isang state transition, ang pangunahing module na nagsasagawa ng state transition ay ang EVM (nasa +state/runtime/evm). + +Ang **dispatch table** ay gumagawa ng pagtugma sa pagitan ng **opcode** at ng instruction. + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +Ang core logic na nagpapagana sa EVM ay ang *Run* loop.
+ +Ito ang pangunahing entry point para sa EVM. Gumagawa ito ng loop at sinusuri ang kasalukuyang opcode, kinukuha ang instruction, sinusuri +kung maaari itong isagawa, kinukunsumo ang gas at isinasagawa ang instruction hanggang sa ito ay pumalya o huminto. + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/tl-edge/architecture/modules/storage.md b/archive/edge/tl-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..22ea337f74 --- /dev/null +++ b/archive/edge/tl-edge/architecture/modules/storage.md @@ -0,0 +1,118 @@ +--- +id: storage +title: Storage +description: Paliwanag para sa storage module ng Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## Pangkalahatang-ideya {#overview} + +Kasalukuyang gumagamit ang Polygon Edge ng **LevelDB** para sa data storage, at ng **in-memory** data store. + +Sa buong Polygon Edge, kapag kinakailangan ng mga module na makipag-interaksyon sa pangunahing data store, +hindi kailangang malaman ng mga ito kung aling DB engine o serbisyo ang kinakausap nila. + +Ang layer ng DB ay abstraction sa pagitan ng module na tinatawag na **Storage**, na nag-e-export ng mga interface na kinu-query ng mga module. + +Ipinapatupad ng bawat layer ng DB, sa ngayon ay ng **LevelDB** lang, ang mga paraan na ito nang magkakahiwalay, na tumitiyak na akma ang mga ito sa implementasyon ng mga ito. + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### Mga Prefix {#prefixes} + +Para maging deterministiko ang pag-query sa LevelDB storage, at maiwasan ang salungatan ng storage ng key, gumagamit ang Polygon Edge ng +mga prefix at sub-prefix kapag nagi-store ng data + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## Mga Plano sa Hinaharap {#future-plans} + +Kabilang sa mga plano para sa nalalapit na hinaharap ang pagdadagdag ng ilan sa mga pinaka-popular na solusyon sa DB, tulad ng: +* PostgreSQL +* MySQL + + +## 📜 Mga Resource {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/tl-edge/architecture/modules/syncer.md b/archive/edge/tl-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..ff73e9e4b3 --- /dev/null +++ b/archive/edge/tl-edge/architecture/modules/syncer.md @@ -0,0 +1,68 @@ +--- +id: syncer +title: Syncer +description: Paliwanag para sa syncer module ng Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## Pangkalahatang-ideya {#overview} + +Nilalaman ng module na ito ang logic para sa protokol sa pag-synchronize. Ginagamit ito para sa pag-sync ng bagong node sa tumatakbong network o para sa pag-validate/pagsingit ng mga bagong block para sa mga node na hindi lumalahok sa consensus (mga non-validator). + +Ang Polygon Edge ay gumagamit ng **libp2p** bilang layer ng networking, at dagdag dito ay nagpapatakbo rin ito ng **gRPC**. + +Mayroong mahahalagang 2 type ng sync sa Polygon Edge: +* Maramihang Pag-sync - pag-sync ng malaking hanay ng mga block nang sabay-sabay +* Watch Sync - pag-sync ng block nang paisa-isa + +### Maramihang Pag-sync {#bulk-sync} + +Ang mga hakbang para sa Maramihang Pag-sync ay madali lang para matugunan ang layunin ng Maramihang Pag-sync - mag-sync ng maraming block (na available) mula sa ibang peer para makahabol, sa lalong madaling panahon. + +Ito ang daloy ng proseso ng Maramihang Pag-sync: + +1. ** Tukuyin kung ang node ay kailangang magsagawa ng Maramihang Pag-sync ** - Sa hakbang na ito, tinitingnan ng node ang peer map para makita kung mayroong may mas malaking block number kaysa sa mayroon ang node sa lokal +2. ** Hanapin ang pinakamahusay na peer (gamit ang sync peer map) ** - Sa hakbang na ito, hinahanap ng node ang pinakamahusay na peer kung saan magsi-sync batay sa nabanggit na mga pamantayan sa halimbawa sa itaas. +3. ** Magbukas ng stream ng maramihang pag-sync ** - Sa hakbang na ito, nagbubukas ang node ng stream ng gRPC sa pinakamahusay na peer para maramihang mag-sync ng mga block mula sa karaniwang block number +4. ** Isinasara ng pinakamahusay na peer ang stream kapag tapos nang magpadala nang maramihan ** - Sa hakbang na ito, isasara ng pinakamahusay na peer, kung saan nagsi-sync ang node, ang stream sa sandaling maipadala na nito ang lahat ng available na block na mayroon ito +5. ** Kapag tapos nang maramihang mag-sync, tingnan kung validator ang node ** - Sa hakbang na ito, ang stream ay isinasara ng pinakamahusay na peer, at kailangang tingnan ng node kung validator ang mga ito pagkatapos na maramihang mag-sync. + * Kung validator ang mga ito, aalis sa sync state ang mga ito at magsisimulang lumahok ang mga ito sa consensus + * Kung hindi validator ang mga ito, magpapatuloy ang mga ito sa ** Watch Sync ** + +### Watch Sync {#watch-sync} + +:::info + +Ang hakbang para sa Watch na Pag-sync ay isinasagawa lang kung ang node ay hindi validator, ngunit isang regular na non-validator node sa network na nakikinig lang ng mga paparating na block. + +::: + +Ang gawi ng Watch Sync ay diretsahan lang, naka-sync na sa iba pang bahagi ng network ang node at kinakailangan lang nito na i-parse ang mga papasok na bagong block. + +Ito ang daloy ng proseso ng Watch Sync: + +1. ** Magdagdag ng bagong block kapag na-update ang status ng peer ** - Sa hakbang na ito, ang mga node ay nakikinig ng mga event ng bagong block, kapag mayroon itong bagong block, magpapatakbo ito ng gRPC function call, kukunin nito ang block at ia-update nito ang local state. +2. ** Tingnan kung ang node ay validator pagkatapos i-sync ang pinakabagong block ** + * Kung validator ito, aalis sa sync state + * Kung hindi ito validator, magpatuloy na makinig ng mga event ng bagong block + +## Ulat sa performance {#perfomance-report} + +:::info + +Sinukat ang performance sa isang local machine sa pamamagitan ng pag-sync ng ** milyong mga block ** + +::: + +| Pangalan | Resulta | +|----------------------|----------------| +| Nagsi-sync ng 1M mga block | ~ 25 minuto | +| Naglilipat ng 1M mga block | ~ 1 minuto | +| Bilang ng mga GRPC call | 2 | +| Sakop ng pagsubok | ~ 93% | \ No newline at end of file diff --git a/archive/edge/tl-edge/architecture/modules/txpool.md b/archive/edge/tl-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..056e630cca --- /dev/null +++ b/archive/edge/tl-edge/architecture/modules/txpool.md @@ -0,0 +1,231 @@ +--- +id: txpool +title: TxPool +description: Paliwanag para sa TxPool module ng Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## Pangkalahatang-ideya {#overview} + +Ang TxPool module ay kumakatawan sa implementasyon ng transaction pool, kung saan idinadagdag ang mga transaksyon mula sa iba't ibang bahagi ng +system. Inihahayag din ng module na ito ang ilang kapaki-pakinabang na mga feature para sa mga node operator, na sinaklaw sa ibaba. + +## Mga Command ng Operator {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +Maaring mag-query ang mga node operator sa mga GRPC endpoint na ito, tulad ng inilarawan sa **[CLI Command](/docs/edge/get-started/cli-commands#transaction-pool-commands)** na seksyon. + +## Pagproseso ng mga Transaksyon {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +Ang pamamaraang ***addImpl*** ay ang pinakapangunahin sa **TxPool** module. +Ito ang sentrong lugar kung saan idinadagdag ang mga transaksyon sa system, bilang kino-call mula sa GRPC service, mga JSON RPC endpoint, +at sa tuwing nakakatanggap ang client ng isang transaksyon sa pamamagitan ng **gossip** na protokol. + +Pumapasok ito bilang isang argument **ctx**, na nangangahulugan lamang ng konteksto kung saan idinadagdag ang mga transaksyon (GRPC, JSON RPC...).
+Ang iba pang parameter ay ang listahan ng mga transaksyon na idadagdag sa pool. + +Ang mahalagang bagay na dapat tandaan dito ay ang pag-check sa field na **From** sa loob ng transaksyon: +* Kung ang **From** na field ay **walang laman**, itinuturing itong hindi naka-encrypt/hindi na-sign na transaksyon. Ang mga ganitong uri ng transaksyon ay +tinatanggap lamang sa development mode +* Kung ang **From** na field ay **may laman**, nangangahulugan ito na ito ay isang na-sign na transaksyon, kaya magkakaroon ng signature verification + +Pagkatapos ng lahat ng mga validation na ito, ituturing na valid ang mga transaksyon. + +## Mga data structure {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +Ang mga field sa TxPool object na maaaring maging sanhi ng pagkalito ay ang **queue** at **sorted** na mga listahan. +* **queue** - Maramihang pagpapatupad ng isang nakaayos na listahan ng mga account transaction (sa pamamagitan ng nonce) +* **sorted** - Nakaayos na listahan para sa lahat mga kasalukuyang promoted transaction (lahat ng mga transaksyong maaaring isagawa). Inayos ayon sa gas price + +## Pamamahala ng error ng gas limit {#gas-limit-error-management} + +Kapag nagsumite ka ng isang transaksyon, may tatlong paraan ng pagpoproseso nito sa pamamagitan ng TxPool. + +1. Lahat ng mga nakabinbing transaksyon ay maaaring magkasya sa isang block +2. Ang isa o higit pang mga nakabinbing transaksyon ay hindi maaaring magkasya sa isang block +3. Ang isa o higit pang mga nakabinbing transaksyon ay hindi kailanman magkakasya sa isang block + +Dito, ang salitang **_magkasya_** ay nangangahulugan na ang transaksyon ay may gas limit na mas mababa kaysa sa natitirang gas sa TxPool. + +Ang unang scenario ay hindi makakagawa ng anumang error. + +### Ikalawang scenario {#second-scenario} + +- Ang natitirang gas ng TxPool ay itinakda sa gas limit ng huling block, sabihin nating **5000** +- Ang unang transaksyon ay pinoproseso at nagkukunsumo ng **3000** gas ng TxPool + - Ang natitirang gas ng TxPool ay **2000** na ngayon. +- Ang ikalawang transaksyon, na katulad ng nauna - magkapareho silang kumukunsumo ng 3000 unit ng gas, ay isinumite +- Dahil **mas mababa** ang natitirang gas ng TxPool kaysa sa gas ng transaksyon, hindi ito maaaring iproseso sa kasalukuyang +block + - Ibabalik ito sa isang nakabinbing transaction queue para maproseso ito sa susunod na block +- Isusulat ang unang block, tatawagin natin itong **block #1** +- Ang natitirang gas ng TxPool ay nakatakda sa parent block - gas limit ng **block #1** +- Ang transaksyon na ibinalik sa nakabinbing transaction queue ng TxPool ay pinoproseso na ngayon at isinusulat sa block + - Ang natitirang gas ng TxPool ay **2000** na ngayon +- Ang ikalawang block ay isinusulat +- ... + +![TxPool Error scenario #1](/img/edge/txpool-error-1.png) + +### Ikatlong scenario {#third-scenario} +- Ang natitirang gas ng TxPool ay itinakda sa gas limit ng huling block, sabihin nating **5000** +- Ang unang transaksyon ay pinoproseso at nagkukunsumo ng **3000** gas ng TxPool + - Ang natitirang gas ng TxPool ay **2000** na ngayon +- Ang ikalawang transaksyon na may gas field na itinakdsa **6000** ay isinumite +- Dahil **mas mababa** ang gas limit kaysa sa gas ng transaksyon, ang transaksyon na ito ay inalis + - Hindi ito kailanman magkakasya sa isang block +- Ang unang block ay isinusulat +- ... + + +![TxPool Error scenario #2](/img/edge/txpool-error-2.png) + +> Nangyayari ito sa tuwing makakakuha ka ng sumusunod na error: +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## Block Gas Target {#block-gas-target} + +Mayroong mga sitwasyon kung kailan gustong panatilihin ng mga node ang gas limit na mas mababa o nasa isang tiyak na target sa isang tumatakbong chain. + +Maaring magtakda ng target gas limit ang node operator sa isang espisipikong node, na sisikaping gamitin ang limitasyong ito sa mga bagong likhang block. +Kung karamihan sa ibang mga node ay mayroon ding katulad (o kaparehong) itinakdang target gas limit, ang block gas limit ay palaging mag-aabang +sa paligid ng block gas target na iyon, na dahan-dahang umuusad patungo rito (sa max na `1/1024 * parent block gas limit`) habang nililikha ang mga bagong block. + +### Halimbawang scenario {#example-scenario} + +* Itatakda ng node operator ang block gas limit para sa isang single node para maging `5000` +* Ang ibang mga node ay isasaayos para maging `5000` din, bukod sa isang single node na isinaayos para maging `7000` +* Kung ang mga node na may itinakdang gas target na `5000` ay naging mga proposer, titingnan nila kung ang gas limit ay nasa target na +* Kung ang gas limit ay wala sa target (mas malaki ito / mas mababa), itatakda ng proposer node ang block gas target sa pinakamataas (1/1024 * parent gas limit) sa direksyon ng target + 1. Hal: `parentGasLimit = 4500` at `blockGasTarget = 5000`, kukwentahin ng proposer ang gas limit para sa bagong block bilang `4504.39453125` (`4500/1024 + 4500`) + 2. Hal: `parentGasLimit = 5500` at `blockGasTarget = 5000`, kukwentahin ng proposer ang gas limit para sa bagong block bilang `5494.62890625` (`5500 - 5500/1024`) +* Tinitiyak nito na ang block gas limit sa chain ay iingatan sa target, dahil ang single proposer na nagsaayos ng taget sa `7000` ay hindi maaaring mag-advance ng limitasyon, at ang karamihan +ng mga node na itinakda nito sa `5000` ay palaging magtatangka na panatilihin ito roon \ No newline at end of file diff --git a/archive/edge/tl-edge/architecture/modules/types.md b/archive/edge/tl-edge/architecture/modules/types.md new file mode 100644 index 0000000000..669e5725af --- /dev/null +++ b/archive/edge/tl-edge/architecture/modules/types.md @@ -0,0 +1,43 @@ +--- +id: types +title: Mga Type +description: Paliwanag para sa mga type na module ng Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## Pangkalahatang-ideya {#overview} + +Ipinapatupad ng module na mga **Type** ang mga type ng core object, tulad ng: + +* **Address** +* **Hash** +* **Header** +* maraming mga helper function + +## Pag-encode / Pag-decode ng RLP {#rlp-encoding-decoding} + +Hindi tulad ng mga client gaya ng GETH, ang Polygon Edge ay hindi gumagamit ng reflection para sa pag-encode.
+Pinili na hindi gumamit ng reflection dahil nagpapasimula ito ng mga bagong problema, tulad ng +pagkasira ng performance, at mas mahirap na scaling. + +Ang module na mga **Type** ay nagbibigay ng madaling gamiting interface para sa marshaling at unmarshalling ng RLP, gamit ang FastRLP package. + +Isinasagawa ang marshaling sa pamamagitan ng mga paraang *MarshalRLPWith* at *MarshalRLPTo*. Mayroong katulad na mga paraan para sa +unmarshalling. + +Sa pamamagitan ng manual na pagtukoy sa mga paraang ito, hindi kinakailangan ng Polygon Edge na gumamit ng reflection. Sa *rlp_marshal.go*, makakahanap ka ng +mga paraan para sa marshaling: + +* **Mga Body** +* **Mga Block** +* **Mga Header** +* **Mga Resibo** +* **Mga Log** +* **Mga Transaksyon** \ No newline at end of file diff --git a/archive/edge/tl-edge/architecture/overview.md b/archive/edge/tl-edge/architecture/overview.md new file mode 100644 index 0000000000..bde665c8c7 --- /dev/null +++ b/archive/edge/tl-edge/architecture/overview.md @@ -0,0 +1,61 @@ +--- +id: overview +title: Pangkalahatang-ideya ng Arkitektura +sidebar_label: Overview +description: Introduksyon sa arkitektura ng Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +Sinimulan namin sa pamamagitan ng idea na gumawa ng software na *modular*. + +Isa itong bagay na nasa halos lahat ng bahagi ng Polygon Edge. Sa ibaba, makikita mo ang maikling pangkalahatang-ideya ng +ginawang arkitektura at layering nito. + +## Layering ng Polygon Edge {#polygon-edge-layering} + +![Arkitektura ng Polygon Edge](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +Nagsisimula ang lahat ng ito sa layer ng base networking, na gumagamit ng **libp2p**. Nagpasya kaming piliin ang teknolohiyang ito dahil +akma ito sa mga pilosopiya ng pagdidisenyo ng Polygon Edge. Ang Libp2p ay: + +- Modular +- Extensible +- Mabilis + +Higit sa lahat, nagbibigay ito ng mahusay na pundasyon para sa mga mas advanced na feature, na tatalakayin natin sa susunod. + + +## Pag-synchronize at Consensus {#synchronization-consensus} +Ang pagiging hiwalay ng mga protokol ng pag-synchronize at consensus ay nagbibigay-daan sa modularity at implementasyon ng mga **custom** na mekanismo ng sync at consensus - depende kung paano pinapatakbo ang client. + +Ang Polygon Edge ay idinisenyo na mag-alok ng mga off-the-shelf na pluggable na algorithm ng consensus. + +Ang kasalukuyang listahan ng mga sinusuportahang algorithm ng consensus: + +* IBFT PoA +* IBFT PoS + +## Blockchain {#blockchain} +Ang layer na Blockchain ay ang central na layer na nagko-coordinate ng lahat sa system ng Polygon Edge. Tinatalakay ito nang detalyado sa kaugnay na seksyong mga *Module*. + +## State {#state} +Ang panloob na layer ng State ay naglalaman ng state transition logic. Pinapangasiwaan nito kung paano nagbabago ang state kapag isinama ang isang bagong block. Tinatalakay ito nang detalyado sa kaugnay na seksyong mga *Module*. + +## JSON RPC {#json-rpc} +Ang layer na JSON RPC ay isang API layer na ginagamit ng mga dApp developer para makipag-interaksyon sa blockchain. Tinatalakay ito nang detalyado sa kaugnay na seksyong mga *Module*. + +## TxPool {#txpool} +Kinakatawan ng layer na TxPool ang pool ng transaksyon, at lubos na nauugnay ito sa iba pang module sa system, dahil ang mga transaksyon ay maaaring idagdag mula sa maraming entry point. + +## gRPC {#grpc} +Ang gRPC, o Google Remote Procedure Call, ay isang matatag na open-source na RPC framework na una nang nilikha ng Google para magtayo ng scalable at mabilis na API. Mahalaga ang layer na GRPC para sa mga interaksyon ng operator. Sa pamamagitan nito, madaling nagagawa ng mga operator ng node na makipag-interaksyon sa client, na nagdudulot ng nae-enjoy na UX. diff --git a/archive/edge/tl-edge/community/propose-new-feature.md b/archive/edge/tl-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..fc9cd4d513 --- /dev/null +++ b/archive/edge/tl-edge/community/propose-new-feature.md @@ -0,0 +1,60 @@ +--- +id: propose-new-feature +title: Magpanukala ng isang bagong feature +description: "PR template at mga tagubilin para sa pagpapanukala ng isang bagong feature." +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## Pangkalahatang-ideya {#overview} + +Kung nais mong magsama ng isang fix, o mag-ambag lamang sa code, lubos kang hinihikayat na makipag-ugnayan muna sa team.
+Gumagamit ang Polygon Edge ng isang halos panimulang feature proposition template, na maikli at diretso sa punto. + +## PR Template {#pr-template} + +### Paglalarawan {#description} + +Mangyaring magbigay ng detalyadong paglalarawan kung ano ang ginawa sa PR na ito + +### Kabilang sa mga pagbabago ang {#changes-include} + +- [ ] Bugfix (non-breaking change na lumulutas sa isang issue) +- [ ] Hotfix (pagbabago na lumulutas sa isang apurahang issue, at nangangailangan ng agarang pansin) +- [ ] Bagong feature (non-breaking change na nagdadagdag ng functionality) +- [ ] Breaking change (pagbabago na hindi backward-compatible at/o nagbabago sa kasalukuyang functionality) + +### Mga breaking change {#breaking-changes} + +Mangyaring kumpletuhin ang seksyon na ito kung ginawa ang anumang mga breaking change, kung hindi, tanggalin ito + +### Checklist {#checklist} + +- [ ] In-assign ko ang PR na ito sa aking sarili +- [ ] Nagdagdag ako ng hindi bababa sa 1 reviewer +- [ ] Nagdagdag ako ng mga kaugnay na label +- [ ] In-update ko ang opisyal na dokumentasyon +- [ ] Nagdagdag ako ng sapat na dokumentasyon sa code + +### Pagsubok {#testing} + +- [ ] Sinubukan ko ang code na ito sa pamamagitan ng opisyal na test suite +- [ ] Sinubukan ko nang manual ang code na ito + +## Mga manual na pagsubok {#manual-tests} + +Mangyaring kumpletuhin ang seksyon na ito kung nagpatakbo ka ng mga manual na pagsubok para sa functionality na ito, kung hindi, tanggalin ito + +### Update sa dokumentasyon {#documentation-update} + +Mangyaring i-link ang update sa dokumentasyon ng PR sa seksyong ito kung mayroon, kung wala, tanggalin ito + +### Karagdagang mga komento {#additional-comments} + +Mangyaring mag-post ng karagdagang komento sa seksyong ito kung mayroon, kung wala, tanggalin ito \ No newline at end of file diff --git a/archive/edge/tl-edge/community/report-bug.md b/archive/edge/tl-edge/community/report-bug.md new file mode 100644 index 0000000000..e7def81c40 --- /dev/null +++ b/archive/edge/tl-edge/community/report-bug.md @@ -0,0 +1,55 @@ +--- +id: report-bug +title: Mag-ulat ng issue +description: Template at mga tagubilin para sa pag-uulat ng issue sa Polygon Edge. +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## Pangkalahatang-ideya {#overview} + +Minsan, nasisira ang mga bagay-bagay.
+Laging mas mabuting ipagbigay-alam sa team ang tungkol sa anumang issue na maaaring nararanasan mo.
+Sa pahina ng GitHub ng Polygon Edge, maaari kang mag-file ng bagong issue, at simulan itong talakayin sa team. + +## Template para sa Issue {#issue-template} + +## [Paksa ng issue] + +### Paglalarawan {#description} + +Hangga't maaari, detalyadong ilarawan mo dito ang iyong issue + +### Ang iyong environment {#your-environment} + +* OS at bersyon +* bersyon ng Polygon Edge +* branch na nagdudulot ng issue na ito + +### Mga hakbang na ire-reproduce {#steps-to-reproduce} + +* Sabihin sa amin kung paano ire-reproduce ang issue na ito
+* Kung nasaan ang issue, kung alam mo
+* Aling mga command ang nag-trigger sa issue, kung mayroon man + +### Inaasahang gawi {#expected-behaviour} + +Sabihin sa amin kung ano ang dapat mangyari + +### Aktwal na gawi {#actual-behaviour} + +Sabihin na lang sa amin kung ano ang nangyayari + +### Mga log {#logs} + +Mangyaring i-paste dito ang anumang log na nagpapakita sa issue, kung mayroong mga ganito + +### Iminumungkahing solusyon {#proposed-solution} + +Kung may idea ka kung paano ayusin ang issue na ito, mangyaring isulat ito rito, para masimulan namin itong talakayin \ No newline at end of file diff --git a/archive/edge/tl-edge/configuration/manage-private-keys.md b/archive/edge/tl-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..b3fdbbee69 --- /dev/null +++ b/archive/edge/tl-edge/configuration/manage-private-keys.md @@ -0,0 +1,79 @@ +--- +id: manage-private-keys +title: Pamahalaan ang mga pribadong key +description: "Paano pamahalaan ang mga pribadong key at kung anong mga uri ng mga key ang mayroon." +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## Pangkalahatang-ideya {#overview} + +May dalawang uri ng pribadong key ang Polygon Edge na tuwiran nitong pinamamahalaan: + +* **Pribadong key na ginagamit para sa consensus mechanism** +* **Pribadong key na ginagamit para sa networking ng libp2p** +* **(Optional) BLS Pribadong key na ginagamit para sa concensus mechanism para pagsama-samahin ang mga pirma ng mga validator** + +Sa kasalukuyan, ang Polygon Edge ay hindi nag-aalok ng suporta para sa tuwirang pamamahala ng account. + +Batay sa istraktura ng directory na binalangkas sa [Backup & Restore guide](/docs/edge/working-with-node/backup-restore), +ang Polygon Edge ay nag-iimbak ng mga binanggit na key file sa dalawang natatanging directory - **consensus** at **keystore**. + +## Format ng key {#key-format} + +Ang mga pribadong key ay inimbak sa simpleng **Base64 format**, para mabasa ng tao at portable. + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info Uri ng Key + +Lahat ng mga pribadong key file na binuo at ginamit sa loob ng Polygon Edge ay umaasa sa ECDSA na may curve na [secp256k1](https://en.bitcoin.it/wiki/Secp256k1). + +Dahil ang curve ay non-standard, hindi ito maaaring i-encode at iimbak sa anumang standardized na PEM format. +Ang pag-import ng mga key na hindi sumusunod sa uri ng key na ito ay hindi sinusuportahan. + +::: +## Pribadong Key ng Consensus {#consensus-private-key} + +Ang pribadong key file na binanggit bilang *pribadong key ng consensus* ay tinutukoy din bilang **pribadong key ng validator**. +Ang pribadong key na ito ay ginagamit kapag ang node ay kumikilos bilang isang validator sa network at kailangang mag-sign ng bagong data. + +Ang pribadong key file ay matatagpuan sa `consensus/validator.key`, at sumusunod sa [format ng key](/docs/edge/configuration/manage-private-keys#key-format) na nabanggit. + +:::warning + +Ang pribadong key ng validator ay natatangi sa bawat validator node. Ang parehong key ay hindi dapat ibahagi sa lahat ng mga validator, dahil maaari nitong makompromiso ang seguridad ng iyong chain. + +::: + +## Pribadong Key sa Networking {#networking-private-key} + +Ang pribadong key file na binanggit para sa networking ay ginagamit ng libp2p para bumuo ng kaukulang PeerID, at pinapahintulutan ang node na lumahok sa network. + +Ito ay matatagpuan sa `keystore/libp2p.key`, at sumusunod sa [format ng key](/docs/edge/configuration/manage-private-keys#key-format) na nabanggit. + +## BLS Secret Key {#bls-secret-key} + +Ang BLS secret key file ay ginagamit para pagsama-samahin ang mga committed seal sa consensus layer. Ang sukat ng pinagsama-samang mga committed seal ng BLS ay mas mababa sa mga serialized committed na ECDSA signature. + +Ang BLS feature ay optional at maaaring pumili kung gagamit ng BLS o hindi. Sumangguni sa [BLS](/docs/edge/consensus/bls) para sa higit pang detalye. + +## Import / Export {#import-export} + +Dahil ang mga key file ay nakaimbak sa simpleng Base64 sa disk, madali ma-back up o ma-import ang mga ito. + +:::caution Pagbabago ng mga key file + +Anumang uri ng pagbabagong ginawa sa mga key file sa naka-set up / tumatakbo nang network ay maaaring humantong sa malubhang pagkagambala sa network/consensus, +dahil ang consensus at mga peer discovery mechanism ay nag-iimbak ng data na hinango mula sa mga key na ito sa node-specific na storage, at umaasa sa data na ito para +pasimulan ang mga koneksyon at magsagawa ng consensus logic + +::: \ No newline at end of file diff --git a/archive/edge/tl-edge/configuration/prometheus-metrics.md b/archive/edge/tl-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..16e6634bc2 --- /dev/null +++ b/archive/edge/tl-edge/configuration/prometheus-metrics.md @@ -0,0 +1,35 @@ +--- +id: prometheus-metrics +title: Prometheus metrics +description: "Kung paano i-enable ang Prometheus metrics para sa Polygon Edge." +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## Pangkalahatang-ideya {#overview} + +Ang Polygon Edge ay maaaring mag-ulat at gumamit ng Prometheus metrics, na sa kalaunan ay maaaring maubos gamit ang Prometheus collector(s). + +Pinagana ang mga metrics ng Prometheus ng Prometheus sa pamamagitan ng default. Maaari itong i-enable sa pamamagitan ng pagtukoy sa address ng tagapakinig gamit ang `--prometheus`f[lag ](/docs/edge/get-started/cli-commands#prometheus)o `Telemetry.prometheus`field sa config file. Ang mga metrics ay gagamitin sa ilalim ng `/metrics` sa tinukoy na address. + +## Mga available na metrics {#available-metrics} + +Ang mga sumusunod na metrics ay available: + +| **Pangalan** | **Uri** | **Paglalarawan** | +|-------------------------------------------------|----------|---------------------------------------------| +| edge_txpool_pending_transactions | Gauge | Bilang ng mga nakabinbing transaksyon sa TxPool | +| edge_consensus_validators | Gauge | Bilang ng mga Validator | +| edge_consensus_rounds | Gauge | Bilang ng mga Round | +| edge_consensus_num_txs | Gauge | Bilang ng mga Transaksyon sa pinakahuling block | +| edge_consensus_block_interval | Gauge | Oras sa pagitan nito at ng huling block sa mga segundo | +| edge_network_peers | Gauge | Bilang ng mga Konektadong peer | +| edge_network_outbound_connections_count | Gauge | Bilang ng mga outbound na koneksyon | +| edge_network_inbound_connections_count | Gauge | Bilang ng mga inbound na koneksyon | +| edge_network_pending_inbound_connections_count | Gauge | Bilang ng mga nakabinbing outbound na koneksyon | +| edge_network_pending_outbound_connections_count | Gauge | Bilang ng mga nakabinbing inbound na koneksyon | +| edge_consensus_epoch_number | Gauge | Kasalukuyang numero ng epoch | \ No newline at end of file diff --git a/archive/edge/tl-edge/configuration/sample-config.md b/archive/edge/tl-edge/configuration/sample-config.md new file mode 100644 index 0000000000..d7c8e98c08 --- /dev/null +++ b/archive/edge/tl-edge/configuration/sample-config.md @@ -0,0 +1,151 @@ +--- +id: sample-config +title: Config File ng Server +description: "Paganahin ang Polygon Edge server gamit ang isang configuration file." +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# Configuration file ng server {#server-configuration-file} +Ang pagpapagana ng server sa pamamagitan ng iba't ibang mga configuration option ay maaaring gawin gamit ang isang configuration file sa halip na gumamit lang ng mga flag. +Ang command na ginamit para paganahin ang server sa pamamagitan ng isang config file: `polygon-edge server --config ` + +## I-export ang config file na may default configuration {#export-config-file-with-default-configuration} +Ang configuration na may default na mga setting para sa Polygon Edge server ay maaaring i-export sa isang config file sa alinman sa `yaml` o `json` na file format. +Ang file na ito ay maaaring gamitin bilang isang template para sa pagpapatakbo ng server gamit ang isang configuration file. + +### YAML {#yaml} +Para buuin ang config file sa `yaml` na format: +```bash +polygon-edge server export --type yaml +``` +o ang +```bash +polygon-edge server export +``` +config file lang na pinangalanang `default-config.yaml` ay malilikha sa kaparehong directory kung saan pinatakbo ang command na ito. + +Halimbawa ng file: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +Para buuin ang config file sa `json` na format: +```bash +polygon-edge server export --type json +``` +config file lang na pinangalanang `default-config.json` ay malilikha sa kaparehong directory kung saan pinatakbo ang command na ito. + +Halimbawa ng file: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +Tingnan ang [CLI Commands](/docs/edge/get-started/cli-commands) na seksyon para makakuha ng impormasyon kung paano gamitin ang mga parameter na ito. + +### Typescript schema {#typescript-schema} + +Ang sumusunod ay ang sample format para sa configuration file. Ito ay nakasulat sa TypeScript para ipahayag ang mga type ng properties (`string`, `number`, `boolean`), mula rito ay maaari mong kunin ang iyong configuration. Mahalagang banggitin na ang `PartialDeep` na type mula sa `type-fest` ay ginagamit para ipahayag na ang lahat ng properties ay optional. + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/tl-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/tl-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..6d088e32c2 --- /dev/null +++ b/archive/edge/tl-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,139 @@ +--- +id: set-up-aws-ssm +title: I-set up ang AWS SSM (Systems Manager) +description: "I-set up ang AWS SSM (Systems Manager) para sa Polygon Edge." +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## Pangkalahatang-ideya {#overview} + +Sa kasalukuyan, ang Polygon Edge ay may gustong panatilihing 2 pangunahing runtime secret: +* Ang **pribadong key ng validator** na ginagamit ng node, kung validator ang node +* Ang **pribadong key para sa networking** na ginagamit ng libp2p, para sa pakikilahok at pakikipag-ugnayan sa iba pang peer + +Para sa karagdagang impormasyon, pakibasa ang [Gabay sa Pamamahala sa Mga Pribadong Key](/docs/edge/configuration/manage-private-keys) + +Ang mga module ng Polygon Edge ay **hindi kailangang malaman kung paano magpanatili ng mga secret**. Sa pangkalahatan, ang isang module ay walang kaugnayan sa kung ang +isang secret ay naka-store sa isang malayong server o kung lokal itong naka-store sa disk ng node. + +Ang lahat ng kailangang malaman ng module tungkol sa pagpapanatili ng secret ay ang **alamin kung paano gamitin ang secret** at **alamin kung aling mga secret ang kukunin +o ise-save**. Ang mga mas pinong detalye ng pagpapatupad ng mga operasyong ito ay itinakda sa `SecretsManager`, na siyempre ay isang abstraction. + +Magagawa na ngayon ng operator ng node na nagsisimula sa Polygon Edge na tukuyin kung aling mga manager ng secret ang gusto nitong gamitin, at sa sandaling +ma-instantiate ang wastong manager ng mga secret, ipinoproseso ng mga module ang mga secret sa pamamagitan ng nabanggit na interface +nang hindi isinasaalang-alang kung ang mga secret ay naka-store sa isang disk o server. + +Idinedetalye sa artikulong ito ang mga kinakailangang hakbang para mapatakbo ang Polygon Edge sa +[AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html). + +:::info mga nakaraang gabay + +**Mariing inirerekomenda** na bago basahin ang artikulong ito, nabasa na dapat ang mga artikulo tungkol sa [**Lokal na Pag-Setup**](/docs/edge/get-started/set-up-ibft-locally) +at [**Pag-Setup sa Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +::: + + +## Mga paunang kinakailangan {#prerequisites} +### IAM Policy {#iam-policy} +Kinakailangan ng user na gumawa ng IAM Policy na pinapayagan ang mga read/write na operasyon para sa AWS Systems Manager Parameter Store. +Pagkatapos matagumpay na magawa ang IAM Policy, kinakailangan ng user na ilakip ito sa EC2 instance na tumatakbo sa server ng Polygon Edge. +Parang ganito dapat ang hitsura ng IAM Policy: +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +Mayroon kang mahahanap na higit pang impormasyon tungkol sa AWS SSM IAM Roles sa [mga dokumento ng AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html). + +Kinakailangang impormasyon bago magpatuloy: +* **Region** (ang region na kinaroroonan ng Systems Manager at mga node) +* **Parameter Path** (arbitrary path kung saan ilalagay ang secret, halimbawa `/polygon-edge/nodes`) + +## Hakbang 1 - Buuin ang configuration ng manager ng mga secret {#step-1-generate-the-secrets-manager-configuration} + +Para magawa ng Polygon Edge na maayos na makipag-ugnayan sa AWS SSM, kinakailangan nitong mag-parse ng +nabuo nang config file na naglalaman ng kinakailangang impormasyon para sa secret storage sa AWS SSM. + +Para mabuo ang configuration, patakbuhin ang sumusunod na command: + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +Mga umiiral na parameter: +* `PATH` ay ang path kung saan dapat i-export ang configuration file. Default na `./secretsManagerConfig.json` +* `NODE_NAME` ay ang pangalan ng kasalukuyang node na nilalayong node sa pag-set up ng AWS SSM. Maaari itong maging arbitrary na value. Default na `polygon-edge-node` +* `REGION` ay ang region na kinaroroonan ng AWS SSM. Kinakailangan nitong maging region na pareho sa region ng node na gumagamit ng AWS SSM. +* `SSM_PARAM_PATH` ay ang pangalan ng path kung saan i-store ang secret. Halimbawa, kung tinukoy ang `--name node1` at `ssm-parameter-path=/polygon-edge/nodes` +ii-store ang secret bilang `/polygon-edge/nodes/node1/` + +:::caution Mga pangalan ng node + +Mag-ingat kapag tinutukoy ang mga pangalan ng node. + +Ginagamit ng Polygon Edge ang tinukoy na pangalan ng node para subaybayan ang mga secret na binubuo at ginagamit nito sa AWS SSM. +Ang pagtukoy ng pangalan ng umiiral na node ay maaaring magresulta sa pagkabigong maisulat ang secret sa AWS SSM. + +Ini-store ang mga secret sa sumusunod na base path: `SSM_PARAM_PATH/NODE_NAME` + +::: + +## Hakbang 2 - Simulan ang mga secret key gamit ang configuration {#step-2-initialize-secret-keys-using-the-configuration} + +Ngayong mayroon nang configuration file, maaari nating simulan ang mga kinakailangang secret key sa pamamagitan ng pag-set up ng configuration +file sa hakbang 1, gamit ang `--config`: + +```bash +polygon-edge secrets init --config +``` + +Ang `PATH` param ay ang lokasyon ng naunang nabuong param ng manager ng mga secret mula sa hakbang 1. + +:::info IAM Policy + +Papalya ang hakbang na ito kung ang IAM Policy na nagbibigay-daan sa mga operasyon sa pagbabasa/pagsusulat ay hindi naka-configure nang maayos at/o hindi naka-attach sa EC2 instance na nagpapatakbo sa command na ito. + +::: + +## Hakbang 3 - Buuin ang genesis file {#step-3-generate-the-genesis-file} + +Dapat buuin ang genesis file gaya ng nakasaad sa mga gabay sa [**Lokal na Pag-Setup**](/docs/edge/get-started/set-up-ibft-locally) +at [**Pag-Setup sa Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud), na may kaunting pagbabago. + +Dahil ginagamit ang AWS SSM sa halip na ang local file system, dapat idagdag ang mga address ng validator sa pamamagitan ng `--ibft-validator` flag: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Hakbang 4: Simulan ang Polygon Edge client {#step-4-start-the-polygon-edge-client} + +Ngayon naka-set up na ang mga key, at nabuo na ang genesis file, ang huling hakbang sa prosesong ito ay simulan ang +Polygon Edge sa pamamagitan ng command na `server`. + +Ginagamit ang command na `server` sa katulad na paraan gaya ng nakasaad sa mga naunang nabanggit na gabay, na may kaunting idinagdag - ang `--secrets-config` flag: +```bash +polygon-edge server --secrets-config ... +``` + +Ang `PATH` param ay ang lokasyon ng naunang nabuong param ng manager ng mga secret mula sa hakbang 1. \ No newline at end of file diff --git a/archive/edge/tl-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/tl-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..1651123bf1 --- /dev/null +++ b/archive/edge/tl-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,120 @@ +--- +id: set-up-gcp-secrets-manager +title: Mag-set up ng GCP Secrets Manager +description: "Mag-set up ng GCP Secrets Manager para sa Polygon Edge." +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## Pangkalahatang-ideya {#overview} + +Sa kasalukuyan, ang Polygon Edge ay may gustong panatilihing 2 pangunahing runtime secret: +* Ang **pribadong key ng validator** na ginagamit ng node, kung validator ang node +* Ang **pribadong key para sa networking** na ginagamit ng libp2p, para sa pakikilahok at pakikipag-ugnayan sa iba pang peer + +Para sa karagdagang impormasyon, pakibasa ang [Gabay sa Pamamahala sa Mga Pribadong Key](/docs/edge/configuration/manage-private-keys) + +Ang mga module ng Polygon Edge ay **hindi kailangang malaman kung paano magpanatili ng mga secret**. Sa pangkalahatan, ang isang module ay walang kaugnayan sa kung ang +isang secret ay naka-store sa isang malayong server o kung lokal itong naka-store sa disk ng node. + +Ang lahat ng kailangang malaman ng module tungkol sa pagpapanatili ng secret ay ang **alamin kung paano gamitin ang secret** at **alamin kung aling mga secret ang kukunin +o ise-save**. Ang mga mas pinong detalye ng pagpapatupad ng mga operasyong ito ay itinakda sa `SecretsManager`, na siyempre ay isang abstraction. + +Magagawa na ngayon ng operator ng node na nagsisimula sa Polygon Edge na tukuyin kung aling mga manager ng secret ang gusto nitong gamitin, at sa sandaling +ma-instantiate ang wastong manager ng mga secret, ipinoproseso ng mga module ang mga secret sa pamamagitan ng nabanggit na interface +nang hindi isinasaalang-alang kung ang mga secret ay naka-store sa isang disk o server. + +Idinedetalye sa artikulong ito ang mga kinakailangang hakbang para mapatakbo ang Polygon Edge gamit ang [GCP Secret Manager](https://cloud.google.com/secret-manager). + +:::info mga nakaraang gabay + +**Mariing inirerekomenda** na bago basahin ang artikulong ito, nabasa na dapat ang mga artikulo tungkol sa [**Lokal na Pag-Setup**](/docs/edge/get-started/set-up-ibft-locally) +at [**Pag-Setup sa Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +::: + + +## Mga Paunang Kinakailangan {#prerequisites} +### GCP Billing Account {#gcp-billing-account} +Para magamit ang GCP Secrets Manager, kailangan ng user ng naka-enable na [Billing Account](https://console.cloud.google.com/) sa GCP portal. +Ang mga bagong Google account sa GCP platform ay inilaan nang may ilang mga pondo para makapagsimula, bilang hari ng free trial. +Higit na impormasyon sa [mga dokumentong GCP](https://cloud.google.com/free) + +### Secrets Manager API {#secrets-manager-api} +Kakailanganin ng user na i-enable ang GCP Secrets Manager API bago niya ito magamit. Magagawa ito sa pamamagitan ng [Secrets Manager API portal](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com). +Higit na impormasyon: [Pag-configure ng Secret Manger](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + +### GCP Credentials {#gcp-credentials} +Panghuli, kailangan ng user na bumuo ng mga bagong credential na gagamitin para sa authentication. +Magagawa ito sa pamamagitan ng pagsunod sa mga instruksyon na naka-post [dito](https://cloud.google.com/secret-manager/docs/reference/libraries). +Ang nabuong json file na naglalaman ng mga credential, ay dapat ilipat sa bawat node na kailangang gumamit ng GCP Secrets Manager. + +Kinakailangang impormasyon bago magpatuloy: +* **Project ID** (ang project id na tinukoy sa GCP platform) +* **Credentials File Location** (ang path patungo sa json file na naglalaman ng mga credential) + +## Hakbang 1 - Buuin ang configuration ng manager ng mga secret {#step-1-generate-the-secrets-manager-configuration} + +Para magawa ng Polygon Edge na maayos na makipag-ugnayan sa GCP SM, kinakailangan nitong mag-parse ng +nabuo nang config file na naglalaman ng kinakailangang impormasyon para sa secret storage sa GCP SM. + +Para mabuo ang configuration, patakbuhin ang sumusunod na command: + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +Mga umiiral na parameter: +* `PATH` ay ang path kung saan dapat i-export ang configuration file. Default na `./secretsManagerConfig.json` +* `NODE_NAME` ay ang pangalan ng kasalukuyang node kung saan naka-set up ang GCP SM configuration. Maaari itong maging arbitrary na value. Default na `polygon-edge-node` +* `PROJECT_ID` ay ang ID ng proyekto na tinukoy ng user sa GCP console account sa panahon ng pag-set up ng account at pag-activate ng Secrets Manager API. +* `GCP_CREDS_FILE` ay ang path patungo sa json file na naglalaman ng mga credentials na magpapahintulot sa read/write na access sa Secrets Manager. + +:::caution Mga pangalan ng node + +Mag-ingat kapag tinutukoy ang mga pangalan ng node. + +Ginagamit ng Polygon Edge ang tinukoy na pangalan ng node para subaybayan ang mga secret na binubuo at ginagamit nito sa GCP SM. +Ang pagtukoy sa isang umiiral na pangalan ng node ay maaaring magkaroon ng mga kahihinatnan ng pagpalya ng pag-write ng secret sa GCP SM. + +Ini-store ang mga secret sa sumusunod na base path: `projects/PROJECT_ID/NODE_NAME` + +::: + +## Hakbang 2 - Simulan ang mga secret key gamit ang configuration {#step-2-initialize-secret-keys-using-the-configuration} + +Ngayong mayroon nang configuration file, maaari nating simulan ang mga kinakailangang secret key sa pamamagitan ng pag-set up ng configuration +file sa hakbang 1, gamit ang `--config`: + +```bash +polygon-edge secrets init --config +``` + +Ang `PATH` param ay ang lokasyon ng naunang nabuong param ng manager ng mga secret mula sa hakbang 1. + +## Hakbang 3 - Buuin ang genesis file {#step-3-generate-the-genesis-file} + +Dapat buuin ang genesis file gaya ng nakasaad sa mga gabay sa [**Lokal na Pag-Setup**](/docs/edge/get-started/set-up-ibft-locally) +at [**Pag-set Up sa Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud), na may kaunting pagbabago. + +Dahil ginagamit ang GCP SM sa halip na ang local file system, dapat idagdag ang mga address ng validator sa pamamagitan ng `--ibft-validator` flag: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Hakbang 4: Simulan ang Polygon Edge client {#step-4-start-the-polygon-edge-client} + +Ngayon naka-set up na ang mga key, at nabuo na ang genesis file, ang huling hakbang sa prosesong ito ay simulan ang +Polygon Edge sa pamamagitan ng command na `server`. + +Ginagamit ang command na `server` sa katulad na paraan gaya ng nakasaad sa mga naunang nabanggit na gabay, na may kaunting idinagdag - ang `--secrets-config` flag: +```bash +polygon-edge server --secrets-config ... +``` + +Ang `PATH` param ay ang lokasyon ng naunang nabuong param ng manager ng mga secret mula sa hakbang 1. \ No newline at end of file diff --git a/archive/edge/tl-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/tl-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..ebb9093256 --- /dev/null +++ b/archive/edge/tl-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,118 @@ +--- +id: set-up-hashicorp-vault +title: I-set up ang Hashicorp Vault +description: "I-set up ang Hashicorp Vault para sa Polygon Edge." +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## Pangkalahatang-ideya {#overview} + +Sa kasalukuyan, ang Polygon Edge ay may gustong panatilihing 2 pangunahing runtime secret: +* Ang **pribadong key ng validator** na ginagamit ng node, kung validator ang node +* Ang **pribadong key para sa networking** na ginagamit ng libp2p, para sa pakikilahok at pakikipag-ugnayan sa iba pang peer + +:::warning + +Ang validator private key ay natatangi sa bawat validator node. Ang parehong key ay hindi dapat ibahagi sa lahat ng mga validator, dahil maaari nitong makompromiso ang seguridad ng iyong chain. + +::: + +Para sa karagdagang impormasyon, pakibasa ang [Gabay sa Pamamahala sa Mga Pribadong Key](/docs/edge/configuration/manage-private-keys) + +Ang mga module ng Polygon Edge ay **hindi kailangang malaman kung paano magpanatili ng mga secret**. Sa pangkalahatan, ang isang module ay walang kaugnayan sa kung ang +isang secret ay naka-store sa isang malayong server o kung lokal itong naka-store sa disk ng node. + +Ang lahat ng kailangang malaman ng module tungkol sa pagpapanatili ng secret ay ang **alamin kung paano gamitin ang secret** at **alamin kung aling mga secret ang kukunin +o ise-save**. Ang mga mas pinong detalye ng pagpapatupad ng mga operasyong ito ay itinakda sa `SecretsManager`, na siyempre ay isang abstraction. + +Magagawa na ngayon ng operator ng node na nagsisimula sa Polygon Edge na tukuyin kung aling mga manager ng secret ang gusto nitong gamitin, at sa sandaling +ma-instantiate ang wastong manager ng mga secret, ipinoproseso ng mga module ang mga secret sa pamamagitan ng nabanggit na interface +nang hindi isinasaalang-alang kung ang mga secret ay naka-store sa isang disk o server. + +Idinedetalye sa artikulong ito ang mga kinakailangang hakbang para mapatakbo ang Polygon Edge gamit ang [Hashicorp Vault](https://www.vaultproject.io/) server. + +:::info mga nakaraang gabay + +**Mariing inirerekomenda** na bago basahin ang artikulong ito, nabasa na dapat ang mga artikulo tungkol sa [**Lokal na Pag-Setup**](/docs/edge/get-started/set-up-ibft-locally) +at [**Pag-Setup sa Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +::: + + +## Mga Paunang Kinakailangan {#prerequisites} + +Ipinagpapalagay ng artikulong ito na ang isang halimbawang paggana ng Hashicorp Vault server **ay naka-set up na**. + +Bukod pa rito, kinakailangan na ang Hashicorp Vault server na ginagamit para sa Polygon Edge ay dapat na may **enabled KV storage**. + +Kinakailangang impormasyon bago magpatuloy: +* **Ang URL ng server** (ang API URL ng Hashicorp Vault server) +* **Token** (access token na ginagamit para sa access sa KV storage engine) + +## Hakbang 1 - Buuin ang configuration ng manager ng mga secret {#step-1-generate-the-secrets-manager-configuration} + +Para magawa ng Polygon Edge na maayos na makipag-ugnayan sa Vault server, kinakailangan nitong mag-parse ng +nabuo nang config file na naglalaman ng kinakailangang impormasyon para sa secret storage sa Vault. + +Para mabuo ang configuration, patakbuhin ang sumusunod na command: + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +Mga umiiral na parameter: +* `PATH` ay ang path kung saan dapat i-export ang configuration file. Default na `./secretsManagerConfig.json` +* `TOKEN` ay ang access token na dati nang binabanggit sa [seksyon ng mga paunang kinakailangan](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `SERVER_URL` ay ang URL ng API para sa Vault server, na binabanggit din sa [seksyon ng mga paunang kinakailangan](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) +* `NODE_NAME` ay ang pangalan ng kasalukuyang node kung saan sine-set up ang Vault configuration. Maaari itong maging arbitrary na value. Default na `polygon-edge-node` + +:::caution Mga pangalan ng node + +Mag-ingat kapag tinutukoy ang mga pangalan ng node. + +Ginagamit ng Polygon Edge ang tinukoy na pangalan ng node para subaybayan ang mga secret storage na binubuo at ginagamit nito sa Vault instance. +Ang pagtukoy sa umiiral na pangalan ng node ay maaaring magkaroon ng mga kahihinatnan na maging overwritten ang data sa Vault server. + +Ini-store ang mga secret sa sumusunod na base path: `secrets/node_name` + +::: + +## Hakbang 2 - Simulan ang mga secret key gamit ang configuration {#step-2-initialize-secret-keys-using-the-configuration} + +Ngayong mayroon nang configuration file, maaari nating simulan ang mga kinakailangang secret key sa pamamagitan ng pag-set up ng configuration +file sa hakbang 1, gamit ang `--config`: + +```bash +polygon-edge secrets init --config +``` + +Ang `PATH` param ay ang lokasyon ng naunang nabuong param ng manager ng mga secret mula sa hakbang 1. + +## Hakbang 3 - Buuin ang genesis file {#step-3-generate-the-genesis-file} + +Dapat buuin ang genesis file gaya ng nakasaad sa mga gabay sa [**Lokal na Pag-Setup**](/docs/edge/get-started/set-up-ibft-locally) +at [**Pag-set Up sa Cloud**](/docs/edge/get-started/set-up-ibft-on-the-cloud), na may kaunting pagbabago. + +Dahil ginagamit ang Hashicorp Vault sa halip na ang local file system, dapat idagdag ang mga address ng validator sa pamamagitan ng `--ibft-validator` flag: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Hakbang 4: Simulan ang Polygon Edge client {#step-4-start-the-polygon-edge-client} + +Ngayon naka-set up na ang mga key, at nabuo na ang genesis file, ang huling hakbang sa prosesong ito ay simulan ang +Polygon Edge sa pamamagitan ng command na `server`. + +Ginagamit ang command na `server` sa katulad na paraan gaya ng nakasaad sa mga naunang nabanggit na gabay, na may kaunting idinagdag - ang `--secrets-config` flag: +```bash +polygon-edge server --secrets-config ... +``` + +Ang `PATH` param ay ang lokasyon ng naunang nabuong param ng manager ng mga secret mula sa hakbang 1. \ No newline at end of file diff --git a/archive/edge/tl-edge/consensus/bls.md b/archive/edge/tl-edge/consensus/bls.md new file mode 100644 index 0000000000..774e285aca --- /dev/null +++ b/archive/edge/tl-edge/consensus/bls.md @@ -0,0 +1,144 @@ +--- +id: bls +title: BLS +description: "Paliwanag at mga tagubilin tungkol sa BLS mode." +keywords: + - docs + - polygon + - edge + - bls +--- + +## Pangkalahatang-ideya {#overview} + +Kilala rin ang BLS bilang Boneh–Lynn–Shacham (BLS)—is isang cryptographic signature scheme na nagpapahintulot sa isang user na i-verify na ang isang signer ay tunay. Ito ay isang signature scheme na maaaring aggregate ng maraming signatures. Sa Polygon Edge, ginagamit ang BLS bilang defaut para makapagbigay ng mas maigting na seguridad sa consensus mode ng IBFT. Magagawa ng BLS na ipagsama-sama ang mga signature sa iisang byte array at bawasan ang size ng block header. Maaaring pumili ang bawat chain kung gagamitin ang BLS o hindi. Ginagamit ang ECDSA key naka-enable man o hindi ang BLS mode. + +## Video presentation {#video-presentation} + +[![bls - video](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## Paano mag-set up ng bagong chain gamit ang BLS {#how-to-setup-a-new-chain-using-bls} + +Sumangguni sa mga seksyong [Lokal na Pag-set Up](/docs/edge/get-started/set-up-ibft-locally) / [Pag-set Up sa Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) para sa detalyadong mga tagubilin sa pag-set up. + +## Paano mag-migrate mula sa umiiral na ECDSA PoA chain patungo sa BLS PoA chain {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +Inilalarawan sa seksyong ito kung paano gamitin ang BLS mode sa umiiral na PoA chain. +kinakailangan ang mga sumusunod na hakbang para ma-enable ang BLS sa PoA chain. + +1. Itigil ang lahat ng node +2. Buuin ang mga BLS key para sa mga validator +3. Magdagdag ng setting ng fork sa genesis.json +4. I-restart ang lahat ng node + +### 1. Itigil ang lahat ng node {#1-stop-all-nodes} + +Wakasan ang lahat ng proseso ng mga validator sa pamamagitan ng pagpindot sa Ctrl + c (Control + c). Mangyaring tandaan ang pinakabagong block height (ang pinakamataas na sequence number sa log ng naka-commit na block). + +### 2. Buuin ang BLS key {#2-generate-the-bls-key} + +Nakakabuo ng BLS key ang `secrets init` kasama ang `--bls`. Para mapanatili ang kasalukuyang ECDSA at Network key, at makapagdagdag ng bagong BLS key, kailangang naka-disable ang `--ecdsa` at `--network`. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Magdagdag ng setting ng fork {#3-add-fork-setting} + +Ang command na `ibft switch` ay nagdadagdag sa `genesis.json` ng setting ng fork, na nag-e-enable sa BLS sa umiiral na chain. + +Para sa mga PoA network, kailangang tukuyin sa command ang mga validator. Gaya ng paraan ng command na `genesis`, magagamit ang `--ibft-validators-prefix-path` flag o `--ibft-validator` flag para tukuyin ang validator. + +Tukuyin ang height kung saan nagsisimula ang chain gamit ang BLS sa pamamagitan ng `--from` flag. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. I-restart ang lahat ng node {#4-restart-all-nodes} + +I-restart ang lahat ng node sa pamamagitan ng command na `server`. Pagkatapos magawa ang block sa `from` na tinukoy sa naunang hakbang, ine-enable ng chain ang BLS at nagpapakita ito ng mga log gaya ng nasa ibaba: + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +Ipinapakita rin ng mga log kung aling mode ng pag-verify ang ginamit para buuin ang bawat block pagkatapos magawa ang block. + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## Paano mag-migrate mula sa umiiral na ECDSA PoS chain patungo sa BLS PoS chain {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +Inilalarawan sa seksyong ito kung paano gamitin ang BLS mode sa umiiral na PoS chain. +Kinakailangan ang mga sumusunod na hakbang para ma-enable ang BLS sa PoS chain. + +1. Itigil ang lahat ng node +2. Buuin ang mga BLS key para sa mga validator +3. Magdagdag ng setting ng fork sa genesis.json +4. I-call ang kontrata sa pag-stake para i-register ang Pampublikong Key ng BLS +5. I-restart ang lahat ng node + +### 1. Itigil ang lahat ng node {#1-stop-all-nodes-1} + +Wakasan ang lahat ng proseso ng mga validator sa pamamagitan ng pagpindot sa Ctrl + c (Control + c). Mangyaring tandaan ang pinakabagong block height (ang pinakamataas na sequence number sa log ng naka-commit na block). + +### 2. Buuin ang BLS key {#2-generate-the-bls-key-1} + +Nabubuo ang BLS key gamit ang `secrets init` kasama ang `--bls` na flag. Para mapanatili ang kasalukuyang ECDSA at Network key, at makapagdagdag ng bagong BLS key, kailangang naka-disable ang `--ecdsa` at `--network`. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Magdagdag ng setting ng fork {#3-add-fork-setting-1} + +Ang command na `ibft switch` ay nagdadagdag sa `genesis.json` ng setting ng fork, na nag-e-enable sa BLS mula sa gitna ng chain. + +Tukuyin ang height kung saan nagsisimula ang chain gamit ang BLS mode sa pamamagitan ng `from` flag, at ang height kung saan ina-update ang kontrata sa pamamagitan ng `development` flag. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. Irehistro ang Pampublikong Key ng BLS sa staking na kontrata {#4-register-bls-public-key-in-staking-contract} + +Pagkatapos maidagdag ang fork at na-restart na ang mga validator, kailangang i-call ng bawat validator ang `registerBLSPublicKey` sa staking na kontrata para irehistro ang Pampublikong Key ng BLS. Kailangan itong gawin pagkatapos ng height na tinukoy sa `--deployment` bago ang height na tinukoy sa `--from`. + +Ang script para irehistro ang Pampublikong Key ng BLS ay tinutukoy sa [repo ng Smart na Kontrata sa Pag-stake](https://github.com/0xPolygon/staking-contracts). + +Itakda ang `BLS_PUBLIC_KEY` na irerehistro sa `.env` file. Sumangguni sa [pos-stake-unstake](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) para sa higit pang detalye tungkol sa iba pang parameter. + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +Inirerehistro ng sumusunod na command ang Pampublikong Key ng BLS na ibinigay sa `.env` sa kontrata. + +```bash +npm run register-blskey +``` + +:::warning Kailangang manual na irehistro ng mga validator ang Pampublikong Key ng BLS + +Sa BLS mode, ang mga validator ay mayroon dapat pampublikong key ng BLS at sarili nilang address. Binabalewala ng consensus layer ang mga validator na hindi nagrehistro ng pampublikong key ng BLS sa kontrata kapag fine-fetch ng consensus ang impormasyon ng validator mula sa kontrata. + +::: + +### 5. I-restart ang lahat ng node {#5-restart-all-nodes} + +I-restart ang lahat ng node sa pamamagitan ng command na `server`. Ine-enable ng chain ang BLS pagkatapos magawa ang block sa `from` na tinutukoy sa naunang hakbang. diff --git a/archive/edge/tl-edge/consensus/migration-to-pos.md b/archive/edge/tl-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..1b6beb8116 --- /dev/null +++ b/archive/edge/tl-edge/consensus/migration-to-pos.md @@ -0,0 +1,40 @@ +--- +id: migration-to-pos +title: Pag-migrate mula sa PoA patungo sa PoS +description: "Paano mag-migrate mula sa PoA patungo sa PoS IBFT mode, at vice versa." +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## Pangkalahatang-ideya {#overview} + +Ang seksyong ito ay gumagabay sa iyo sa pag-migrate mula sa PoA patungo sa mga PoS IBFT mode, at vice versa, para sa tumatakbong cluster - nang hindi kinakailangang i-reset ang blockchain. + +## Paano mag-migrate sa PoS {#how-to-migrate-to-pos} + +Kakailanganin mong itigil ang lahat ng node, magdagdag ng configuration ng fork sa genesis.json sa pamamagitan ng `ibft switch` command, at i-restart ang mga node. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution Paglipat habang gumagamit ng ECDSA +Kapag gumagamit ng ECDSA, dapat idagdag ang `--ibft-validator-type`bandila sa switch, na binabanggit ang ginagamit na ECDSA. Kung hindi kasama, awtomatikong lumipat ang Edge sa BLS. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::Para lumipat sa PoS, kakailanganin mong tukuyin ang 2 block heights: `deployment`at . ay `from`ang taas na i-deploy ang staking contract at ito `from``deployment`ang taas ng simula ng PoS. Ang staking contract ay ide-deploy sa address na `0x0000000000000000000000000000000000001001` sa `deployment`, gaya sa kaso ng paunang na-deploy na kontrata. + +Pakitingnan ang [Proof of Stake](/docs/edge/consensus/pos-concepts) para sa higit pang detalye tungkol sa Staking na kontrata. + +:::warning Kinakailangan ng mga validator na manual na mag-stake + +Ang bawat validator ay kinakailangang mag-stake pagkatapos mag-deploy ng kontrata sa `deployment` at bago ang `from` para maging validator sa simula ng PoS. Ia-update ng bawat validator ang sarili nitong validator set ayon sa set sa staking na kontrata sa simula ng PoS. + +Para malaman ang higit pa tungkol sa Stake, bisitahin ang **[set up at gamitin ang Proof of Stake](/docs/edge/consensus/pos-stake-unstake)**. +::: diff --git a/archive/edge/tl-edge/consensus/poa.md b/archive/edge/tl-edge/consensus/poa.md new file mode 100644 index 0000000000..200c6a25b7 --- /dev/null +++ b/archive/edge/tl-edge/consensus/poa.md @@ -0,0 +1,110 @@ +--- +id: poa +title: Proof of Authority (PoA) +description: "Paliwanag at mga tagubilin tungkol sa Proof of Authority." +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## Pangkalahatang-ideya {#overview} + +Ang PoA ng IBFT ay ang default na consensus mechanism sa Polygon Edge. Sa PoA, tungkulin ng mga validator na gawin ang mga block at idagdag ang mga ito sa blockchain sa isang serye. + +Ang lahat ng validator ay bumubuo ng dynamic na validator-set kung saan maaaring idagdag o alisin sa set ang mga validator sa pamamagitan ng pag-employ ng mekanismo ng pagboto. Ibig sabihin, ang mga validator ay maaaring iboto na idagdag/alisin sa validator-set kung iboboto ng mayorya (51%) ng mga validator node na idagdag/alisin sa set ang isang partikular na validator. Sa ganitong paraan, matutukoy ang mga mapaminsalang validator at maaalis sa network ang mga ito, habang maidadagdag sa network ang mga pinagkakatiwalaang validator. + +Nagsasalitan ang lahat ng validator sa pag-propose sa susunod na block (round-robin), at para ma-validate/maipasok sa blockchain ang block, dapat aprubahan ng supermajority (mahigit 2/3) ng mga validator ang naturang block. + +Bukod sa mga validator, may mga non-validator na hindi lumalahok sa paggawa ng block ngunit lumalahok sa proseso ng pag-validate ng block. + +## Pagdadagdag ng validator sa validator-set {#adding-a-validator-to-the-validator-set} + +Inilalarawan sa gabay na ito kung paano magdagdag ng bagong validator node sa isang aktibong IBFT network na may 4 na validator node. +Kung kailangan mo ng tulong sa pag-set up ng network ay tumutukoy sa mga seksyon ng [Local Setup](/edge/get-started/set-up-ibft-locally.md) / [Cloud Setup](/edge/get-started/set-up-ibft-on-the-cloud.md). + +### Hakbang 1: Gawin ang mga folder ng data para sa IBFT at bumuo ng mga validator key​ para sa bagong node {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +Para mapatakbo ang IBFT sa bagong node, kinakailangan mong gawin ang mga folder ng data at buuin ang mga key: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +Ipi-print ng command na ito ang validator key (address) at ang node ID. Kakailanganin mo ang validator key (address) para sa susunod na hakbang. + +### Hakbang 2: Mag-propose ng bagong candidate mula sa iba pang validator node {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +Para maging validator ang isang bagong node, hindi bababa sa 51% ng mga validator ang kailangang mag-propose sa kanya. + +Halimbawa ng kung paano mag-propose ng bagong validator (`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`) mula sa umiiral na validator node sa grpc address: 127.0.0.1:10000: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +Ang istruktura ng mga IBFT command ay tinatalakay sa seksyong mga [CLI Command](/docs/edge/get-started/cli-commands). + +:::info Pampublikong key ng BLS + +Ang pampublikong key ay kinakailangan lang kung ang network ay tumatakbo na may BLS, para sa network na hindi tumatakbo sa BLS mode, hindi kinakailangan ang `--bls` + +::: + +### Hakbang 3: Patakbuhin ang client node {#step-3-run-the-client-node} + +Dahil sa halimbawang ito ay sinusubukan nating patakbuhin ang network kung saan ang lahat ng node ay nasa iisang machine, kinakailangan nating mag-ingat para maiwasan ang mga conflict ng port. + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +Pagkatapos na i-fetch ang lahat ng block, mapapansin mo sa loob ng iyong console na may bagong node na lumalahok sa pag-validate + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info Pag-promote ng non-validator sa isang validator + +Sa karaniwan, ang isang non-validator ay maaaring maging validator sa pamamagitan ng proseso ng pagboto, ngunit para matagumpay itong maisama sa validator-set pagkatapos ng proseso ng pagboto, kailangang i-restart ang node sa pamamagitan ng `--seal` flag. + +::: + +## Pag-aalis ng validator sa validator-set {#removing-a-validator-from-the-validator-set} + +Madali lang ang operasyong ito. Para mag-alis ng validator node sa validator-set, kinakailangang isagawa ang command na ito para sa karamihan ng mga validator node. + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info Pampublikong key ng BLS + +Ang pampublikong key ay kinakailangan lang kung ang network ay tumatakbo na may BLS, para sa network na hindi tumatakbo sa BLS mode, hindi kinakailangan ang `--bls` + +::: + +Pagkatapos maisagawa ang mga command, mapapansing bumaba ang bilang ng mga validator (sa halimbawang ito ng log, mula 4 ay naging 3). + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/tl-edge/consensus/pos-concepts.md b/archive/edge/tl-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..9ded55dd0f --- /dev/null +++ b/archive/edge/tl-edge/consensus/pos-concepts.md @@ -0,0 +1,121 @@ +--- +id: pos-concepts +title: Proof of Stake +description: "Paliwanag at mga tagubilin tungkol sa Proof of Stake." +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## Pangkalahatang-ideya {#overview} + +Nilalayon ng seksyong ito na magbigay ng mas mahusay na pangkalahatang-ideya ng ilang konseptong kasalukuyang umiiral sa Proof of Stake (PoS) +na implementasyon ng Polygon Edge. + +Ang implementasyon ng Proof of Stake (PoS) ng Polygon Edge ay naglalayong maging alternatibo sa umiiral na implementasyon ng PoA ng IBFT, +na nagbibigay sa mga operator ng node ng kakayahang madaling mamili sa pagitan ng dalawa kapag nagsisimula ng chain. + +## Mga Feature ng PoS {#pos-features} + +Ang core logic sa likod ng implementasyon ng Proof of Stake ay nasa +ang **[Staking Smart Contract](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)**. + +Paunang dine-deploy ang kontratang ito sa tuwing nagsisimula ng chain ng Polygon Edge ng mekanismo ng PoS at available ito sa address +`0x0000000000000000000000000000000000001001` mula sa block na `0`. + +### Mga Epoch {#epochs} + +Ang mga Epoch ay isang konseptong ipinakilala kasama ng pagdadagdag ng PoS sa Polygon Edge. + +Ang mga Epoch ay itinuturing na espesyal na time frame (ayon sa mga block) kung saan makakabuo ng mga block ang isang partikular na hanay ng mga validator. +Nababago ang haba ng mga ito, ibig sabihin, maaaring i-configure ng mga operator ng node ang haba ng epoch sa panahon ng pagbuo ng genesis. + +Sa katapusan ng bawat epoch, nabubuo ang isang _epoch block_, at pagkatapos ng event iyon, magsisimula ang isang bagong epoch. Para malaman ang higit pa tungkol sa +mga epoch block, tingnan ang seksyong [Mga Epoch Block](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Ina-update ang mga validator set sa katapusan ng bawat epoch. Kinu-query ng mga node ang validator set mula sa Smart na Kontrata sa Pag-stake +sa panahon ng paggawa ng epoch block, at sine-save nito sa lokal na storage ang nakuhang data. Ang cycle na ito ng pag-query at pag-save ay +inuulit sa katapusan ng bawat epoch. + +Sa pangkalahatan, tinitiyak nito na ang Smart na Kontrata sa Pagstake ay may ganap na kontrol sa mga address sa validator set, at +nagbibigay ito sa mga node ng 1 responsibilidad lang - na i-query ang kontrata nang isang beses sa panahon ng epoch para sa pag-fetch sa pinakabagong +impormasyon ng validator set. Inaalis nito ang responsibilidad sa mga indibidwal na node mula sa pangangasiwa ng mga validator set. + +### Pag-stake {#staking} + +Ang mga address ay maaaring mag-stake ng mga pondo sa Smart na Kontrata sa Pag-stake sa pamamagitan ng pag-invoke sa paraang `stake` at sa pamamagitan ng pagtukoy sa value para sa +na-stake na halaga sa transaksyon: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +Sa pamamagitan ng pag-stake ng mga pondo sa Smart na Kontrata sa Pag-stake, magagawa ng mga address na pumasok sa validator set at bilang resulta, magagawa ng mga ito na lumahok sa +proseso ng produksyon ng block. + +:::info Threshold para sa pag-stake + +Sa kasalukuyan, ang minimum na threshold para sa pagpasok sa validator set ay pag-stake sa `1 ETH` + +::: + +### Pag-unstake {#unstaking} + +Ang mga address na nag-stake ng mga pondo ay sabay-sabay lang **na makakapag-unstake ng lahat ng mga na-stake na pondo nito**. + +Mai-invoke ang pag-unstake sa pamamagitan ng pag-call sa paraang `unstake` sa Smart na Kontrata sa Pag-stake: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +Pagkatapos i-unstake ang mga pondo ng mga ito, inaalis ang mga address sa validator set sa Smart na Kontrata sa Pag-stake, at hindi +ituturing na mga validator ang mga ito sa susunod na epoch. + +## Mga Epoch Block {#epoch-blocks} + +Ang **Mga Epoch Block** ay isang konseptong ipinakilala sa pagpapatupad ng PoS ng IBFT sa Polygon Edge. + +Sa pangkalahatan, ang mga epoch block ay mga espesyal na block na hindi naglalaman ng **mga transaksyon** at nagaganap lang sa **katapusan ng epoch**. +Halimbawa, kung nakatakda ang **laki** ng epoch sa mga `50``50`bloke, ituturing na mga block ng epoch ang mga bloke na ito , `100``150`at iba pa. + +Ginagamit ang mga ito para magsagawa ng mga karagdagang logic na hindi dapat mangyari sa produksyon ng regular na block. + +Higit sa lahat, indikasyon ang mga ito sa node na **kinakailangan nitong i-fetch ang pinakabagong impormasyon ng validator set** +mula sa Smart na Kontrata sa Pag-stake. + +Pagkatapos i-update ang validator set sa epoch block, ang validator set (nagbago man o hindi) +ay ginagamit para sa mga kasunod na `epochSize - 1` block, hanggang sa ma-update ulit ito sa pamamagitan ng pagkuha sa pinakabagong impormasyon mula sa +Smart na Kontrata sa Pag-stake. + +Nababago ang mga haba ng epoch (ayon sa bilang ng mga block) kapag binubuo ang genesis file, sa pamamagitan ng paggamit ng espesyal na flag na `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +Ang default na size ng isang epoch ay `100000` block sa Polygon Edge. + +## Paunang pag-deploy ng kontrata {#contract-pre-deployment} + +_Paunang dine-deploy_ ng Polygon Edge ang +seksyong [ Smart na Kontrata sa Pag-stake](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol) +sa panahon ng **pagbuo ng genesis** sa address na `0x0000000000000000000000000000000000001001`. + +Isinasagawa nito ito nang hindi nagpapatakbo ng EVM, sa pamamagitan ng direktang pagbabago sa state ng blockchain ng Smart na Kontrata, gamit ang na-pass in +na mga value ng configuration sa command ng genesis. diff --git a/archive/edge/tl-edge/consensus/pos-stake-unstake.md b/archive/edge/tl-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..2ed575bad6 --- /dev/null +++ b/archive/edge/tl-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,177 @@ +--- +id: pos-stake-unstake +title: I-set up at gamitin ang Proof of Stake (PoS) +description: "Pag-stake, pag-unstake, at iba pang tagubilin na nauugnay sa pag-stake." +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## Pangkalahatang-ideya {#overview} + +Tinatalakay nang detalyado sa gabay na ito kung paano mag-set up ng Proof of Stake network gamit ang Polygon Edge, paano mag-stake ng mga pondo para sa mga node +para maging mga validator at kung paano mag-unstake ng mga pondo. + +**Lubhang hinihikayat** itong magbasa at dumaan [Lokal na Pag-set Up](/docs/edge/get-started/set-up-ibft-locally) +/ [Pag-set Up ng Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud) bago magpatuloy +sa gabay na ito sa PoS. Naka-outline sa mga seksyong ito ang mga hakbang na kinakailangan para magsimula ng Proof of Authority (PoA) cluster sa pamamagitan ng +Polygon Edge. + +Sa kasalukuyan, walang limitasyon sa bilang ng mga validator na maaaring mag-stake ng mga pondo sa Smart na Kontrata sa Pag-stake. + +## Smart na Kontrata sa Pag-stake {#staking-smart-contract} + +Ang repo para sa Smart na Kontrata sa Pag-stake ay matatagpuan [dito](https://github.com/0xPolygon/staking-contracts). + +Hawak nito ang mga kinakailangang testing script, mga ABI file, at higit sa lahat, ang mismong Smart na Kontrata sa Pag-stake. + +## Pag-set up ng N node cluster {#setting-up-an-n-node-cluster} + +Ang pag-set up ng network sa pamamagitan ng Polygon Edge ay tinatalakay sa mga seksyong +[Lokal na Pag-set Up](/docs/edge/get-started/set-up-ibft-locally) +/ [Pag-set Up ng Cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +Ang **tanging pagkakaiba** ng pag-set up ng PoS cluster at ng PoA cluster ay nasa bahaging pagbuo ng genesis. + +**Kapag binubuo ang genesis file para sa PoS cluster, nangangailangan ng karagdagang flag `--pos`**: + +```bash +polygon-edge genesis --pos ... +``` + +## Pagtatakda sa haba ng epoch {#setting-the-length-of-an-epoch} + +Ang mga epoch ay detalyadong tinatalakay sa seksyong [Mga Epoch Block](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Para itakda ang size ng epoch para sa isang cluster (ayon sa bilang ng mga block), kapag binubuo ang genesis file, may karagdagang flag na +tinutukoy `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +Ang value na ito na tinutukoy sa genesis file na ang size ng epoch ay `50` block dapat. + +Ang default na value para sa size ng epoch (ayon sa bilang ng mga block) ay `100000`. + +:::info Pagpapaikli sa epoch + +Gaya ng nakasaad sa seksyong [Mga Epoch Block](/docs/edge/consensus/pos-concepts#epoch-blocks), +ang mga epoch block ay ginagamit para i-update ang mga validator set para sa mga node. + +Ang default na haba ng epoch ayon sa bilang ng mga block (`100000`) ay maaaring matagal para maisagawa ang mga update sa validator set. Kung isasaalang-alang na nagdadagdag ng mga bagong +block ~2s, aabutin nang ~55.5h ang validator set para sa posibilidad na magbago. + +Ang pagtatakda ng mas mababang value para sa haba ng epoch ay makakatulong na matiyak na mas madalas na naa-update ang validator set. + +::: + +## Paggamit sa mga script ng Smart na Kontrata sa Pag-stake {#using-the-staking-smart-contract-scripts} + +### Mga Paunang Kinakailangan {#prerequisites} + +Ang repo ng Smart na Kontrata sa Pag-stake ay isang Hardhat na proyekto, na nangangailangan ng NPM. + +Para simulan ito nang tama, sa main directory, patakbuhin ang: + +```bash +npm install +```` + +### Pagset-up sa ibinigay na mga helper script {#setting-up-the-provided-helper-scripts} + +Ang mga script para sa pakikipag-interaksyon sa na-deploy na Smart na Kontrata sa Pag-stake ay matatagpuan sa +[repo ng Smart na Kontrata sa Pag-stake](https://github.com/0xPolygon/staking-contracts). + +Gumawa ng `.env` file na may mga sumusunod na parameter sa lokasyon ng repo ng mga Smart na Kontrata: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +Kung saan ang mga parameter ay: + +* **JSONRPC_URL** - ang JSON-RPC endpoint para sa tumatakbong node +* **PRIVATE_KEYS** - mga pribadong key ng staker address. +* **STAKING_CONTRACT_ADDRESS** - ang address ng smart na kontrata sa pag-stake ( +default na `0x0000000000000000000000000000000000001001`) +* **BLS_PUBLIC_KEY** - BLS public key ng staker. Kinakailangan lang kung tumatakbo ang network sa BLS + +### Pag-stake ng mga pondo {#staking-funds} + +:::info Address sa pag-stake + +Ang Smart na Kontrata sa Pag-stake ay paunang naka-deploy sa +address na `0x0000000000000000000000000000000000001001`. + +Ang anumang uri ng pakikipag-interaksyon sa mekanismo sa pag-stake ay isinasagawa sa pamamagitan ng Smart na Kontrata sa Pag-stake sa tinutukoy na address. + +Para malaman ang higit pa tungkol sa Smart na Kontrata sa Pag-stake, pumunta sa +ang **[Staking Smart Contract](/docs/edge/consensus/pos-concepts#contract-pre-deployment)** . + +::: + +Para maging bahagi ng validator set, kinakailangan ng address na mag-stake ng partikular na halaga ng mga pondo na lampas sa threshold. + +Sa kasalukuyan, ang default na threshold para maging bahagi ng validator set ay `1 ETH`. + +Masisimulan ang pag-stake sa pamamagitan ng pagtawag sa paraang `stake` ng Smart na Kontrata sa Pag-stake at pagtukoy ng value na `>= 1 ETH`. + +Pagkatapos ma-set up ang `.env` file na binanggit sa +[nakaraang seksyon](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts), at +nakapagsimula na ng chain sa PoS mode, maisasagawa ang pag-stake sa pamamagitan ng sumusunod na command sa repo ng Smart na Kontrata sa Pag-stake: + +```bash +npm run stake +``` + +Ang script ng Hardhat na `stake` ay nagi-stake ng default na halaga na `1 ETH`, na maaaring baguhin sa pamamagitan ng pagmodipika sa `scripts/stake.ts` +file. + +Kung ang mga pondo na ini-stake ay `>= 1 ETH`, ina-update ang validator set sa Smart na Kontrata sa Pag-stake, at ang address +ay magiging bahagi ng validator set na nagsisimula sa susunod na epoch. + +:::info Pagpaparehistro ng mga key ng BLS + +Kung ang network ay tumatakbo sa BLS mode, para maging mga validator ang mga node, kailangang iparehistro ng mga ito ang kanilang BLS public keys pagkatapos ng pag-stake + +Magagawa ito sa pamamagitan ng sumusunod na command: + +```bash +npm run register-blskey +``` +::: + +### Pag-unstake ng mga pondo {#unstaking-funds} + +Ang mga address na may stake ay maaari **lang mag-unstake ng lahat ng pondo ng mga ito** nang sabay-sabay. + +Pagkatapos ma-set up ang `.env` file na binanggit sa +[nakaraang seksyon](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts), +at nakapagsimula na ng chain sa PoS mode, maisasagawa ang pag-unstake sa pamamagitan ng sumusunod na command sa +repo ng Smart na Kontrata sa Pag-stake: + +```bash +npm run unstake +``` + +### Pag-fetch sa listahan ng mga staker {#fetching-the-list-of-stakers} + +Ang lahat ng address na nagi-stake ng mga pondo ay sine-save sa Smart na Kontrata sa Pag-stake. + +Pagkatapos ma-set up ang `.env` file na binanggit sa +[nakaraang seksyon](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts), +at nakapagsimula na ng chain sa PoS mode, maisasagawa ang pag-fetch sa listahan ng mga validator sa pamamagitan ng +sumusunod na command sa repo ng Smart na Kontrata sa Pag-stake: + +```bash +npm run info +``` diff --git a/archive/edge/tl-edge/faq/Contracts.md b/archive/edge/tl-edge/faq/Contracts.md new file mode 100644 index 0000000000..dab8ad41af --- /dev/null +++ b/archive/edge/tl-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: FAQ Tungkol sa mga Smart na Kontrata +description: "FAQ para sa mga Smart na Kontrata ng Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## Sinusuportahan ba ng Polygon Edge ang mga Smart na Kontrata? {#does-polygon-edge-support-smart-contracts} + +Oo. Ang mga network ng Polygon Edge ay mga blockchain na compatible sa Ethereum, kaya ang mga Smart na Kontrata na nade-deploy sa Ethereum ay nade-deploy rin sa mga chain ng Polygon Edge. + +## Maaari mo bang i-update ang contract logic sa pag-stake para sa PoS pagkatapos ma-deploy? {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +Sa ngayon, pagkatapos mong simulan ang PoS network, hindi mo maaaring baguhin ang logic ng kontrata sa pag-stake, dahil bahagi ito ng genesis file. Halimbawa, hindi mo maaaring baguhin ang minimum/maximum na bilang ng mga validator. Magagawa mong mag-stake o mag-unstake, para magdagdag o mag-alis ng mga validator. + + + diff --git a/archive/edge/tl-edge/faq/Gas.md b/archive/edge/tl-edge/faq/Gas.md new file mode 100644 index 0000000000..6bde96a6f5 --- /dev/null +++ b/archive/edge/tl-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: FAQ Tungkol sa Gas +description: "FAQ Tungkol sa Gas para sa Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Paano magpatupad ng minimum na gas price? {#how-to-enforce-a-minimum-gas-price} +Maaari mong gamitin ang `--price-limit` flag na ibinigay sa server command. Mag-aatas ito sa iyong node na tumanggap lang ng mga transaksyon na may gas na mas mataas sa o katumbas ng limitasyon sa presyo na itinakda mo. Para matiyak na naipatupad ito sa buong network, kailangan mong tiyakin na ang lahat ng node ay may parehong limitasyon sa presyo. + + +## Maaari ka bang magkaroon ng mga transaksyon na may mga 0 gas fee? {#can-you-have-transactions-with-0-gas-fees} +Oo, maaari. Ang default na limitasyon sa presyo na ipinapatupad ng mga node ay `0`, ibig sabihin, tatanggap ang mga node ng mga transaksyon na may gas price na nakatakda sa `0`. + +## Paano itakda ang kabuuang supply ng gas(native) token? {#how-to-set-the-gas-native-token-total-supply} + +Maaari kang magtakda ng na-premine na balanse sa mga account (mga address) gamit ang `--premine flag`. Mangyaring tandaan ito ay isang configuration mula sa genesis file, at hindi ito maaaring baguhin sa ibang pagkakataon. + +Halimbawa kung paano gamitin ang `--premine flag`: + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +Nagtatakda ito ng na-premine na balanse na 1000 ETH sa 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862 (ang halaga mula sa argument ay nasa wei). + +Ang na-premine na halaga ng gas token ay ang magiging kabuuang supply. Walang ibang halaga ng native na currency (gas token) ang maaaring i-mint sa ibang pagkakataon. + +## Sinusuportahan ba ng Edge ang ERC-20 bilang gas token? {#does-edge-support-erc-20-as-a-gas-token} + +Hindi sinusuportahan ng Edge ang ERC-20 token bilang gas token. Ang native na currency ng Edge lang ang sinusuportahan para sa gas. + +## Paano dadagdagan ang limitasyon ng gas? {#how-to-increase-the-gas-limit} + +May dalawang pagpipilian para sa pagtaas ng limitasyon ng gas sa Polygon Edge: +1. Wiping ang chain at pagtaas sa maximum `block-gas-limit`na halaga ng uint64 sa genesis file +2. Gamitin ang `--block-gas-target`bandila na may mataas na halaga para madagdagan ang limitasyon ng gas ng lahat ng node. Nangangailangan ito ng node reboot. Detalyadong paliwanag [dito](/docs/edge/architecture/modules/txpool/#block-gas-target). \ No newline at end of file diff --git a/archive/edge/tl-edge/faq/Tokens.md b/archive/edge/tl-edge/faq/Tokens.md new file mode 100644 index 0000000000..bd29470ee7 --- /dev/null +++ b/archive/edge/tl-edge/faq/Tokens.md @@ -0,0 +1,23 @@ +--- +id: tokens +title: FAQ tungkol sa mga Token +description: "FAQ para sa mga token ng Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## Sinusuportahan ba ng Polygon Edge ang EIP-1559? {#does-polygon-edge-support-eip-1559} +Sa ngayon, hindi sinusuportahan ng Polygon Edge ang EIP-1559. + +## Paano itakda ang simbolo ng currency(token)? {#how-to-set-the-currency-token-symbol} + +Ang simbolo ng token ay isang bagay lang sa UI, hindi ito mako-configure o maha-hardcode kahit saan sa network. +Gayunpaman, maaari mo itong baguhin kapag idinagdag mo ang network sa isang wallet, gaya ng Metamask, halimbawa. + +## Ano ang nangyayari sa mga transaksyon kapag a ang isang chain? {#what-happens-to-transactions-when-a-chain-halts} + +Lahat ng transaksyon na hindi pa napoproseso ay nasa loob ng TxPool(enqueued o promote queue). Kung humihinto ang chain (tumigil ang lahat ng produksyon ng block ), hindi na papasok ang mga transaksyong ito.
Hindi lang ito ang kaso kapag halts. ang chain. Kung tumigil o restarted, ang mga node, ang lahat ng transaksyon na hindi pa naisagawa at nasa TxPool, tahimik na aalis ang
Ganito ang mangyayari sa mga transaksyon kapag nagpakilala ang isang paglabag na pagbabago, dahil kinakailangan para change ang mga node. diff --git a/archive/edge/tl-edge/faq/Validators.md b/archive/edge/tl-edge/faq/Validators.md new file mode 100644 index 0000000000..0f1b4eec42 --- /dev/null +++ b/archive/edge/tl-edge/faq/Validators.md @@ -0,0 +1,85 @@ +--- +id: validators +title: FAQ ng mga Validator +description: "FAQ para sa mga Polygon Edge validator" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Paano magdagdag/mag-alis ng isang validator? {#how-to-add-remove-a-validator} + +### PoA {#poa} +Ang pagdadagdag/pag-aalis ng mga validator ay ginagawa sa pamamagitan ng pagboto. Makikita mo [rito](/docs/edge/consensus/poa) ang buong gabay tungkol dito. + +### PoS {#pos} +Maaari mong makita ang gabay kung paano i-stake ang mga pondo [rito](/docs/edge/consensus/pos-stake-unstake), para maging validator ang isang node, at kung paano mag-unstake (alisin ang validator). + +Mangyaring tandaan: +- Maaari mong gamitin ang genesis flag `--max-validator-count` para itakda ang maximum na bilang ng mga staker na maaaring sumali sa validator set. +- Maaari mong gamitin ang genesis flag `--min-validator-count ` para itakda ang minimum na bilang ng mga staker na kinakailangang sumali sa validator set (`1` bilang default). +- Kapag ang maximum na bilang ng validator ay naabot na, hindi ka na maaaring makapagdagdag ng isa pang validator hanggang alisin mo ang isang umiiral mula sa set (hindi mahalaga kung ang staked amount ng bago ay mas mataas). Kung nag-alis ka ng isa ng validator, ang bilang ng mga validator na natitira ay hindi maaaring bumaba sa `--min-validator-count`. +- Mayroong default na threshold ng `1` na unit ng native network(gas) currency para maging isang validator. + + + +## Gaano karaming disk space ang inirerekomenda para sa isang validator? {#how-much-disk-space-is-recommended-for-a-validator} + +Inirerekomenda naming magsimula sa 100G bilang isang maingat na tinatayang runway, at tiyaking posible na i-scale ang disk pagkatapos. + + +## Mayroon bang limitasyon sa bilang ng mga validator? {#is-there-a-limit-to-the-number-of-validators} + +Kung tungkol sa mga teknikal na limitasyon, walang takdang limitasyon ang Polygon Edge sa bilang ng mga node na maaari mong taglayin sa isang network. Maaari kang magtakda ng mga limitasyon ng koneksyon (bilang ng inbound / outbound na koneksyon) sa isang per-node na batayan. + +Kung tungkol sa mga praktikal na limitasyon, makikita mo ang isang mas pinababang performance na may 100 node cluster kaysa sa 10 node cluster. Sa pamamagitan ng pagtaas ng bilang ng mga node sa iyong cluster, pinataas mo ang complexity ng komunikasyon at ng pangkalahatang networking overhead. Nakadepende ang lahat ng ito sa kung anong uri ng network ang pinapatakbo mo, at kung anong uri ng network topology ang mayroon ka. + +## Paano lumipat mula PoA patungong PoS? {#how-to-switch-from-poa-to-pos} + +Ang PoA ay ang default na consensus mechanism. Para sa isang bagong cluster, para lumipat patungong PoS, kakailanganin mong dagdagan ang `--pos` flag kapag bumubuo ng genesis file. Kung mayroon kang tumatakbong cluster, makikita mo [rito](/docs/edge/consensus/migration-to-pos) kung paano gawin ang paglipat. Ang lahat ng impormasyon na kailangan mo tungkol sa aming consensus mechanism at pag-setup ay maaaring matagpuan sa aming [consensus na seksyon](/docs/edge/consensus/poa). + +## Paano ko i-update ang mga node ko kapag may breaking change? {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +Maaari mong mahanap ang detalyadong gabay kung paano gawin ang pamamaraang ito [dito](/docs/edge/validator-hosting#update). + +## Maaari bang ma-configure ang minimum na staking amount para sa PoS Edge? {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +Ang minimum na staking amount bilang default ay `1 ETH`, at hindi ito maaaring ma-configure. + +## Bakit ang mga JSON RPC command ay `eth_getBlockByNumber` at `eth_getBlockByHash` hindi nagbabalik sa address ng miner? {#not-return-the-miner-s-address} + +Ang concensus na kasalukuyang ginagamit sa Polygon Edge ay ang IBFT 2.0, na sa kalaunan ay nabubuo sa mekanismo ng pagboto na ipinaliwanag sa Clique PoA: [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225). + +Sa pagsuri sa EIP-225 (Clique PoA), ito ang kaugnay na bahagi na nagpapaliwanag kung ano ang gamit sa `miner` (aka `beneficiary`): + +
+Ginamit namin muli ang mga field ng ethash header tulad ng mga sumusunod: +
    +
  • benepisyaryo / miner: Address na ipanukala ang pag-modify sa listahan ng mga awtorisadong tagapaglagda.
  • +
      +
    • Dapat normal na mapuno ng mga zero, mababago lamang habang bumoboto.
    • +
    • Ang mga arbitraryong halaga ay pinapayagan naman (kahit ang mga walang kabuluhan tulad ng pagboto sa mga hindi tagapaglagda) para maiwasan ang labis na complexity sa mga implementasyon sa paligid ng mga mechanics sa pagboto.
    • +
    • Dapat mapuno ng mga zeroes sa checkpoint (ibig sabihin, epoch transition) na mga block.
    • +
    + +
+ +
+ +Sa gayon, ang `miner` na field ay ginagamit para sa pag-propose ng isang boto para sa isang tiyak na address, hindi para ipakita ang proposer ng block. + +Ang impormasyon tungkol sa proposer ng block ay maaaring matagpuan sa pamamagitan ng pagbawi sa pubkey mula sa Seal field ng RLP encoded Istanbul extra data field sa mga block header. + +## Aling mga bahagi at halaga ng Genesis ang ligtas na mababago? {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +Please na lumikha ng manu-manong kopya ng umiiral na genesis.json file bago subukang i-edit ito. Gayundin, kailangang tumigil ang buong chain bago i-edit ang genesis.json file. Kapag nabago ang genesis file, kailangan nitong ipamahagi ang mas bagong bersyon nito sa lahat ng non-validator at valdiator node. + +::: + +**Tanging ang seksyon ng bootnode ng genesis file** ay ligtas na mababago, kung saan maaari kang magdagdag o mag-alis ng mga bootnode mula sa listahan. \ No newline at end of file diff --git a/archive/edge/tl-edge/get-started/cli-commands.md b/archive/edge/tl-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..0f4104a28b --- /dev/null +++ b/archive/edge/tl-edge/get-started/cli-commands.md @@ -0,0 +1,2220 @@ +--- +id: cli-commands +title: Mga CLI Command +description: "Listahan ng mga CLI command at mga command flag para sa Polygon Edge." +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +Idinedetalye ng seksyong ito ang mga kasalukuyang command at mga command flag sa Polygon Edge, at kung paano ginagamit ang mga ito. + +:::tip Suporta sa JSON output + +Ang `--json` flag ay sinusuportahan sa ilang command. Ang flag na ito ay nag-uutos sa command na i-print ang output sa JSON format + +::: + +## Mga Startup Command {#startup-commands} + +| **Command** | **Paglalarawan** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| server | Ang default na command na nagpapasimula sa blockchain client, sa pamamagitan ng pag-bootstrap ng lahat ng module nang magkakasama | +| genesis | Bumubuo ng *genesis.json* file na ginagamit para magtakda ng paunang natukoy na state ng chain bago simulan ang client. Ang istruktura ng genesis file ay inilalarawan sa ibaba | +| genesis predeploy | Predeploys ang isang Smart Contract para sa mga sariwang network | + +### mga server flag {#server-flags} + + +| **Lahat ng server flag** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [prometheus](/docs/edge/get-started/cli-commands#prometheus) | [block-gas-target](/docs/edge/get-started/cli-commands#block-gas-target) | +| [max-peers](/docs/edge/get-started/cli-commands#max-peers) | [max-inbound-peers](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [max-outbound-peers](/docs/edge/get-started/cli-commands#max-outbound-peers) | [max-enqueued](/docs/edge/get-started/cli-commands#max-enqueued) | +| [log-level](/docs/edge/get-started/cli-commands#log-level) | [log-to](/docs/edge/get-started/cli-commands#log-to) | +| [chain](/docs/edge/get-started/cli-commands#chain) | [join](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [limitasyon ng presyo.](/docs/edge/get-started/cli-commands#price-limit) | [max-slots](/docs/edge/get-started/cli-commands#max-slots) | +| [config](/docs/edge/get-started/cli-commands#config) | [secrets-config](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-interval](/docs/edge/get-started/cli-commands#dev-interval) | +| [no-discover](/docs/edge/get-started/cli-commands#no-discover) | [restore](/docs/edge/get-started/cli-commands#restore) | +| [block-time](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +Ginagamit para tukuyin directory ng data na ginagamit para sa pag-store ng data ng client ng Polygon Edge. Default: `./test-chain`. + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +Itinatakda ang address at port para sa serbisyo ng JSON-RPC `address:port`. +Kung ang port lang ang tinutukoy `:10001` magba-bind ito sa lahat ng interface `0.0.0.0:10001`. +Kung inalis ang serbisyo, magba-bind ito sa default `address:port`. +Default na address: `0.0.0.0:8545`. + +--- + +####

json-rpc-block-range-limit + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +Sets ang maximum na hanay ng block na ituturing kapag executing ng mga kahilingan ng json-rpc na kinabibilangan ng mga values ng fromBlock/toBlock (hal. eth_getLogs). Maaaring ganap na hindi pinagana ang limitasyong ito sa pamamagitan ng pagtatakda ng halaga sa `0`. Default:`1000`. + +--- + +####

json-rpc-batch-request-limit + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +Nakatakda ang maximum na haba na ituturing kapag hinawakan ang mga kahilingan ng batch ng json-rpc. Maaaring ganap na hindi pinagana ang limitasyong ito sa pamamagitan ng pagtatakda ng halaga sa `0`. Default: `20`. + +--- + +####

grpc + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +Itinatakda ang address at port para sa serbisyo ng gRPC `address:port`. Default address: `127.0.0.1:9632`. + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +Itinatakda ang address at port para sa serbisyo ng libp2p `address:port`. Default address: `127.0.0.1:1478`. + +--- + +####

prometheus + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +Itinatakda ang address at port para sa prometheus server `address:port`. +Kung ang port lang ang tinutukoy, `:5001` magba-bind ang serbisyo sa lahat ng interface `0.0.0.0:5001`. +Kung aalisin, hindi sisimulan ang serbisyo. + +--- + +####

block-gas-target + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +Itinatakda ang target na limitasyon sa gas kada block para sa chain. Default (hindi ipinatutupad): `0`. + +May mas detalyadong paliwanag tungkol sa block gas target na matatagpuan sa [seksyong TxPool](/docs/edge/architecture/modules/txpool#block-gas-target). + +--- + +####

max-peers + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +Itinatakda ang maximum na bilang ng peer ng client. Default: `40`. + +Dapat tukuyin ang peer limit sa pamamagitan ng paggamit ng `max-peers`o `max-inbound/outbound-peers` flag. + +--- + +####

max-inbound-peers + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +Itinatakda ang maximum na bilang ng inbound na peer ng client. Kung nakatakda ang `max-peers`, ang max-inbound-peer limit ay kinakalkula gamit ang mga sumusunod na formula. + +`max-inbound-peer = InboundRatio * max-peers`, kung saan ang `InboundRatio` ay `0.8`. + +--- + +####

max-outbound-peers + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +Itinatakda ang maximum na bilang ng outbound na peer. Kung nakatakda ang `max-peers`, ang max-outbound-peer count ay kinakalkula gamit ang mga sumusunod na formula. + +`max-outbound-peer = OutboundRatio * max-peers`, kung saan ang `OutboundRatio` ay `0.2`. + +--- + +####

max-enqueued + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +Itinatakda ang maximum na bilang ng mga na-enqueue na transaksyon kada account. Default:`128`. + +--- + +####

log-level + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +Itinatakda ang antas ng log para sa console output. Default: `INFO`. + +--- + +####

log-to + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +Tinutukoy ang pangalan ng log file na hahawak sa lahat ng log output mula sa server command. +Bilang default, ang lahat ng server log ay ia-output sa console (stdout), +ngunit kung nakatakda ang flag, hindi magkakaroon ng output sa console kapag nagpapatakbo ng server command. + +--- + +####

chain + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +Tinutukoy ang genesis file na ginagamit para sa pagsisimula ng chain. Default: `./genesis.json`. + +--- + +####

join + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Tinutukoy ang address ng peer na nakasali dapat. + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +Itinatakda ang panlabas na IP address nang walang port, dahil nakikita ito ng mga peer. + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +Itinatakda ang DNS address ng host. Magagamit ito para mag-advertise ng external na DNS. Sinusuportahan ang `dns`,`dns4`,`dns6`. + +--- + +####

limitasyon ng presyo. + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +Itinatakda ang limitasyon sa gas price para ipatupad ang pagtanggap sa pool. Default: `1`. + +--- + +####

max-slots + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +Itinatakda ang maximum na bilang ng mga slot sa pool. Default: `4096`. + +--- + +####

config + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +Tinutukoy ang path sa CLI config. Sinusuportahan ang `.json`. + +--- + +####

secrets-config + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +Itinatakda ang path sa config file ng SecretsManager. Ginagamit para sa Hashicorp Vault, AWS SSM at GCP Secrets Manager. Kung aalisin, gagamitin ang lokal na FS secrets manager. + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +Itinatakda sa dev mode ang client. Default: `false`. Sa dev mode, pinagana ang peer discovery sa pamamagitan ng default. + +--- + +####

dev-interval + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +Itinatakda ang agwat ng dev notification ng client sa segundo. Default: `0`. + +--- + +####

no-discover + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +Pinipigilan ang client na matuklasan ang iba pang peer. Default: `false`. + +--- + +####

restore + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +I-restore ang mga block mula sa tinukoy na archive file + +--- + +####

block-time + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +Itinatakda ang tagal ng produksyon ng block sa segundo. Default: `2` + +--- + +####

access-control-allow-origins + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +Itinatakda ang mga awtorisadong domain para makapagbahagi ng mga response mula sa mga kahilingan ng JSON-RPC. +Nagdadagdag ng maraming flag `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"` para pahintulutan ang maraming domain. +Kung aalisin, ang Access-Control-Allow-Origins header ay itatakda sa `*` at ang lahat ng domain ay pahihintulutan. + +--- + +### mga flag sa genesis {#genesis-flags} +| **Lahat ng genesis flag** | +|---------------------------------------|---------------------------------------------| +| [dir](/docs/edge/get-started/cli-commands#dir) | [Pangalan](/docs/edge/get-started/cli-commands#name) | +| [pos](/docs/edge/get-started/cli-commands#pos) | [epoch-size](/docs/edge/get-started/cli-commands#epoch-size) | +| [premine](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [ibft-validator-type](/docs/edge/get-started/cli-commands#ibft-validator-type) | [ibft-validators-prefix-path](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [ibft-validator](/docs/edge/get-started/cli-commands#ibft-validator) | [block-gas-limit](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [consensus](/docs/edge/get-started/cli-commands#consensus) | [bootnode](/docs/edge/get-started/cli-commands#bootnode) | +| [max-validator-count](/docs/edge/get-started/cli-commands#max-validator-count) | [min-validator-count](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

dir + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +Itinatakda ang direktoryo para sa genesis data ng Polygon Edge. Default: `./genesis.json`. + +--- + +####

Pangalan + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +Itinatakda ang name para sa chain. Default: `polygon-edge`. + +--- + +####

pos + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +Itinatakda ang flag na nagpapahiwatig na dapat gamitin ng client ang Proof of Stake IBFT. +Nagde-default sa Proof of Authority kung hindi ibinigay ang flag o `false`. + +--- + +####

epoch-size + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +Itinatakda ang laki ng epoch para sa chain. Default na `100000`. + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +Itinatakda ang mga premined na account at balanse sa format na `address:amount`. +Ang halaga ay maaaring decimal o hex. +Default na premined balanse: `0xD3C21BCECCEDA1000000`(1 milyong katutubong currency tokens). + +--- + +####

chainid + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +Itinatakda ang ID ng chain. Default: `100`. + +--- + +####

ibft-validator-type + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +Tinutukoy ang validation mode ng mga block header. Mga posibleng value: `[ecdsa, bls]`. Default: `bls`. + +--- + +####

ibft-validators-prefix-path + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +Prefix path para sa direktoryo ng folder ng validator. Mayroon dapat kung ang flag na `ibft-validator` ay inalis. + +--- + +####

ibft-validator + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Itinatakda ang mga naipasang address bilang mga validator ng IBFT. Mayroon dapat kung ang flag na `ibft-validators-prefix-path` ay inalis. +1. Kung ang network ay tumatakbo sa pamamagitan ng ECDSA, ang format ay `--ibft-validator [ADDRESS]`. +2. Kung ang network ay tumatakbo sa pamamagitan ng BLS, ang format ay `--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]`. + +--- + +####

block-gas-limit + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +Tumutukoy sa maximum na dami ng gas na ginagamit ng lahat ng operasyon sa isang block. Default: `5242880`. + +--- + +####

consensus + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +Itinatakda ang protokol ng consensus. Default: `pow`. + +--- + +####

bootnode + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Multiaddr URL para sa p2p discovery bootstrap. Magagamit ang flag na ito nang maraming beses. +Sa halip na isang IP address, maaaring ibigay ang DNS address ng bootnode. + +--- + +####

max-validator-count + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +Ang maximum na bilang ng mga staker na makakasali sa validator na itinakda sa PoS consensus. +Ang bilang na ito ay hindi maaaring lumampas sa value ng MAX_SAFE_INTEGER (2^53 - 2). + +--- + +####

min-validator-count + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +Ang minimum na bilang ng mga staker na kinakailangang sumali sa validator na itinakda sa PoS consensus. +Ang bilang na ito ay hindi maaaring lumampas sa value ng max-validator-count. +Nagde-default sa 1. + +--- + +### genesis predeploy flag {#genesis-predeploy-flags} + +

artifacts-path

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +Sets ng landas sa mga artifacts ng kontrata na JSON na naglalaman ng `abi`, `bytecode`at .`deployedBytecode` + +--- + +

chain

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +I-set ang landas sa `genesis.json`file na dapat i-update. Default na `./genesis.json`. + +--- + +

constructor-args

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +Nakatakda ang mga argument ng constructor ng Smart Contract, kung meron man. Para sa isang detalyadong gabay kung paano dapat magmukhang reference ang mga argumento na [ito](/docs/edge/additional-features/predeployment). + +--- + +

predeploy-address

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +I-set ang address para to ang. Default na `0x0000000000000000000000000000000000001100`. + +--- + + +## Mga Command ng Operator {#operator-commands} + +### Mga Command ng Peer {#peer-commands} + +| **Command** | **Paglalarawan** | +|------------------------|-------------------------------------------------------------------------------------| +| peers add | Nagdadagdag ng bagong peer gamit ang kanilang libp2p address | +| peers list | Inililista ang lahat ng peer kung saan nakakonekta ang client sa pamamagitan ng libp2p | +| peers status | Ibinabalik ang status ng partikular na peer mula sa listahan ng mga peer, gamit ang libp2p address | + +

mga peers add flag

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Ang libp2p address ng peer sa multiaddr format. + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +Address ng gRPC API. Default: `127.0.0.1:9632`. + +

mga peers list flag

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +Address ng gRPC API. Default: `127.0.0.1:9632`. + +

mga peers status flag

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Libp2p node ID ng partikular na peer sa p2p network. + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +Address ng gRPC API. Default: `127.0.0.1:9632`. + +### Mga Command ng IBFT {#ibft-commands} + +| **Command** | **Paglalarawan** | +|------------------------|-------------------------------------------------------------------------------------| +| ibft snapshot | Ibinabalik ang IBFT snapshot | +| ibft candidates | Kini-query ang kasalukuyang set ng mga iminungkahing candidate, pati na rin ang mga candidate na hindi pa naisasama | +| ibft propose | Nagmumungkahi ng bagong candidate na idadagdag/aalisin sa validator set | +| ibft status | Ibinabalik ang pangkalahatang status ng IBFT client | +| ibft switch | Magdagdag ng mga configuration ng fork sa genesis.json file para magpalit ng type ng IBFT | +| ibft quorum | Tinutukoy ang bilang ng block kung saan pagkatapos ay gagamitin ang optimal quorum size na paraan para maabot ang consensus | + + +

mga ibft snapshot flag

+ +

number

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +Ang block height (number) para sa snapshot. + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +Address ng gRPC API. Default: `127.0.0.1:9632`. + +

mga ibft candidates flag

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Address ng gRPC API. Default: `127.0.0.1:9632`. + +

mga ibft propose flag

+ +

vote

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +Nagmumungkahi ng pagbabago sa validator set. Mga posibleng value: `[auth, drop]`. + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +Address ng account na iboboto. + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +BLS Public Key ng account na iboboto, kinakailangan lang sa BLS mode. + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Address ng gRPC API. Default: `127.0.0.1:9632`. + +

mga ibft status flag

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +Address ng gRPC API. Default: `127.0.0.1:9632`. + +

mga ibft switch flag

+ +

chain

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +Tinutukoy ang genesis file na ia-update. Default: `./genesis.json`. + +--- + +

Uri

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +Tinutukoy ang uri ng IBFT na papalitan. Mga posibleng value: `[PoA, PoS]`. + +--- + +

deployment

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +Tinutukoy ang height ng deployment ng kontrata. Available lang sa PoS. + +--- + +

from

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +Tinutukoy ang validation mode ng mga block header. Mga posibleng value: `[ecdsa, bls]`. Default: `bls`. + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +Prefix path para sa mga direktoryo ng mga bagong validator. Mayroon dapat kung ang flag na `ibft-validator` ay inalis. Available lang kapag PoA ang IBFT mode (inalis ang flag na `--pos`). + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Mga set na naipapasa sa mga address bilang mga validator ng IBFT na ginagamit pagkatapos ng fork. Mayroon dapat kung ang flag na `ibft-validators-prefix-path` ay inalis. Available lang sa PoA mode. +1. Kung ang network ay tumatakbo sa pamamagitan ng ECDSA, ang format ay `--ibft-validator [ADDRESS]`. +2. Kung ang network ay tumatakbo sa pamamagitan ng BLS, ang format ay `--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]`. + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +Ang maximum na bilang ng mga staker na makakasali sa validator na itinakda sa PoS consensus. +Ang bilang na ito ay hindi maaaring lumampas sa value ng MAX_SAFE_INTEGER (2^53 - 2). + +--- + +

min-validator-count

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +Ang minimum na bilang ng mga staker na kinakailangang sumali sa validator na itinakda sa PoS consensus. +Ang bilang na ito ay hindi maaaring lumampas sa value ng max-validator-count. +Nagde-default sa 1. + +Tinutukoy ang simulang height ng fork. + +--- + +

mga ibft quorum flag

+ +

from

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +Ang height para gawing QuorumOptimal, ang kalkulasyon ng quorum, kung saan ginagamit ang formula na `(2/3 * N)`, at `N` ang bilang ng mga validator node. Mangyaring tandaan na ito ay para sa backwards compatibility, ibig sabihin, para lang sa mga chain na gumagamit ng Quorum legacy calculation hanggang sa partikular na block height. + +--- + +

chain

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +Tinutukoy ang genesis file na ia-update. Default: `./genesis.json`. + +### Mga Command sa Pool ng Transaksyon {#transaction-pool-commands} + +| **Command** | **Paglalarawan** | +|------------------------|--------------------------------------------------------------------------------------| +| txpool status | Ibinabalik ang bilang ng mga transaksyon sa pool | +| txpool subscribe | Nagsu-subscribe para sa mga event sa transaction pool | + +

mga txpool status flag

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +Address ng gRPC API. Default: `127.0.0.1:9632`. + +

mga txpool subscribe flag

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +Address ng gRPC API. Default: `127.0.0.1:9632`. + +--- + +

promoted

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +Nagsu-subscribe para sa mga promoted na event ng tx sa TxPool. + +--- + +

dropped

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +Nagsu-subscribe para sa mga dropped na event ng tx sa TxPool. + +--- + +

demoted

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +Nagsu-subscribe para sa mga demoted na event ng tx sa TxPool. + +--- + +

added

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +Nagsu-subscribe para sa mga added na event ng tx sa TxPool. + +--- + +

enqueued

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +Nagsu-subscribe para sa mga enqueued na event ng tx sa mga account queue. + +--- + +### Mga blockchain command {#blockchain-commands} + +| **Command** | **Paglalarawan** | +|------------------------|-------------------------------------------------------------------------------------| +| status | Ibinabalik ang status ng client. Makikita sa ibaba ang detalyadong response | +| monitor | Nagsu-subscribe sa stream ng blockchain event. Makikita sa ibaba ang detalyadong response | +| version | Ibinabalik ang kasalukuyang bersyon ng client | + +

mga status flag

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +Address ng gRPC API. Default: `127.0.0.1:9632`. + +

mga monitor flag

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +Address ng gRPC API. Default: `127.0.0.1:9632`. + +--- +

command ng bersyon

+ + + + + + version + + + + +Nagpapakita ng release version, git branch, mag-commit ng hash at magtayo ng oras. + +## Mga Sikretong Command {#secrets-commands} + +| **Command** | **Paglalarawan** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| secrets init | Ini-initialize ang mga pribadong key sa kaukulang secrets manager | +| secrets generate | Bumubuo ng configuration file sa secrets manager na maaaring i-parse ng Polygon Edge | +| secrets output | I-print ang public key address ng BLS, validator public key address, at node id para sa sanggunian | + +### mga secrets init flag {#secrets-init-flags} + +

config

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +Itinatakda ang path sa config file ng SecretsManager. Ginagamit para sa Hashicorp Vault. Kung aalisin, gagamitin ang lokal na FS secrets manager. + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +Itinatakda ang direktoryo para sa data ng Polygon Edge kung ginagamit ang lokal na FS. + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +Itinatakda ang flag na nagpapahiwatig kung dapat bumuo ng ECDSA key. Default: `true`. + +--- + +

network

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +Itinatakda ang flag na nagpapahiwatig kung dapat bumuo ng Libp2p Network key. Default: `true`. + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +Itinatakda ang flag na nagpapahiwatig kung dapat bumuo ng BLS key. Default: `true`. + +### mga secrets generate flag {#secrets-generate-flags} + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +Itinatakda ang direktoryo para sa configuration file ng secrets manager Default: `./secretsManagerConfig.json` + +--- + +

Uri

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +Tinutukoy ang uri ng secrets manager [`hashicorp-vault`]. Default: `hashicorp-vault` + +--- + +

token

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +Tinutukoy ang access token para sa serbisyo + +--- + +

server-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +Tinutukoy ang URL ng server para sa serbisyo + +--- + +

Pangalan

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +Tinutukoy ang pangalan ng node para sa pagpapanatili ng record sa serbisyo. Default: `polygon-edge-node` + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Tinutukoy ang namespace na ginagamit para sa secrets manager ng Hashicorp Vault. Default: `admin` + +### mga secret output flag {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +Nakatakda ang bandila na nagpapahiwatig kung i-output lamang ang public key ng BLS. Default: `true` + +--- + +

config

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +Itinatakda ang path sa config file ng SecretsManager. Kung aalisin, gagamitin ang lokal na FS secrets manager. + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +Itinatakda ang direktoryo para sa data ng Polygon Edge kung ginagamit ang lokal na FS. + +--- + +

node-id

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +Nakatakda ang bandila na nagpapahiwatig kung i-output lamang ang network node ID. Default: `true` + +--- + +

Validator

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +I-set ang flag na nagpapahiwatig kung i-output lamang ang validator address. Default: `true` + +--- + +## Mga Response {#responses} + +### Status Response {#status-response} + +Tinutukoy ang response object gamit ang mga Protokol ng Buffer. +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### Monitor Response {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## Mga Utility {#utilities} + +### mga whitelist command {#whitelist-commands} + +| **Command** | **Paglalarawan** | +|------------------------|-------------------------------------------------------------------------------------| +| whitelist show | Nagpapakita ng impormasyon ng whitelist | +| whitelist deployment | Ina-update ang whitelist ng deployment ng smart na kontrata | + +

whitelist show

+ + + + + whitelist show + + + + +Nagpapakita ng impormasyon ng whitelist. + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +Tinutukoy ang genesis file na ia-update. Default: `./genesis.json`. + +--- + +

whitelist deployment

+ +

chain

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +Tinutukoy ang genesis file na ia-update. Default: `./genesis.json`. + +--- + +

add

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Nagdaragdag ng bagong address sa contract deployment whitelist. Ang mga address lang sa contract deployment whitelist ang maaaring mag-deploy ng mga kontrata. Kung walang laman, ang anumang address ay maaaring magsagawa ng deployment ng kontrata + +--- + +

remove

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Nag-aalis ng address sa contract deployment whitelist. Ang mga address lang sa contract deployment whitelist ang maaaring mag-deploy ng mga kontrata. Kung walang laman, ang anumang address ay maaaring magsagawa ng contract deployment + +--- + +### mga backup flag {#backup-flags} + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +Address ng gRPC API. Default: `127.0.0.1:9632`. + +--- + +

out

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +Path ng file ng archive na ise-save. + +--- + +

from

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +Ang simulang height ng mga block sa archive. Default: 0. + +--- + +

to

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +Ang end height ng mga block sa archive. + +--- + +## Template ng Genesis {#genesis-template} +Dapat gamitin ang genesis file para itakda ang inisyal na state ng blockchain (hal. kung ang ilang account ay dapat na magkaroon ng panimulang balanse). + +Nabubuo ang sumusunod na *./genesis.json* file: +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### Data Directory {#data-directory} + +Kapag isinasagawa ang flag na *data-dir*, may nabubuong folder na **test-chain**. +Ang istruktura ng folder ay naglalaman ng mga sumusunod na sub-folder: +* **blockchain** - Ini-store ang LevelDB para sa mga blockchain object +* **trie** - Ini-store ang LevelDB para sa Merkle tries +* **keystore** - Nagi-store ng mga pribadong key para sa client. Kabilang dito ang pribadong key ng libp2p at ang pribadong key ng sealing/validator +* **consensus** - Nagi-store ng anumang impormasyon ng consensus na maaaring kailanganin ng client habang tumatakbo + +## Mga Resource {#resources} +* **[Mga Protokol ng Buffer](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/tl-edge/get-started/installation.md b/archive/edge/tl-edge/get-started/installation.md new file mode 100644 index 0000000000..fe12159059 --- /dev/null +++ b/archive/edge/tl-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: Pag-install +description: "Kung paano i-install ang Polygon Edge." +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +Mangyaring sumangguni sa paraan ng pag-install na mas naaangkop sa iyo. + +Ang aming rekomendasyon ay ang paggamit ng mga pre-built na release at i-verify ang mga ibinigay na checksum. + +## Mga pre-built na release {#pre-built-releases} + +Mangyaring sumangguni sa pahina ng [mga GitHub Release](https://github.com/0xPolygon/polygon-edge/releases) para sa listahan ng mga release. + +Ang Polygon Edge ay may cross-compiled na AMD64/ARM64 na mga binary para sa Darwin at Linux. + +--- + +## Docker image {#docker-image} + +Ang mga opisyal na Docker image ay naka-host sa ilalim ng [registry ng hub.docker.com](https://hub.docker.com/r/0xpolygon/polygon-edge). + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## Pagbuo mula sa source {#building-from-source} + +Bago gamitin ang `go install` siguraduhin na mayroon kang Go na `>=1.18` naka-install at maayos na naka-configure. + +Ang matatag na branch ang sangay ng pinakabagong release. + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## Paggamit `go install` + +Bago gamitin ang `go install` siguraduhin na mayroon kang Go na `>=1.17` naka-install at maayos na naka-configure. + +`go install github.com/0xPolygon/polygon-edge@release/` + +Makukuha ang binary sa variable ng iyong `GOBIN`kapaligiran, at isasama ang mga pagbabago mula sa pinakabagong release. Maaari mong checkout ang [Mga Release](https://github.com/0xPolygon/polygon-edge/releases) ng GitHub para malaman kung alin ang isa ang pinakabago. diff --git a/archive/edge/tl-edge/get-started/set-up-ibft-locally.md b/archive/edge/tl-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..1cff8660aa --- /dev/null +++ b/archive/edge/tl-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,367 @@ +--- +id: set-up-ibft-locally +title: Lokal na Pag-Setup +description: "Step-by-step na gabay sa lokal na pag-setup." +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution Ang gabay na ito ay para lang sa mga layunin sa pagsubok + +Tuturuan ka ng gabay sa ibaba kung paano mag-set up ng Polygon Edge network sa iyong lokal na machine para sa mga layunin sa pagsubok at +pag-develop. + +Ang pamamaraan ay lubos na naiiba sa paraan kung paano mo gustong mag-set up ng Polygon Edge network para sa scenario ng totoong paggamit sa +isang cloud provider: **[Cloud Setup](/docs/edge/get-started/set-up-ibft-on-the-cloud)** + +::: + + +## Mga Kinakailangan {#requirements} + +Sumangguni sa [Pag-install](/docs/edge/get-started/installation) para i-install ang Polygon Edge. + +## Pangkalahatang-ideya {#overview} + +![Lokal na Pag-Setup](/img/edge/ibft-setup/local.svg) + +Sa gabay na ito, ang layunin natin ay magtatag ng isang gumaganang `polygon-edge`blockchain network na gumagana sa [protokol ng consensus ng IBFT](https://github.com/ethereum/EIPs/issues/650). +Ang blockchain network ay bubuuin ng 4 na node kung saan ang 4 na ito ay mga validator node, at dahil dito, kwalipikado ang mga ito para sa proposing block at mga nagba-validate na block na nagmula sa iba pang proposer. +Ang 4 na node ay tatakbo sa parehong machine, dahil ang layunin ng gabay na ito ay magbigay sa iyo ng ganap na gumaganang IBFT cluster sa loob ng pinakamaikling panahon. + +Para magawa iyon, gagabayan ka namin sa pamamagitan ng 4 na madaling hakbang: + +1. Kapag nagsimula ng mga data directory, mabubuo ang mga validator key para sa bawat isa sa 4 na node, at magsisimula ito ng mga walang lamang data directory ng blockchain. Mahalaga ang mga validator key dahil kailangan nating i-bootstrap ang genesis block sa pamamagitan ng paunang set ng mga validator gamit ang mga key na ito. +2. Ang paghahanda sa connection string para sa bootnode ay magiging mahalagang impormasyon para sa bawat node na papatakbuhin natin kaugnay sa kung sa aling node kokonekta kapag nagsisimula sa kauna-unahang pagkakataon. +3. Ang pagbuo sa `genesis.json` file ay mangangailangan, bilang input, ng magkaparehong mga validator key na nabuo sa **hakbang 1** na ginamit para sa pagtatakda ng mga paunang validator ng network sa genesis block at ng bootnode connection string mula sa **hakbang 2**. +4. Ang pagpapatakbo sa lahat ng node ay ang pinal na layunin ng gabay na ito at ito ang magiging huling hakbang na gagawin natin, iuutos natin sa mga node kung aling data directory ang gagamitin, at kung saan hahanapin ang `genesis.json` na nagbu-bootstrap sa paunang state ng network. + +Dahil lahat ng apat na node ay tatakbo sa localhost, sa panahon ng proseso ng pag-setup, inaasahan na ang lahat ng data directory +para sa bawat isa sa mga node ay nasa iisang parent directory. + +:::info Bilang ng mga validator + +Walang minimum sa bilang ng mga node sa isang cluster, na nangangahulugang ang mga cluster na may 1 lang na validator node ay posible. +Tandaan na sa pamamagitan ng _single_ node cluster, **walang crash tolerance** at **walang BFT guarantee**. + +Ang minimum na inirerekomendang bilang ng mga node para makakamit ng BFT guarantee ay 4 - dahil sa isang 4 na node cluster, ang pagpalya ng +1 node ay maaaring i-tolerate, hangga't gumagana nang normal ang 3 natitira. + +::: + +## Hakbang 1: Magsimula ng mga folder ng data para sa IBFT at bumuo ng mga validator key {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +Para masimulan at mapatakbo ang IBFT, kailangan mong simulan ang mga folder ng data, +isa para sa bawat node: + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +Ipi-print ng bawat isa sa mga command na ito ang validator key, bls public key, at [node ID](https://docs.libp2p.io/concepts/peer-id/). Kakailanganin mo ang Node ID ng unang node para sa susunod na hakbang. + +### Mga output Secret {#outputting-secrets} +Maaaring i-retrieve ulit ang output ng lihim, kung kinakailangan. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## Hakbang 2: Ihanda ang multiaddr connection string para sa bootnode {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Para matagumpay na makagawa ng koneksyon ang isang node, alam dapat nito kung sa aling `bootnode`server kokonekta para makakuha ng +impormasyon tungkol sa lahat ng natitirang node sa network. Kilala rin minsan ang `bootnode` bilang `rendezvous` server sa p2p jargon. + +Ang `bootnode` ay hindi espesyal na instance ng polygon-edge node. Maaaring magsilbi bilang `bootnode` ang bawat polygon-edge node, ngunit +ang bawat polygon-edge node ay kailangang magkaroon ng set ng mga bootnode na tinukoy na ikokontak para magbigay ng impormasyon tungkol sa kung paano kumonekta sa +lahat ng natitirang node sa network. + +Para magawa ang connection string para sa pagtukoy sa bootnode, kakailanganin nating sundin +ang [multiaddr format](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +Sa gabay na ito, ituturing natin ang unang node at pangalawang node bilang mga bootnode para sa lahat ng iba pang node. Ang mangyayari sa scenario na ito ay +ang mga node na kumokonekta sa `node 1` o `node 2` ay makakakuha ng impormasyon tungkol sa kung paano kumonekta sa isa pa sa pamamagitan ng parehong +nakontak na bootnode. + +:::info Kailangan mong tumukoy ng hindi bababa sa isang bootnode para makapagsimula ng node + +Nangangailangan ng hindi bababa sa **isang** bootnode para magawa ng iba pang node sa network na ma-discover ang isa't isa. Inirerekomenda ang mas maraming node, dahil +ang mga ito ay nagbibigay ng katatagan sa network kung sakaling magkaroon ng mga outage. +Sa gabay na ito, maglilista tayo ng dalawang node, ngunit maaari itong baguhin nang mabilisan, nang walang epekto sa pagiging valid ng `genesis.json` na file. + +::: + +Dahil tumatakbo tayo sa localhost, ligtas na ipagpalagay na ang `` ay `127.0.0.1`. + +Para sa ``, gagamitin natin ang `10001` dahil iko-configure natin ang libp2p server para sa `node 1` na papakinggan sa port na ito sa ibang pagkakataon. + +At panghuli, kailangan natin ang `` na maaari nating makuha sa output ng dating pinatakbong command na `polygon-edge secrets init --data-dir test-chain-1` command (na ginamit para bumuo ng mga key at data directory para sa `node1`) + +Pagkatapos ng pagbuo, ang multiaddr connection string sa `node 1` na gagamitin natin bilang bootnode ay magiging parang ganito (ang `` lang na nasa dulo ay naiiba dapat): +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Sa katulad na paraan, binubuo natin ang multiaddr para sa pangalawang bootnode gaya ng ipinapakita sa ibaba ng +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info mga DNS hostname sa halip na ips + +Sumusuporta ang Polygon Edge gamit ang mga DNS hostname para sa configuration ng mga node. Lubos na kapaki-pakinabang na feature ito para sa mga cloud based na deployment, dahil ang ip ng node ay maaaring magbago dahil sa iba't ibang dahilan. + +Ang multiaddr format para sa connection string habang ginagamit ang mga DNS hostname ay gaya ng sumusunod: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## Hakbang 3: Buuin ang genesis file gamit ang 4 na node bilang mga validator {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +Ang ginagawa ng command na ito: + +* Itinatakda ng `--ibft-validators-prefix-path` ang prefix folder path sa tinukoy kung aling IBFT sa Polygon Edge ang maaaring +gamitin. Ginagamit ang directory na ito para panatilihin ang `consensus/` folder, kung saan nakalagay ang pribadong key ng validator. Ang +pampublikong key ng validator ay kinakailangan para magawa ang genesis file - ang paunang listahan ng mga bootstrap node. +Lohikal lang ang flag na ito kapag sine-set up ang network sa localhost, dahil sa real-world na scenario, hindi tayo maaaring umasa na ang lahat ng +data directory ng mga node ay nasa iisang filesystem kung saan madali nating mababasa ang pampublikong key ng mga ito. +* Itinatakda ng `--bootnode` ang address ng bootnode na magbibigay-daan sa mga node na mahanap ng mga ito ang isa't isa. +Gagamitin natin ang multiaddr string ng `node 1`, tulad ng nabanggit sa **hakbang 2**. + +Ang resulta ng command na ito ay ang file na `genesis.json` na naglalaman ng genesis block ng aming bagong blockchain, kasama ang paunang natukoy na validator set at ang configuration kung aling node ang unang kokontakin para makagawa ng koneksyon. + +:::info Lumipat sa ECDSA + +Ang BLS ang default na validation mode ng mga block header. Kung gusto mong tumakbo ang iyong chain sa ECDSA mode, magagamit mo ang flag `—ibft-validator-type`, gamit ang `ecdsa`argument: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info Mga premining na balanse ng account + +Marahil ay gusto mong i-set up ang iyong blockchain network nang may mga "premined" na balanse ang ilang address. + +Para magawa ito, magpasa ng maraming `--premine` flag na gusto mo ayon sa address na gusto mong simulan nang may partikular na balanse +sa blockchain. + +Halimbawa, kung gusto nating mag-premine ng 1000 ETH sa address na `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` sa ating genesis block, kakailanganin nating ibigay ang sumusunod na argumento: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Tandaang ang na-premine na halaga ay nasa WEI, hindi ETH.** + +::: + +:::info Itakda ang block gas limit + +Ang default na gas limit kada block ay `5242880`. Ang value na ito ay nakasulat sa genesis file, ngunit kung gusto mo, maaari mo itong +dagdagan / bawasan. + +Para gawin ito, maaari mong gamitin ang flag na `--block-gas-limit` na sinusundan ng gustong value gaya ng ipinapakita sa ibaba: + +```shell +--block-gas-limit 1000000000 +``` +::: + +:::info Itakda ang file descriptor limit ng system + +Maaaring mababa ang default na file descriptor limit (maximum na bilang ng mga bukas na file) at sa Linux, ang lahat ay isang file. Kung inaasahang magkakaroon ng mataas na throughput ang mga node, maaari mong isaalang-alang ang pagtaas ng limitasyong ito. I-check ang mga opisyal na docs ng iyong linux distro para sa karagdagang detalye. + +#### Tingnan ang mga kasalukuyang limitasyon ng os (mga bukas na file) {#check-current-os-limits-open-files} +```shell title="ulimit -n" +1024 # Ubuntu default +``` + +#### Dagdagan ang limitasyon sa mga bukas na file {#increase-open-files-limit} +- Tumatakbo `polygon-edge`sa foreground (shell) + ```shell title="Set FD limit for the current session" + ulimit -n 65535 # affects only current session, limit won't persist after logging out + ``` + + ```shell title="Edit /etc/security/limits.conf" + # add the following lines to the end of the file to modify FD limits + * soft nofile 65535 # sets FD soft limit for all users + * hard nofile 65535 # sets FD hard limit for all users + + # End of file + ``` +I-save ang file at i-restart ang system. + +- Tumatakbo `polygon-edge`sa background bilang serbisyo + +Kung `polygon-edge`tumakbo bilang serbisyo ng system, gamit ang tool tulad ng , nililimitahan ng descriptor ng `systemd`file dapat na pinamamahalaan ang paggamit ng `systemd`. + ```shell title="Edit /etc/systemd/system/polygon-edge.service" + [Service] + ... + LimitNOFILE=65535 + ``` + +### Pag-troubleshoot {#troubleshooting} +```shell title="Watch FD limits of polygon edge running process" +watch -n 1 "ls /proc/$(pidof polygon-edge)/fd | wc -l" +``` + +```shell title="Check max FD limits for polygon-edge running process" +cat /proc/$(pidof polygon-edge)/limits +``` +::: + + +## Hakbang 4: Patakbuhin ang lahat ng client {#step-4-run-all-the-clients} + +Dahil sinusubukan nating magpatakbo ng Polygon Edge network na may 4 na node sa iisang machine, kailangan nating mag-ingat para +maiwasan ang mga conflict sa port. Ito ang dahilan kung bakit gagamitin natin ang sumusunod na rason para sa pagtukoy sa mga port sa pakikinig ng bawat server ng node: + +- `10000` para sa gRPC server ng `node 1`, `20000` para sa GRPC server ng `node 2`, atbp. +- `10001` para sa libp2p server ng `node 1`, `20001` para sa libp2p server ng `node 2`, atbp. +- `10002` para sa JSON-RPC server ng `node 1`, `20002` para sa JSON-RPC server ng `node 2`, atbp. + +Para patakbuhin ang **unang** client (tandaan ang port `10001` dahil ginamit ito bilang bahagi ng libp2p multiaddr sa **hakbang 2** kasama ang Node ID ng node 1): + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +Para patakbuhin ang **pangalawang** client: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +Para patakbuhin ang **pangatlong** client: + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +Para patakbuhin ang **pang-apat** na client: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +Para mabilis na suriin kung ano na ang nagawa sa ngayon: + +* Ang directory para sa data ng client ay tinukoy bilang **./test-chain-\*** +* Ang mga GRPC server ay sinimulan na sa mga port **10000**, **20000**, **30000** at **40000**, para sa bawat node ayon sa pagkakasunud-sunod ng mga ito +* Ang mga libp2p server ay sinimulan na sa mga port **10001**, **20001**, **30001** at **40001**, para sa bawat node ayon sa pagkakasunud-sunod ng mga ito +* Ang mga JSON-RPC server ay sinimulan na sa mga port **10002**, **20002**, **30002** at **40002**, para sa bawat node ayon sa pagkakasunud-sunod ng mga ito +* Ang *seal* flag ay nangangahulugan na ang node na sinisimulan ay lalahok sa pag-seal ng block +* Tinutukoy ng *chain* flag kung aling genesis file ang dapat gamitin para sa configuration ng chain + +Ang istruktura ng genesis file ay tinatalakay sa seksyong [Mga CLI Command](/docs/edge/get-started/cli-commands). + +Pagkatapos patakbuhin ang mga naunang command, nakapag-set up ka na ng 4 na node na Polygon Edge network na may kakayahang mag-seal ng mga block at mag-recover +pagkatapos pumalya ang node. + +:::info Simulan ang client gamit ang config file + +Sa halip na tukuyin ang lahat ng paramater ng configuration bilang mga argumento sa CLI, maaari ring simulan ang Client gamit ang isang config file sa pamamagitan ng pagsasagawa sa sumusunod na command: + +````bash +polygon-edge server --config +```` +Halimbawa: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Sa kasalukuyan, sinusuportahan namin `yaml`at `json`batay **[sa](/docs/edge/configuration/sample-config)** mga configuration files, makikita ang mga sample config files dito + +::: + +:::info Mga hakbang para makapagpatakbo ng non-validator node + +Isi-sync palagi ng Non-validator ang mga pinakabagong block na natanggap mula sa validator node, maaari kang magsimula ng non-validator node sa pamamagitan ng pagpapatakbo sa sumusunod na command. + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +Halimbawa, maaari kang magdagdag ng **panlimang** Non-validator client sa pamamagitan ng pagsasagawa ng sumusunod na command: + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info Tukuyin ang limitasyon sa presyo + +Ang isang Polygon Edge node ay maaaring simulan nang may nakatakdang **limitasyon sa presyo** para sa mga papasok na transaksyon. + +Ang unit para sa limitasyon sa presyo ay `wei`. + +Kapag nagtakda ng limitasyon sa presyo, nangangahulugan ito na ang anumang transaksyon na naiproseso ng kasalukuyang node ay kailangang magkaroon ng gas price na **mas mataas** +kaysa sa itinakdang limitasyon sa presyo, kung hindi, hindi ito isasama sa isang block. + +Ang pagsunod ng karamihan ng mga node sa partikular na limitasyon sa presyo ay nagpapatupad sa panuntunan na ang mga transaksyon sa network ay +hindi maaaring mas mababa sa partikular na threshold sa presyo. + +Ang default na value para sa limitasyon sa presyo ay `0`, ibig sabihin, hindi talaga ito ipinapatupad bilang default. + +Halimbawa ng paggamit sa `--price-limit` flag: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Mahalaga ring banggitin na ang mga limitasyon sa presyo **ay ipinapatupad lang sa mga hindi lokal na transaksyon**, ibig sabihin +na ang limitasyon sa presyo ay hindi nalalapat sa mga transaksyon na lokal na idinagdag sa node. + +::: + +:::info WebSocket URL + +Bilang default, kapag pinatakbo mo ang Polygon Edge, bumubuo ito ng WebSocket URL batay sa lokasyon ng chain. +Ang URL scheme na `wss://` ay ginagamit para sa mga HTTPS link, at `ws://` para sa HTTP. + +Localhost WebSocket URL: +````bash +ws://localhost:10002/ws +```` +Mangyaring tandaan na ang port number ay nakadepende sa napiling JSON-RPC port para sa node. + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## Hakbang 5: Magkipag-interaksyon sa polygon-edge network {#step-5-interact-with-the-polygon-edge-network} + +Ngayong nakapag-set up ka ng kahit 1 lang na tumatakbong client, maaari ka nang makipag-interaksyon sa blockchain gamit account na na-premine mo sa itaas +at sa pamamagitan ng pagtukoy sa JSON-RPC URL sa alinman sa 4 na node: +- Node 1: `http://localhost:10002` +- Node 2: `http://localhost:20002` +- Node 3: `http://localhost:30002` +- Node 4: `http://localhost:40002` + +Sundin ang gabay na ito para magbigay ng mga operator command sa bagong gawang cluster: [Paano mag-query ng impormasyon tungkol sa operator](/docs/edge/working-with-node/query-operator-info) (ang mga GRPC port para sa cluster na ginawa natin ay `10000`/`20000`/`30000`/`40000` para sa bawat node ayon sa pagkakasunud-sunod ng mga ito) diff --git a/archive/edge/tl-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/tl-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..ffaf7e8fe8 --- /dev/null +++ b/archive/edge/tl-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,385 @@ +--- +id: set-up-ibft-on-the-cloud +title: Pag-Setup sa Cloud +description: "Step-by-step na gabay sa pag-setup sa cloud." +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info Ang gabay na ito ay para sa mga mainnet o testnet na pag-setup + +Ang gabay sa ibaba ay magtuturo sa iyo kung paano i-set up ang isang Polygon Edge network sa isang cloud provider para sa isang production na pag-setup ng iyong testnet o mainnet. + +Kung nais mong i-setup ang isang Polygon Edge network nang lokal para mabilisang i-test ang `polygon-edge` bago gawin ang isang production-like na pag-setup, mangyaring sumangguni sa +**[Lokal na pag-setup](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## Mga kinakailangan {#requirements} + +Sumangguni sa [Pag-install](/docs/edge/get-started/installation) para i-install ang Polygon Edge. + +### Pag-set up ng VM connectivity {#setting-up-the-vm-connectivity} + +Depende sa pagpili mo ng cloud provider, maaari mong i-set up ang mga connectivity at mga patakaran sa pagitan ng mga VM gamit ang isang firewall, mga security group, o mga access control list. + +Bilang tanging bahagi ng `polygon-edge` na kailangang ilantad sa iba pang mga VM ay ang libp2p server, ang simpleng pagpapahintulot lamang +sa lahat ng komunikasyon sa pagitan ng mga VM sa default libp2p port `1478` ay sapat na. + +## Pangkalahatang-ideya {#overview} + +![Pag-Setup sa Cloud](/img/edge/ibft-setup/cloud.svg) + +Sa gabay na ito, ang layunin natin ay magtatag ng isang gumaganang `polygon-edge` blockchain network na gumagana sa [protokol ng consensus ng IBFT](https://github.com/ethereum/EIPs/issues/650). +Ang blockchain network ay bubuuin ng 4 na node kung saan ang lahat ng 4 na ito ay mga validator node, at dahil dito, kwalipikado ang mga ito para sa proposing block at mga validating block na nagmula sa ibang mga proposer. +Ang bawat isa sa 4 na mga node ay magpapatakbo sa sarili nitong VM, dahil ang idea ng gabay na ito ay magbigay sa iyo ng isang ganap na gumaganang Polygon Edge network habang pinapanatiling pribado ang mga validator key para matiyak ang isang trustless na network na setup. + +Para magawa iyon, gagabayan ka namin sa pamamagitan ng 4 na madaling hakbang: + +0. Tingnan ang listahan ng mga **Kinakailangan** sa itaas +1. Buuin ang mga pribadong key para sa bawat validator, at simulan ang data directory +2. Ihanda ang connection string para sa bootnode na ilalagay sa ibinabahaging `genesis.json` +3. Likhain ang `genesis.json` sa iyong lokal na machine, at ipadala/ilipat ito sa bawat node +4. Simulan ang lahat ng mga node + +:::info Bilang ng mga validator + +Walang minimum sa bilang ng mga node sa isang cluster, na nangangahulugang ang mga cluster na may 1 lang na validator node ay posible. +Tandaan na sa pamamagitan ng _single_ node cluster, **walang crash tolerance** at **walang BFT guarantee**. + +Ang minimum na inirerekomendang bilang ng mga node para makakamit ng BFT guarantee ay 4 - dahil sa isang 4 na node cluster, ang pagpalya ng +1 node ay maaaring i-tolerate, hangga't gumagana nang normal ang 3 natitira. + +::: + +## Hakbang 1: Simulan ang mga data folder at bumuo ng mga validator key {#step-1-initialize-data-folders-and-generate-validator-keys} + +Para mapagana at mapatakbo ang Polygon Edge, kailangan mong simulan ang mga data folder sa bawat node: + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +Ipi-print ng bawat isa sa mga command na ito ang validator key, bls public key, at [node ID](https://docs.libp2p.io/concepts/peer-id/). Kakailanganin mo ang Node ID ng unang node para sa susunod na hakbang. + +### Mga output Secret {#outputting-secrets} +Maaaring i-retrieve ulit ang output ng lihim, kung kinakailangan. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning Sa iyo lang dapat ang iyong data directory! + +Ang mga data directory na binuo sa itaas, bukod sa pagpapasimula ng mga directory para sa pagpapanatili ng blockchain state, ay magbubuo rin ng iyong validator's private key. +**Pananatilihing lihim ang key na ito, dahil ang pagnanakaw rito ay magpapahintulot para magpanggap na validator sa network!** + +::: + +## Hakbang 2: Ihanda ang multiaddr connection string para sa bootnode {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Para matagumpay na makagawa ng koneksyon ang isang node, alam dapat nito kung sa aling `bootnode` server kokonekta para makakuha ng +impormasyon tungkol sa lahat ng natitirang node sa network. Kilala rin minsan ang `bootnode` bilang `rendezvous` server sa p2p jargon. + +`bootnode` ay hindi isang espesyal na instance ng isang Polygon Edge node. Bawat Polgyon Edge node ay maaaring magsilbing isang `bootnode` at +bawat Polygon Edge node ay dapat magkaroon ng isang set ng mga bootnode na tinukoy na makokontak para makapaglaan ng impormasyon kung paano makikipag-ugnayan dito ang lahat ng natitirang node sa network. + +Para magawa ang connection string para sa pagtukoy sa bootnode, kakailanganin nating sundin +ang [multiaddr format](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +Sa gabay na ito, ituturing natin ang unang node at pangalawang node bilang mga bootnode para sa lahat ng iba pang node. Ang mangyayari sa scenario na ito ay +ang mga node na kumokonekta sa `node 1` o `node 2` ay makakakuha ng impormasyon tungkol sa kung paano kumonekta sa isa pa sa pamamagitan ng parehong +nakontak na bootnode. + +:::info Kailangan mong tumukoy ng hindi bababa sa isang bootnode para makapagsimula ng node + +Nangangailangan ng hindi bababa sa **isang** bootnode para magawa ng iba pang node sa network na ma-discover ang isa't isa. Inirerekomenda ang mas maraming node, dahil +ang mga ito ay nagbibigay ng katatagan sa network kung sakaling magkaroon ng mga outage. +Sa gabay na ito, maglilista tayo ng dalawang node, ngunit maaari itong baguhin nang mabilisan, nang walang epekto sa pagiging valid ng `genesis.json` na file. + +::: + +Bilang unang bahagi ng multiaddr connection string ang ``, dito kakailanganin mong i-enter ang IP address na maaabot ng ibang mga node, ito ay maaaring maging pribado o pampublikong IP address depende sa iyong setup, hindi `127.0.0.1`. + +Para sa `` gagamitin natin ang `1478`, dahil ito ang default na libp2p port. + +At panghuli, kailangan natin ang `` na maaari nating makuha sa output ng dating pinatakbong command na `polygon-edge secrets init --data-dir data-dir` command (na ginamit para bumuo ng mga key at data directory para sa `node 1`) + +Pagkatapos ng pagbuo, ang multiaddr connection string sa `node 1` na gagamitin natin bilang bootnode ay magiging parang ganito (ang `` lang na nasa dulo ay naiiba dapat): +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Sa katulad na paraan, binubuo natin ang multiaddr para sa pangalawang bootnode gaya ng ipinapakita sa ibaba +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info Mga DNS hostname sa halip na ips + +Sumusuporta ang Polygon Edge gamit ang mga DNS hostname para sa configuration ng mga node. Lubos na kapaki-pakinabang na feature ito para sa mga cloud based na deployment, dahil ang ip ng node ay maaaring magbago dahil sa iba't ibang dahilan. + +Ang multiaddr format para sa connection string habang ginagamit ang mga DNS hostname ay gaya ng sumusunod: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## Hakbang 3: Buuin ang genesis file gamit ang 4 na node bilang mga validator {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +Ang hakbang na ito ay maaaring patakbuhin sa iyong lokal na machine, ngunit kakailanganin mo ang mga pampublikong validator key para sa bawat isa sa 4 na validator. + +Maaaring ligtas na maibahagi ng mga validator ang `Public key (address)` gaya ng ipinapakita sa ibaba sa output ng kanilang `secrets init` mga command, para +maaari mong ligtas na mabuo ang genesis.json kasama ang mga validator na iyon sa panimulang validator set, na kinilala ng kanilang mga pampublikong key: + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +Kapag natanggap mo ang lahat ng 4 na mga pampublikong key ng validator, maaari mong patakbuhin ang sumusunod na command para mabuo ang `genesis.json` + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +Ang ginagawa ng command na ito: + +* Itinatakda ng `--ibft-validator` ang pampublikong key ng validator na dapat isama sa paunang validator set sa genesis block. Maaaring magkaroon ng maraming mga paunang validator. +* Itinatakda ng `--bootnode` ang address ng bootnode na magbibigay-daan sa mga node na mahanap ng mga ito ang isa't isa. +Gagamitin natin ang multiaddr string ng `node 1`, gaya ng nabanggit sa **hakbang 2** , kahit maaari kang magdagdag ng gaano karaming bootnode na gusto mo, gaya ng ipinapakita sa itaas. + +:::info Lumipat sa ECDSA + +Ang BLS ang default na validation mode ng mga block header. Kung gusto mong tumakbo ang iyong chain sa ECDSA mode, magagamit mo ang flag `—ibft-validator-type`, gamit ang `ecdsa`argument: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info Mga premining na balanse ng account + +Marahil ay gusto mong i-set up ang iyong blockchain network nang may mga "premined" na balanse ang ilang address. + +Para magawa ito, magpasa ng maraming `--premine` flag na gusto mo ayon sa address na gusto mong simulan nang may partikular na balanse +sa blockchain. + +Halimbawa, kung gusto nating mag-premine ng 1000 ETH sa address na `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` sa ating genesis block, kakailanganin nating ibigay ang sumusunod na argumento: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Tandaang ang na-premine na halaga ay nasa WEI, hindi ETH.** + +::: + +:::info Itakda ang block gas limit + +Ang default na gas limit kada block ay `5242880`. Ang value na ito ay nakasulat sa genesis file, ngunit kung gusto mo, maaari mo itong +dagdagan / bawasan. + +Para gawin ito, maaari mong gamitin ang flag na `--block-gas-limit` na sinusundan ng gustong value gaya ng ipinapakita sa ibaba: + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Itakda ang file descriptor limit ng system + +Maaaring mababa ang default na file descriptor limit (maximum na bilang ng mga bukas na file) at sa Linux, ang lahat ay isang file. Kung inaasahang magkakaroon ng mataas na throughput ang mga node, maaari mong isaalang-alang ang pagtaas ng limitasyong ito. I-check ang mga opisyal na docs ng iyong linux distro para sa karagdagang detalye. + +#### Tingnan ang mga kasalukuyang limitasyon ng os (mga bukas na file) {#check-current-os-limits-open-files} +```shell title="ulimit -n" +1024 # Ubuntu default +``` + +#### Dagdagan ang limitasyon sa mga bukas na file {#increase-open-files-limit} +- Tumatakbo `polygon-edge`sa foreground (shell) + ```shell title="Set FD limit for the current session" + ulimit -n 65535 # affects only current session, limit won't persist after logging out + ``` + + ```shell title="Edit /etc/security/limits.conf" + # add the following lines to the end of the file to modify FD limits + * soft nofile 65535 # sets FD soft limit for all users + * hard nofile 65535 # sets FD hard limit for all users + + # End of file + ``` +I-save ang file at i-restart ang system. + +- Tumatakbo `polygon-edge`sa background bilang serbisyo + +Kung `polygon-edge`tumakbo bilang serbisyo ng system, gamit ang tool tulad ng , nililimitahan ng descriptor ng `systemd`file dapat na pinamamahalaan ang paggamit ng `systemd`. + ```shell title="Edit /etc/systemd/system/polygon-edge.service" + [Service] + ... + LimitNOFILE=65535 + ``` + +### Pag-troubleshoot {#troubleshooting} +```shell title="Watch FD limits of polygon edge running process" +watch -n 1 "ls /proc/$(pidof polygon-edge)/fd | wc -l" +``` + +```shell title="Check max FD limits for polygon-edge running process" +cat /proc/$(pidof polygon-edge)/limits +``` +::: + +Pagkatapos tukuyin ang: +1. Mga pampublikong key ng validator na dapat isama sa genesis block bilang validator set +2. Bootnode multiaddr connection strings +3. Mga premined na account at balanse na isasama sa genesis block + +at pagbuo ng `genesis.json`, dapat mong kopyahin ito sa lahat ng mga VM sa network. Depende sa iyong setup, maaari mong +kopyahin/i-paste, ipadala ito sa node operator, o simpleng i-SCP/FTP ito. + +Ang istruktura ng genesis file ay tinatalakay sa seksyong [Mga CLI Command](/docs/edge/get-started/cli-commands). + +## Hakbang 4: Patakbuhin ang lahat ng client {#step-4-run-all-the-clients} + +:::note Networking sa mga Cloud provider + +Karamihan ng mga cloud provider ay hindi naglalantad ng mga IP address (lalo na ang mga pampubliko) bilang isang tuwirang network interface sa iyong VM, sa halip ay mag-setup ng hindi nakikitang NAT proxy. + + +Para pahintulutan ang mga node na makakonekta sa isa't isa, kailangan mong makinig sa `0.0.0.0` IP address para mag-bind sa lahat ng mga interface, ngunit kailangan mo pa ring tukuyin ang IP address o DNS address na maaaring gamitin ng ibang mga node para makakonekta sa iyong instance. Makakamit ito sa pamamagitan ng alinman sa paggamit ng `--nat` o `--dns`argumento kung saan maaari mong tukuyin ang iyong external IP o DNS address. + +#### Halimbawa {#example} + +Ang kaugnay na IP address na gusto mong mapakinggan ay `192.0.2.1`, ngunit hindi ito tuwirang naka-bound sa alinman sa iyong mga network interface. + +Para pahintulutan ang mga node na maka-connect, kailangan mong mapasa ang sumusunod na mga parameter: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +O kung gusto mong tukuyin ang isang DNS address `dns/example.io`, ipasa ang sumusunod na mga parameter: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +Gagawin nitong nakikinig ang iyong mga node sa lahat ng mga interface, ngunit ipinapaalam din nito na ang mga kliyente ay kumokonekta rito sa pamamagitan ng isang tinukoy na `--nat` o `--dns` address. + +::: + +Para patakbuhin ang **unang** client: + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Para patakbuhin ang **pangalawang** client: + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Para patakbuhin ang **pangatlong** client: + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Para patakbuhin ang **pang-apat** na client: + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Pagkatapos patakbuhin ang mga naunang command, nakapag-set up ka na ng 4 na node na Polygon Edge network na may kakayahang mag-seal ng mga block at mag-recover +pagkatapos pumalya ang node. + +:::info Simulan ang client gamit ang config file + +Sa halip na tukuyin ang lahat ng paramater ng configuration bilang mga argumento sa CLI, maaari ring simulan ang Client gamit ang isang config file sa pamamagitan ng pagsasagawa sa sumusunod na command: + +````bash +polygon-edge server --config +```` +Halimbawa: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Sa kasalukuyan, sinusuportahan lang namin ang `json`configuration file, makikita ang sample config file **[dito](/docs/edge/configuration/sample-config)** + +::: + +:::info Mga hakbang para makapagpatakbo ng non-validator node + +Isi-sync palagi ng Non-validator ang mga pinakabagong block na natanggap mula sa validator node, maaari kang magsimula ng non-validator node sa pamamagitan ng pagpapatakbo sa sumusunod na command. + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +Halimbawa, maaari kang magdagdag ng **panlimang** Non-validator client sa pamamagitan ng pagsasagawa ng sumusunod na command: + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info Tukuyin ang limitasyon sa presyo + +Ang isang Polygon Edge node ay maaaring simulan nang may nakatakdang **limitasyon sa presyo** para sa mga papasok na transaksyon. + +Ang unit para sa limitasyon sa presyo ay `wei`. + +Kapag nagtakda ng limitasyon sa presyo, nangangahulugan ito na ang anumang transaksyon na naiproseso ng kasalukuyang node ay kailangang magkaroon ng gas price na **mas mataas** +kaysa sa itinakdang limitasyon sa presyo, kung hindi ay hindi ito masasama sa isang block. + +Ang pagsunod ng karamihan ng mga node sa partikular na limitasyon sa presyo ay nagpapatupad sa panuntunan na ang mga transaksyon sa network ay +hindi maaaring mas mababa sa partikular na threshold sa presyo. + +Ang default na value para sa limitasyon sa presyo ay `0`, ibig sabihin, hindi talaga ito ipinapatupad bilang default. + +Halimbawa ng paggamit sa `--price-limit` flag: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Mahalaga ring banggitin na ang mga limitasyon sa presyo **ay ipinapatupad lang sa mga hindi lokal na transaksyon**, ibig sabihin +na ang limitasyon sa presyo ay hindi nalalapat sa mga transaksyon na lokal na idinagdag sa node. + +::: + +:::info WebSocket URL + +Bilang default, kapag pinatakbo mo ang Polygon Edge, bumubuo ito ng WebSocket URL batay sa lokasyon ng chain. +Ang URL scheme na `wss://` ay ginagamit para sa mga HTTPS link, at `ws://` para sa HTTP. + +Localhost WebSocket URL: +````bash +ws://localhost:10002/ws +```` +Mangyaring tandaan na ang port number ay nakadepende sa napiling JSON-RPC port para sa node. + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/tl-edge/get-started/terraform-aws-deployment.md b/archive/edge/tl-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..437077fd82 --- /dev/null +++ b/archive/edge/tl-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,176 @@ +--- +id: terraform-aws-deployment +title: Pag-deploy ng Terraform AWS +description: "I-deploy ang Polygon Edge network sa AWS cloud provider gamit ang Terraform" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info Gabay sa pag-deploy ng produksyon + +Ito ang opisyal, handa na sa produksyon, ganap na automated, na gabay sa deployment ng AWS. + +Ang mga manual na pag-deploy sa ***[Cloud](set-up-ibft-on-the-cloud)*** o ***[Lokal](set-up-ibft-locally)*** +ay inirerekomenda para sa pagsubok at/o kung ang iyong cloud provider ay hindi AWS. + +::: + +:::info + +Ang pag-deploy na ito ay PoA lamang. +Kung kinakailangan ang PoS mechanism, sundin lamang ang ***[gabay](/docs/edge/consensus/migration-to-pos)*** na ito kung paano gawin ang paglipat mula PoA patungong PoS. + +::: + +Detalyadong ilalarawan ng gabay na ito ang proseso ng pag-deploy ng isang Polygon Edge blockchain network sa AWS cloud provider, +na handa na sa produksyon habang ang mga validator node ay nakakalat sa maraming mga availability zone. + +## Mga Paunang Kinakailangan {#prerequisites} + +### Mga system tool {#system-tools} +* [terraform](https://www.terraform.io/) +* [aws cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [aws access key ID at secret access key](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Mga Terraform variable {#terraform-variables} +Dalawang variable na dapat ibigay, bago patakbuhin ang deployment: + +* `alb_ssl_certificate`- ang ARN ng sertipiko mula sa AWS Certificate Manager na gagamitin ng ALB para sa https protocol. Ang sertipiko ay dapat na mabuo bago simulan ang pag-deploy, at dapat mayroon itong **Inilabas** na status +* `premine` - ang account na makakatanggap ng pre-mined na native currency. +Dapat sundin ng value ang opisyal na [CLI](/docs/edge/get-started/cli-commands#genesis-flags) flag specification + +## Impormasyon sa pag-deploy {#deployment-information} +### Mga na-deploy na resources {#deployed-resources} +High level na pangkalahatang-ideya ng mga resources na ide-deploy: + +* Dedicated VPC +* 4 na mga validator node (na mga boot node rin) +* 4 na mga NAT gateway para pahintulutan ang mga node outbound internet traffic +* Ang Lambda function na ginamit para sa pagbuo ng unang (genesis) block at simulan ang chain +* Mga dedicated security group at mga tungkulin ng IAM +* Ang S3 bucket na gamit para sa pag-imbak ng genesis.json file +* Ang Application Load Balancer na gamit para sa paglalantad sa JSON-RPC endpoint + +### Fault tolerance {#fault-tolerance} + +Ang mga region lamang na may 4 na availability zone ang kinakailangan para sa pag-deploy na ito. Ang bawat node ay na-deploy sa nag-iisang AZ. + +Sa pamamagitan ng paglalagay ng bawat node sa nag-iisang AZ, ang buong blockchain cluster ay fault-tolerant sa nag-iisang node (AZ) failure, habang ipinapatupad ng Polygon Edge ang IBFT +consensus na nagpapahintulot sa nag-iisang node na papalya sa 4 na validator node cluster. + +### Command line access {#command-line-access} + +Ang mga validator node ay hindi nakalantad sa anumang paraan sa pampublikong internet (ang JSON-PRC ay maa-access lamang sa pamamagitan ng ALB) +at walang naka-attach na pampublikong IP address sa kanila. +Ang node command line access ay posible lamang sa pamamagitan ng [AWS Systems Manager - Session Manager](https://aws.amazon.com/systems-manager/features/). + +### Base AMI upgrade {#base-ami-upgrade} + +Ang pag-deploy na ito ay gumagamit ng `ubuntu-focal-20.04-amd64-server` AWS AMI. **Hindi** ito magti-trigger ng EC2 *redeployment* kung ang AWS AMI ay naka-update. + +Kung sa ilang kadahilanan ay kinakailangang i-update ang base AMI, +maaari itong makamit sa pamamagitan ng pagpapatakbo ng `terraform taint`command ng para sa bawat instance, bago ang `terraform apply`. +Ang mga instance ay maaaring mabahiran sa pamamagitan ng pagpapatakbo ng +`terraform taint module.instances[].aws_instance.polygon_edge_instance` na command. + +Halimbawa: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info + +Sa isang kapaligirang pamproduksyon ang `terraform taint` ay dapat patakbuhin nang isa-isa para mapanatiling gumagana ang blockchain network. + +::: + +## Pamamaraan sa pag-deploy {#deployment-procedure} + +### Mga hakbang bago ang pag-deploy {#pre-deployment-steps} +* basahin ang [polygon-technology-edge](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) terraform registry readme +* idagdag ang `polygon-technology-edge` module sa iyong `main.tf` file na gamit ang mga *probisyong tagubilin* sa readme page ng module +* patakbuhin ang `terraform init` command upang i-install ang kinakailangang mga Terraform dependency +* magbigay ng bagong sertipiko sa [AWS Certificate Manager](https://aws.amazon.com/certificate-manager/) +* tiyaking ang ibinigay na sertipiko ay nasa **Issued** na state at kunin ang note ng **ARN** ng sertipiko +* i-set up ang iyong output statement para makuha ang output ng mga module sa cli + +#### `main.tf` halimbawa {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### `terraform.tfvars` halimbawa {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### Mga hakbang sa pag-deploy {#deployment-steps} +* likhain ang `terraform.tfvars` file +* itakda ang mga kinakailangang terraform variable sa file na ito (gaya ng ipinaliwanag sa itaas). +:::info + +May mga iba pang mga non-mandatory variable na maaaring ganap na ma-customize ang pag-deploy na ito. +Maaari mong i-override ang mga default na value sa pamamagitan ng pagdadagdag ng sarili mo sa `terraform.tfvars` file. + + Ang specification para sa lahat ng mga available na variable ay matatagpuan Terraform ***[registry](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)*** ng mga module + +::: +* tiyaking nag-set up ka ng aws cli authentication nang maayos sa pamamagitan ng pagpapatakbo ng `aws s3 ls` - dapat walang mga error +* i-deploy ang imprastraktura `terraform apply` + +### Mga hakbang pagkatapos ng pag-deploy {#post-deployment-steps} +* kapag tapos na ang pag-deploy, tandaan ang `json_rpc_dns_name` variable value na nakaimprenta sa cli +* gumawa ng isang pampublikong dns cname record na nagtuturo sa iyong domain name sa ibinigay na `json_rpc_dns_name` value. Halimbawa: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* kapag lumaganap ang cname record, tingnan kung gumagana nang maayos ang chain sa pamamagitan ng pagtawag sa iyong JSON-PRC endpoint. + Mula sa halimbawa sa itaas: + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## Pamamaraan ng pagsira {#destroy-procedure} +:::warning + +Ang sumusunod na pamamaraan ay permanenteng magtatanggal sa iyong buong imprastrukturang na-deploy sa mga terraform script na ito. +Tiyaking mayroon kang maayos na [blockchain data backup](docs/edge/working-with-node/backup-restore) at/o gumagawa ka sa isang testing environment. + +::: + +Kung kailangan mong alisin ang buong imprastraktura, patakbuhin ang sumusunod na command `terraform destroy`. +Bukod pa rito, kakailanganin mong manual na alisin ang mga secret na naka-imbak sa AWS [Parameter Store](https://aws.amazon.com/systems-manager/features/) +para sa region kung saan naganap ang pag-deploy. diff --git a/archive/edge/tl-edge/overview.md b/archive/edge/tl-edge/overview.md new file mode 100644 index 0000000000..3af2b98808 --- /dev/null +++ b/archive/edge/tl-edge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Polygon Edge +sidebar_label: What is Edge +description: "Isang introduksyon sa Polygon Edge." +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +Ang Polygon Edge ay isang modular at napapalawak na framework para sa pagbuo ng Ethereum-compatible na blockchain network, mga sidechain, at mga pangkalahatang solusyong pag-scale. + +Ang pangunahing gamit nito ay para i-bootstrap ang isang bagong blockchain network habang naglalaan ng ganap na compatibility gamit ang mga Ethereum na smart na kontrata at transaksyon. Ginagamit nito ang IBFT (Istanbul Byzantine Fault Tolerant) na consensus mechanism, na sinusuportahan sa dalawang paraan [PoA (proof of authority)](/docs/edge/consensus/poa) at [PoS (proof of stake)](/docs/edge/consensus/pos-stake-unstake). + +Sinusuportahan din ng Polygon Edge ang komunikasyon sa maraming mga blockchain network, na nagpapahintulot ng paglilipat sa parehong [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) at [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) na mga token, sa pamamagitan ng paggamit sa [centralised bridge solution](/docs/edge/additional-features/chainbridge/overview). + +Ang mga industry standard na wallet ay maaaring gamitin para makipag-interaksyon sa Polygon Edge sa pamamagitan ng [JSON-RPC](/docs/edge/working-with-node/query-json-rpc) mga endpoint at maaaring makagawa ang mga node operator ng iba't ibang action sa mga node sa pamamagitan ng [gRPC](/docs/edge/working-with-node/query-operator-info) na protokol. + +Para malaman ang higit pa tungkol sa Polygon, bisitahin ang [opisyal na website](https://polygon.technology). + +**[GitHub repository](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +Isa pa lang itong work in progress kaya ang mga pagbabago sa arkitektura ay maaaring mangyari sa hinaharap. Ang code ay hindi pa na-audit +kaya mangyaring makipag-ugnayan sa Polygon team kung gusto mong gamitin ito sa produksyon. + +::: + + + +Para makapagsimula ng pagpapatakbo ng isang `polygon-edge` network nang lokal, mangyaring basahin: [Pag-install](/docs/edge/get-started/installation) at [Lokal na Pag-Setup](/docs/edge/get-started/set-up-ibft-locally). diff --git a/archive/edge/tl-edge/performance-reports/overview.md b/archive/edge/tl-edge/performance-reports/overview.md new file mode 100644 index 0000000000..3908fba755 --- /dev/null +++ b/archive/edge/tl-edge/performance-reports/overview.md @@ -0,0 +1,32 @@ +--- +id: overview +title: Pangkalahatang-ideya +description: "Introduksyon sa Polygon Edge testing." +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +Mangyaring tandaan na ang aming , na ginamit para sa pagsasagawa ng mga pagsubok `loadbot`na ito, ay niloloko na ngayon. +::: + +| Uri | Value | Link sa test | +| ---- | ----- | ------------ | +| Mga Regular na Paglilipat | 1428 tps | [Ika-4 ng Hulyo 2022](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| Mga Paglilipat ng ERC-20 | 1111 tps | [Ika-4 ng Hulyo 2022](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| NFT Minting | 714 tps | [Ika-4 ng Hulyo 2022](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +Ang layunin namin ay gumawa ng isang mahusay, sagana sa feature at madaling i-setup at i-maintain na blockchain client software. +Lahat ng mga test ay ginawa gamit ang Polygon Edge Loadbot. +Ang bawat performance report na makikita mo sa seksyong ito ay may wastong petsa, malinaw na inilarawan ang kapaligiran at malinaw na ipinaliwanag ang pamamaraan ng pag-test. + +Ang layunin ng mga performance test na ito ay upang ipakita ang tunay na kakayahan ng Polygon Edge blockchain network. +Ang sinuman ay tiyak na makakakuha ng kaparehong resulta na ipinaskil dito, sa parehong kapaligiran, gamit ang aming loadbot. + +Ang lahat ng mga performance test ay isinagawa sa AWS platform sa isang chain na binubuo ng mga EC2 instance node. \ No newline at end of file diff --git a/archive/edge/tl-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/tl-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..f4125aaddc --- /dev/null +++ b/archive/edge/tl-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,132 @@ +--- +id: test-2022-01-21 +title: Ika-21 ng Enero 2022 +description: "Pagsubok sa performance mula ika-21 ng Enero." +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## Ika-21 ng Enero 2022 {#january-21st-2022} + +### Buod {#summary} + +:::caution +Mangyaring tandaan na ang aming , na ginamit para sa pagsasagawa ng mga pagsubok `loadbot`na ito, ay niloloko na ngayon. +::: + +Isinagawa ang pagsubok na ito pagkatapos ng TxPool refactor na lubos na nakapagpahusay sa performance (inilabas sa [v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0)). + +Ang layunin ay ang mag-setup ng malaking network na binubuo ng 30 aktibong lumalahok na validator para maayos na isailalim sa stress test ang +consensus at TxPool transaction gossiping dahil ang lahat ng transaksyon ay ipinadala sa JSON-RPC ng isang single node. + +Hindi namin layunin na magsikap na makaabot ng maximum na posibleng TPS, dahil ang size ng network ay negatibong nakaaapekto sa performance, +at dahil ang lblock gas limit at tagal ng block ay nakatakda sa mga naaangkop na value na hindi masyadong gumagamit ng mga resource ng system, at na magbibigay-daan dito na tumakbo gamit ang commodity hardware. + +### Mga Resulta {#results} + +| Metric | Value | +| ------ | ----- | +| Mga transaksyon kada segundo | 344 | +| Pumalya ang mga transaksyon | 0 | +| Nagtagumpay ang mga transaksyon | 10000 | +| Kabuuang run time | 30s | + +### Kapaligiran {#environment} + +
+ Configuration ng Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Size ng instancet2.xlarge
Networkingpribadong subnet
Operating systemLinux Ubuntu 20.04 LTS - Focal Fossa
File descriptor limit65535
Max na mga proseso ng user65535
+
+
+
+
+ +
+ Configuration ng Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Bersyong Polygon EdgeI-commit ang 8377162281d1a2e4342ae27cd4e5367c4364aee2 sa develop branch
Mga validator node30
Mga non-validator node0
ConsensusIBFT PoA
Block time2000ms
Block gas limit5242880
+
+
+
+
+ +
+ Configuration ng Loadbot +
+
+ + + + + + + + + + + + + +
Kabuuang Bilang ng Mga Transaksyon10000
Mga transaksyong naipapadala kada segundo400
Uri ng mga transaksyonMga EOA to EOA na paglilipat
+
+
+
+
diff --git a/archive/edge/tl-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/tl-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..d1409ed536 --- /dev/null +++ b/archive/edge/tl-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,390 @@ +--- +id: test-2022-03-02 +title: Ika-2 ng Marso 2022 +description: "Pagsubok sa performance mula noong Ika-2 ng Marso." +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### Buod {#summary} + +:::caution +Mangyaring tandaan na ang aming , na ginamit para sa pagsasagawa ng mga pagsubok `loadbot`na ito, ay niloloko na ngayon. +::: + +Isinagawa ang pagsubok na ito para masukat ang mga paglipat ng SC ERC20 token at ang functionality ng pag-mint ng SC ERC721 token na may mabibigat na load at bilis ng mga transaksyon. + +Ang layunin ay tingnan kung ang lahat ay gumana tulad ng inaasahan sa mabibigat na load. Iyon din ang dahilan kung bakit namin idinagdag ang gas metrics sa output ng loadbot, na nagpapakita sa amin kung ang mga block ay maayos na nalalagyan ng mga transaksyon. + +Ang lahat ng transaksyon ay ipinadala sa isang single node sa pamamagitan ng GRPC API, at natanggap ang mga resibo sa pamamagitan ng JSON-RPC API. Pagkatapos ng lahat ng transaksyon, binasa mula sa bawat block ang impormasyon ng gas, gamit ang paraan na eth_getBlockByNumber JSON-RPC. + +Hindi namin layunin na magsikap na maabot ang maximum na posibleng TPS, +dahil ang block gas limit at tagal ng block ay nakatakda sa mga naaangkop na value na hindi masyadong gumagamit ng mga resource ng system, at na magbibigay-daan dito na tumakbo gamit ang commodity hardware. + +### Mga Resulta sa ERC20 {#results-erc20} + +| Metric | Value | +| ------ | ----- | +| Uri ng transaksyon | ERC20 | +| Mga transaksyon kada segundo | 65 | +| Pumalya ang mga transaksyon | 0 | +| Nagtagumpay ang mga transaksyon | 5000 | +| Tagal ng pagtakbo ng transaksyon sa ERC20 | 76.681690s | +| Tagal ng Pag-deploy ng SC | 4.048250s | + +### Mga Resulta sa ERC721 {#results-erc721} + +| Metric | Value | +| ------ | ----- | +| Uri ng transaksyon | ERC721 | +| Mga transaksyon kada segundo | 20 | +| Pumalya ang mga transaksyon | 0 | +| Nagtagumpay ang mga transaksyon | 2000 | +| Tagal ng pagtakbo ng transaksyon sa ERC721 | 97.239920s | +| Tagal ng Pag-deploy ng SC | 3.048970s | + +### Environment ERC20 {#environment-erc20} + +
+ Configuration ng Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Size ng instancet2.micro
Networkingpribadong subnet
Operating systemLinux Ubuntu 20.04 LTS - Focal Fossa
File descriptor limit65535
Max na mga proseso ng user65535
+
+
+
+
+ +
+ Configuration ng Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bersyong Polygon EdgeI-commit ang 8a033aa1afb191abdac04636d318f83f32511f3c sa develop branch
Mga validator node6
Mga non-validator node0
ConsensusIBFT PoA
Block time2s
Block gas limit5242880
Average na utilization ng block95%
+
+
+
+
+ +
+ Configuration ng Loadbot +
+
+ + + + + + + + + + + + + +
Kabuuang Bilang ng Mga Transaksyon5000
Mga transaksyong naipapadala kada segundo200
Uri ng mga transaksyonMga ERC20 to ERC20 na paglilipat
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### Environment ERC721 {#environment-erc721} + +
+ Configuration ng Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Size ng instancet2.micro
Networkingpribadong subnet
Operating systemLinux Ubuntu 20.04 LTS - Focal Fossa
File descriptor limit65535
Max na mga proseso ng user65535
+
+
+
+
+ +
+ Configuration ng Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bersyong Polygon EdgeI-commit ang 8a033aa1afb191abdac04636d318f83f32511f3c sa develop branch
Mga validator node6
Mga non-validator node0
ConsensusIBFT PoA
Block time2s
Block gas limit5242880
Average na utilization ng block94%
+
+
+
+
+ +
+ Configuration ng Loadbot +
+
+ + + + + + + + + + + + + +
Kabuuang Bilang ng Mga Transaksyon2000
Mga transaksyong naipapadala kada segundo200
Uri ng mga transaksyonPag-mint ng ERC721 token
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/tl-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/tl-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..ab51fdad20 --- /dev/null +++ b/archive/edge/tl-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,960 @@ +--- +id: test-2022-03-23 +title: Ika-23 ng Marso 2022 +description: "Pagsubok sa performance mula ika-23 ng Marso." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### Buod {#summary} + +:::caution +Mangyaring tandaan na ang aming , na ginamit para sa pagsasagawa ng mga pagsubok `loadbot`na ito, ay niloloko na ngayon. +::: + +Isinagawa ang pagsubok na ito para masukat ang mga paglipat ng SC ERC20 token, pag-mint ng SC ERC721 token, at functionality ng mga EOA to EOA na transaksyon sa pamamagitan ng mabibigat na load at bilis ng mga transaksyon sa mga node na mas mataas ang mga hardware resource. + +Ang layunin ay tingnan kung ang lahat ay gumagana tulad ng inaasahan sa mabibigat na load. Iyon din ang dahilan kung bakit namin idinagdag ang mga gas metric sa output ng loadbot, na nagpapakita sa amin kung ang mga block ay maayos na nalalagyan ng mga transaksyon. + +Ang lahat ng transaksyon ay ipinadala sa isang single node sa pamamagitan ng GRPC API, at natanggap ang mga resibo sa pamamagitan ng JSON-RPC API. Pagkatapos ng lahat ng transaksyon, binasa mula sa bawat block ang impormasyon ng gas, gamit ang paraan na eth_getBlockByNumber JSON-RPC. + +Layunin namin na makaabot ng maximum na posibleng TPS sa mga hardware resource na available. +Upang maabot ito, binago namin ang mga parameter na block gas limit at block time, para maibigay sa amin ang pinakamahuhusay na posibleng resulta ng tps at mapanatili ang integridad at katatagan ng system. + +:::info Block Gas Limit + +Maaaring mapataas ang block gas limit sa medyo mataas na numero kung ang mga transaksyon ay gumagamit ng maraming gas para makapagsagawa. +Sa halimbawang nakasaad sa ibaba, naisagawa ang pag-mint ng ERC721 token nang lubos na mas mabilis kapag nakatakda ang block gas limit sa 80 000 000 (sa halip na 20 Mil.), ngunit sa mga paglipat ng ERC20 token na may nakatakdang 80 Mil. na block gas limit, nag-crash ang server. + +::: + +:::info Mga Environment ng Produksyon + +Kapag nagko-configure ng environment ng produksyon, kailangan mong mag-ingat kung sinusubukan mong makakuha ng mataas na performance ng chain. +Kung nakatakda sa mataas na value ang parameter na block gas limit, ang block time ay nakatakda sa 1s, at may mataas na load ng transaksyon sa isang single node, ang node na iyon ay gagamit ng maraming (kung hindi ang lahat ng available) RAM at maaari itong magresulta sa pag-crash ng server. +Gamitin ang loadbot para ganap na masubukan ang lahat, subaybayan ang utilization ng resource ng system at itakda ang iyong mga parameter ng configuration nang naaayon. + +::: + +:::info Mga Out of Memory Error + +Awtomatikong papatayin ng ilang linux distro ang prosesong may napakataas na paggamit ng RAM (OOM error), upang mapanatili ang katatagan ng system. +Ang log output ng OOM error na ito ay mukhang katulad ng nasa ibaba. +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### Mga resulta ng mga EOA to EOA na paglilipat {#results-of-eoa-to-eoa-transfers} +| Metric | Value | +| ------ | ----- | +| Uri ng transaksyon | EOA to EOA | +| Mga transaksyon kada segundo | 689 | +| Pumalya ang mga transaksyon | 0 | +| Nagtagumpay ang mga transaksyon | 20000 | +| Kauuang bilang ng mga block na ginagamit | 25 | +| Kabuuang run time | 29.921110s | + +### Mga resulta ng mga paglilipat ng ERC20 token {#results-of-erc20-token-transfers} + +| Metric | Value | +| ------ | ----- | +| Uri ng transaksyon | ERC20 | +| Mga transaksyon kada segundo | 500 | +| Pumalya ang mga transaksyon | 0 | +| Nagtagumpay ang mga transaksyon | 20000 | +| Kauuang bilang ng mga block na ginagamit | 33 | +| Tagal ng pagtakbo ng transaksyon sa ERC20 | 40.402900s | +| Tagal ng Pag-deploy ng SC | 2.004140s | + +### Mga resulta ng pag-mint ng ERC721 token {#results-of-erc721-token-minting} + +| Metric | Value | +| ------ | ----- | +| Uri ng transaksyon | ERC721 | +| Mga transaksyon kada segundo | 157 | +| Pumalya ang mga transaksyon | 0 | +| Nagtagumpay ang mga transaksyon | 20000 | +| Kauuang bilang ng mga block na ginagamit | 124 | +| Tagal ng pagtakbo ng transaksyon sa ERC721 | 127.537340s | +| Tagal ng Pag-deploy ng SC | 2.004420s | + + +### Mga resulta ng pag-mint ng ERC721 token na may napakataas na block gas limit (80 Mil.) {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| Metric | Value | +| ------ | ----- | +| Uri ng transaksyon | ERC721 | +| Mga transaksyon kada segundo | 487 | +| Pumalya ang mga transaksyon | 0 | +| Nagtagumpay ang mga transaksyon | 20000 | +| Kauuang bilang ng mga block na ginagamit | 34 | +| Tagal ng pagtakbo ng transaksyon sa ERC721 | 41.098410s | +| Tagal ng Pag-deploy ng SC | 2.004300s | + + +### Environment na EOA to EOA {#environment-eoa-to-eoa} +
+ Configuration ng Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Size ng instancec5.2xlarge
Networkingpribadong subnet
Operating systemAmazon Linux 2 AMI (HVM) - Kernel 5.10
File descriptor limit65535
Max na mga proseso ng user65535
+
+
+
+
+ +
+ Configuration ng Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bersyong Polygon EdgeI-commit ang 06e11eac8da98c79c938fc53dda2da3318cfbe04 sa develop branch
Mga validator node4
Mga non-validator node0
ConsensusIBFT PoA
Block time1s
Block gas limit20000000
Max na mga slot1000000
Average na utilization ng block84.00%
+
+
+
+
+ +
+ Configuration ng Loadbot +
+
+ + + + + + + + + + + + + +
Kabuuang Bilang ng Mga Transaksyon20000
Mga transaksyong naipapadala kada segundo689
Uri ng mga transaksyonMga EOA to EOA na paglilipat
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### Environment ERC20 {#environment-erc20} +
+ Configuration ng Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Size ng instancec5.2xlarge
Networkingpribadong subnet
Operating systemAmazon Linux 2 AMI (HVM) - Kernel 5.10
File descriptor limit65535
Max na mga proseso ng user65535
+
+
+
+
+ +
+ Configuration ng Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bersyong Polygon EdgeI-commit ang 06e11eac8da98c79c938fc53dda2da3318cfbe04 sa develop branch
Mga validator node4
Mga non-validator node0
ConsensusIBFT PoA
Block time1s
Block gas limit20000000
Max na mga slot1000000
Average na utilization ng block88.38%
+
+
+
+
+ +
+ Configuration ng Loadbot +
+
+ + + + + + + + + + + + + +
Kabuuang Bilang ng Mga Transaksyon20000
Mga transaksyong naipapadala kada segundo500
Uri ng mga transaksyonMga ERC20 to ERC20 na paglilipat
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### Environment ERC721 {#environment-erc721} +
+ Configuration ng Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Size ng instancec5.2xlarge
Networkingpribadong subnet
Operating systemAmazon Linux 2 AMI (HVM) - Kernel 5.10
File descriptor limit65535
Max na mga proseso ng user65535
+
+
+
+
+ +
+ Configuration ng Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bersyong Polygon EdgeI-commit ang 06e11eac8da98c79c938fc53dda2da3318cfbe04 sa develop branch
Mga validator node4
Mga non-validator node0
ConsensusIBFT PoA
Block time1s
Block gas limit20000000
Max na mga slot1000000
Average na utilization ng block92.90%
+
+
+
+
+ +
+ Configuration ng Loadbot +
+
+ + + + + + + + + + + + + +
Kabuuang Bilang ng Mga Transaksyon20000
Mga transaksyong naipapadala kada segundo157
Uri ng mga transaksyonPag-mint ng ERC721 token
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### Environment ERC20 - napakataas na limitaasyon sa gas kada block {#environment-erc20-very-high-block-gas-limit} +
+ Configuration ng Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Size ng instancec5.2xlarge
Networkingpribadong subnet
Operating systemAmazon Linux 2 AMI (HVM) - Kernel 5.10
File descriptor limit65535
Max na mga proseso ng user65535
+
+
+
+
+ +
+ Configuration ng Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bersyong Polygon EdgeI-commit ang 06e11eac8da98c79c938fc53dda2da3318cfbe04 sa develop branch
Mga validator node4
Mga non-validator node0
ConsensusIBFT PoA
Block time1s
Block gas limit80000000
Max na mga slot1000000
Average na utilization ng block---
+
+
+
+
+ +
+ Configuration ng Loadbot +
+
+ + + + + + + + + + + + + +
Kabuuang Bilang ng Mga Transaksyon20000
Mga transaksyong naipapadala kada segundo---
Uri ng mga transaksyonMga ERC20 to ERC20 na paglilipat
+
+
+
+
+ +
+ Log ng OOM Error + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### Environment ERC721 - napakataas na limitasyon sa gas kada block {#environment-erc721-very-high-block-gas-limit} +
+ Configuration ng Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS
Size ng instancec5.2xlarge
Networkingpribadong subnet
Operating systemAmazon Linux 2 AMI (HVM) - Kernel 5.10
File descriptor limit65535
Max na mga proseso ng user65535
+
+
+
+
+ +
+ Configuration ng Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bersyong Polygon EdgeI-commit ang 06e11eac8da98c79c938fc53dda2da3318cfbe04 sa develop branch
Mga validator node4
Mga non-validator node0
ConsensusIBFT PoA
Block time1s
Block gas limit80000000
Max na mga slot1000000
Average na utilization ng block84.68%
+
+
+
+
+ +
+ Configuration ng Loadbot +
+
+ + + + + + + + + + + + + +
Kabuuang Bilang ng Mga Transaksyon20000
Mga transaksyong naipapadala kada segundo487
Uri ng mga transaksyonPag-mint ng ERC721 token
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/tl-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/tl-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..d10560900d --- /dev/null +++ b/archive/edge/tl-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,568 @@ +--- +id: test-2022-07-04 +title: Ika-4 ng Hulyo 2022 +description: "Performance test mula ika-4 ng Hulyo." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### Buod {#summary} + +:::caution +Mangyaring tandaan na ang aming , na ginamit para sa pagsasagawa ng mga pagsubok `loadbot`na ito, ay niloloko na ngayon. +::: + +Isinagawa ang pagsubok na ito para masukat ang mga paglipat ng SC ERC20 token, pag-mint ng SC ERC721 token, at functionality ng mga EOA to EOA na transaksyon sa pamamagitan ng mabibigat na load at bilis ng mga transaksyon sa mga node na mas mataas ang mga hardware resource. + +Ang layunin ay tingnan kung ang lahat ay gumagana tulad ng inaasahan sa mabibigat na load. Iyon din ang dahilan kung bakit namin idinagdag ang mga gas metric sa output ng loadbot, na nagpapakita sa amin kung ang mga block ay maayos na nalalagyan ng mga transaksyon. + +Ang lahat ng transaksyon ay ipinadala sa isang single node sa pamamagitan ng GRPC API, at natanggap ang mga resibo sa pamamagitan ng JSON-RPC API. Pagkatapos ng lahat ng transaksyon, binasa mula sa bawat block ang impormasyon ng gas, gamit ang paraan na eth_getBlockByNumber JSON-RPC. + +Layunin namin na makaabot ng maximum na posibleng TPS sa mga hardware resource na available. +Upang maabot ito, binago namin ang mga parameter na block gas limit at block time, para maibigay sa amin ang pinakamahuhusay na posibleng resulta ng tps at mapanatili ang integridad at katatagan ng system. + + +:::info Mga Environment ng Produksyon + +Kapag nagko-configure ng environment ng produksyon, kailangan mong mag-ingat kung sinusubukan mong makakuha ng mataas na performance ng chain. +Kung nakatakda sa mataas na value ang parameter na block gas limit, ang block time ay nakatakda sa 1s, at may mataas na load ng transaksyon sa isang single node, ang node na iyon ay gagamit ng maraming (kung hindi ang lahat ng available) RAM at maaari itong magresulta sa pag-crash ng server. +Gamitin ang loadbot para ganap na masubukan ang lahat, subaybayan ang utilization ng resource ng system at itakda ang iyong mga parameter ng configuration nang naaayon. + +::: + + + +### Mga resulta ng mga EOA to EOA na paglilipat {#results-of-eoa-to-eoa-transfers} +| Metric | Value | +| ------ | ----- | +| Uri ng transaksyon | EOA to EOA | +| Mga transaksyon kada segundo | 1428 | +| Pumalya ang mga transaksyon | 0 | +| Nagtagumpay ang mga transaksyon | 30000 | +| Kauuang bilang ng mga block na ginagamit | 15 | +| Kabuuang run time | 21.374620s | + +### Mga resulta ng mga paglilipat ng ERC20 token {#results-of-erc20-token-transfers} + +| Metric | Value | +| ------ | ----- | +| Uri ng transaksyon | ERC20 | +| Mga transaksyon kada segundo | 1111 | +| Pumalya ang mga transaksyon | 0 | +| Nagtagumpay ang mga transaksyon | 50000 | +| Kauuang bilang ng mga block na ginagamit | 38 | +| Tagal ng pagtakbo ng transaksyon sa ERC20 | 45.906450s | +| Tagal ng Pag-deploy ng SC | 2.006580s | + +### Mga resulta ng pag-mint ng ERC721 token {#results-of-erc721-token-minting} + +| Metric | Value | +| ------ | ----- | +| Uri ng transaksyon | ERC721 | +| Mga transaksyon kada segundo | 714 | +| Pumalya ang mga transaksyon | 0 | +| Nagtagumpay ang mga transaksyon | 30000 | +| Kauuang bilang ng mga block na ginagamit | 39 | +| Tagal ng pagtakbo ng transaksyon sa ERC721 | 42.864140s | +| Tagal ng Pag-deploy ng SC | 2.005500s | + + + + +### Environment na EOA to EOA {#environment-eoa-to-eoa} +
+ Configuration ng Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS EC2
Size ng instancec6a.48xlarge
Networkingpribadong subnet
Operating systemLinux Ubuntu 20.04 LTS - Focal Fossa
File descriptor limit65535
Max na mga proseso ng user65535
+
+
+
+
+ +
+ Configuration ng Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bersyong Polygon EdgeRelease v0.4.1
Mga validator node4
Mga non-validator node0
ConsensusIBFT PoA
Block time1s
Block gas limit70778880
Max na mga slot276480
Average na utilization ng block59.34%
+
+
+
+
+ +
+ Configuration ng Loadbot +
+
+ + + + + + + + + + + + + +
Kabuuang Bilang ng Mga Transaksyon30000
Mga transaksyong naipapadala kada segundo1428
Uri ng mga transaksyonMga EOA to EOA na paglilipat
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### Environment ERC20 {#environment-erc20} +
+ Configuration ng Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS EC2
Size ng instancec6a.48xlarge
Networkingpribadong subnet
Operating systemLinux Ubuntu 20.04 LTS - Focal Fossa
File descriptor limit65535
Max na mga proseso ng user65535
+
+
+
+
+ +
+ Configuration ng Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bersyong Polygon EdgeRelease v0.4.1
Mga validator node4
Mga non-validator node0
ConsensusIBFT PoA
Block time1s
Block gas limit47185920
Max na mga slot184320
Average na utilization ng block81.29%
+
+
+
+
+ +
+ Configuration ng Loadbot +
+
+ + + + + + + + + + + + + +
Kabuuang Bilang ng Mga Transaksyon50000
Mga transaksyong naipapadala kada segundo1111
Uri ng mga transaksyonMga ERC20 to ERC20 na paglilipat
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### Environment ERC721 {#environment-erc721} +
+ Configuration ng Host +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Cloud providerAWS EC2
Size ng instancec6a.48xlarge
Networkingpribadong subnet
Operating systemLinux Ubuntu 20.04 LTS - Focal Fossa
File descriptor limit65535
Max na mga proseso ng user65535
+
+
+
+
+ +
+ Configuration ng Blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bersyong Polygon EdgeRelease v0.4.1
Mga validator node4
Mga non-validator node0
ConsensusIBFT PoA
Block time1s
Block gas limit94371840
Max na mga slot1000000
Average na utilization ng block93.88%
+
+
+
+
+ +
+ Configuration ng Loadbot +
+
+ + + + + + + + + + + + + +
Kabuuang Bilang ng Mga Transaksyon30000
Mga transaksyong naipapadala kada segundo714
Uri ng mga transaksyonPag-mint ng ERC721 token
+
+
+
+
+ +
+ Loadbot log + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/tl-edge/troubleshooting.md b/archive/edge/tl-edge/troubleshooting.md new file mode 100644 index 0000000000..a4ccbec172 --- /dev/null +++ b/archive/edge/tl-edge/troubleshooting.md @@ -0,0 +1,71 @@ +--- +id: troubleshooting +title: Pag-troubleshoot +description: "Seksyong Pag-troubleshoot para sa Polygon Edge" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# Pag-troubleshoot {#troubleshooting} + +## `method=eth_call err="invalid signature"` ng error {#error} + +Kapag gumagamit ka ng wallet para gumawa ng transaksyon sa Polygon Edge, tiyakin na sa setup ng lokal na network ng iyong wallet: + +1. Ang `chainID` ay ang tama Ang default na `chainID` para sa Edge ay `100`, ngunit maaari itong i-customize gamit ang genesis flag na `--chain-id`. + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. Tiyakin na sa “RPC URL” field, ginagamit mo ang JSON RPC port ng node kung saan ka kumokonekta. + + +## Paano makakuha ng WebSocket URL {#how-to-get-a-websocket-url} + +Bilang default, kapag pinatakbo mo ang Polygon Edge, nagpapakita ito ng WebSocket endpoint batay sa lokasyon ng chain. +Ang URL scheme na `wss://` ay ginagamit para sa mga HTTPS link, at `ws://` para sa HTTP. + +Localhost WebSocket URL: +````bash +ws://:/ws +```` +Mangyaring tandaan na ang port number ay nakadepende sa napiling JSON-RPC port para sa node. + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## `insufficient funds` error kapag sinusubukang mag-deploy ng kontrata {#error-when-trying-to-deploy-a-contract} + +Kung makakaranas ka ng ganitong error, mangyaring tiyakin na mayroon kang sapat na mga pondo sa gustong address, at ang address na ginagamit ay ang tamang address.
+Para maitakda ang premined na balanse, maaari mong gamitin ang genesis flag na `genesis [--premine ADDRESS:VALUE]` habang binubuo ang genesis file. +Halimbawa ng paggamit ng flag na ito: +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +Nagpi-premine ito ng 1000000000000000000000 WEI sa 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862. + + +## Hindi inire-release ang mga ERC20 token habang ginagamit ang Chainbridge {#erc20-tokens-not-released-while-using-chainbridge} + +Kung susubukan mong maglipat ng mga ERC20 token sa pagitan ng Polygon POS at isang lokal na Edge network, at naideposito ang iyong mga ERC20 token, at naisagawa ang proposal sa relayer, ngunit hindi na-release ang mga token sa iyong Edge network, mangyaring tiyakin na ang ERC20 Handler sa Polygon Edge chain ay may sapat na mga token na maire-release.
+Ang kontrata ng Handler sa destination na chain ay mayroon dapat sapat na mga token na maire-release para sa lock-release mode. Kung wala kang anumang ERC20 token sa ERC20 Handler ng iyong lokal na Edge network, mag-mint ng mga bagong token at ilipat ang mga ito sa ERC20 Handler. + +## `Incorrect fee supplied` error kapag ginagamit ang Chainbridge {#error-when-using-chainbridge} + +Maaari kang makaranas ng ganitong error kapag sinusubukang maglipat ng mga ERC20 token sa pagitan ng Mumbai Polygon POS chain at isang lokal na setup ng Polygon Edge. Lumalabas ang ganitong error kapag itinakda mo ang bayad sa pag-deploy gamit ang `--fee` flag, ngunit hindi mo itinakda ang parehong value sa deposit na transaksyon. +Maaari mong gamitin ang command sa ibaba para baguhin ang bayad: +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +Makakahanap ka ng karagdagang impormasyon tungkol sa bandilang ito [dito](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md). + + + + + diff --git a/archive/edge/tl-edge/validator-hosting.md b/archive/edge/tl-edge/validator-hosting.md new file mode 100644 index 0000000000..f61407a80e --- /dev/null +++ b/archive/edge/tl-edge/validator-hosting.md @@ -0,0 +1,265 @@ +--- +id: validator-hosting +title: Pag-host ng Validator +description: "Mga kinakailangan sa pag-host para sa Polygon Edge" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +Makikita sa ibaba ang mga mungkahi para sa maayos na pag-host ng isang validator node sa isang Polygon Edge network. Mangyaring maingat na bigyang-pansin ang lahat ng mga bagay na nakalista sa ibaba para matiyak +na ang iyong pag-setup ng validator ay maayos na na-configure para maging ligtas, matatag, at gumagana. + +## Batayang kaalaman {#knowledge-base} + +Bago subukang patakbuhin ang validator node, mangyaring basahin nang mabuti ang dokumentong ito. +Ang mga karagdagang dokumento na maaaring makatulong ay: + +- [Pag-install](get-started/installation) +- [Pag-setup sa Cloud](get-started/set-up-ibft-on-the-cloud) +- [Mga CLI Command](get-started/cli-commands) +- [Server config file](configuration/sample-config) +- [Mga pribadong key](configuration/manage-private-keys) +- [Prometheus metrics](configuration/prometheus-metrics) +- [Mga secret manager](/docs/category/secret-managers) +- [Pag-backup/Pag-restore](working-with-node/backup-restore) + +## Minimum na kailangan ng sytem {#minimum-system-requirements} + +| Uri | Value | Inimpluwensiyahan ng | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 2 core |
  • Bilang ng mga JSON-RPC query
  • Size ng blockchain state
  • Block gas limit
  • Block time
| +| RAM | 2 GB |
  • Bilang ng mga JSON-RPC query
  • Size ng blockchain state
  • Block gas limit
| +| Disk |
  • 10 GB root partition
  • 30 GB root partition na may LVM para sa disk extension
|
  • Size ng blockchain state
| + + +## Service configuration {#service-configuration} + +Kailangang awtomatikong tumakbo ang `polygon-edge` binary bilang isang system service pagkatapos ma-establish ang network connectivity at mayroong simulan / itigil / i-restart +na mga functionality. Inirerekomenda namin ang paggamit ng isang service manager tulad ng `systemd.` + +Halimbawa `systemd`system configuration file: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### Binary {#binary} + +Sa mga production workload dapat na i-deploy ang `polygon-edge` binary mula sa mga pre-built GitHub release binary - hindi sa manual na pag-compile. +:::info + +Sa pamamagitan ng manual na pag-compile ng `develop` GitHub branch, maaari mong ipakilala ang mga breaking change sa iyong environment. +Sa dahilang iyon, inirerekomendang i-deploy lamang ang Polygon Edge binary mula sa mga release, dahil naglalaman ito ng +impormasyon tungkol sa mga breaking change at kung paano pagtagumpayan ang mga ito. + +::: + +Mangyaring tingnan ang [Pag-install](/docs/edge/get-started/installation) para sa isang kumpletong pangkalahatang-ideya ng paraan ng pag-install. + +### Data storage {#data-storage} + +Ang `data/` folder na naglalaman ng kabuuang blockchain state ay dapat i-mount sa isang partikular na disk / volume na para sa +awtomatikong disk backup, volume extension at opsyonal na pag-mount ng disk/volume sa ibang instance kung sakaling magkaroon ng pagpalya. + + +### Mga log file {#log-files} + +Kailangang paikutin ang mga log araw-araw (gamit ang tool tulad ng `logrotate`). +:::warning + +Kung naka-configure nang walang log rotation, maaaring ubusin ng mga log file ang lahat ng available na disk space na maaaring makagambala sa validator uptime. + +::: + +Halimbawang `logrotate` configuration: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +Sumangguni sa [Logging](#logging) na seksyon sa ibaba para sa mga rekomendasyon sa log storage. + +### Karagdagang mga dependency {#additional-dependencies} + +`polygon-edge` ay na-compile nang hindi nagbabago, na hindi nangangailangan ng mga karagdagang host OS dependency. + +## Maintenance {#maintenance} + +Makikita sa ibaba ang mga pinakamahusay na gawain para ma-maintain ang isang gumaganang validator node ng isang Polygon Edge network. + +### Pag-backup {#backup} + +May dalawang uri ng mga pamamaraan sa pag-back up na inirerekomenda para sa mga Polygon Edge node. + +Ang mungkahi ay gamitin itong pareho, hangga't maaari, na ang Polygon Edge backup ang laging available na opsyon. + +* Pag-***backup ng Volume*** + Araw-araw na incremental backup ng `data/` volume ng Polygon Edge node, o ng kumpletong VM kung posible. + + +* ***Polygon Edge backup***: + Inirerekomenda ang araw-araw na CRON job na ginagawa ang mga regular na pag-backup ng Polygon Edge at inililipat ang mga `.dat` file sa isang offsite na lokasyon o sa isang ligtas na cloud object storage. + +Ang Polygon Edge backup ay hindi dapat mag-overlap sa Volume backup na inilarawan sa itaas. + +Sumangguni sa [Pag-backup/ibalik na node instance](working-with-node/backup-restore) para sa mga tagubilin kung paano isagawa ang mga backup sa Polygon Edge. + +### Pag-log {#logging} + +Ang mga log na in-output ng mga Polygon Edge node ay dapat: +- ipadala sa isang external data store na may kakayahan sa indexing at pag-search +- mayroong panahon ng log retention na 30 araw + +Kung ito ang unang beses mong pag-set up ng isang Polygon Edge validator, inirerekomenda naming simulan ang node +gamit ang `--log-level=DEBUG` na opsyon para mabilis na i-debug ang anumang mga isyung maaari mong makaharap. + +:::info + +Ang`--log-level=DEBUG` ay gagawing verbose ang log output ng node hangga't maaari. +Ang mga debug log ay mabilis na magdadagdag sa size ng log file at dapat isaalang-alang kapag nag-set up +ng log rotation solution. + +::: +### Mga OS security patch {#os-security-patches} + +Kailangan tiyakin ng mga administrator na ang validator instance OS ay palaging updated sa mga pinakabagong patch nang hindi bababa sa isang beses bawat buwan. + +## Metrics {#metrics} + +### Metrics ng system {#system-metrics} + +Kailangang i-setup ng mga administrator ang ilang uri ng pag-monitor sa metrics ng system, (hal. Telegraf + InfluxDB + Grafana o isang 3rd party SaaS). + +Metrics na kailangang masubaybayan at kailangang magkaroon ng alarm notification setup: + +| Pangalan ng metric | Alarm threshold | +|-----------------------|-------------------------------| +| CPU usage (%) | > 90% sa loob ng higit sa 5 minuto | +| RAM utilization (%) | > 90% sa loob ng higit sa 5 minuto | +| Root disk utilization | > 90% | +| Data disk utilization | > 90% | + +### Validator metrics {#validator-metrics} + +Kailangang i-setup ng mga administrator ang koleksyon ng metrics mula sa Polygon Edge Prometheus API para +masubaybayan ang blockchain performance. + +Sumangguni sa [Prometheus metrics](configuration/prometheus-metrics) para maunawaan kung aling metrics ang inilantad at kung paano i-set up ang Prometheus metric collection. + + +Kailangan ng karagdagang pansin sa sumusunod na metrics: +- ***Panahon ng block production*** - kung ang panahon ng block production ay mas mataas kaysa sa normal, mayroong potensyal na problema sa network +- ***Bilang ng mga consensus round*** - kung mayroong higit sa 1 round, mayroong potensyal na problema sa validator na nakatakda sa network +- ***Bilang ng mga peer*** - kung bumaba ang bilang ng mga peer, mayroong isyu sa koneksyon sa network + +## Seguridad {#security} + +Makikita sa ibaba ang mga pinakamahusay na gawain para panatilihing ligtas ang isang gumaganang validator node ng isang Polygon Edge network. + +### Mga serbisyo ng API {#api-services} + +- ***JSON-RPC*** - +Tanging ang API service lamang ang kailangang ilantad sa publiko (sa pamamagitan ng load balancer o direkta). +Ang API na ito ay dapat gumana sa lahat ng mga interface o sa espisipikong IP address (halimbawa: `--json-rpc 0.0.0.0:8545` o `--json-prc 192.168.1.1:8545`). +:::info + +Dahil ito ay pampublikong API, inirerekomendang magkaroon ng load balancer / reverse proxy sa front nito para maglaan ng seguridad at rate limiting. + +::: + + +- ***LibP2P*** - +Ito ang networking API na ginagamit ng mga node para sa peer communication. Kailangang gumana ito sa lahat ng mga interface o sa isang espisipikong ip address +(`--libp2p 0.0.0.0:1478` o `--libp2p 192.168.1.1:1478`). Ang API na ito ay hindi dapat ilantad sa publiko, +ngunit dapat itong maabot mula sa lahat ng iba pang mga node. +:::info + +Kung tumakbo sa localhost ( `--libp2p 127.0.0.1:1478` ) hindi makaka-connect ang ibang mga node. + +::: + + +- ***GRPC*** - +Ang API na ito ay ginagamit lamang para sa pagpapatakbo ng mga operator command at wala nang iba pa. Kaya dapat itong tumakbo lamang sa localhost (`--grpc-address 127.0.0.1:9632`). + +### Mga Polygon Edge secret {#polygon-edge-secrets} + +Ang mga Polygon Edge secret (`ibft` at `libp2p` key) ay hindi dapat i-imbak sa isang local file system. +Sa halip, dapat gamitin ang isang suportadong [Secret Manager](configuration/secret-managers/set-up-aws-ssm). +Ang pag-imbak ng mga secret sa local file system ay dapat lamang gamitin sa mga non-production environment. + +## Update {#update} + +Ang sumusunod ay ang inirerekomendang update procedure para sa mga validator node, na inilarawan nang step-by-step na mga tagubilin. + +### Update procedure {#update-procedure} + +- I-download ang pinakabagong Polygon Edge binary mula sa opisyal na mga GitHub [release](https://github.com/0xPolygon/polygon-edge/releases) +- Ihinto ang Polygon Edge service (halimbawa: `sudo systemctl stop polygon-edge.service`) +- Palitan ang umiiral na `polygon-edge` binary na gamit ang na-download na (halimbawa: `sudo mv polygon-edge /usr/local/bin/`) +- Tingnan kung tama ang `polygon-edge` bersyon sa pamamagitan ng pagpapatakbo ng `polygon-edge version` - dapat na katugma ito ng bersyon ng release +- Tingnan ang dokumentasyon ng release kung mayroong mga backwards compatibility step na kailangang gawin bago simulan ang `polygon-edge` service +- Simulan ang `polygon-edge` service (halimbawa: `sudo systemctl start polygon-edge.service`) +- Panghuli, tingnan ang `polygon-edge` log output at tiyaking tumatakbo ang lahat nang walang anumang mga `[ERROR]` log + +:::warning + +Kapag mayroong breaking release, dapat isagawa ang update procedure na ito sa lahat ng mga node dahil +ang kasalukuyang tumatakbong binary ay hindi compatible sa bagong release. + +Nangangahulugan ito na dapat ihinto ang chain nang pansamantala (hanggang ang mga `polygon-edge` binary ay mapalitan o ma-restart ang service) +kaya planuhin nang maayos. + +Maaari kang gumamit ng mga tool tulad ng **[Ansible](https://www.ansible.com/)** o ng custom script para maisagawa nang mahusay ang update +at mabasawan ang chain downtime. + +::: + +## Startup procedure {#startup-procedure} + +Ang sumusunod ay ang inirerekomendang daloy ng startup procedure para sa Polygon Edge validator + +- Basahin ang mga dokumento na nakalista sa [Batayang Kaalaman](#knowledge-base) na seksyon +- I-apply ang pinakabagong mga OS patch sa validator node +- I-download ang pinakabagong `polygon-edge` binary mula sa opisyal na mga GitHub [release](https://github.com/0xPolygon/polygon-edge/releases) at ilagay ito sa local instance `PATH` +- Simulan ang isa sa mga suportadong [secret manager](/docs/category/secret-managers) gamit ang `polygon-edge secrets generate` CLI command +- Bumuo at mag-imbak ng mga secret gamit ang `polygon-edge secrets init` [CLI command](/docs/edge/get-started/cli-commands#secrets-init-flags) +- Tandaan ang mga `NodeID` at `Public key (address)` na value +- Buuin ang `genesis.json` file na inilarawan sa [pag-setup sa cloud](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators) gamit ang `polygon-edge genesis` [CLI command](/docs/edge/get-started/cli-commands#genesis-flags) +- Buuin ang default config file gamit ang `polygon-edge server export` [CLI command](/docs/edge/configuration/sample-config) +- I-edit ang `default-config.yaml` file para ma-accommodate ang local validator node environment (mga file path, atbp.) +- Gumawa ng isang Polygon Edge service (`systemd` o katulad) kung saan ang patatakbuhin ng `polygon-edge` binary ang server mula sa isang `default-config.yaml` file +- Simulan ang Polygon Edge server sa pamamagitan ng pagsisimula ng service (halimbawa: `systemctl start polygon-edge`) +- Tingnan ang mga `polygon-edge` log output at tiyaking nabubuo ang mga block at walang mga `[ERROR]` log +- Tingnan ang functionality ng chain sa pamamagitan ng pagtawag ng isang JSON-RPC na pamamaraan tulad ng [`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid) diff --git a/archive/edge/tl-edge/working-with-node/backup-restore.md b/archive/edge/tl-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..255a0c72f4 --- /dev/null +++ b/archive/edge/tl-edge/working-with-node/backup-restore.md @@ -0,0 +1,92 @@ +--- +id: backup-restore +title: Backup/restore ng node instance +description: "Kung paano i-back up at i-restore ang Polygon Edge node instance." +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## Pangkalahatang-ideya {#overview} + +Ang gabay na ito ay nagdedetalye kung paano i-back up at mai-restore ang isang Polygon Edge node instance. +Sinasaklaw nito ang mga base folder at kung ano ang kanilang nilalaman, pati na rin kung anong mga file ang kritikal para sa pagsasagawa ng isang matagumpay na pag-back up at pag-restore. + +## Mga base folder {#base-folders} + +Gumagamit ang Polygon Edge ng LevelDB bilang storage engine nito. +Kapag nagpapasimula ng isang Polygon Edge node, ang mga sumusunod na sub-folder ay nililikha sa tinukoy na working directory: +* **blockchain** - Nag-iimbak ng blockchain data +* **trie** - Nag-iimbak ng mga Merkle trie (world state data) +* **keystore** - Nag-iimbak ng mga pribadong key para sa client. Kabilang dito ang pribadong key ng libp2p at ang pribadong key ng sealing/validator +* **consensus** - Nag-iimbak ng anumang impormasyon ng consensus na maaaring kailanganin ng client habang gumagawa. Sa ngayon, nag-iimbak ito ng *pribadong validator key* ng node + +Mahalaga para sa mga folder na ito na mapangalagaan para gumana nang maayos ang Polygon Edge instance. + +## Gumawa ng backup mula sa isang gumaganang node at ibalik para sa bagong node {#create-backup-from-a-running-node-and-restore-for-new-node} + +Ang seksyong ito ay gumagabay sa iyo sa paglikha ng archive data ng blockchain sa isang gumaganang node at pagpapanumbalik nito sa ibang instance. + +### Pag-backup {#backup} + +Ang `backup`command ay nagpapadala ng mga block mula sa isang gumaganang node sa pamamagitan ng gRPC at bumubuo ng isang archive file. Kung ang `--from` at `--to` ay wala sa command, ang command na ito ay magdadala ng mga block mula genesis hanggang sa pinakabago. + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### Pag-restore {#restore} + +Ang isang server ay nagsisimulang mag-import mula sa isang archive kapag nagsisimula sa `--restore` flag. Mangyaring tiyakin na mayroong key para sa bagong node. Para malaman ang higit pa tungkol sa pag-import o pagbuo ng mga key, bisitahin ang [Secret Managers na seksyon](/docs/edge/configuration/secret-managers/set-up-aws-ssm). + +```bash +$ polygon-edge server --restore archive.dat +``` + +## I-back up/I-restore ang Buong data {#back-up-restore-whole-data} + +Ang seksyong ito ay gumagabay sa iyo sa pag-backup ng data kasama ang state data at key at pagpapanumbalik sa bagong instance. + +### Hakbang 1: Itigil ang tumatakbong client {#step-1-stop-the-running-client} + +Dahil gumagamit ang Polygon Edge ng **LevelDB** para sa data storage, kailangang ihinto ang node sa panahon ng pag-backup, +dahil ang **LevelDB** ay hindi nagpapahintulot sa mga magkakasabay na pag-access sa mga database file nito. + +Bukod pa rito, nagsasagawa rin ang Polygon Edge ng data flushing kapag magsara. + +Ang unang hakbang ay nagsasangkot ng pagpapahinto sa tumatakbong client (alinman sa pamamagitan ng isang service manager o iba pang mekanismo na nagpapadala ng isang SIGINT signal sa proseso), +para ma-trigger nito ang 2 mga event habang maayos na nagsasara: +* Pagpapatakbo ng data flush sa disk +* Pag-release ng mga DB file lock sa pamamagitan ng LevelDB + +### Hakbang 2: I-backup ang directory {#step-2-backup-the-directory} + +Ngayong hindi na tumatakbo ang client, maaari nang i-back up ang data directory sa ibang medium. +Tandaan na ang mga file na may `.key` extension ay naglalaman ng pribadong key data na maaaring gamitin para gayahin ang kasalukuyang node, +at hindi sila dapat ibahagi sa isang third/hindi kilalang party. + +:::info + +Mangyaring manual na i-back up at i-restore ang file `genesis`, para ang mga naibalik na node ay maayos na magagamit. + +::: + +## Pag-restore {#restore-1} + +### Hakbang 1: Itigil ang tumatakbong client {#step-1-stop-the-running-client-1} + +Kung anumang instance ng Polygon Edge ay tumatakbo, kailangan itong mapahinto para maging matagumpay ang hakbang 2. + +### Hakbang 2: Kopyahin ang na-back up na data directory tungo sa nais na folder {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +Kapag hindi na tumatakbo ang client, ang data directory na na-back up kamakailan ay maaari nang kopyahin sa nais na folder. Bukod pa rito, i-restore ang kinopyang `genesis` file kamakailan. + +### Hakbang 3: Patakbuhin ang Polygon Edge client habang tinutukoy ang tamang data directory {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +Para magamit ng Polygon Edge ang ni-restore na data directory, sa paglulunsad, kailangang tukuyin ng user ang path patungo sa +data directory. Mangyaring kumonsulta sa [CLI Commands](/docs/edge/get-started/cli-commands) na seksyon para sa impormasyon tungkol sa `data-dir` flag. diff --git a/archive/edge/tl-edge/working-with-node/query-json-rpc.md b/archive/edge/tl-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..c67d633ffc --- /dev/null +++ b/archive/edge/tl-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,93 @@ +--- +id: query-json-rpc +title: I-query ang mga endpoint ng JSON RPC +description: "I-query ang data at simulan ang chain sa pamamagitan ng na-premine na account." +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## Pangkalahatang-ideya {#overview} + +Ang layer ng JSON-RPC ng Polygon Edge ay nagbibigay sa mga developer ng kakayahang makipag-interaksyon sa blockchain nang walang kahirap-hirap, +sa pamamagitan ng mga request sa HTTP. + +Saklaw sa halimbawang ito ang paggamit ng mga tool tulad ng **curl** para mag-query ng impormasyon at simulan ang chain sa pamamagitan ng na-premine na account, +at magpadala ng transaksyon. + +## Hakbang 1: Gumawa ng genesis file sa pamamagitan ng na-premine na account {#step-1-create-a-genesis-file-with-a-premined-account} + +Para gumawa ng genesis file, patakbuhin ang sumusunod na command: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +Itinatakda ng **premine** flag ang address na dapat idagdag kasama ng panimulang balanse sa **genesis** file.
+Sa kasong ito, ang address na `0x1010101010101010101010101010101010101010` ay magkakaroon ng panimulang **default na balanse** na +`0xD3C21BCECCEDA1000000`(1 milyong katutubong currency token). + +Kung gusto nating tumukoy ng balanse, maaari nating paghiwalayin ang balanse at address sa pamamagitan ng `:`, gaya nito: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +Ang balanse ay maaaring maging value na `hex` o `uint256`. + +:::warning Para lang sa mga premine na account na mayroon kang pribadong key! + +Kung mayroon kang mga premine na account at wala kang pribadong key para i-access ang mga ito, hindi magagamit ang iyong na-premine na balanse + +::: + +## Hakbang 2: Simulan ang Polygon Edge sa dev mode {#step-2-start-the-polygon-edge-in-dev-mode} + +Para simulan ang Polygon Edge sa development mode, na ipinapaliwanag sa seksyong [Mga CLI Command](/docs/edge/get-started/cli-commands), +patakbuhin ang sumusunod: +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## Hakbang 3: I-query ang balanse ng account {#step-3-query-the-account-balance} + +Ngayong tumatakbo na ang client sa dev mode, gamit ang genesis file na binuo sa **hakbang 1**, maaari tayong gumamit ng tool gaya ng +**curl** para i-query ang balanse ng account: +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +Dapat ibalik ng command ang sumusunod na output: +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## Hakbang 4: Magpadala ng paglipat na transaksyon {#step-4-send-a-transfer-transaction} + +Ngayon na nakumpirma na natin na may tamang balanse ang account na na-set up natin bilang na-premine, maaari tayong maglipat ng ilang ether: + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/tl-edge/working-with-node/query-operator-info.md b/archive/edge/tl-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..6eb4a1359f --- /dev/null +++ b/archive/edge/tl-edge/working-with-node/query-operator-info.md @@ -0,0 +1,85 @@ +--- +id: query-operator-info +title: Pag-query ng impormasyon ng operator +description: "Kung paano mag-query ng impormasyon ng operator." +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## Mga Paunang Kinakailangan {#prerequisites} + +Ipinagpapalagay ng gabay na ito na sinundan mo ang [Local na Pag-Setup](/docs/edge/get-started/set-up-ibft-locally) o [ang gabay kung paano i-set up ang isang IBFT cluster sa cloud](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +Kinakailangan ang isang gumaganang node para makapag-query ng anumang uri ng impormasyon ng operator. + +Gamit ang Polygon Edge, kontrolado at alam ng mga node operator kung anong ginagawa ng kanilang node.
+Anumang oras, maaari nilang gamitin ang node information layer, na binuo sa itaas ng gRPC, at makakuha ng makabuluhang impormasyon nang hindi nangangailangan ng pagsusuri sa log. + +:::note + +Kung ang iyong node ay hindi tumatakbo sa `127.0.0.1:8545` kailangan mong magdagdag ng isang flag `--grpc-address ` sa mga command na nakalista sa dokumentong ito. + +::: + +## Peer information {#peer-information} + +### Listahan ng mga peer {#peers-list} + +Para makuha ang kumpletong listahan ng mga konektadong peer (kasama ang mismong tumatakbong node), patakbuhin ang sumusunod na command: +````bash +polygon-edge peers list +```` + +Ibabalik nito ang isang listahan ng mga libp2p address na kasalukuyang mga peer ng tumatakbong client. + +### Peer status {#peer-status} + +Para sa status ng isang partikular na peer, patakbuhin ang: +````bash +polygon-edge peers status --peer-id
+```` +Gamit ang *address* parameter bilang ang libp2p address ng peer. + +## impormasyon ng IBFT {#ibft-info} + +Kadalasan, maaaring gustong malaman ng isang operator ang tungkol sa state ng gumaganang node sa IBFT consensus. + +Sa kabutihang-palad, naglalaan ang Polygon Edge ng isang madaling paraan para mahanap ang impormasyong ito. + +### Mga Snapshot {#snapshots} + +Ang pagpapatakbo ng sumusunod na command ay nagbabalik ng pinakahuling snapshot. +````bash +polygon-edge ibft snapshot +```` +Para i-query ang snapshot sa isang espisipikong taas (bilang ng block), maaaring patakbuhin ng operator ang: +````bash +polygon-edge ibft snapshot --num +```` + +### Mga Candidate {#candidates} + +Para makuha ang pinakabagong impormasyon sa mga candidate, maaaring patakbuhin ng operator ang: +````bash +polygon-edge ibft candidates +```` +Kini-query ng command na ito ang kasalukuyang set ng mga iminungkahing candidate, pati na rin ang mga candidate na hindi pa naisasama + +### Status {#status} + +Ang sumusunod na command ay nagbabalik sa kasalukuyang validator key ng tumatakbong IBFT client: +````bash +polygon-edge ibft status +```` + +## Transaction pool {#transaction-pool} + +Para malaman ang kasalukuyang bilang ng mga transaksyong nasa pool ng transaksyon, maaaring patakbuhin ng operator ang: +````bash +polygon-edge txpool status +```` diff --git a/archive/edge/tr-edge/additional-features/blockscout.md b/archive/edge/tr-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..5dccf7baba --- /dev/null +++ b/archive/edge/tr-edge/additional-features/blockscout.md @@ -0,0 +1,418 @@ +--- +id: blockscout +title: Blockscout +description: Blockscout oturumu Polygon Edge ile çalışacak şekilde nasıl yapılandırılır? +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## Genel Bakış {#overview} +Bu kılavuz, Blackscout oturumunun Polygon-Edge ile birlikte çalışacak şekilde nasıl derleneceğini ve devreye alınacağını ayrıntılarıyla ele alır. +Blockscout'un kendi [belgeleri](https://docs.blockscout.com/for-developers/manual-deployment) bulunmaktadır; ancak bu kılavuz Blockscout oturumunun nasıl yapılandırılacağına dair basit ama adım adım ayrıntılı talimatlara odaklanır. + +## Ortam {#environment} +* İşletim Sistemi: Ubuntu Server 20.04 LTS sudo izinleri içeren [indirme bağlantısı](https://releases.ubuntu.com/20.04/) +* Sunucu Donanımı: 8CPU / 16GB RAM / 50GB HDD (LVM) +* Veri Tabanı Sunucusu: 2 CPU / 4GB RAM / 100GB SSD / PostgreSQL 13.4 özellikli ayrılmış sunucu + +### DB Sunucusu {#db-server} +Bu kılavuza uymak için gereksinim, bir veri tabanı sunucusu hazır bulundurulması ve veri tabanı ile veri tabanı kullanıcısının yapılandırılmış olmasıdır. +Bu kılavuz PostgreSQL sunucusunun nasıl devreye alınacağı ve yapılandırılacağı hakkında ayrıntılara girmeyecektir. +Bunun nasıl yapılacağı ile ilgili birçok kılavuz mevcuttur; örneğin [DigitalOcean Kılavuzu](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart) + +:::info YASAL UYARI + +Bu kılavuz, Blockscout'u idal üretim kurulumu olmayan tek bir oturumda çalışır hâle getirmenize yardımcı olmaya yöneliktir. +Üretim için muhtemelen mimari içine ters proxy, yük dengeleyici, ölçeklenebilirlik seçenekleri vb. eklemek isteyeceksiniz. + +::: + +# Blockscout Devreye Alma Prosedürü {#blockscout-deployment-procedure} + +## Bölüm 1 - Bağımlılıkları kurun {#part-1-install-dependencies} +Başlamadan önce, blockscout'un bağımlı olduğu tüm ikili dosyaları kurduğumuzdan emin olmamız gerekir. + +### Sistemi güncelleyin ve yükseltin {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### Erlang bilgi depolarını ekleyin {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### NodeJS bilgi depolarını ekleyin {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### Rust kurun {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### Erlang için gerekli sürümü kurun {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### Elixir için gerekli sürümü kurun {#install-required-version-of-elixir} +Elixir sürümü `1.13` olmalıdır. Bu sürümü resmî bilgi deposundan kurmayı denersek, +`erlang`, `Erlang/OTP 25` sürümüne güncellenecektir ve bu istemediğimiz bir durumdur . +Bu yüzden önceden derlenmiş özel `elixir` sürümünü GitHub sürümler sayfasından alarak kurmamız gerekir. + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +Şimdi `exlixir` sistemi ikili dosyalarını doğru bir şekilde yapılandırmamız gerekiyor. +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +`elixir` ve `erlang` için kurulumun doğru bir şekilde yapılıp yapılmadığını `elixir -v` çalıştırarak kontrol edin. +Çıktı şu şekilde olmalıdır: +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning + +`Erlang/OTP` sürümü `24` olmalı ve `Elixir` sürümü `1.13.*` olmalıdır. +Aksi halde Blockscout derlemesi yaparken ve/veya çalıştırırken sorunlarla karşılaşırsınız. + +::: +:::info + +Resmî ***[Blockscout gereksinimler sayfasına](https://docs.blockscout.com/for-developers/information-and-settings/requirements)*** göz atın + +::: + +### NodeJS kurun {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### Cargo kurun {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### Diğer bağımlılıkları kurun {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### Veri tabanı bağlantınızı denetlemek için isteğe bağlı olarak postgresql istemcisini kurun {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## Bölüm 2 - Ortam değişkenlerini ayarlayın {#part-2-set-environment-variables} +Blockscout derlemesine başlamadan önce ortam değişkenlerini ayarlamamız gerekir. +Bu kılavuzda yalnızca çalışmasını sağlamak için temel yapılandırmaları yapacağız. +Ayarlanabilir değişkenlerin tam bir listesini [burada](https://docs.blockscout.com/for-developers/information-and-settings/env-variables) bulabilirsiniz + +### Veri tabanını ortam değişkeni olarak belirleyin {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +Şimdi sağlanan parametrelerle veri tabanı bağlantınızı test edin. +PG ortam değişkenlerini sağladığınıza göre, veri tabanına yalnızca şunu çalıştırarak bağlanabiliyor olmanız gerekir: +```bash +psql +``` + +Veri tabanı doğru bir şekilde yapılandırıldığında bir psql istemi görmeniz gerekir: +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +Aksi takdirde aşağıdaki gibi bir hata görebilirsiniz: +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +Bu durumda [bu belgeler](https://ubuntu.com/server/docs/databases-postgresql) size yardımcı olabilir. + +:::info Veri tabanı bağlantısı + +Bir sonraki bölüme geçmeden önce tüm veri tabanı bağlantı sorunlarını çözdüğünüzden emin olun. +Blockscout kullanıcısı için süper kullanıcı ayrıcalıkları sağlamanız gerekir. + +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## Bölüm 3 - Blockscout'u klonlayın ve derleyin {#part-3-clone-and-compile-blockscout} +Şimdi en sonunda Blockscout kurulumuna başlıyoruz. + +### Blockscout bilgi deposunu klonlayın {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### Üretim derlemesini korumak için gizli anahtar tabanını oluşturun {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +Son satırda rastgele karakterlerden oluşan uzun bir dize görmeniz gerekir. +Bu, bir sonraki adımdan önce `SECRET_KEY_BASE` ortam değişkeniniz olarak ayarlanmalıdır. +Örneğin: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### Üretim modunu ayarlayın {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### Derleyin {#compile} +Klon dizinine girin ve derlemeye başlayın + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info + +Daha önce kurulum gerçekleştirdiyseniz, statik varlıkları önceki derlemeden kaldırın ***mix phx.digest.clean***. + +::: + +### Veri tabanlarını taşıyın {#migrate-databases} +:::info + +Veri tabanı bağlantınızı doğru bir şekilde yapılandırmadıysanız, +veya DATABASE_URL ortam değişkenini sağlamadıysanız ya da yanlış parametrelerle tanımladıysanız bu bölüm başarısız olacaktır. +Veri tabanı kullanıcısının süper kullanıcı ayrıcalıklarına sahip olması gerekir. + +::: +```bash +mix do ecto.create, ecto.migrate +``` + +Önce veri tabanını bırakmanız gerekiyorsa, şunu çalıştırın: +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### Npm bağımlılıklarını kurun ve ön uç varlıklarını derleyin {#install-npm-dependencies-and-compile-frontend-assets} +Dizini ön uç varlıklarını içeren klasör olacak şekilde değiştirmeniz gerekir. + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info Lütfen bekleyin + +Bu varlıkların derlenmesi birkaç dakika sürebilir ve herhangi bir çıktı göstermez. +İşlem takılmış gibi görünebilir ama sabırlı olmalısınız. +Derleme işlemi tamamlandığında, aşağıdaki gibi bir çıktı vermelidir: `webpack 5.69.1 compiled with 3 warnings in 104942 ms` + +::: + +### Statik varlıkları oluşturun {#build-static-assets} +Bu adım için Blockscout klon klasörünüzün köküne geri dönmeniz gerekir. +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### Kendinden imzalı sertifikalar oluşturun {#generate-self-signed-certificates} +:::info + +`https` kullanmayacaksanız bu adımı atlayabilirsiniz. + +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## Bölüm 4 - Blockscout hizmetini oluşturun ve çalıştırın {#part-4-create-and-run-blockscout-service} +Bu bölümde Blockscout'un arka planda çalışmasını ve sistemi yeniden başlattıktan sonra çalışmaya devam etmesini istediğimiz için bir sistem hizmeti kurmamız gerekir. + +### Hizmet dosyası oluşturun {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### Hizmet dosyasını düzenleyin {#edit-service-file} +Bu dosyayı düzenlemek ve hizmeti yapılandırmak için en sık kullandığınız linux metin editörünü kullanın. +```bash +sudo vi /etc/systemd/system/explorer.service +``` +Explorer.service dosyasının içeriği şuna benzemelidir: +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### Sistem önyükleme sırasında hizmet başlatmayı etkinleştirin {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### Blockscout klon klasörünüzü system-wide konumuna taşıyın {#move-your-blockscout-clone-folder-to-system-wide-location} +Blockscout hizmetinin Blockscout bilgi deposundan klonladığınız klasöre erişmesi ve tüm varlıkları derlemiş olması gerekir. +```bash +sudo mv ~/blockscout /usr/local +``` + +### Blockscout hizmeti tarafından kullanılacak ortam değişkenleri dosyasını oluşturun {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info + +Bölüm 3'te oluşturduğunuz `SECRET_KEY_BASE`'i kullanın. + +::: +Dosyayı kaydedin ve çıkın. + +### Son olarak, Blockscout hizmetini başlatın {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## Bölüm 5 - Blockscout örneğinizin işlevselliğini test edin {#part-5-test-out-the-functionality-of-your-blockscout-instance} +Şimdi tek yapmanız gereken, Blockscout hizmetinin çalışıp çalışmadığını kontrol etmektir. +Hizmet durumunu kontrol etmek için: +```bash +sudo systemctl status explorer.service +``` + +Hizmet çıktısını kontrol etmek için: +```bash +sudo journalctl -u explorer.service -f +``` + +Yeni dinleme portları olup olmadığını kontrol edebilirsiniz: +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +Dinleme portlarının bir listesini almanız gerekir ve listede şuna benzer bir şey yer almalıdır: +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +Blockscout ortam dosyası içinde tanımlanan web hizmeti portu ve protokolü çalıştırır. Bu örnekte `4000`(http) üzerinde çalışır. +Her şey yolunda ise, Blockscout web portalına `http://:4000` ile erişebilirsiniz. + +## Dikkate Alınacak Konular {#considerations} +En iyi performans için, özel/yerel bir `polygon-edge` doğrulayıcı olmayan tam arşivli bir düğüme sahip olunması +ve bu düğümün sadece Blockscout sorguları için kullanılması tavsiye edilir. +Bu düğümün `json-rpc` API'sinin herkese açık hâle getirilmesi gerekmez çünkü Blockscout tüm sorguları arka uçtan çalıştırır. + + +## Son olarak {#final-thoughts} +Düzgün bir şekilde çalışan tek bir Blockscout oturumunu az önce devreye aldık; ancak üretim için bu oturumu Nginx gibi bir ters proxy arkasına yerleştirmeyi değerlendirmelisiniz. +Ayrıca kullanım durumunuza bağlı olarak veri tabanı ve örnek ölçeklenebilirliği hakkında da düşünmelisiniz. + +Birçok özelleştirme seçeneği bulunan resmî [Blockscout belgelerine](https://docs.blockscout.com/) mutlaka göz atmalısınız. \ No newline at end of file diff --git a/archive/edge/tr-edge/additional-features/chainbridge/definitions.md b/archive/edge/tr-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..5a802e61b5 --- /dev/null +++ b/archive/edge/tr-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,220 @@ +--- +id: definitions +title: Genel Tanımlar +description: chainBridge'de kullanılan terimler için Genel Tanımlar +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## Yönlendirici {#relayer} +Chainbridge, yönlendirici tipi bir köprüdür. Bir yönlendiricinin rolü, bir isteğin yürütülmesi için oy vermektir (örneğin, kaç token'ın yakılacağı/serbest bırakılacağı). +Her zincirdeki olayları izler ve bir zincirden bir `Deposit` olayı aldığında hedef zincirin Köprü sözleşmesinde bir teklif için oy kullanır. Bir yönlendirici, gerekli sayıda oy gönderildikten sonra teklifi yürütmek için Köprü sözleşmesindeki bir yöntemi çağırır. Köprü, yürütme işlemini İşleyici sözleşmesine delege eder. + + +## Sözleşme türleri {#types-of-contracts} +ChainBridge'de her zincir üzerinde Köprü/İşleyici/Hedef adı verilen üç sözleşme türü vardır. + +| **Tip** | **Açıklama** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Köprü sözleşmesi | Her zincirde istekleri, oyları ve uygulamaları yöneten bir Köprü sözleşmesi devreye alınmalıdır. Kullanıcılar, bir aktarımı başlatmak için Köprüde `deposit` çağrısı yapar ve Köprü, süreci Hedef sözleşmesine karşılık gelen İşleyici sözleşmesine delege eder. İşleyici sözleşmesi Hedef sözleşmesini çağırmada başarılı olduktan sonra, Köprü sözleşmesi yönlendiricileri bilgilendirmek için bir `Deposit` olayı yayımlar. | +| İşleyici sözleşmesi | Bu sözleşme, bir fon yatırmak veya teklif yürütmek için Hedef sözleşmesi ile etkileşime girer. Kullanıcının isteğini doğrular, Hedef sözleşmeyi çağırır ve Hedef sözleşmesi için bazı ayarlara yardımcı olur. Farklı bir arabirime sahip olan her bir Hedef sözleşmesini çağırmak için belirli İşleyici sözleşmeleri vardır. İşleyici sözleşmesinin dolaylı çağrıları, her türlü varlık veya verinin aktarımını sağlamak için köprü oluşturur. Şu anda ChainBridge tarafından uygulanan üç tür İşleyici sözleşmesi vardır: ERC20Handler, ERC721Handler ve GenericHandler. | +| Hedef sözleşme | Zincirler arasında değiş tokuş edilecek varlıkları veya iletilen mesajları yöneten bir sözleşmedir. Bu sözleşme ile etkileşim köprünün her iki tarafından yapılır. | + +
+ +![ChainBridge Mimarisi](/img/edge/chainbridge/architecture.svg) +*ChainBridge Mimarisi* + +
+ +
+ +![ERC20 token aktarımının iş akışı](/img/edge/chainbridge/erc20-workflow.svg) +*ör. ERC20 token aktarımının iş akışı* + +
+ +## Hesap türleri {#types-of-accounts} + +Başlamadan önce lütfen hesapların işlem oluşturmaya yetecek kadar yerel token'a sahip olduğundan emin olun. Polygon Edge'de, genesis bloğunu oluştururken hesaplara önceden mine edilmiş bakiyeler atayabilirsiniz. + +| **Tip** | **Açıklama** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Yönetici | Bu hesaba varsayılan olarak yönetici rolü verilir. | +| Kullanıcı | Varlıkları gönderen/alan gönderici/alıcı hesabı. Gönderici hesabı, token aktarımını onaylarken ve bir aktarıma başlamak için Köprü sözleşmesinde depozitoyu çağırırken gaz ücretlerini öder. | + +:::info Yönetici rolü + +Belirli eylemler sadece yönetici rolündeki hesap tarafından gerçekleştirilebilir. Varsayılan olarak, Köprü sözleşmesinin devreye alan, yönetici rolüne sahip olur. Yönetici rolünü başka bir hesaba nasıl vereceğinizi veya kaldıracağınızı aşağıda bulabilirsiniz. + +### Yönetici rolü ekle {#add-admin-role} + +Bir yönetici ekler + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### Yönetici rolünü iptal et {#revoke-admin-role} + +Bir yöneticiyi kaldırır + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## `admin` hesabı tarafından izin verilen işlemler aşağıdaki gibidir. {#account-are-as-below} + +### Kaynak Ayarla {#set-resource} + +Bir işleyici için sözleşme adresi ile bir kaynak kimliği kaydeder. + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Sözleşmeyi yakılabilir/mint edilebilir yap {#make-contract-burnable-mintable} + +Bir işleyicide token sözleşmesini mint edilebilir/yakılabilir olarak ayarlar. + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Teklifi iptal et {#cancel-proposal} + +Yürütme için teklifi iptal eder + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### Duraklat/Devam Et {#pause-unpause} + +Fon yatırma, teklif oluşturma, oylama ve fon yürütme işlemlerini geçici olarak durdurur. + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### Ücret Değiştir {#change-fee} + +Köprü Sözleşmesi için ödenecek ücreti değiştirir + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### Bir yönlendirici Ekle/Kaldır {#add-remove-a-relayer} + +Yeni bir yönlendirici olarak bir hesap ekler veya bir hesabı yönlendiricilerden kaldırır + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### Yönlendirici eşiğini değiştir {#change-relayer-threshold} + +Teklifin yürütülmesi için gereken oy sayısını değiştirir + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## Zincir Kimliği {#chain-id} + +Chainbridge `chainId`, blok zinciri ağları arasında ayrım yapmak için köprüde kullanılan rastgele bir değer olup, uint8 aralığında olmalıdır. Ağın zincir kimliği ile karıştırılmaması gerekir; bunlar aynı şey değildir. Bu değerin eşsiz olması gerekir ama ağın kimliği ile aynı olması gerekmez. + +Bu örnekte, Mumbai test ağı, zincir kimliği bir uint8 ile gösterilemeyen `80001` olduğundan `chainId` için `99` atadık. + +## Kaynak Kimliği {#resource-id} + +Kaynak kimliği, ağlar arasında aktarılan belirli bir varlık (kaynak) ile ilişkili olan, zincirler arası bir ortamda 32 baytlık eşsiz bir değerdir. + +Kaynak kimliği rastgeledir ancak genel bir kural olarak, genellikle son bayt kaynak zincirin (varlığın geldiği ağ) zincir kimliğini içerir. + +## Polygon PoS için JSON-RPC URL {#json-rpc-url-for-polygon-pos} + +Bu kılavuz için, Polygon tarafından sağlanan, trafik veya hız sınırları olabilecek genel bir JSON-RPC URL'si olan https://rpc-mumbai.matic.today'i kullanacağız. Bu yalnızca Polygon Mumbai test ağına bağlanmak için kullanılacaktır. Dağıtım sözleşmeleri JSON-RPC adresinize birçok sorgu/istek göndereceğinden, JSON-RPC URL'inizi Infura gibi harici bir servisten almanızı öneririz. + +## Token aktarımını işleme yolları {#ways-of-processing-the-transfer-of-tokens} +ERC20 token'ları zincirler arasında aktarılırken iki farklı modda işlenebilir: + +### Kilitleme/serbest bırakma modu {#lock-release-mode} +Kaynak zinciri: Gönderdiğiniz token'lar İşleyici Sözleşmesi'nde kilitlenecektir.
+Hedef zincir: Kaynak zincirde gönderdiğiniz ile aynı miktarda token kilitli durumdan çıkarılır ve İşleyici sözleşmesinden hedef zincirdeki alıcı hesabına aktarılır. + +### Yakma/mint etme modu {#burn-mint-mode} +Kaynak Zincir: Gönderdiğiniz token'lar yakılır.
Hedef zincir: Kaynak zincirde gönderdiğiniz ve yaktığınızla aynı miktarda token, hedef zincirde mint edilir ve alıcı hesabına gönderilir. + +Her zincirde farklı modlar kullanabilirsiniz. Bu, aktarım için alt zincir üzerinde bir token'ı mint ederken, ana zincir üzerinde bir token'ı kilitleyebileceğiniz anlamına gelir. Örneğin, toplam arz veya mint programı kontrol ediliyorsa, token'ları kilitlemek/serbest bırakmak mantıklı olabilir. Alt zincirdeki sözleşmenin ana zincirdeki arzı takip etmesi gerekiyorsa token'lar mint edilmelidir/yakılmalıdır. + +Varsayılan mod kilitleme/serbest bırakma modudur. Token'ları mint edilebilir/yakılabilir yapmak istiyorsanız, `adminSetBurnable` yöntemini çağırmanız gerekir. Yürütme esnasında token'ları mint etmek istiyorsanız, ERC20 İşleyici sözleşmesine `minter` rolü vermeniz gerekir. + + diff --git a/archive/edge/tr-edge/additional-features/chainbridge/overview.md b/archive/edge/tr-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..a764043139 --- /dev/null +++ b/archive/edge/tr-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Genel Bakış +description: ChainBridge'e genel bakış +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## ChainBridge nedir? {#what-is-chainbridge} + +ChainBridge, ChainSafe tarafından oluşturulan, EVM ve Substrate uyumlu zincirleri destekleyen modüler, çok yönlü bir blok zinciri köprüsüdür. Kullanıcıların iki farklı zincir arasında her türlü varlığı veya mesajı aktarmasına olanak tanır. + +ChainBridge hakkında daha fazla bilgi edinmek için lütfen öncelikle geliştiricileri tarafından sağlanan [resmî dokümanları](https://chainbridge.chainsafe.io/) inceleyin. + +Bu kılavuz, Polygon Edge ile Chainbridge entegrasyonuna yardımcı olmak için hazırlanmıştır. Çalışan bir Polygon PoS (Mumbai test ağı) ve yerel bir Polygon Edge ağı arasında köprü kurulumunu adım adım anlatmaktadır. + +## Gereksinimler {#requirements} + +Bu kılavuzda, Polygon Edge düğümlerini, bir ChainBridge yönlendiricisini (daha fazla bilgiyi [burada](/docs/edge/additional-features/chainbridge/definitions) bulabilirsiniz) ve sözleşmeleri yerel olarak devreye almak, kaynağı kaydetmek ve köprü ayarlarını değiştirmek için bir CLI aracı olan cb-sol-cli aracını çalıştıracaksınız ([bunu](https://chainbridge.chainsafe.io/cli-options/#cli-options) da inceleyebilirsiniz). Kuruluma başlamadan önce aşağıdaki ortamlar gereklidir: + +* Go: >= 1.17 +* Node.js >= 16.13.0 +* Git + + +Buna ek olarak, bazı uygulamaları çalıştırmak için aşağıdaki depoları sürümleriyle birlikte klonlamanız gerekecektir. + +* [Polygon Edge](https://github.com/0xPolygon/polygon-edge): `develop` dalında +* [ChainBridge](https://github.com/ChainSafe/ChainBridge): v1.1.5 +* [ChainBridge Dağıtım Araçları](https://github.com/ChainSafe/chainbridge-deploy): `main` dalda `f2aa093` + + +Bir sonraki bölüme geçmeden önce bir Polygon Edge ağı kurmanız gerekir. Daha fazla bilgi için lütfen [Yerel Kurulum](/docs/edge/get-started/set-up-ibft-locally) veya [Bulut Kurulumu](/docs/edge/get-started/set-up-ibft-on-the-cloud)'nu kontrol edin. \ No newline at end of file diff --git a/archive/edge/tr-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/tr-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..0ad0d07125 --- /dev/null +++ b/archive/edge/tr-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,142 @@ +--- +id: setup-erc20-transfer +title: ERC20 Token Aktarımı +description: ChainBridge'de ERC-20 aktarımı nasıl kurulur? +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Şimdiye kadar varlıkları/verileri Polygon PoS ve Polygon Edge zincirleri arasında değiş tokuş etmek için köprü kurduk. Bu bölüm, bir ERC20 köprüsü kurmanız ve farklı blok zincirleri arasında token'ları göndermeniz için size kılavuz olacaktır. + +## 1. Adım: Kaynak kimliğini kaydetme {#step-1-register-resource-id} + +Öncelikle, zincirler arası bir ortamda kaynakları ilişkilendiren bir kaynak kimliği kaydedeceksiniz. Kaynak Kimliği, bu blok zincirleri arasında aktardığımız kaynağa özgü olması gereken 32 baytlık bir değerdir. Kaynak kimlikleri rastgeledir, ancak bir kural olarak son baytta ana zincirin zincir kimliğini alabilirler (ana zincir, bu kaynakların nereden geldiğini belirten ağı işaret eder). + +Kaynak kimliğini kaydetmek için `cb-sol-cli bridge register-resource` komutunu kullanabilirsiniz. `admin` hesabının özel anahtarını vermeniz gerekecektir. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (İsteğe bağlı) Sözleşmeleri mint edilebilir/yakılabilir yapın {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## 2. Adım: ERC20 Token Aktarımı {#step-2-transfer-erc20-token} + +Polygon PoS zincirinden Polygon Edge zincirine ERC20 Token'ları göndereceğiz. + +Önce mint ederek token'ları alacaksınız. `minter` rolüne sahip bir hesap, yeni token'ları mint edebilir. ERC20 sözleşmesini devreye alan hesap, varsayılan olarak `minter` rolüne sahiptir. `minter` rolünün üyeleri olarak diğer hesapları belirtmek için `cb-sol-cli erc20 add-minter` komutunu çalıştırmanız gerekir. + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +Mevcut bakiyeyi denetlemek için `cb-sol-cli erc20 balance` komutunu kullanabilirsiniz. + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +Ardından, ERC20 İşleyicisi tarafından hesap üzerinden ERC20 token aktarımını onaylamanız gerekir + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +Token'ları Polygon Edge zincirlerine aktarmak için `deposit` çağırmalısınız. + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Fon yatırma işlemi başarılı olduktan sonra, yönlendirici olayı alacak ve teklif için oy kullanacaktır. Gerekli sayıda oy gönderildikten sonra, Polygon Edge zincirindeki hesap adresine token'ları göndermek için bir işlem yürütür. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Yürütme işlemi başarılı olduğunda, Polygon Edge zincirinde token'ları alabilirsiniz. + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/tr-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/tr-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..0b50fc9584 --- /dev/null +++ b/archive/edge/tr-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,134 @@ +--- +id: setup-erc721-transfer +title: ERC721 NFT Aktarımı +description: ChainBridge'de ERC721 aktarımı nasıl ayarlanır? +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Bu bölüm, bir ERC721 köprüsü kurma ve blok zinciri ağları arasında NFT'ler gönderme konusunda size rehberlik eder. + +## 1. Adım: Kaynak kimliğini kaydetme {#step-1-register-resource-id} + +Öncelikle her iki zincirdeki Köprü sözleşmelerinde ERC721 token'ı için kaynak kimliğini kaydetmeniz gerekir. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (İsteğe bağlı): Sözleşmeleri mint edilebilir/yakılabilir yapın {#optional-make-contracts-mintable-burnable} + +Token'ları mint edilebilir/yakılabilir yapmak için aşağıdaki komutları çağırmanız gerekir: + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## 2. Adım: NFT Aktarımı {#step-2-transfer-nft} + +Öncelikle, ihtiyacınız varsa bir NFT mint edin. + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +NFT sahibini denetlemek için `cb-sol-cli erc721 owner` kullanabilirsiniz + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Ardından, ERC721 İşleyicisi tarafından NFT aktarımını onaylayın + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Son olarak, aktarıma başlayın + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +Yönlendirici olayı alır ve teklif için oy kullanır. Gerekli sayıda oy gönderildikten sonra, Polygon Edge zincirindeki hesap adresine NFT'leri göndermek için bir işlem yürütür. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Yürütme tamamlandıktan sonra Polygon Edge ağında NFT sahibini denetleyebilirsiniz. + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/tr-edge/additional-features/chainbridge/setup.md b/archive/edge/tr-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..73e454af5e --- /dev/null +++ b/archive/edge/tr-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,198 @@ +--- +id: setup +title: Kurulum +description: chainBridge nasıl kurulur? +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Sözleşmeleri devreye alma {#contracts-deployment} + +Bu bölümde, Polygon PoS ve Polygon Edge için gerekli sözleşmeleri `cb-sol-cli` kullanarak devreye alacaksınız. + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +Öncelikle, `cb-sol-cli deploy` komutunu kullanarak sözleşmeleri Polygon PoS zinciri üzerinde devreye alacağız. `--all` bayrağı; komutun Köprü, ERC20 İşleyicisi, ERC721 İşleyicisi, Jenerik İşleyici, ERC20 ve ERC 721 sözleşmesi dâhil tüm sözleşmeleri devreye almasını sağlar. Buna ek olarak, varsayılan yönlendirici hesap adresini ve eşiğini ayarlar + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +chainID ve JSON-RPC URL hakkında [buradan](/docs/edge/additional-features/chainbridge/definitions) bilgi edinin + +:::caution + +`cb-sol-cli` üzerindeki varsayılan gaz fiyatı `20000000` olarak belirlenmiştir (`0.02 Gwei`). Bir işlem içinde uygun gaz fiyatını ayarlamak için `--gasPrice` argümanını kullanarak değeri belirleyin. + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +Köprü sözleşmesinin devreye alınması için yaklaşık 0x3f97b8 (4167608) gaz gerekir. Lütfen oluşturulan blokların sözleşme oluşturma işlemini kapsayacak kadar blok gaz limitine sahip olduğundan emin olun. Polygon Edge üzerinde blok gaz limitini değiştirme hakkında daha fazla bilgi edinmek için lütfen +[Yerel Kurulum](/docs/edge/get-started/set-up-ibft-locally) kısmını ziyaret edin + +::: + +Sözleşmeler devreye alındıktan sonra aşağıdaki sonucu alacaksınız: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +Artık sözleşmeleri Polygon Edge zinciri üzerinde devreye alabiliriz. + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Bir sonraki adım için ihtiyaç duyacağımız devreye alınmış akıllı sözleşme adreslerini içeren terminal çıktılarını kaydedin. + +## Yönlendirici kurulumu {#relayer-setup} + +Bu bölümde, iki zincir arasında değişim için bir yönlendirici başlatacaksınız. + +Önce ChainBridge bilgi deposunu klonlayıp oluşturmamız gerekir. + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +Ardından, her zincir için `config.json` oluşturmalı ve JSON-RPC URL'lerini, yönlendirici adresini ve sözleşme adresini ayarlamalısınız. + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +Bir yönlendirici başlatmak için yönlendirici hesap adresine karşılık gelen özel anahtarı içe aktarmanız gerekir. Özel anahtarı içe aktarırken bir şifre girmeniz gerekecektir. İçe aktarma başarılı olduktan sonra, anahtar `keys/
.key` altında depolanacaktır. + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +Bundan sonra, yönlendiriciyi başlatabilirsiniz. Başlangıçta anahtarı depolamak için seçtiğiniz şifrenin aynısını girmeniz gerekecektir. + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +Yönlendirici çalışmaya başladıktan sonra, her zincir üzerinde yeni blokları izlemeye başlayacaktır. diff --git a/archive/edge/tr-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/tr-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..7536a708c2 --- /dev/null +++ b/archive/edge/tr-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,255 @@ +--- +id: use-case-erc20-bridge +title: Kullanım durumu - ERC20 Köprüsü +description: ERC20 sözleşmesini köprüleme örneği +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +Bu bölüm, pratik bir kullanım durumu için size ERC20 Köprü kurulum akışını sağlamayı amaçlamaktadır. + +Bu kılavuzda Mumbai Polygon PoS test ağını ve Polygon Edge yerel ağını kullanacaksınız. Lütfen Mumbai için JSON-RPC uç noktasına sahip olduğunuzdan ve yerel ortamda Polygon Edge kurulumunu yaptığınızdan emin olun. Daha fazla bilgi için lütfen [Yerel Kurulum](/docs/edge/get-started/set-up-ibft-locally) veya [Bulut Kurulumu](/docs/edge/get-started/set-up-ibft-on-the-cloud) bölümüne başvurun. + +## Senaryo {#scenario} + +Bu senaryo, olağan durumdaki kullanıcıların özel bir zincir üzerinde düşük maliyetli aktarımlarına olanak tanımak için genel zincirde (Polygon PoS) zaten devreye alınmış bir ERC20 token Köprüsü kurmayı kapsar. Böyle bir durumda, toplam token arzı genel zincir üzerinde tanımlanmıştır. Genel zincirden özel zincire aktarılmış olan token miktarı, özel zincirde mevcut olmalıdır. Bu nedenle, genel zincir içinde kilitleme/serbest bırakma modunu kullanmanız ve özel zincirde yakma/mint modunu kullanmanız gerekecektir. + +Genel zincirden özel zincire token gönderirken, token genel zincirin ERC20 İşleyici sözleşmesinde kilitlenecek ve aynı miktarda token özel zincirde mint edilecektir. Öte yandan, özel zincirden genel zincire aktarım durumunda, özel zincirdeki token yakılır ve genel zincirde aynı miktarda token ERC20 İşleyici sözleşmesinden serbest bırakılır. + +## Sözleşmeler {#contracts} + +ChainBridge tarafından geliştirilen sözleşmenin yerine basit bir ERC20 sözleşmesi ile açıklama. Yakma/mint modu için ERC20 sözleşmesinin, ERC20 için yöntemlerin yanı sıra aşağıdakiler gibi `mint` ve `burnFrom` yöntemlerine sahip olması gerekir: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +Tüm kodlar ve komut dizileri Github Repo üzerinde [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example) içinde bulunur. + +## Adım 1: Köprü ve ERC20 İşleyici sözleşmelerini devreye alın {#step1-deploy-bridge-and-erc20-handler-contracts} + +Öncelikle, her iki zincirde `cb-sol-cli` kullanarak Köprü ve ERC20Handler sözleşmelerini devreye alacaksınız. + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Köprü ve ERC20Handler sözleşme adreslerini aşağıdaki gibi alacaksınız: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Adım 2: ERC20 sözleşmenizi devreye alın {#step2-deploy-your-erc20-contract} + +ERC20 sözleşmenizi devreye alacaksınız. Bu örnek, hardhat projesi [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example) için size rehberlik eder. + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Lütfen `.env` dosyasını oluşturun ve aşağıdaki değerleri ayarlayın. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Ardından, her iki zincirde ERC20 sözleşmesi devreye alacaksınız. + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +Kurulum başarılı olduktan sonra, aşağıdaki gibi bir sözleşme adresi alacaksınız: + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## Adım 3: Köprü üzerinde kaynak kimliğini kaydedin {#step3-register-resource-id-in-bridge} + +Zincirler arası bir ortamda kaynakları ilişkilendiren bir kaynak kimliği kaydedeceksiniz. Her iki zincirde aynı kaynak kimliğini ayarlamanız gerekir. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## Adım 4: Edge üzerinde ERC20 köprüsü için Mint/Yakma modunu ayarlayın {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +Köprünün, Polygon Edge üzerinde yakma/mint modunda çalışması beklenir. `cb-sol-cli` kullanarak yakma/mint modunu ayarlayacaksınız. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +Ayrıca, ERC20 İşleyici sözleşmesi için bir mint ve yakma rolü atamanız gerekir. + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Adım 5: Token mint edin {#step5-mint-token} + +Mumbai zinciri üzerinde yeni ERC20 token'ları mint edeceksiniz. + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +İşlem başarılı olduktan sonra, hesap mint edilen token'lara sahip olacaktır. + +## Adım 6: ERC20 aktarımını başlatın {#step6-start-erc20-transfer} + +Bu adıma başlamadan önce, lütfen bir yönlendirici başlattığınızdan emin olun. Daha fazla bilgi için lütfen [Kurulum](/docs/edge/additional-features/chainbridge/setup) kısmına göz atın. + +Mumbai'den Edge üzerine token aktarımı yaparken, Mumbai üzerindeki ERC20 İşleyici sözleşmesi hesabınızdan token çeker. Aktarıma başlamadan önce approve çağrısını yapacaksınız. + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +Son olarak, `cb-sol-cli` kullanarak Mumbai'den Edge'e token aktarımına başlayacaksınız. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Fon yatırma işlemi başarılı olduktan sonra, yönlendirici olayı alacak ve teklifi oylayacaktır. Gerekli sayıda oy gönderildikten sonra, Polygon Edge zincirindeki hesap adresine token'ları göndermek için bir işlem yürütür. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Yürütme işlemi başarılı olduktan sonra, Polygon Edge zinciri üzerinde token'ları alacaksınız. diff --git a/archive/edge/tr-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/tr-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..7cde36f990 --- /dev/null +++ b/archive/edge/tr-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,308 @@ +--- +id: use-case-erc721-bridge +title: Kullanım durumu - ERC721 Köprüsü +description: ERC721 sözleşme köprüsüne ilişkin örnek +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +Bu bölüm, pratik bir kullanım durumu için size ER721 Köprü kurulum akışını sağlamayı amaçlamaktadır. + +Bu kılavuzda Mumbai Polygon PoS test ağını ve Polygon Edge yerel ağını kullanacaksınız. Lütfen Mumbai için JSON-RPC uç noktasına sahip olduğunuzdan ve yerel ortamda Polygon Edge kurulumunu yaptığınızdan emin olun. Daha fazla bilgi için lütfen [Yerel Kurulum](/docs/edge/get-started/set-up-ibft-locally) veya [Bulut Kurulumu](/docs/edge/get-started/set-up-ibft-on-the-cloud) bölümüne başvurun. + +## Senaryo {#scenario} + +Bu senaryo, normal bir durumda olan kullanıcılar için özel bir zincirde (Polygon Edge) düşük maliyetli aktarımı etkinleştirmek için halihazırda genel zincirde (Polygon POS) devreye alınmış ERC721 NFT için bir köprü kurmaktır. Böyle bir durumda, orijinal meta veriler genel zincir içinde tanımlanmıştır ve yalnızca genel zincirden aktarılan NFT'ler özel zincir içinde mevcut olabilir. Bu nedenle, genel zincir içinde kilitleme/serbest bırakma modunu kullanmanız ve özel zincirde yakma/mint modunu kullanmanız gerekecektir. + +Genel zincirden özel zincire NFT'leri gönderirken, NFT genel zincirde ERC721 İşleyici sözleşmesinde kilitlenecek ve aynı NFT özel zincirde mint edilecektir. Öte yandan, özel zincirden genel zincire aktarım durumunda, özel zincirdeki NFT yakılacak ve genel zincirde aynı NFT ERC721 İşleyici sözleşmesinden serbest bırakılacaktır. + +## Sözleşmeler {#contracts} + +ChainBridge tarafından geliştirilen sözleşme yerine basit bir ERC721 sözleşmesi ile açıklama. Yakma/mint etme modu için, ERC721 sözleşmesi, ERC721'de tanımlanan yöntemlere ek olarak `mint` ve `burn` yöntemlerine sahip olmalıdır: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +Tüm kodlar ve komut dizileri Github Repo [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example) içinde bulunur. + +## Adım 1: Köprü ve ERC721 İşleyici sözleşmelerini devreye alın {#step1-deploy-bridge-and-erc721-handler-contracts} + +Öncelikle, her iki zincirde `cb-sol-cli` kullanarak Köprü ve ERC721 İşleyici sözleşmelerini devreye alacaksınız. + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Köprü ve ERC721 İşleyici sözleşme adreslerini aşağıdaki gibi alacaksınız: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Adım 2: ERC721 sözleşmesini devreye alın {#step2-deploy-your-erc721-contract} + +ERC721 sözleşmesini devreye alacaksınız. Bu örnek, hardhat projesi [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example) için size rehberlik eder. + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Lütfen `.env` dosyasını oluşturun ve aşağıdaki değerleri ayarlayın. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Ardından, her iki zincirde ERC721 sözleşmesini devreye alacaksınız. + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +Devreye alma başarılı olduktan sonra, aşağıdaki gibi bir sözleşme adresi alacaksınız: + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## Adım 3: Köprüye kaynak kimliğini kaydedin {#step3-register-resource-id-in-bridge} + +Zincirler arası bir ortamda kaynakları ilişkilendiren bir kaynak kimliği kaydedeceksiniz. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## Adım 4: Edge üzerinde ERC721 köprüsünde Mint Etme/Yakma modunu ayarlayın {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +Köprü, Edge'de yakma/mint etme modunda çalışmayı bekler. Yakma/mint etme modunu ayarlayacaksınız. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +Ve ERC721 İşleyici sözleşmesi için bir mint edici ve yakıcı rolü vermeniz gerekir. + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Adım 5: NFT'yi mint edin {#step5-mint-nft} + +Mumbai zincirinde ERC721 NFT'yi mint edeceksiniz. + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +İşlem başarılı olduktan sonra, hesap mint edilen NFT'lere sahip olacaktır. + +## Adım 6: ERC721 aktarımını başlatın {#step6-start-erc721-transfer} + +Bu adıma başlamadan önce, lütfen yönlendiriciyi başlattığınızdan emin olun. Daha fazla bilgi için lütfen [Kurulum](/docs/edge/additional-features/chainbridge/setup) kısmına göz atın. + +Mumbai'den Edge'e NFT aktarımı sırasında, Mumbai'deki ERC721 İşleyici sözleşmesi, hesabınızdan NFT'yi çeker. Aktarıma başlamadan önce approve çağrısını yapacaksınız. + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +Son olarak, Mumbai'den Edge'e NFT aktarımına başlayacaksınız. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +Fon yatırma işlemi başarılı olduktan sonra, yönlendirici olayı almalı ve teklif için oy kullanmalıdır. +Gerekli sayıda oy gönderildikten sonra Polygon Edge zincirindeki alıcı hesabına NFT'yi göndermek için bir işlem yürütür. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Yürütme işlemi başarılı olduktan sonra, Polygon Edge zincirinde üzerinde NFT'yi alacaksınız. diff --git a/archive/edge/tr-edge/additional-features/permission-contract-deployment.md b/archive/edge/tr-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..245c3f1bae --- /dev/null +++ b/archive/edge/tr-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,86 @@ +--- +id: permission-contract-deployment +title: Akıllı sözleşme devreye alma izni +description: Akıllı sözleşme devreye alma izni nasıl eklenir? +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## Genel Bakış {#overview} + +Bu kılavuz, akıllı sözleşmeleri devreye alabilecek adreslerin nasıl beyaz listeye alınacağı hakkında ayrıntılı bilgi vermektedir. +Bazen ağ operatörleri, kullanıcıların ağın amacıyla ilgisi olmayan akıllı sözleşmeleri devreye almalarını önlemek ister. Ağ operatörleri şunları yapabilir: + +1. Akıllı Sözleşme devreye alma için beyaz liste adresleri +2. Akıllı Sözleşme devreye alma için beyaz listeden adres çıkarma + +## Video sunumu {#video-presentation} + +[![izin sözleşmesi dağıtımı - video](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## Nasıl kullanılır? {#how-to-use-it} + + +Devreye alma beyaz listesiyle ilgili tüm cli komutlarını [CLI Komutları](/docs/edge/get-started/cli-commands#whitelist-commands) sayfasında bulabilirsiniz. + +* `whitelist show`: Beyaz liste bilgilerini görüntüler +* `whitelist deployment --add`: Sözleşme devreye alma beyaz listesine yeni bir adres ekler +* `whitelist deployment --remove`: Sözleşme devreye alma beyaz listesinden yeni bir adres kaldırır + +#### Devreye alma beyaz listesindeki tüm adresleri gösterir {#show-all-addresses-in-the-deployment-whitelist} + +Devreye alma beyaz listesindeki adresleri bulmanın 2 yolu vardır. +1. Beyaz listelerin kaydedildiği `genesis.json`'a bakma +2. Polygon Edge tarafından desteklenen tüm beyaz listelerin bilgilerini yazdıran `whitelist show`yürütme + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### Devreye alma beyaz listesine adres ekleme {#add-an-address-to-the-deployment-whitelist} + +Devreye alma beyaz listesine yeni bir adres eklemek için `whitelist deployment --add [ADDRESS]` CLI komutunu çalıştırın. Beyaz listede bulunan adres sayısı için hiçbir limit yoktur. Yalnızca sözleşme devreye alma beyaz listesinde bulunan adresler, sözleşmeleri devreye alabilir. Beyaz liste boş ise, her adres devreye alma işlemi yapabilir + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### Devreye alma beyaz listesinden adres kaldırma {#remove-an-address-from-the-deployment-whitelist} + +Devreye alma beyaz listesinden bir adresi çıkarmak için `whitelist deployment --remove [ADDRESS]` CLI komutunu çalıştırın. Yalnızca sözleşme devreye alma beyaz listesinde bulunan adresler, sözleşmeleri devreye alabilir. Beyaz liste boş ise, her adres devreye alma işlemi yapabilir + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/tr-edge/architecture/modules/blockchain.md b/archive/edge/tr-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..17f46bfed5 --- /dev/null +++ b/archive/edge/tr-edge/architecture/modules/blockchain.md @@ -0,0 +1,160 @@ +--- +id: blockchain +title: Blok zinciri +description: Polygon Edge'in blok zinciri ve durum modüllerinin açıklaması. +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## Genel Bakış {#overview} + +Polygon Edge'in ana modüllerinden ikisi **Blok Zinciri** ve **Durum** modülleridir.
+ +**Blok Zinciri**, sistemin blokların yeniden yapılandırılması ile ilgilenen dinamosudur. Yani blok zincirine yeni bir blok eklendiğinde gerçekleşen tüm mantığı yönetir. + +**Durum**, *durum geçişi* nesnesini temsil eder. Yeni bir blok eklendiğinde durumun nasıl değiştiği ile ilgilenir.
Diğer özelliklerinin yanı sıra, **Durum** şu işlevleri yönetir: +* İşlemleri yürütme +* EVM'yi yürütme +* Merkle ağaçlarını değiştirme +* Çok daha fazlası, ilgili **Durum** bölümünde ele alınmaktadır. 🙂 + +İşin özünde; bu iki parça birbiriyle çok bağlantılıdır ve istemcinin işlemesi için yakın ilişki içinde çalışırlar.
Örneğin, **Blok Zinciri** katmanı, yeni bir blok aldığında (ve yeniden yapılandırma gerçekleşmediyse) bir durum geçişi gerçekleştirmek için **Durum** çağrısı yapar. + +**Blok Zinciri** konsensüs ile ilgili bazı bölümlerle de ilgilenir (ör. *bu ethHash doğru mu?*, *bu PoW doğru mu?*).
Bir cümleyle anlatmak gerekirse, **tüm blokların dâhil olduğu mantığın ana çekirdeğidir**. + +## *WriteBlocks* + +**Blok Zinciri** katmanı ile ilgili en önemli bileşenlerden biri *WriteBlocks* yöntemidir: + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +*WriteBlocks* yöntemi blok zinciri içine blok yazmak için giriş noktasıdır. Parametre olarak bir blok aralığı alır.
+Öncelikle, bloklar doğrulanır. Ondan sonra, zincir üzerine yazılır. + +Asıl *durum geçişi* *WriteBlocks* içindeki *processBlock* yöntemi çağırılarak gerçekleştirilir. + +Blok zincirine blok yazmak için giriş noktası olduğundan, diğer modüllerin (**Mühürleyici** gibi) bu yöntemi kullandığı belirtilmelidir. + +## Blok Zinciri Abonelikleri {#blockchain-subscriptions} + +Blok zinciri ile ilgili değişiklikleri izlemek için bir yol bulunması gerekir.
+Burada **Abonelikler** devreye girer. + +Abonelikler, blok zinciri olay akışları ile bağlantı kurmanın ve anında anlamlı veri elde etmenin bir yoludur. + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +**Blok Zinciri Olayları** asıl zincirde yapılan her türlü değişiklik hakkında bilgi içerir. Bu bilgi yeniden yapılandırmaları ve yeni blokları içerir: + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip Hatırlatma + +[CLI Komutları](/docs/edge/get-started/cli-commands) içinde ***monitör*** komutundan bahsettiğimizi hatırlıyor musunuz? + +Blok Zinciri Olayları, Polygon Edge içinde gerçekleşen asıl olaylardır ve bunlar daha sonra kolay aktarım için bir Protokol Arabelleği mesaj formatına eşlenirler. + +::: \ No newline at end of file diff --git a/archive/edge/tr-edge/architecture/modules/consensus.md b/archive/edge/tr-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..db6ca04b99 --- /dev/null +++ b/archive/edge/tr-edge/architecture/modules/consensus.md @@ -0,0 +1,512 @@ +--- +id: consensus +title: Konsensüs +description: Polygon Edge'in konsensüs modülünün açıklaması. +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## Genel Bakış {#overview} + +**Konsensüs** modülü, konsensüs mekanizmaları için bir arabirim sağlar. + +Şu anda aşağıdaki konsensüs motorları mevcuttur: +* **IBFT PoA** +* **IBFT PoS** + +Polygon Edge modülerlik ve eklenebilirlik durumunu korumak ister.
+Bu nedenle çekirdek konsensüs mantığı sistem dışına soyutlanmıştır, böylece yeni konsensüs mekanizmaları temel alınabilir, +bunu yaparken kullanılabilirlik ve kullanım kolaylığından ödün vermeye gerek kalmaz. + +## Konsensüs Arabirimi {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + +***Konsensüs*** arabirimi, bahsedilen soyutlamanın temelinde yer alır.
+* **VerifyHeader** yöntemi, konsensüs katmanının **blok zinciri** katmanı için açığa çıkardığı bir yardımcı işlevi temsil eder +Başlık doğrulaması için işlev gösterir +* **Start** yöntemi konsensüs işlemini ve onunla ilişkili her şeyi başlatır. Bunun içerisinde senkronizasyon, +mühürleme ve yapılması gereken her şey yer alır +* **Close** yöntemi konsensüs bağlantısını kapatır + +## Konsensüs Yapılandırması {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +Konsensüs protokolünde veri depolaması için özel bir konum veya +konsensüs mekanizmasının kullanmasını istediğiniz özel bir anahtar değeri eşlemesi geçmek isteyebileceğiniz durumlar olabilir. Bu ***Config*** yapısı ile yapılabilir, +bu yapı yeni bir konsensüs örneği oluşturulduğunda okunur. + +## IBFT {#ibft} + +### ExtraData {#extradata} + +Blok zinciri başlık nesnesi diğer alanların yanında **ExtraData** adında bir alana sahiptir. + +IBFT blok hakkında operasyonel bilgi depolamak için bu ekstra alanı kullanır ve aşağıdaki gibi soruları yanıtlar: +* "Bu bloğu kim imzaladı?" +* "Bu bloğun doğrulayıcıları kimler?" + +IBFT için bu ekstra alanlar aşağıdaki gibi tanımlanır: +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### Veriyi İmzalama {#signing-data} + +Düğüm IBFT içinde bilgiyi imzalamak için *signHash* yöntemini kullanır: +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +Bir diğer kayda değer yöntem olan *VerifyCommittedFields*, geçerli doğrulayıcılardan alınan taahhütlü mühürleri doğrular: +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### Anlık görüntüler {#snapshots} + +Anlık görüntüler, adından da anlaşılacağı gibi, herhangi bir blok yüksekliği (sayısı) için *sistemin anlık görüntüsünü* veya *durumunu* sağlamak için vardır. + +Anlık görüntüler, doğrulayıcılardan oluşan bir düğüm kümesinin yanında oylama bilgisini içerir (doğrulayıcılar diğer doğrulayıcılar için oy kullanabilir). +Doğrulayıcılar, **Miner** başlığı alanına oylama bilgisini ekler ve tek seferlik anahtar (**nonce**) değerini değiştirir: +* Düğüm bir doğrulayıcı kaldırmak istiyorsa nonce değeri **tamamen 1'lerden** oluşur +* Düğüm bir doğrulayıcı eklemek istiyorsa nonce değeri **tamamen 0'lardan** oluşur + +Anlık görüntüler ***processHeaders*** yöntemi kullanılarak hesaplanır: + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +Bu yöntem genellikle 1 başlık ile çağrılır; ancak akış birden fazla başlık için de aynıdır.
+Her geçirilmiş başlık için IBFT'nin başlığın teklif sahibinin doğrulayıcı olduğunu doğrulaması gerekir. Bu doğrulamayı kolayca yapmak için +en son anlık görüntü alınır ve düğümün doğrulayıcı kümesinde olup olmadığı kontrol edilir. + +Ardından, nonce kontrol edilir. Oy dâhil edilmiş ve sayımı yapılmıştır ve yeterli oy varsa düğüm +doğrulayıcı kümesine eklenir veya kümeden kaldırılır, ardından yeni anlık görüntü kaydedilir. + +#### Anlık Görüntü Deposu {#snapshot-store} + +Anlık görüntü hizmeti, tüm mevcut anlık görüntülerin listesini depolayan **snapshotStore** adında bir varlığı yönetir ve günceller. +Bunu kullanarak, hizmet hangi anlık görüntünün hangi blok yüksekliği ile ilişkili olduğunu hızlı bir şekilde anlayabilecektir. +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### IBFT Başlangıcı {#ibft-startup} + +IBFT'yi başlatmak için Polygon Edge'in öncelikle IBFT aktarımını ayarlaması gerekir: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +Esasında yeni bir proto buff mesajı içeren, IBFT proto'lu yeni bir konu oluşturur.
+Mesajların doğrulayıcılar tarafından kullanılması amaçlanır. Polygon Edge ardından konuya abone olur ve mesajları uygun şekilde işler. + +#### MessageReq {#messagereq} + +Doğrulayıcılar arasında alınıp verilen mesaj: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +**MessageReq** içindeki **View** alanı, zincir içindeki güncel düğüm konumunu temsil eder. +Bir *round* ve bir *sequence* özelliğine sahiptir. +* **round**, yükseklik için teklif sahibinin round'unu temsil eder +* **sequence**, blok zinciri yüksekliğini temsil eder + +IBFT uygulamasının içinde dosyalanan *msgQueue*, mesaj isteklerini depolamak amacına sahiptir. Mesajları +*View* alanına göre (önce sequence'a göre, ardından round'a göre) sıralar. IBFT uygulaması sistem içindeki farklı durumlar için farklı kuyrukları da içerir. + +### IBFT Durumları {#ibft-states} + +Konsensüs mekanizması **Start** yöntemi kullanarak başlatıldıktan sonra, bir durum makinesini simüle eden sonsuz bir döngü içine girer: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### SyncState {#syncstate} + +Tüm düğümler başlangıçta **Sync** durumu ile çalışır. + +Bunun nedeni, blok zinciri üzerinden taze verinin alınması gerekliliğidir. İstemcinin doğrulayıcı olup olmadığını öğrenmesi, +güncel anlık görüntüyü bulması gerekir. Bu durum bekleyen tüm blokları çözer. + +Eşitleme bittikten ve istemci gerçekten bir doğrulayıcı olduğunu belirledikten sonra, **AcceptState** durumuna geçmesi gerekir. +İstemci bir doğrulayıcı **değilse**, eşitlemeye devam edecek ve **SyncState** durumunda kalacaktır + +#### AcceptState {#acceptstate} + +**Accept** durumu her seferinde anlık görüntüyü ve doğrulayıcı kümesini kontrol eder. Güncel düğüm doğrulayıcılar kümesinde değilse, +**Sync** durumuna geri döner. + +Öte yandan, düğüm bir doğrulayıcı **ise**, teklif sahibini hesaplar. Mevcut düğümün teklif sahibi olduğu ortaya çıkarsa, +bir blok oluşturur ve ön hazırlık ve ardından hazırlık mesajlarını gönderir. + +* Ön hazırlık mesajları: teklif sahipleri tarafından doğrulayıcılara, teklif hakkında bilgi vermek için gönderilen mesajlar +* Hazırlık mesajları: doğrulayıcıların bir teklif üzerinde hemfikir olduğu mesajlar. Tüm düğümler tüm hazırlık mesajlarını alır +* Taahhüt mesajları: teklif için taahhüt bilgisini içeren mesajlar + +Mevcut düğüm bir doğrulayıcı **değilse**, önceden gösterilen kuyruktan bir mesaj okumak için *getNextMessage* yöntemini kullanır.
+Ön hazırlık mesajlarını bekler. Her şeyin muntazam olduğu doğrulandıktan sonra, düğüm **Validate** durumuna geçer. + +#### ValidateState {#validatestate} + +**Validate** durumu oldukça basittir; bu durumdaki tüm düğümler mesajları okur ve kendi yerel anlık görüntü durumuna ekler. diff --git a/archive/edge/tr-edge/architecture/modules/json-rpc.md b/archive/edge/tr-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..ee697ad5bc --- /dev/null +++ b/archive/edge/tr-edge/architecture/modules/json-rpc.md @@ -0,0 +1,181 @@ +--- +id: json-rpc +title: JSON RPC +description: Polygon Edge'in JSON RPC modülünün açıklaması. +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## Genel Bakış {#overview} + +**JSON RPC** modülü, dApp geliştiricilerin blok zinciri ile etkileşim kurmakta kullandığı **JSON RPC API katmanını** +uygular. + +Standart **[json-rpc uç noktaların](https://eth.wiki/json-rpc/API)** yanında websocket uç noktaları için destek +içerir. + +## Blok Zinciri Arabirimi {#blockchain-interface} + +Polygon Edge, JSON RPC modülünün kullanması gereken tüm yöntemleri tanımlamak için ***blok zinciri*** arabirimini kullanarak +uç noktalarını sunar. + +Blok zinciri arabirimi **[Minimal](/docs/edge/architecture/modules/minimal)** sunucusu tarafından uygulanır. Bu, JSON RPC katmanına geçirilen +temel uygulamadır. + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## ETH Uç noktaları {#eth-endpoints} + +Tüm standart JSON RPC uç noktaları şurada uygulanır: + +````bash +jsonrpc/eth_endpoint.go +```` + +## Filtre Yöneticisi {#filter-manager} + +**Filtre Yöneticisi**, JSON RPC sunucusunun yanında çalışan bir hizmettir. + +Blok zinciri üzerinde blok filtreleme için destek sağlar.
+Özel olarak, bir **günlük** ve **blok** seviyesi filtre içerir. + +Filtre Yöneticisi büyük ölçüde Abonelik Olayları'na dayanır; bu konuya +[Block Zinciri](blockchain#blockchain-subscriptions) bölümünde değinilmiştir + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +Filtre Yöneticisi *Run* yöntemi ile görevlendirilir: + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## 📜 Kaynaklar {#resources} +* **[Ethereum JSON-RPC](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/tr-edge/architecture/modules/minimal.md b/archive/edge/tr-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..25647e2f7a --- /dev/null +++ b/archive/edge/tr-edge/architecture/modules/minimal.md @@ -0,0 +1,119 @@ +--- +id: minimal +title: Minimal +description: Polygon Edge'in minimal modülüne ilişkin açıklama. +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## Genel Bakış {#overview} + +Daha önce de belirtildiği üzere, Polygon Edge, hepsi birbirine bağlı olan farklı modüller kümesidir.
+**Blok Zinciri**, **Duruma** veya örneğin, **Blok Zincirine** yeni blokları bağlayan **Senkronizasyona** bağlıdır. + +**Minimal**, birbirine bağlı bu modüllerin önemli unsurlarından biridir.
+Polygon Edge üzerinde çalışan tüm hizmetler için merkezî bir dağıtıcı görevi görür. + +## Başlangıç Büyüsü {#startup-magic} + +Diğer şeylerin yanı sıra, Minimal aşağıdakilerden sorumludur: +* Veri dizinlerini kurma +* libp2p iletişimi için bir keystore oluşturma +* Depolama alanı oluşturma +* Konsensüs oluşturma +* GRPC, JSON RPC ve Senkronizasyon ile blok zinciri nesnesini kurma + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/tr-edge/architecture/modules/networking.md b/archive/edge/tr-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..34359ff5e6 --- /dev/null +++ b/archive/edge/tr-edge/architecture/modules/networking.md @@ -0,0 +1,80 @@ +--- +id: networking +title: Ağ oluşturma +description: Polygon Edge'in ağ oluşturma modülüne ilişkin açıklama. +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## Genel Bakış {#overview} + +Bir düğüm, yararlı bilgi alışverişinde bulunmak için ağdaki diğer düğümlerle iletişim kurmalıdır.
+Polygon Edge, bu görevi gerçekleştirmek için güvenilirliği test edilip kanıtlanmış **libp2p** çerçevesinden yararlanır. + + **libp2p** çerçevesinin seçilme nedeni esas olarak aşağıdakilere dayanmaktadır: +* **Hız** - libp2p, devp2p'ye göre (GETH ve diğer istemcilerde kullanılır) önemli bir performans artışına sahiptir +* **Genişletilebilirlik**- sistemin diğer özellikleri için harika bir temel olarak hizmet eder +* **Modülerlik** - libp2p, niteliği itibariyle Polygon Edge gibi modüler bir yapıya sahiptir. Bu özellikle Polygon Edge'in parçalarının değiştirilebilmesi gerektiğinde daha fazla esneklik sağlar + +## GRPC {#grpc} + + **libp2p** nin yanı sıra, Polygon Edge **GRPC** protokolünü de kullanır.
+Teknik olarak, Polygon Edge, birkaç GRPC protokolünü kullanır; bunlar daha sonra ele alınacaktır. + +GRPC katmanı tüm istek/yanıt protokollerini özetlemeye yardımcı olur ve Polygon Edge'in çalışması için gereken akış protokollerini basitleştirir. + +GRPC, *hizmetleri* ve *mesaj yapılarını * tanımlamak için **Protokol Arabellekleri**'ne güvenir.
+Hizmetler ve yapılar, derlenen ve dilden bağımsız olan *.proto* dosyalarında tanımlanır. + +Daha önce, Polygon Edge'in birkaç GRPC protokolünden yararlandığından bahsetmiştik.
+Bu, genellikle GETH ve Parity gibi istemcilerle gecikme yaşayan düğüm operatörünün UX'ini geliştirmek için yapılmıştır. + +Düğüm operatörü, aradığı bilgiyi bulmak için logları gözden geçirmek yerine GRPC hizmetini çağırarak sistemde neler olduğuna dair daha iyi bir genel bakışa sahip olur. + +### Düğüm Operatörleri için GRPC {#grpc-for-node-operators} + +Aşağıdaki bölüm, [CLI Komutları](/docs/edge/get-started/cli-commands) bölümünde kısaca ele alınmış olduğu için tanıdık gelebilir. + +**Düğüm operatörleri** tarafından kullanılması amaçlanan GRPC hizmeti şu şekilde tanımlanır: +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip + +CLI komutları aslında bu hizmet yöntemlerinin uygulamalarını çağırır. + +Bu yöntemler ***minimal/system_service.go*** içinde uygulanmaktadır. + +::: + +### Diğer Düğümler için GRPC {#grpc-for-other-nodes} + +Polygon Edge, ağdaki diğer düğümler tarafından kullanılan çeşitli hizmet yöntemlerini de uygular.
+Bahsedilen hizmet **[Protokol](docs/edge/architecture/modules/consensus)** bölümünde açıklanmıştır. + +## 📜 Kaynaklar {#resources} +* **[Protokol Arabellekleri](https://developers.google.com/protocol-buffers)** +* **[libp2p](https://libp2p.io/)** +* **[gRPC](https://grpc.io/)** diff --git a/archive/edge/tr-edge/architecture/modules/other-modules.md b/archive/edge/tr-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..30aaddc1dd --- /dev/null +++ b/archive/edge/tr-edge/architecture/modules/other-modules.md @@ -0,0 +1,36 @@ +--- +id: other-modules +title: Diğer modüller +description: Polygon Edge'in bazı modüllerine ilişkin açıklama. +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## Kripto {#crypto} + +**Kripto** modülü, kripto yardımcı işlevlerini içerir. + +## Zincir {#chain} + +**Zincir** modülü, zincir parametrelerini (aktif çatallar, konsensüs motoru, vb.) içerir + +* **zincirler** - Ön tanımlı zincir yapılandırmaları (mainnet, goerli, ibft) + +## Yardımcı {#helper} + +**Yardımcı** modülü, yardımcı paketlerini içerir. + +* **dao** - Dao yardımcı programları +* **enode** - Enode kodlama/kod çözme işlevi +* **hex** - Hex kodlama/kod çözme işlevleri +* **ipc** - IPC bağlantı fonksiyonları +* **keccak** - Keccak fonksiyonları +* **rlputil** - Rlp kodlama/kod çözme yardımcı işlevi + +## Komut {#command} + +**Komut** modülü, CLI komutları için arabirimler içerir. \ No newline at end of file diff --git a/archive/edge/tr-edge/architecture/modules/sealer.md b/archive/edge/tr-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..15a98c83a1 --- /dev/null +++ b/archive/edge/tr-edge/architecture/modules/sealer.md @@ -0,0 +1,73 @@ +--- +id: sealer +title: Mühürleyici +description: Polygon Edge'in mühürleyici modülüne ilişkin açıklama. +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## Genel Bakış {#overview} + +**Mühürleyici** (Sealer) işlemleri bir araya getiren ve yeni bir blok oluşturan bir varlıktır.
+Ardından, bu blok mühürlenmesi için **Konsensüs** modülüne gönderilir. + +Son mühür mantığı **Konsensüs** modülünde bulunur. + +## Çalıştırma Yöntemi {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution Devam eden çalışma + +**Mühürleyici** ve **Konsensüs** modülleri yakın gelecekte tek bir varlık içinde birleştirilecektir. + +Yeni modül, farklı mühürleme uygulamaları gerektiren farklı konsensüs mekanizmaları için modüler mantık içerecektir: +* **PoS** (Hisse Kanıtı) +* **PoA** (Yetki Kanıtı) + +Şu anda, **Mühürleyici** ve **Konsensüs** modülleri PoW (İş Kanıtı) ile çalışmaktadır. + +::: \ No newline at end of file diff --git a/archive/edge/tr-edge/architecture/modules/state.md b/archive/edge/tr-edge/architecture/modules/state.md new file mode 100644 index 0000000000..ebd84e2988 --- /dev/null +++ b/archive/edge/tr-edge/architecture/modules/state.md @@ -0,0 +1,248 @@ +--- +id: state +title: Durum +description: Polygon Edge'in durum modülüne ilişkin açıklama. +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +**Durum** modülünün nasıl çalıştığını gerçekten anlamak için, bazı temel Ethereum kavramlarını anlamalısınız.
+ +**[Ethereum'da durum rehberini](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)** okumanızı tavsiye ederiz. + +## Genel Bakış {#overview} + +Artık temel Ethereum kavramlarına aşina olduğumuza göre, bir sonraki genel bakış kolay olacaktır. + +**Global durum ağacının** mevcut tüm Ethereum hesaplarına sahip olduğundan bahsetmiştik.
+Bu hesaplar, Merkle ağacının yapraklarıdır. Her yaprak, **Hesap Durumu** bilgisini kodlamıştır. + +Bu, Polygon Edge'in belirli bir zaman dilimi için belirli bir Merkle ağacını almasını sağlar.
+Örneğin, 10. bloktaki durumun hash'ini alabiliriz. + +Merkle ağacı, herhangi bir zaman diliminde ***Anlık Görüntü*** olarak adlandırılır. + +**Durum ağacı** için veya **depolama ağacı** için ***Anlık Görüntüler*** alabiliriz; bunlar temelde aynıdır.
+Tek fark, yaprakların neyi temsil ettiğidir: + +* Depolama ağacı söz konusu olduğunda, yapraklar, orada işlem yapamayacağımız veya içinde ne olduğunu bilemeyeceğimiz rastgele bir durum içerir +* Durum ağacı söz konusu olduğunda, yapraklar hesapları temsil eder + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + + **Anlık Görüntü** arabirimi şu şekilde tanımlanır: + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +Taahhüt edilebilecek bilgiler, *Nesne yapısı* tarafından tanımlanır: + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +Merkle ağacının uygulaması *state/immutable-trie* klasöründedir.
+*state/immutable-trie/state.go* dosyası, **Durum** arabirimini uygular. + +*state/immutable-trie/trie.go* temel Merkle ağacı nesnesidir. Merkle ağacının, mümkün olduğunca çok bellek +kullanan optimize edilmiş bir sürümünü temsil eder. + +## Yürütücü {#executor} + +*state/executor.go*, Polygon Edge'in bir bloğun mevcut durumu nasıl değiştirdiğine karar vermesi için gereken tüm bilgileri +içerir. *ProcessBlock*'un uygulanması burada yer almaktadır. + +*apply* yöntemi, gerçek durum geçişini yapar. Yürütücü EVM'yi çağırır. + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## Çalışma süresi {#runtime} + +Bir durum geçişi yürütüldüğünde, durum geçişini yürüten ana modül EVM'dir +(state/runtime/evm içinde bulunur). + +**Gönderme tablosu**, **opcode** ve talimat arasında bir eşleşme yapar. + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +EVM'yi güçlendiren temel mantık *Çalıştır* döngüsüdür.
+ +EVM için ana giriş noktasıdır. Bir döngü gerçekleştirir ve mevcut işlem kodunu denetler, talimatı alır, +yürütülüp yürütülemeyeceğini kontrol eder, gaz tüketir ve başarısız olana ya da durana kadar komutu yürütür. + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/tr-edge/architecture/modules/storage.md b/archive/edge/tr-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..4d0184b226 --- /dev/null +++ b/archive/edge/tr-edge/architecture/modules/storage.md @@ -0,0 +1,118 @@ +--- +id: storage +title: Depolama +description: Polygon Edge'in depolama modülüne ilişkin açıklama. +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## Genel Bakış {#overview} + +Polygon Edge şu anda veri depolama ve **bellek içi** veri depolama için **LevelDB** kullanır. + +Polygon Edge genelinde, modüller altta yatan veri depolaması ile etkileşim kurmak istediğinde, +bunun için hangi DB motoru veya hizmet ile konuştuklarını bilmelerine gerek yoktur. + +DB katmanı, modüllerin sorguladığı arabirimleri dışa aktaran **Depolama** adlı bir modül arasında sadeleştirilir. + +Şimdilik sadece **LevelDB** olacak şekilde her DB katmanı, bu yöntemleri ayrı ayrı uygulayarak, uygulamalarına uygun olmalarını sağlar. + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### Ön Ekler {#prefixes} + +LevelDB depolama sorgulamasını deterministik hle getirmek ve anahtar depolama çakışmasını önlemek için Polygon Edge +veri depolarken ön ekler ve alt ön ekler kullanır + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## Gelecek Planları {#future-plans} + +Yakın gelecek planları arasında aşağıdakiler gibi en popüler DB çözümlerinden bazılarını eklemek bulunur: +* PostgreSQL +* MySQL + + +## 📜 Kaynaklar {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/tr-edge/architecture/modules/syncer.md b/archive/edge/tr-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..aa08ea5abc --- /dev/null +++ b/archive/edge/tr-edge/architecture/modules/syncer.md @@ -0,0 +1,68 @@ +--- +id: syncer +title: Eşitleyici +description: Polygon Edge'in eşitleyici modülüne ilişkin açıklama. +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## Genel Bakış {#overview} + +Bu modül, senkronizasyon protokolü mantığını içerir. Çalışan ağda yeni bir düğümü eşitlemek veya konsensüse katılmayan düğümler (doğrulayıcı olmayanlar) için yeni blok doğrulamak/eklemek için kullanılır. + +Polygon Edge ağ katmanı olarak **libp2p** kullanır ve bunun yanında **gRPC** çalıştırır. + +Polygon Edge'de temelde 2 eşitleme türü bulunur: +* Toplu Eşitleme - tek seferde büyük bir blok aralığını eşitleme +* İzleme Eşitleme - blok bazında eşitleme + +### Toplu Eşitleme {#bulk-sync} + +Toplu Eşitleme adımları, Toplu Eşitleme hedefini uygulamak için oldukça basittir; diğer eşte mümkün (kullanılabilir) olan en çok bloğu, mümkün olduğunca çabuk eşitleyerek yetişmek. + +Toplu Eşitleme işleminin akışı şu şekildedir: + +1. ** Düğümün Toplu Eşitleme ihtiyacı olup olmadığını belirleme ** - Bu adımda düğüm eş haritasını kontrol ederek düğümün yerel olarak sahip olduğundan daha büyük bir blok numarası olan biri olup olmadığını kontrol eder +2. ** En iyi eşi bulma (eşitleme eş haritasını kullanarak) ** - Bu adımda düğüm yukarıdaki örnekte belirtilen kriterlere bağlı olarak eşitlenecek en iyi eşi bulur. +3. ** Toplu bir eşitleme akışı açma ** - Bu adımda düğüm ortak blok numarasından blokları eşitlemek için en iyi eşe bir gRPC akışı açar +4. ** Toplu gönderme tamamlandığında akışı en iyi eş kapatır ** - Bu adımda düğümün eşitleme yaptığı en iyi eş, sahip olduğu tüm mevcut blokları gönderdiği anda akışı kapatır +5. ** Toplu eşitleme tamamlandığında düğümün bir doğrulayıcı olup olmadığını kontrol etme ** - Bu adımda akış en iyi eş tarafından kapatılır ve düğümün toplu eşitleme sonrasında onun bir doğrulayıcı olup olmadığını kontrol etmesi gerekir. + * Eğer öyleyse, eşitleme durumundan çıkar ve konsensüs sürecine katılmaya başlar + * Öyle değilse, ** İzleme Eşitleme ** durumunda devam eder + +### İzleme Eşitleme {#watch-sync} + +:::info + +İzleme Eşitleme adımı yalnızca düğüm bir doğrulayıcı değilse ama ağdaki normal doğrulayıcı olmayan bir düğüm ise ve sadece gelen blokları dinliyorsa yürütülür. + +::: + +İzleme Eşitleme davranışı oldukça basittir; düğüm zaten ağın geri kalanı ile eşitlenmiştir ve yalnızca gelen yeni blokları ayrıştırması gerekir. + +İzleme Eşitleme işleminin akışı bu şekildedir: + +1. ** Bir eşin durumu güncellendiğinde yeni bir blok ekleme ** - Bu adımda düğümler yeni blok olaylarını dinler ve yeni bir blok geldiğinde bir gRPC işlev çağrısı yapar, bloku alır ve yerel durumu günceller. +2. ** En son bloku eşitledikten sonra düğümün bir doğrulayıcı olup olmadığını kontrol etme ** + * Eğer öyleyse, eşitleme durumundan çıkar + * Değilse, yeni blok olaylarını dinlemeye devam eder + +## Performans raporu {#perfomance-report} + +:::info + +Performans yerel bir makine üzerinde ** bir milyon blok ** eşitleyerek ölçülmüştür + +::: + +| Ad | Sonuç | +|----------------------|----------------| +| 1M blok eşitleme | ~ 25 dakika | +| 1M blok aktarma | ~ 1 dakika | +| GRPC çağrı sayısı | 2 | +| Test kapsamı | ~ %93 | \ No newline at end of file diff --git a/archive/edge/tr-edge/architecture/modules/txpool.md b/archive/edge/tr-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..f9c877c860 --- /dev/null +++ b/archive/edge/tr-edge/architecture/modules/txpool.md @@ -0,0 +1,230 @@ +--- +id: txpool +title: TxPool +description: Polygon Edge'in TxPool modülüne ilişkin açıklama. +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## Genel Bakış {#overview} + +TxPool modülü, işlemlerin sistemin farklı bölümlerinden eklendiği işlem havuzu uygulamasını +temsil eder. Modül ayrıca, aşağıda ele alınan düğüm operatörleri için birkaç yararlı özellik sunar. + +## Operatör Komutları {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +Düğüm operatörleri, **[CLI Komutları](/docs/edge/get-started/cli-commands#transaction-pool-commands)** bölümünde açıklandığı üzere bu GRPC uç noktalarında sorgu yapabilir. + +## İşlemlerin İşlenmesi {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +***addImpl*** yöntemi, **TxPool** modülünün olmazsa olmazıdır. Burası işlemlerin sisteme eklendiği merkezdir; bu ekleme işlemi GRPC hizmeti, JSON RPC uç noktalarından çağrılarak +ve istemci **gossip** protokolü işlem aldığında gerçekleşir. + +Sadece işlemlerin eklendiği bağlamı (GRPC, JSON RPC...) ifade eden bir **ctx** argümanını alır.
+Diğer parametre ise havuza eklenecek işlemlerin listesidir. + +Burada not edilmesi gereken en önemli şey, işlem içindeki **From** alanının kontrolüdür: +* **From** alanı **boşsa**, şifrelenmemiş/imzalanmamış bir işlem olarak kabul edilir. Bu tür işlemler yalnızca +geliştirme modunda kabul edilir +* **From** alanı **boş değilse**, bu, imzalanmış bir işlem olduğu anlamına gelir ve bu nedenle imza doğrulaması gerçekleşir + +Tüm bu doğrulamalardan sonra, yapılan işlemler geçerli olarak kabul edilir. + +## Veri yapıları {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +TxPool nesnesi içinde karışıklığa neden olabilecek alanlar **kuyruk** ve **sıralı** listelerdir. +* **kuyruk** - Sıralı bir hesap hareketleri listesinin yığın uygulaması (nonce ile) +* **sıralı** - Geçerli tüm desteklenen işlemler için sıralı liste (tüm yürütülebilir işlemler). Gaz fiyatına göre sıralanmış + +## Gaz limiti hata yönetimi {#gas-limit-error-management} + +Bir işlem gönderdiğinizde, TxPool tarafından işlenmesinin üç yolu vardır. + +1. Tüm bekleyen işlemler bir blok içine sığabilir +2. Bir veya daha fazla bekleyen işlem bir blok içine sığamaz +3. Bir veya daha fazla bekleyen işlem asla bir blok içine sığmayacaktır + +Burada, **_sığmak_** kelimesi, işlemin TxPool içindeki kalan gaz miktarından daha düşük bir gaz limitine sahip olduğu anlamına gelir. + +İlk senaryo herhangi bir hata üretmez. + +### İkinci senaryo {#second-scenario} + +- TxPool'da kalan gaz, son blokun gaz limitine ayarlanır; diyelim ki **5000** +- İlk işlem işlenir ve TxPool'dan **3000** gaz tüketir + - TxPool'un kalan gazı artık **2000**'dir +- İlk işlem ile aynı olan ikinci bir işlem gönderilir; her ikisi de 3000 birim gaz tüketir +- TxPool'un kalan gazı işlem gazından **daha düşük** olduğu için işlem mevcut blokta +işlenemez + - Bir sonraki blokta işlenebilmesi için bekleyen işlem kuyruğuna geri konur +- İlk blok yazılır; buna **blok #1** diyelim +- Kalan TxPool gazı ana bloka ayarlanır - **blok #1**'in gaz limiti +- TxPool bekleyen işlem kuyruğuna geri konan işlem artık işlenir ve bloka yazılır + - TxPool'un kalan gazı artık **2000**'dir +- İkinci blok yazılır +- ... + +![TxPool Hata senaryosu #1](/img/edge/txpool-error-1.png) + +### Üçüncü senaryo {#third-scenario} +- TxPool'da kalan gaz, son blokun gaz limitine ayarlanır; diyelim ki **5000** +- İlk işlem işlenir ve TxPool'dan **3000** gaz tüketir + - TxPool'un kalan gazı artık **2000**'dir +- Gaz alanı **6000**'e ayarlanmış ikinci bir işlem gönderilir +- Blok gaz limiti, işlem gazından **daha düşük** olduğu için bu işlem iptal edilir + - Bir blok içine asla sığamayacaktır +- İlk blok yazılır +- ... + + +![TxPool Hata senaryosu #2](/img/edge/txpool-error-2.png) + +> Bu, aşağıdaki hatayı aldığınızda gerçekleşir: +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## Blok Gaz Hedefi {#block-gas-target} + +Düğümlerin çalışan bir zincirde blok gaz limitini aşağıda veya belirli bir hedefte tutmak istediği durumlar vardır. + +Düğüm operatörü, bu limiti yeni oluşturulan bloklara uygulamaya çalışacak olan belirli bir düğümde hedef gaz limitini ayarlayabilir. +Diğer düğümlerin çoğunluğunun da benzer (veya aynı) bir hedef gaz limiti kümesi varsa, o zaman blok gaz limiti her zaman +o blok gaz hedefinin etrafında gezinecek ve yeni bloklar oluşturuldukça yavaş yavaş (en fazla `1/1024 * parent block gas limit`) ona doğru ilerleyecektir. + +### Örnek senaryo {#example-scenario} + +* Düğüm operatörü, tek bir düğüm için blok gaz limitini `5000` olarak ayarlar +* `7000` olarak yapılandırılan tek bir düğüm dışında diğer düğümler de `5000` olacak şekilde yapılandırılmıştır +* Gaz hedefi `5000` olarak ayarlanmış düğümler teklif sahibi olduklarında gaz limitinin zaten hedefte olup olmadığını denetleyeceklerdir +* Gaz limiti hedefte değilse (daha büyük/düşük ise), teklif sahibi düğüm, blok gaz hedefini hedef doğrultusunda en fazla (1/1024 * ana gaz limiti) olarak ayarlar + 1. Ör: `parentGasLimit = 4500` ve `blockGasTarget = 5000`; teklif sahibi blok için gaz limitini `4504.39453125` (`4500/1024 + 4500`) olarak hesaplayacaktır + 2. Ör: `parentGasLimit = 5500` ve `blockGasTarget = 5000`; teklif sahibi blok için gaz limitini `5494.62890625` (`5500 - 5500/1024`) olarak hesaplayacaktır +* Bu, zincir içindeki gaz limitinin hedefte tutulmasını sağlar çünkü hedefi `7000` olarak yapılandıran tek teklif sahibi limiti çok fazla artıramayacak ve +düğümlerin çoğunluğu `5000` olarak ayarladıkları için her zaman hedefi o noktada tutmaya çalışacaktır \ No newline at end of file diff --git a/archive/edge/tr-edge/architecture/modules/types.md b/archive/edge/tr-edge/architecture/modules/types.md new file mode 100644 index 0000000000..9065b1ab3d --- /dev/null +++ b/archive/edge/tr-edge/architecture/modules/types.md @@ -0,0 +1,43 @@ +--- +id: types +title: Türler +description: Polygon Edge'in modül türlerine ilişkin açıklama. +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## Genel Bakış {#overview} + +**Türler** modülü, temel nesne türlerini uygular; örneğin: + +* **Adres** +* **Hash** +* **Başlık** +* birçok yardımcı işlev + +## RLP Kodlama / Çözme {#rlp-encoding-decoding} + +GETH gibi istemcilerin aksine, Polygon Edge kodlama için yansıtma kullanmaz.
+Yansıtma tercih edilmemiştir çünkü bazı yeni sorunlar ortaya çıkarır, örneğin performans, +bozunma ve daha zor ölçekleme. + +**Türler** modülü, FastRLP paketi kullanarak RLP marshaling ve unmarshaling için kolay bir arabirim sunar. + +Marshaling *MarshalRLPWith* ve *MarshalRLPTo* yöntemleri ile yapılır. Benzer yöntemler unmarshaling +için de mevcuttur. + +Bu yöntemleri manuel olarak tanımlayan Polygon Edge'in yansıtma kullanması gerekmez. *rlp_marshal.go* üzerinde +marshaling için yöntemler bulabilirsiniz: + +* **Gövdeler** +* **Bloklar** +* **Başlıklar** +* **Alındılar** +* **Günlükler** +* **İşlemler** \ No newline at end of file diff --git a/archive/edge/tr-edge/architecture/overview.md b/archive/edge/tr-edge/architecture/overview.md new file mode 100644 index 0000000000..5211aff07b --- /dev/null +++ b/archive/edge/tr-edge/architecture/overview.md @@ -0,0 +1,61 @@ +--- +id: overview +title: Mimari Genel Görünümü +sidebar_label: Overview +description: Polygon Edge mimarisine giriş. +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +*Modüler* bir yazılım yapma fikriyle başladık. + +Bu yaklaşım Polygon Edge'in hemen hemen tüm bileşenlerinde görülebilir. Aşağıda, oluşturulan mimarinin ve katmanlarının kısa bir +genel görünümünü bulacaksınız. + +## Polygon Edge Katmanlama {#polygon-edge-layering} + +![Polygon Edge Mimarisi](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +Her şey **libp2p** kullanan temel ağ oluşturma katmanı ile başlar. Bu teknoloji ile çalışmaya karar verdik, çünkü +Polygon Edge'in tasarım felsefelerine uymaktadır. Libp2p: + +- Modülerdir +- Genişletilebilirdir +- Hızlıdır + +En önemlisi, daha gelişmiş özellikler için harika bir temel sağlar; bunları ileride ele alacağız. + + +## Eşitleme ve Konsensüs {#synchronization-consensus} +Eşitleme ve konsensüs protokollerinin ayrılması, **istemcinin** nasıl çalıştırıldığına bağlı olarak modülerliğe ve özel eşitleme ve konsensüs mekanizmalarının uygulanmasına olanak tanır. + +Polygon Edge, kullanıma hazır eklenebilir konsensüs algoritmaları sunmak için tasarlanmıştır. + +Desteklenen konsensüs algoritmalarının güncel listesi: + +* IBFT PoA +* IBFT PoS + +## Blok zinciri {#blockchain} +Blok zinciri katmanı, Polygon Edge sistemi içindeki her şeyi koordine eden merkezi katmandır. İlgili *Modüller* bölümü içinde derinlemesine ele alınmaktadır. + +## Durum {#state} +Durum iç katmanı, durum geçiş mantığını içerir. Yeni bir blok eklendiğinde durumun nasıl değiştiği ile ilgilenir. İlgili *Modüller* bölümü içinde derinlemesine ele alınmaktadır. + +## JSON RPC {#json-rpc} +JSON RPC katmanı, dApp geliştiricilerinin blok zinciri ile etkileşim kurmak için kullandıkları API katmanıdır. İlgili *Modüller* bölümü içinde derinlemesine ele alınmaktadır. + +## TxPool {#txpool} +TxPool katmanı işlem havuzunu temsil eder ve işlemler birden fazla giriş noktasından eklenebildiği için sistem içindeki diğer modüller ile yakından bağlantılıdır. + +## grpc {#grpc} +gRPC veya Google Uzaktan İşlem Çağrısı, Google'ın başlangıçta ölçeklenebilir ve hızlı API'ler oluşturmak için yarattığı sağlam bir açık kaynaklı RPC çerçevesidir. GRPC katmanı operatör etkileşimleri için hayati önem taşır. Bu katman üzerinden düğüm operatörleri istemci ile kolayca etkileşim kurarak keyifli bir kullanıcı deneyimi elde edebilir. diff --git a/archive/edge/tr-edge/community/propose-new-feature.md b/archive/edge/tr-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..392a388f1d --- /dev/null +++ b/archive/edge/tr-edge/community/propose-new-feature.md @@ -0,0 +1,60 @@ +--- +id: propose-new-feature +title: Yeni bir özellik teklif edin +description: "Yeni bir özellik teklif etmek için PR şablonu ve talimatları." +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## Genel Bakış {#overview} + +Bir düzeltme eklemek veya yalnızca kod için katkıda bulunmak istiyorsanız, önce ekip ile iletişime geçmeniz tavsiye edilir.
+Polygon Edge, kısa ve öz olan oldukça sade bir özellik teklif şablonu kullanır. + +## PR Şablonu {#pr-template} + +### Açıklama {#description} + +Lütfen bu PR'de ne yapıldığına dair ayrıntılı bir açıklama sağlayın + +### Değişiklikler şunları içerir {#changes-include} + +- [ ]Hata Düzeltme (bir sorunu çözen bölünemez değişiklik) +- [ ]Düzeltme (acil bir sorunu çözen ve hemen müdahale gerektiren değişiklik) +- [ ]Yeni özellik (işlevsellik kazandıran bölünemez değişiklik) +- [ ]Bozucu değişiklikler (geriye dönük uyumlu olmayan ve/veya mevcut işlevselliği değiştiren değişiklik) + +### Bozucu değişiklikler {#breaking-changes} + +Herhangi bozucu değişiklik yapıldıysa lütfen bu bölümü doldurun, aksi takdirde silin + +### Kontrol listesi {#checklist} + +- [ ] Bu PR'yi kendime atadım +- [ ] En az 1 gözden geçiren ekledim +- [ ] İlgili etiketleri ekledim +- [ ] Resmî belgeleri güncelledim +- [ ] Kod içinde yeterince belge ekledim + +### Test Etme {#testing} + +- [ ] Bu kodu resmî test aracı ile test ettim +- [ ] Bu kodu manuel olarak test ettim + +## Manuel testler {#manual-tests} + +Bu işlev için manuel testler yürüttüyseniz lütfen bu bölümü doldurun, aksi takdirde silin + +### Belgeleri güncelleme {#documentation-update} + +Lütfen mevcutsa bu bölümde belge güncelleme PR bağlantısını verin, aksi takdirde silin + +### Ek yorumlar {#additional-comments} + +Lütfen ek yorumunuz varsa bu bölüme girin, aksi takdirde silin \ No newline at end of file diff --git a/archive/edge/tr-edge/community/report-bug.md b/archive/edge/tr-edge/community/report-bug.md new file mode 100644 index 0000000000..c9e1716d39 --- /dev/null +++ b/archive/edge/tr-edge/community/report-bug.md @@ -0,0 +1,55 @@ +--- +id: report-bug +title: Bir sorun bildirin +description: Polygon Edge'de bir sorun bildirmek için şablon ve talimatlar. +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## Genel Bakış {#overview} + +Bazen bazı şeyler bozulur.
+Ekibe karşılaşabileceğiniz herhangi bir sorun hakkında bilgi vermek her zaman en iyisidir.
+Polygon Edge GitHub sayfasında, yeni bir sorun oluşturabilir ve ekiple tartışmaya başlayabilirsiniz. + +## Sorun Şablonu {#issue-template} + +## [Sorunun Konusu] + +### Açıklama {#description} + +Sorununuzu mümkün olduğunca çok ayrıntı vererek burada açıklayın + +### Ortamınız {#your-environment} + +* İşletim Sistemi ve sürümü +* Polygon Edge sürümü +* Bu sorunu yaratan kısım + +### Yeniden üretme adımları {#steps-to-reproduce} + +* Bu sorunu nasıl yeniden üretebileceğimizi bize söyleyin
+* Biliyorsanız, sorunun yeri
+* Varsa, sorunu tetikleyen komutlar + +### Beklenen davranış {#expected-behaviour} + +Bize ne olması gerektiğini söyleyin + +### Gerçekleşen davranış {#actual-behaviour} + +Beklenen yerine ne olduğunu bize söyleyin + +### Günlükler {#logs} + +Varsa, sorunu gösteren herhangi bir günlüğü buraya yapıştırın + +### Önerilen çözüm {#proposed-solution} + +Bu sorunun nasıl çözüleceği hakkında bir fikriniz varsa, lütfen buraya yazın, böylece tartışmaya başlayabiliriz \ No newline at end of file diff --git a/archive/edge/tr-edge/configuration/manage-private-keys.md b/archive/edge/tr-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..704d9f088b --- /dev/null +++ b/archive/edge/tr-edge/configuration/manage-private-keys.md @@ -0,0 +1,79 @@ +--- +id: manage-private-keys +title: Özel anahtarları yönetme +description: "Özel anahtarlar nasıl yönetilir ve anahtar türleri nelerdir?" +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## Genel Bakış {#overview} + +Polygon Edge'in doğrudan yönettiği iki tür özel anahtar vardır: + +* **Konsensüs mekanizması için kullanılan özel anahtar** +* **libp2p tarafından ağ oluşturmak için kullanılan özel anahtar** +* **(İsteğe bağlı) Doğrulayıcıların imzalarını toplamak için konsensüs mekanizması için kullanılan BLS Özel anahtarı** + +Şu anda, Polygon Edge doğrudan hesap yönetimi için destek sunmamaktadır. + +[Yedekleme ve Geri Yükleme kılavuzunda](/docs/edge/working-with-node/backup-restore) özetlenen dizin yapısına göre, +Polygon Edge, bahsedilen bu anahtar dosyalarını iki ayrı dizinde saklar: **konsensüs** ve **keystore**. + +## Anahtar formatı {#key-format} + +Özel anahtarlar basit **Base64 formatında** saklanır, böylece insanlar tarafından okunabilir ve taşınabilir. + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info Anahtar Türü + +Polygon Edge içinde üretilen ve kullanılan tüm özel anahtar dosyaları [secp256k1](https://en.bitcoin.it/wiki/Secp256k1) eğrisi ile ECDSA'ya dayanır. + +Eğri, standart olmadığı için kodlanamaz ve herhangi bir standartlaştırılmış PEM formatında saklanamaz. +Bu anahtar tipine uygun olmayan anahtarların içe aktarımı desteklenmemektedir. + +::: +## Konsensüs Özel Anahtarı {#consensus-private-key} + +*Konsensüs özel anahtarı* olarak bahsedilen özel anahtar dosyası, **doğrulayıcı özel anahtarı** olarak da adlandırılmaktadır. +Bu özel anahtar, düğüm ağda doğrulayıcı görevi gördüğünde ve yeni verileri imzalaması gerektiğinde kullanılır. + +Özel anahtar dosyası `consensus/validator.key`'de yer alır ve bahsedilen [anahtar formatına](/docs/edge/configuration/manage-private-keys#key-format) bağlıdır. + +:::warning + +Doğrulayıcı özel anahtarı, her doğrulayıcı düğüm için benzersizdir. Aynı anahtar tüm doğrulayıcılar arasında paylaşılmamalıdır çünkü bu, zincirinizin güvenliğini tehlikeye atabilir. + +::: + +## Ağ Özel Anahtarı {#networking-private-key} + +Ağ oluşturmak için bahsedilen özel anahtar dosyası, ilgili PeerID'yi oluşturmak ve düğümün ağa katılmasına izin vermek için libp2p tarafından kullanılır. + +`keystore/libp2p.key`'de bulunur ve bahsedilen [anahtar formatına](/docs/edge/configuration/manage-private-keys#key-format) bağlıdır. + +## BLS Gizli Anahtarı {#bls-secret-key} + +BLS gizli anahtar dosyası, konsensüs katmanında taahhüt edilen mühürleri toplamak için kullanılır. BLS tarafından toplu olarak taahhüt edilen mühürlerin boyutu, serileştirilmiş taahhüt edilen ECDSA imzalarından daha azdır. + +BLS özelliği isteğe bağlıdır ve BLS kullanıp kullanmamayı seçmek mümkündür. Daha fazla ayrıntı için [BLS](/docs/edge/consensus/bls)'ye göz atın. + +## İçe Aktarma / Dışa Aktarma {#import-export} + +Anahtar dosyaları diskte basit Base64 formatında depolandığı için kolayca yedeklenebilir veya içe aktarılabilir. + +:::caution Anahtar dosyalarını değiştirme + +Halihazırda kurulmuş/çalışan bir ağdaki anahtar dosyalarında yapılan her türlü değişiklik ciddi ağ/konsensüs bozulmasına yol açabilir +çünkü konsensüs ve eş bulma mekanizmaları bu anahtardan türetilen verileri düğüme özgü depoda saklar ve +bağlantıları başlatmak ve konsensüs mantığını gerçekleştirmek için bu verilere güvenir. + +::: \ No newline at end of file diff --git a/archive/edge/tr-edge/configuration/prometheus-metrics.md b/archive/edge/tr-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..1f1c895c01 --- /dev/null +++ b/archive/edge/tr-edge/configuration/prometheus-metrics.md @@ -0,0 +1,35 @@ +--- +id: prometheus-metrics +title: Prometheus ölçütleri +description: "Polygon Edge için Prometheus ölçütleri nasıl etkinleştirilir?" +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## Genel Bakış {#overview} + +Polygon Edge, sıraları geldiğinde Prometheus toplayıcıları kullanarak tüketilebilen Prometheus ölçütlerini raporlayabilir ve sunabilir. + +Prometheus ölçümleri varsayılan olarak devre dışı bırakılır. Yapılandırma dosyasında `--prometheus`[bayrak](/docs/edge/get-started/cli-commands#prometheus) veya `Telemetry.prometheus`alan kullanarak dinleyici adresini belirleme ile etkinleştirilebilir. Ölçütler, belirtilen adreste `/metrics` altında sunulacaktır. + +## Mevcut ölçütler {#available-metrics} + +Aşağıdaki ölçütler mevcuttur: + +| **Ad** | **Tip** | **Açıklama** | +|-------------------------------------------------|----------|---------------------------------------------| +| edge_txpool_pending_transactions | Ölçü | TxPool'da bekleyen işlem sayısı | +| edge_consensus_validators | Ölçü | Doğrulayıcı Sayısı | +| edge_consensus_rounds | Ölçü | Round Sayısı | +| edge_consensus_num_txs | Ölçü | Son bloktaki İşlem Sayısı | +| edge_consensus_block_interval | Ölçü | Saniye cinsinden bu ve son blok arasındaki zaman | +| edge_network_peers | Ölçü | Bağlı eşlerin sayısı | +| edge_network_outbound_connections_count | Ölçü | Giden bağlantı sayısı | +| edge_network_inbound_connections_count | Ölçü | Gelen bağlantı sayısı | +| edge_network_pending_inbound_connections_count | Ölçü | Bekleyen giden bağlantı sayısı | +| edge_network_pending_outbound_connections_count | Ölçü | Bekleyen gelen bağlantı sayısı | +| edge_consensus_epoch_number | Ölçü | Mevcut dönem numarası | \ No newline at end of file diff --git a/archive/edge/tr-edge/configuration/sample-config.md b/archive/edge/tr-edge/configuration/sample-config.md new file mode 100644 index 0000000000..3237b70271 --- /dev/null +++ b/archive/edge/tr-edge/configuration/sample-config.md @@ -0,0 +1,150 @@ +--- +id: sample-config +title: Sunucu Yapılandırma Dosyası +description: "Bir yapılandırma dosyası kullanarak Polygon Edge sunucusunu başlatın." +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# Sunucu yapılandırma dosyası {#server-configuration-file} +Sunucu, sadece bayrak kullanmak yerine yapılandırma dosyası kullanılarak çeşitli yapılandırma seçenekleriyle başlatılabilir. +Bir yapılandırma dosyası ile sunucuyu başlatmak için kullanılan komut: `polygon-edge server --config ` + +## Yapılandırma dosyasını varsayılan yapılandırma ile dışa aktarma {#export-config-file-with-default-configuration} +Polygon Edge sunucusu için varsayılan ayarları içeren yapılandırma, `yaml` veya `json`dosya biçiminde bir yapılandırma dosyasına aktarılabilir. Bu dosya, bir yapılandırma dosyası kullanarak sunucuyu çalıştırmak için şablon olarak kullanılabilir. + +### YAML {#yaml} +`yaml` formatında yapılandırma dosyası oluşturmak için: +```bash +polygon-edge server export --type yaml +``` +veya sadece +```bash +polygon-edge server export +``` +`default-config.yaml` adlı yapılandırma dosyası bu komutun çalıştırıldığı dizinde oluşturulacaktır. + +Dosya örneği: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +`json` formatında yapılandırma dosyası oluşturmak için: +```bash +polygon-edge server export --type json +``` +`default-config.json` adlı yapılandırma dosyası bu komutun çalıştırıldığı dizinde oluşturulacaktır. + +Dosya örneği: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +Bu parametrelerin nasıl kullanılacağı hakkında bilgi almak için [CLI Komutları](/docs/edge/get-started/cli-commands) bölümüne göz atın. + +### Typescript şeması {#typescript-schema} + +Yapılandırma dosyası için örnek format aşağıdadır. Özellik türlerini (`string`, `number`, `boolean`) ifade etmek için TypeScript'te yazılmıştır, bu özellik türlerinden yapılandırmanızı türetebilirsiniz. Tüm özelliklerin isteğe bağlı olduğunu ifade etmek için `type-fest`'ten `PartialDeep` türünün kullanıldığını belirtmekte fayda var. + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/tr-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/tr-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..b828b98d93 --- /dev/null +++ b/archive/edge/tr-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,139 @@ +--- +id: set-up-aws-ssm +title: AWS SSM (Sistem Yöneticisi) yapılandırması +description: "Polygon Edge için AWS SSM (Sistem Yöneticisi) yapılandırın." +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## Genel Bakış {#overview} + +Şu anda, Polygon Edge 2 temel çalışma zamanı sırrı tutmakla meşguldür: +* Düğüm bir doğrulayıcı ise, düğüm tarafından kullanılan **doğrulayıcı özel anahtarı** +* Diğer eşlere katılmak ve onlarla iletişim kurmak için libp2p tarafından kullanılan **ağ özel anahtarı** + +Daha fazla bilgi için lütfen [Özel Anahtarları Yönetme Kılavuzu](/docs/edge/configuration/manage-private-keys)'nu okuyun + +Polygon Edge modüllerinin **nasıl sır tutulacağını bilmesine gerek yoktur**. Sonuçta, bir modülün +sırrın uzaklarda bir sunucuda veya yerel olarak düğümün diskinde depolandığını umursamaması gerekir. + +Bir modülün sır tutma hakkında bilmesi gereken her şey **sırrı nasıl kullanacağını**, **hangi sırrı alacağını +veya kaydedeceğini** bilmekten ibarettir. Bu operasyonların daha ince uygulama detayları, elbette bir soyutlama olan `SecretsManager` üzerine yüklenmiştir. + +Polygon Edge'i başlatan düğüm operatörü, artık hangi sır yöneticisini kullanmak istediğini belirleyebilir ve +doğru sır yöneticisi somutlaştırıldığında, modüller sözü geçen arabirim aracılığıyla sırları yönetebilir - +bunu sırların bir diskte veya bir sunucuda depolanıp depolanmadığını umursamadan yapar. + +Bu makalede, Polygon Edge'in +[AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) ile sorunsuz bir şekilde çalıştırılması için gereken adımlar ayrıntılarıyla anlatılmaktadır. + +:::info önceki kılavuzlar + +Bu makaleyi okumadan önce, [**Yerel Kurulum**](/docs/edge/get-started/set-up-ibft-locally) ile ilgili makalelerin gözden geçirilmesi **tavsiye edilir** +ve ayrıca [**Bulut Kurulumu**](/docs/edge/get-started/set-up-ibft-on-the-cloud) da okunmalıdır. + +::: + + +## Ön Koşullar {#prerequisites} +### IAM Politikası {#iam-policy} +Kullanıcının AWS Systems Manager Parameter Store için okuma/yazma işlemlerine izin veren bir IAM Politikası oluşturması gerekir. +IAM Politikasını başarıyla oluşturduktan sonra, kullanıcı bunu Polygon Edge sunucusunu çalıştıran EC2 oturumuna eklemelidir. +IAM Politikası şöyle bir şeye benzemelidir: +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +AWS SSM IAM Rolleri hakkında daha bilgiyi [AWS belgeleri](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html) içinde bulabilirsiniz. + +Devam etmeden önce gerekli bilgiler: +* **Bölge** (Sistem Yöneticisinin ve düğümlerin bulunduğu bölge) +* **Parametre Yolu** (sırrın yerleştirileceği gelişigüzel bir dizin, örneğin `/polygon-edge/nodes`) + +## Adım 1 - Sır yöneticisi yapılandırmasını oluşturma {#step-1-generate-the-secrets-manager-configuration} + +Polygon Edge'in AWS SSM ile sorunsuz bir şekilde iletişim kurabilmesi için zaten oluşturulmuş bir yapılandırma dosyasını ayrıştırması gerekir +ve bu dosya AWS SSM üzerinde sır depolama için gerekli tüm bilgiyi içerir. + +Yapılandırmayı oluşturmak için aşağıdaki komutu çalıştırın: + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +Mevcut parametreler: +* `PATH`, yapılandırma dosyasının dışa aktarılacağı dizindir. Varsayılan `./secretsManagerConfig.json` +* `NODE_NAME`, AWS SSM yapılandırmasının kurulduğu mevcut düğümün adıdır. Gelişigüzel bir değer olarak belirlenebilir. Varsayılan `polygon-edge-node` +* `REGION` AWS SSM'nin konumlandığı bölgedir. AWS SSM kullanan düğüm ile aynı bölgede olmalıdır. +* `SSM_PARAM_PATH`, sırrın depolanacağı dizinin adıdır. Örneğin, `--name node1` ve `ssm-parameter-path=/polygon-edge/nodes` +belirlendiyse, sır `/polygon-edge/nodes/node1/` olarak depolanacaktır + +:::caution Düğüm adları + +Düğüm adlarını belirlerken dikkatli olun. + +Polygon Edge, AWS SSM üzerinde oluşturduğu ve kullandığı sırları takip etmek için belirlenen düğüm adını kullanır. +Mevcut bir düğümün adını belirlemek, AWS SSM için sır yazamamak gibi sonuçlara neden olabilir. + +Sırlar aşağıdaki temel dizinde depolanır: `SSM_PARAM_PATH/NODE_NAME` + +::: + +## Adım 2 - Yapılandırmayı kullanarak gizli anahtarları başlatma {#step-2-initialize-secret-keys-using-the-configuration} + +Artık yapılandırma dosyası mevcut olduğuna göre, gerekli gizli anahtarları +adım 1'de ayarlanan yapılandırma dosyası ile `--config` kullanarak başlatabiliriz: + +```bash +polygon-edge secrets init --config +``` + +`PATH` parametresi, daha önce adım 1'de oluşturulan sır yöneticisi parametresinin konumudur. + +:::info IAM Politikası + +Okuma/yazma işlemlerine izin veren IAM Politikası doğru şekilde yapılandırılmadıysa veya bu komutu çalıştıran EC2 oturumuna eklenmediyse bu adım başarısız olacaktır. + +::: + +## Adım 3 - Genesis dosyasını oluşturma {#step-3-generate-the-genesis-file} + +Genesis dosyası [**Yerel Kurulum**](/docs/edge/get-started/set-up-ibft-locally) +ve [**Bulut Kurulumu**](/docs/edge/get-started/set-up-ibft-on-the-cloud) kılavuzları ile benzer şekilde, ancak birkaç küçük değişiklik ile oluşturulmalıdır. + +AWS SSM, yerel dosya sistemi yerine kullanıldığından, doğrulayıcı adresleri `--ibft-validator` bayrağı ile eklenmelidir: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Adım 4 - Polygon Edge istemcisini başlatma {#step-4-start-the-polygon-edge-client} + +Artık anahtarlar kurulduğuna ve genesis dosyası oluşturulduğuna göre, bu işlemin son adımı +Polygon Edge'i `server` komutu ile başlatmak olacaktır. + +`server` komutu daha önce bahsedilen kılavuzlardaki gibi aynı şekilde, küçük bir ekleme ile kullanılmalıdır: `--secrets-config`bayrağı: +```bash +polygon-edge server --secrets-config ... +``` + +`PATH` parametresi, daha önce adım 1'de oluşturulan sır yöneticisi parametresinin konumudur. \ No newline at end of file diff --git a/archive/edge/tr-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/tr-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..6b056b37cb --- /dev/null +++ b/archive/edge/tr-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,120 @@ +--- +id: set-up-gcp-secrets-manager +title: GCP Sır Yöneticisi'ni Kurma +description: "Polygon Edge için GCP Sır Yöneticisi'ni Kurun." +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## Genel Bakış {#overview} + +Şu anda, Polygon Edge 2 temel çalışma zamanı sırrı tutmakla meşguldür: +* Düğüm bir doğrulayıcı ise, düğüm tarafından kullanılan **doğrulayıcı özel anahtarı** +* Diğer eşlere katılmak ve onlarla iletişim kurmak için libp2p tarafından kullanılan **ağ özel anahtarı** + +Daha fazla bilgi için lütfen [Özel Anahtarları Yönetme Kılavuzu](/docs/edge/configuration/manage-private-keys)'nu okuyun + +Polygon Edge modüllerinin **nasıl sır tutulacağını bilmesine gerek yoktur**. Sonuçta, bir modülün +sırrın uzaklarda bir sunucuda veya yerel olarak düğümün diskinde depolandığını umursamaması gerekir. + +Bir modülün sır tutma hakkında bilmesi gereken her şey **sırrı nasıl kullanacağını**, **hangi sırrı alacağını +veya kaydedeceğini** bilmekten ibarettir. Bu operasyonların daha ince uygulama detayları, elbette bir soyutlama olan `SecretsManager` üzerine yüklenmiştir. + +Polygon Edge'i başlatan düğüm operatörü, artık hangi sır yöneticisini kullanmak istediğini belirleyebilir ve +doğru sır yöneticisi somutlaştırıldığında, modüller sözü geçen arabirim aracılığıyla sırları yönetebilir - +bunu sırların bir diskte veya bir sunucuda depolanıp depolanmadığını umursamadan yapar. + +Bu makalede, Polygon Edge'i [GCP Sır Yöneticisi](https://cloud.google.com/secret-manager) ile çalışır duruma getirmek için gerekli adımlar açıklanmaktadır. + +:::info önceki kılavuzlar + +Bu makaleyi okumadan önce, [**Yerel Kurulum**](/docs/edge/get-started/set-up-ibft-locally) ile ilgili makalelerin gözden geçirilmesi **tavsiye edilir** +ve ayrıca [**Bulut Kurulumu**](/docs/edge/get-started/set-up-ibft-on-the-cloud) da okunmalıdır. + +::: + + +## Ön Koşullar {#prerequisites} +### GCP Fatura Hesabı {#gcp-billing-account} +GCP Sır Yöneticisi'ni kullanmak için, kullanıcının GCP portalında [Fatura Hesabını](https://console.cloud.google.com/) etkinleştirmiş olması gerekir. +GCP platformundaki yeni Google hesaplarına, ücretsiz deneme bonusu olarak başlangıç için bazı fonlar verilir. +[GCP belgeleri](https://cloud.google.com/free) hakkında daha fazla bilgi + +### Sır Yöneticisi API'si {#secrets-manager-api} +Kullanıcının, kullanmadan önce GCP Sır Yöneticisi API'sini etkinleştirmesi gerekir. +Bu, [Sır Yöneticisi API portali](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com) üzerinden yapılabilir. Daha fazla bilgi için: [Sır Yöneticisi'ni Yapılandırma](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + +### GCP Kimlik Bilgileri {#gcp-credentials} +Son olarak, kullanıcının kimlik doğrulaması için kullanılacak yeni kimlik bilgilerini oluşturması gerekir. +Bu, [burada](https://cloud.google.com/secret-manager/docs/reference/libraries) yayımlanan talimatlar izlenerek yapılabilir. +Kimlik bilgilerini içeren oluşturulan json dosyası, GCP Sır Yöneticisi'ni kullanması gereken her bir düğüme aktarılmalıdır. + +Devam etmeden önce gerekli bilgiler: +* **Proje Kimliği** (GCP platformunda tanımlanan proje kimliği) +* **Kimlik Bilgileri Dosya Konumu** (kimlik bilgilerini içeren json dosyasının konumu) + +## Adım 1 - Sır yöneticisi yapılandırmasını oluşturma {#step-1-generate-the-secrets-manager-configuration} + +Polygon Edge'in GCP SM ile sorunsuz bir şekilde iletişim kurabilmesi için zaten oluşturulmuş bir yapılandırma dosyasını ayrıştırması gerekir +ve bu dosya GCP SM üzerinde sır depolama için gerekli tüm bilgiyi içerir. + +Yapılandırmayı oluşturmak için aşağıdaki komutu çalıştırın: + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +Mevcut parametreler: +* `PATH`, yapılandırma dosyasının dışa aktarılacağı dizindir. Varsayılan `./secretsManagerConfig.json` +* `NODE_NAME`, GCP SM yapılandırmasının kurulduğu mevcut düğümün adıdır. Gelişigüzel bir değer olarak belirlenebilir. Varsayılan `polygon-edge-node` +* `PROJECT_ID`, kullanıcının hesap kurulumu ve Sır Yöneticisi API etkinleştirmesi sırasında GCP konsolunda tanımladığı projenin kimliğidir. +* `GCP_CREDS_FILE`, Sır Yöneticisi'ne okuma/yazma erişimi sağlayacak olan kimlik bilgilerini içeren json dosyasına giden yoldur. + +:::caution Düğüm adları + +Düğüm adlarını belirlerken dikkatli olun. + +Polygon Edge GCP SM üzerinde oluşturduğu ve kullandığı sırları takip etmek için belirlenen düğüm adını kullanır. +Mevcut bir düğüm adının belirtilmesi, GCP SM'ye sır yazılmaması gibi sonuçlar doğurabilir. + +Sırlar aşağıdaki temel dizinde depolanır: `projects/PROJECT_ID/NODE_NAME` + +::: + +## Adım 2 - Yapılandırmayı kullanarak gizli anahtarları başlatma {#step-2-initialize-secret-keys-using-the-configuration} + +Artık yapılandırma dosyası mevcut olduğuna göre, gerekli gizli anahtarları +adım 1'de ayarlanan yapılandırma dosyası ile `--config` kullanarak başlatabiliriz: + +```bash +polygon-edge secrets init --config +``` + +`PATH` parametresi, daha önce adım 1'de oluşturulan sır yöneticisi parametresinin konumudur. + +## Adım 3 - Genesis dosyasını oluşturma {#step-3-generate-the-genesis-file} + +Genesis dosyası [**Yerel Kurulum**](/docs/edge/get-started/set-up-ibft-locally) +ve [**Bulut Kurulumu**](/docs/edge/get-started/set-up-ibft-on-the-cloud) kılavuzları ile benzer şekilde, ancak birkaç küçük değişiklik ile oluşturulmalıdır. + +GCP SM, yerel dosya sistemi yerine kullanıldığından, doğrulayıcı adresleri `--ibft-validator` bayrağı ile eklenmelidir: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Adım 4 - Polygon Edge istemcisini başlatma {#step-4-start-the-polygon-edge-client} + +Artık anahtarlar kurulduğuna ve genesis dosyası oluşturulduğuna göre, bu işlemin son adımı +Polygon Edge'i `server` komutu ile başlatmak olacaktır. + +`server` komutu daha önce bahsedilen kılavuzlardaki gibi aynı şekilde, küçük bir ekleme ile kullanılmalıdır: `--secrets-config`bayrağı: +```bash +polygon-edge server --secrets-config ... +``` + +`PATH` parametresi, daha önce adım 1'de oluşturulan sır yöneticisi parametresinin konumudur. \ No newline at end of file diff --git a/archive/edge/tr-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/tr-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..90ae0fc488 --- /dev/null +++ b/archive/edge/tr-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,118 @@ +--- +id: set-up-hashicorp-vault +title: Hashicorp Vault'u Kurma +description: "Polygon Edge için Hashicorp Vault kurun." +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## Genel Bakış {#overview} + +Şu anda, Polygon Edge 2 temel çalışma zamanı sırrı tutmakla meşguldür: +* Düğüm bir doğrulayıcı ise, düğüm tarafından kullanılan **doğrulayıcı özel anahtarı** +* Diğer eşlere katılmak ve onlarla iletişim kurmak için libp2p tarafından kullanılan **ağ özel anahtarı** + +:::warning + +Doğrulayıcı özel anahtarı, her doğrulayıcı düğüm için benzersizdir. Aynı anahtar, zincirinizin güvenliğini tehlikeye atabileceği için, tüm doğrulayıcılar arasında paylaşılmamalıdır. + +::: + +Daha fazla bilgi için lütfen [Özel Anahtarları Yönetme Kılavuzu](/docs/edge/configuration/manage-private-keys)'nu okuyun + +Polygon Edge modüllerinin **nasıl sır tutulacağını bilmesine gerek yoktur**. Sonuçta, bir modülün +sırrın uzaklarda bir sunucuda veya yerel olarak düğümün diskinde depolandığını umursamaması gerekir. + +Bir modülün sır tutma hakkında bilmesi gereken her şey **sırrı nasıl kullanacağını**, **hangi sırrı alacağını +veya kaydedeceğini** bilmekten ibarettir. Bu operasyonların daha ince uygulama detayları, elbette bir soyutlama olan `SecretsManager` üzerine yüklenmiştir. + +Polygon Edge'i başlatan düğüm operatörü, artık hangi sır yöneticisini kullanmak istediğini belirleyebilir ve +doğru sır yöneticisi somutlaştırıldığında, modüller sözü geçen arabirim aracılığıyla sırları yönetebilir - +ve bunu sırların bir diskte veya bir sunucuda depolanıp depolanmadığını umursamadan yapar. + +Bu makalede, Polygon Edge'i bir [Hashicorp Vault](https://www.vaultproject.io/) sunucusu ile çalışır duruma getirmek için gerekli adımlar açıklanmaktadır. + +:::info önceki kılavuzlar + +Bu makaleyi okumadan önce, [**Yerel Kurulum**](/docs/edge/get-started/set-up-ibft-locally) ile ilgili makalelerin gözden geçirilmesi **tavsiye edilir** +ve ayrıca [**Bulut Kurulumu**](/docs/edge/get-started/set-up-ibft-on-the-cloud) da okunmalıdır. + +::: + + +## Ön Koşullar {#prerequisites} + +Bu makalede, Hashicorp Vault sunucusunun çalışan bir örneğinin **zaten kurulu olduğu** varsayılmaktadır. + +Buna ek olarak, Polygon Edge için kullanılan Hashicorp Vault sunucusunun **KV depolamasını etkinleştirmiş** olması gerekir. + +Devam etmeden önce gerekli bilgiler: +* **Sunucu URL'si** (Hashicorp Vault sunucusunun API URL'si) +* **Token** (KV depolama motoruna erişim için kullanılan erişim token'ı) + +## Adım 1 - Sır yöneticisi yapılandırmasını oluşturma {#step-1-generate-the-secrets-manager-configuration} + +Polygon Edge'in Vault sunucusu ile sorunsuz bir şekilde iletişim kurabilmesi için zaten oluşturulmuş bir yapılandırma dosyasını ayrıştırması gerekir +ve bu dosya Vault üzerinde sır depolama için gerekli tüm bilgiyi içerir. + +Yapılandırmayı oluşturmak için aşağıdaki komutu çalıştırın: + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +Mevcut parametreler: +* `PATH`, yapılandırma dosyasının dışa aktarılacağı dizindir. Varsayılan `./secretsManagerConfig.json` +* `TOKEN` daha önce [ön koşullar bölümünde](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) bahsedilen erişim token'ıdır +* `SERVER_URL`, Vault sunucusunun API'sinin URL'sidir ve [ön koşullar bölümünde](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) de anlatılmıştır +* `NODE_NAME`, Vault yapılandırmasının ayarlandığı geçerli düğümün adıdır. Gelişigüzel bir değer olarak belirlenebilir. Varsayılan `polygon-edge-node` + +:::caution Düğüm adları + +Düğüm adlarını belirlerken dikkatli olun. + +Polygon Edge, Vault örneğinde oluşturduğu ve kullandığı sırları takip etmek için belirlenen düğüm adını kullanır. +Varolan bir düğüm adı belirtilmesi, Vault sunucusunda verilerin üzerine yazılmasıyla sonuçlanabilir. + +Sırlar aşağıdaki temel dizinde depolanır: `secrets/node_name` + +::: + +## Adım 2 - Yapılandırmayı kullanarak gizli anahtarları başlatma {#step-2-initialize-secret-keys-using-the-configuration} + +Artık yapılandırma dosyası mevcut olduğuna göre, gerekli gizli anahtarları +adım 1'de ayarlanan yapılandırma dosyası ile `--config` kullanarak başlatabiliriz: + +```bash +polygon-edge secrets init --config +``` + +`PATH` parametresi, daha önce adım 1'de oluşturulan sır yöneticisi parametresinin konumudur. + +## Adım 3 - Genesis dosyasını oluşturma {#step-3-generate-the-genesis-file} + +Genesis dosyası [**Yerel Kurulum**](/docs/edge/get-started/set-up-ibft-locally) +ve [**Bulut Kurulumu**](/docs/edge/get-started/set-up-ibft-on-the-cloud) kılavuzları ile benzer şekilde, ancak birkaç küçük değişiklik ile oluşturulmalıdır. + +Hashicorp Vault yerel dosya sistemi yerine kullanıldığından, doğrulayıcı adresleri `--ibft-validator`bayrağı ile eklenmelidir: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Adım 4 - Polygon Edge istemcisini başlatma {#step-4-start-the-polygon-edge-client} + +Artık anahtarlar kurulduğuna ve genesis dosyası oluşturulduğuna göre, bu işlemin son adımı +Polygon Edge'i `server` komutu ile başlatmak olacaktır. + +`server` komutu daha önce bahsedilen kılavuzlardaki gibi aynı şekilde, küçük bir ekleme ile kullanılmalıdır: `--secrets-config`bayrağı: +```bash +polygon-edge server --secrets-config ... +``` + +`PATH` parametresi, daha önce adım 1'de oluşturulan sır yöneticisi parametresinin konumudur. \ No newline at end of file diff --git a/archive/edge/tr-edge/consensus/bls.md b/archive/edge/tr-edge/consensus/bls.md new file mode 100644 index 0000000000..ceb7449f31 --- /dev/null +++ b/archive/edge/tr-edge/consensus/bls.md @@ -0,0 +1,144 @@ +--- +id: bls +title: BLS +description: "BLS modu ile ilgili açıklama ve talimatlar." +keywords: + - docs + - polygon + - edge + - bls +--- + +## Genel Bakış {#overview} + +Boneh–Lynn–Shacham (BLS) olarak da bilinen BLS, bir kullanıcının bir imzanın gerçek olduğunu doğrulamasına izin veren bir kriptografik imza şemasıdır. Bu bir imza planı, birden fazla imzayı toplayabilmektedir. Polygon Edge üzerinde BLS, IBFT konsensüs modu için daha iyi güvenlik sağlamak üzere varsayılan olarak kullanılır. BLS, imzaları tek bir bayt dizisine toplayabilir ve blok başlık boyutunu azaltabilir. Her zincir BLS kullanıp kullanmamak arasında seçin yapabilir. BLS modunun etkinleştirilip etkinleştirilmediğine bakılmaksızın ECDSA anahtarı kullanılır. + +## Video sunumu {#video-presentation} + +[![bls - video](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## BLS kullanarak yeni bir zincir nasıl kurulur? {#how-to-setup-a-new-chain-using-bls} + +Ayrıntılı kurulum talimatları için [Yerel Kurulum](/docs/edge/get-started/set-up-ibft-locally) / [Bulut Kurulumu](/docs/edge/get-started/set-up-ibft-on-the-cloud) bölümlerine göz atın. + +## Mevcut bir ECDSA PoA zincirinden BLS PoA zincirine nasıl geçiş yapılır? {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +Bu bölüm BLS modunun var olan bir PoA zinciri içinde nasıl kullanılacağını açıklar. +Bir PoA zinciri içinde BLS etkinleştirmek için aşağıdaki adımlar gereklidir. + +1. Tüm düğümleri durdurma +2. Doğrulayıcılar için BLS anahtarlarını oluşturma +3. Genesis.json içine çatal ayarı ekleme +4. Tüm düğümleri yeniden başlatma + +### 1. Tüm düğümleri durdurma {#1-stop-all-nodes} + +Ctrl + c (Control + c) tuşlarına basarak doğrulayıcıların tüm işlemlerini sonlandırın. Lütfen en son blok yüksekliğini aklınızda tutun (blok taahhüt günlüğündeki en yüksek sıra numarası). + +### 2. BLS anahtarını oluşturma {#2-generate-the-bls-key} + +`secrets init` ile `--bls` bir BLS anahtarı oluşturur. Mevcut ECDSA ve Ağ anahtarlarını korumak ve yeni bir BLS anahtarı eklemek için `--network` ve `--ecdsa` devre dışı bırakılmalıdır. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Çatal ayarı ekleme {#3-add-fork-setting} + +`ibft switch` komutu mevcut zincir içinde BLS etkinleştiren bir çatal ayarını `genesis.json` içine ekler. + +PoA ağları için doğrulayıcıların komutta belirlenmesi gerekir. `genesis` komutunda olduğu gibi, doğrulayıcıyı belirlemek için `--ibft-validators-prefix-path` veya `--ibft-validator` bayrakları kullanılabilir. + +Zincirin BLS'yi `--from` bayrağı ile kullanmaya başladığı yüksekliği belirleyin. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. Tüm düğümleri yeniden başlatma {#4-restart-all-nodes} + +Tüm düğümleri `server` komutu ile yeniden başlatın. Önceki adımda belirtilen `from` üzerindeki blok oluşturulduktan sonra, zincir BLS'yi etkinleştirir ve aşağıdaki gibi bir günlükte gösterir: + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +Ayrıca günlükler, blok oluşturulduktan sonra her bloku oluşturmak için hangi doğrulama modunun kullanıldığını gösterir. + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## Mevcut bir ECDSA PoS zincirinden bir BLS PoS zincirine nasıl geçiş yapılır? {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +Bu bölüm BLS modunun varolan bir PoS zinciri içinde nasıl kullanılacağını açıklar. +Bir PoS zinciri içinde BLS etkinleştirmek için aşağıdaki adımlar gereklidir. + +1. Tüm düğümleri durdurma +2. Doğrulayıcılar için BLS anahtarlarını oluşturma +3. Genesis.json içine çatal ayarı ekleme +4. BLS Genel Anahtarını kaydetmek için staking sözleşmesini çağırma +5. Tüm düğümleri yeniden başlatma + +### 1. Tüm düğümleri durdurma {#1-stop-all-nodes-1} + +Ctrl + c (Control + c) tuşlarına basarak doğrulayıcıların tüm işlemlerini sonlandırın. Lütfen en son blok yüksekliğini aklınızda tutun (blok taahhüt günlüğündeki en yüksek sıra numarası). + +### 2. BLS anahtarını oluşturma {#2-generate-the-bls-key-1} + +`secrets init` ile `--bls` bayrağı, BLS anahtarını oluşturur. Mevcut ECDSA ve Ağ anahtarlarını korumak ve yeni bir BLS anahtarı eklemek için `--ecdsa` ve `--network` devre dışı bırakılmalıdır. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Çatal ayarı ekleme {#3-add-fork-setting-1} + +`ibft switch` komutu BLS'yi zincirin ortasından etkinleştiren çatal ayarını `genesis.json` içine ekler. + +Zincirin BLS modunu `from` bayrağı ile kullanmaya başladığı yüksekliği ve sözleşmenin `development` bayrağı ile güncellendiği yüksekliği belirleyin. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. Staking sözleşmesi içinde BLS Genel Anahtarını kaydetme {#4-register-bls-public-key-in-staking-contract} + +Çatal eklendikten ve doğrulayıcılar yeniden başlatıldıktan sonra, her doğrulayıcının BLS Genel Anahtarını kaydetmek için staking sözleşmesi içinde `registerBLSPublicKey` çağrısı yapması gerekir. Bunun `--deployment` üzerinde yükseklik belirtildikten sonra ve `--from` içinde yükseklik belirtilmeden önce yapılması gerekir. + +BLS Genel Anahtarını kaydetmek için komut dizisi, [Akıllı Sözleşme Stake Etme bilgi deposunda](https://github.com/0xPolygon/staking-contracts) tanımlanmıştır. + +`BLS_PUBLIC_KEY`'i `.env` dosyası içinde kaydolacak şekilde ayarlayın. Diğer parametreler hakkında daha fazla bilgi için [pos-stake-unstake](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) makalesine göz atın. + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +Aşağıdaki komut, `.env` içinde verilen BLS Genel Anahtarını sözleşmeye kaydeder. + +```bash +npm run register-blskey +``` + +:::warning Doğrulayıcıların BLS Genel Anahtarını manuel olarak kaydetmesi gerekir + +BLS modunda, doğrulayıcıların kendi adresleri ve BLS genel anahtarları olmalıdır. Konsensüs katmanı, konsensüs sözleşmeden doğrulayıcı bilgisini alırken sözleşme içinde BLS genel anahtar kaydını yaptırmamış olan doğrulayıcıları göz ardı eder. + +::: + +### 5. Tüm düğümleri yeniden başlatma {#5-restart-all-nodes} + +Tüm düğümleri `server` komutu ile yeniden başlatın. Zincir, önceki adımda belirtilen `from` üzerindeki blok oluşturulduktan sonra BLS'yi etkinleştirir. diff --git a/archive/edge/tr-edge/consensus/migration-to-pos.md b/archive/edge/tr-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..a0a333377d --- /dev/null +++ b/archive/edge/tr-edge/consensus/migration-to-pos.md @@ -0,0 +1,40 @@ +--- +id: migration-to-pos +title: PoA'dan PoS'a Geçiş +description: "PoA'dan PoS IBFT moduna ve tersine nasıl geçiş yapılır?" +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## Genel Bakış {#overview} + +Bu bölüm, çalışan bir küme için, blok zinciri sıfırlamaya gerek kalmadan PoA'dan PoS IBFT modlarına ve tersine geçişi nasıl yapabileceğiniz konusunda size rehberlik etmektedir. + +## PoS'a nasıl geçiş yapılır? {#how-to-migrate-to-pos} + +Tüm düğümleri durdurmanız, genesis.json içine `ibft switch` komutu ile çatal yapılandırması eklemeniz ve düğümleri yeniden başlatmanız gerekir. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution ECDSA kullanırken geçiş +ECDSA kullanılırken, ECDSA kullanıldığından bahseden `--ibft-validator-type`bayrak düğmeye eklenmelidir. Bu durumda Edge otomatik olarak BLS'ye geçecektir. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::PoS'a geçmek için 2 blok yüksekliğini belirtmeniz gerekir: `deployment``from`ve staking sözleşmesini yerleştirmenin `deployment`yüksekliğidir ve PoS'un başlangıcının `from`yüksekliğidir. Staking sözleşmesi, önceden devreye alınmış sözleşmede olduğu gibi, `deployment` sırasında `0x0000000000000000000000000000000000001001` adresinde devreye alınacaktır. + +Staking sözleşmesi hakkında daha fazla bilgi için lütfen [Hisse Kanıtı](/docs/edge/consensus/pos-concepts) kısmına göz atın. + +:::warning Doğrulayıcıların manuel olarak stake etmesi gerekir + +Her doğrulayıcı, PoS başlangıcında bir doğrulayıcı olmak için, sözleşme devreye alındıktan sonra `deployment` üzerinde ve devreye alınmadan önce `from` üzerinde stake etmelidir. Her doğrulayıcı PoS başlangıcındaki staking sözleşmesi sırasında ayarlanan kendi doğrulayıcısını güncelleyecektir. + +Staking hakkında daha fazla bilgi edinmek için Set Kurulunu ziyaret edin **[ve Proof of of Stake kullanın](/docs/edge/consensus/pos-stake-unstake)**. +::: diff --git a/archive/edge/tr-edge/consensus/poa.md b/archive/edge/tr-edge/consensus/poa.md new file mode 100644 index 0000000000..c36591cf85 --- /dev/null +++ b/archive/edge/tr-edge/consensus/poa.md @@ -0,0 +1,110 @@ +--- +id: poa +title: Yetki Kanıtı (PoA) +description: "Yetki Kanıtı ile ilgili açıklama ve talimatlar." +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## Genel Bakış {#overview} + +IBFT PoA, Polygon Edge içindeki varsayılan konsensüs mekanizmasıdır. PoA içinde doğrulayıcılar blokları oluşturmaktan ve bunları bir dizi halinde blok zinciri içine eklemekten sorumludurlar. + +Tüm doğrulayıcılar dinamik bir doğrulayıcı kümesi oluşturur, burada doğrulayıcılar bir oylama mekanizması kullanılarak kümeye eklenebilir veya kümeden çıkarılabilir. Bu da doğrulayıcı düğümlerinin çoğunluğunun (%51) belli bir doğrulayıcının kümeye eklenmesi veya kümeden çıkarılması yönünde oy kullanması hâlinde, doğrulayıcıların kümeye eklenebileceği veya kümeden çıkarılabileceği anlamına gelir. Bu şekilde, kötü niyetli doğrulayıcılar ağ üzerinde tespit edilebilir ve ağdan atılabilir, aynı zamanda yeni güvenilir doğrulayıcılar ağa eklenebilir. + +Tüm doğrulayıcılar yeni bloku teklif etmek için sırasını bekler (yuvarlak masa düzeni ile) ve blokun blok zinciri içinde doğrulanması/eklenmesi için doğrulayıcıların nitelikli çoğunluğunun (2/3'ten fazlası) mevzubahis bloku onaylaması gerekir. + +Doğrulayıcıların yanı sıra, blok oluşturma sürecine katılmayan ancak blok doğrulama sürecine katılan doğrulayıcı olmayan düğümler de vardır. + +## Doğrulayıcı kümesine bir doğrulayıcı ekleme {#adding-a-validator-to-the-validator-set} + +Bu kılavuz 4 doğrulayıcı düğümlü aktif bir IBFT ağı içine yeni bir doğrulayıcı düğümünün nasıl eklenebileceğini açıklar. +Ağın kurulmasına yardım etmek istiyorsanız [Yerel Kurulum](/edge/get-started/set-up-ibft-locally.md) / [Bulut Kurulum](/edge/get-started/set-up-ibft-on-the-cloud.md) bölümlerine bakın. + +### Adım 1: IBFT için veri klasörlerini başlatma ve yeni düğüm için doğrulayıcı anahtarlarını​ oluşturma {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +Yeni düğümde IBFT ile kurulum yapmak ve çalıştırmaya başlamak için öncelikle veri klasörlerini başlatmanız ve anahtarları oluşturmanız gerekir: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +Bu komut, doğrulayıcı anahtarını (adresinin) ve düğüm kimliğini yazdıracaktır. Bir sonraki adım için doğrulayıcı anahtarına (adresine) ihtiyacınız olacaktır. + +### Adım 2: Diğer doğrulayıcı düğümlerinden yeni bir aday oluşturma {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +Yeni bir düğümün doğrulayıcı olması için doğrulayıcıların en az %51'inin onun için teklifte bulunması gerekir. + +Grpc adresi: 127.0.0.1:10000 üzerinde mevcut doğrulayıcı düğümünden yeni bir doğrulayıcı (`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`) teklif etme örneği: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +IBFT komutlarının yapısı [CLI Komutları](/docs/edge/get-started/cli-commands) bölümünde ele alınmıştır. + +:::info BLS genel anahtarı + +BLS genel anahtarı yalnızca ağın BLS ile çalışması hâlinde gereklidir çünkü BLS modunda çalıştırılmayan ağ için `--bls` gerekmez + +::: + +### Adım 3: İstemci düğümü çalıştırma {#step-3-run-the-client-node} + +Bu örnekte tüm düğümlerin aynı makinede olduğu bir ağı çalıştırmayı denediğimiz için, port çakışmalarını önlemeye özel olarak dikkat etmemiz gerekir. + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +Tüm blokları aldıktan sonra, konsolunuzun içinde yeni bir düğümün doğrulamaya katıldığını fark edeceksiniz + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info Doğrulayıcı olmayan bir düğümü doğrulayıcı olarak terfi etme + +Doğal olarak, doğrulayıcı olmayan düğüm bir oylama sürecinin ardından doğrulayıcı hâline gelebilir; ancak oylama işleminden sonra doğrulayıcı kümesine başarılı bir şekilde dâhil edilebilmesi için düğümün `--seal` bayrağı ile yeniden başlatılması gerekir. + +::: + +## Doğrulayıcı kümesinden bir doğrulayıcıyı kaldırma {#removing-a-validator-from-the-validator-set} + +Bu işlem oldukça basittir. Doğrulayıcı kümesinden bir doğrulayıcı düğümü kaldırmak için bu komutun doğrulayıcı düğümlerinin çoğunluğu için gerçekleştirilmesi gerekir. + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info BLS genel anahtarı + +BLS genel anahtarı yalnızca ağın BLS ile çalışması hâlinde gereklidir çünkü BLS modunda çalıştırılmayan ağ için `--bls` gerekmez + +::: + +Komutlar gerçekleştirildikten sonra, doğrulayıcı sayısının düştüğü gözlemleyin (bu günlük örneğinde 4'ten 3'e). + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/tr-edge/consensus/pos-concepts.md b/archive/edge/tr-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..70c3f5fe5f --- /dev/null +++ b/archive/edge/tr-edge/consensus/pos-concepts.md @@ -0,0 +1,121 @@ +--- +id: pos-concepts +title: Hisse Kanıtı +description: "Hisse Kanıtı (Proof of Stake) ile ilgili açıklama ve talimatlar." +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## Genel Bakış {#overview} + +Bu bölüm, Polygon Edge'in Hisse Kanıtı (PoS) uygulamasında mevcut olan bazı kavramlar hakkında +daha fazla bilgi vermeyi amaçlamaktadır. + +Polygon Edge Hisse Kanıtı (PoS) uygulamasının mevcut PoA IBFT uygulamasına bir alternatif olması amaçlanmaktadır, +bu nedenle düğüm operatörlerine zinciri başlatırken ikisi arasında seçim yapma şansı sunar. + +## PoS Özellikleri {#pos-features} + +Hisse Kanıtı uygulamasının ardındaki temel mantık +**[Staking Smart](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)** Sözleşmesi. + +Bu sözleşme, bir PoS mekanizmalı Polygon Edge zinciri başlatıldığında ve `0x0000000000000000000000000000000000001001` adresinde +(`0` blokundan) mevcut olduğunda önden devreye alınır. + +### Dönemler {#epochs} + +Dönemler, Polygon Edge'e PoS eklenmesi ile ortaya çıkan bir kavramdır. + +Dönemler belirli bir doğrulayıcı kümesinin blok oluşturabileceği özel bir zaman aralığı (blok cinsinden) olarak kabul edilir. +Uzunlukları değiştirilebilir, yani düğüm operatörleri genesis oluşturma sırasında bir dönemin uzunluğunu ayarlayabilir. + +Her dönemin sonunda bir _dönem bloku_ oluşturulur ve bu olay sonrasında yeni bir dönem başlar. Dönem blokları hakkında daha fazla bilgi edinmek için +[Dönem Blokları](/docs/edge/consensus/pos-concepts#epoch-blocks) kısmına göz atın. + +Doğrulayıcı kümeleri her dönemin sonunda güncellenir. Düğümler, Staking Akıllı Sözleşmesi üzerinden doğrulayıcı kümesini +her dönem blokunun oluşturulması sırasında sorgular ve alınan veriyi yerel depolama alanına kaydeder. Bu sorgu ve kayıt döngüsü +her dönemin sonunda tekrarlanır. + +Temel olarak, Staking Akıllı Sözleşmesi'nin doğrulayıcı kümesindeki adresler üzerinde tam kontrole sahip olmasını sağlar ve +düğümlere sadece 1 sorumluluk bırakır: en son doğrulayıcı kümesi bilgisini almak için sözleşmeyi her dönem içinde +bir kere sorgulamak. Bu da tekil düğümlerin doğrulayıcı kümelerini yönetme sorumluluğunu hafifletir. + +### Staking {#staking} + +Adresler, Staking Akıllı Sözleşmesi üzerinde `stake` yöntemini çağırarak ve işlemde stake edilen miktar için bir değer belirleyerek +fon stake edebilirler: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +Staking Akıllı Sözleşmesi'nde fon stake ederek, adresler doğrulayıcı kümesine girebilirler ve bu sayede +blok üretim sürecine katılabilirler. + +:::info Staking için eşik + +Şu anda, doğrulayıcı kümesine girmek için minimum eşik `1 ETH` stake etmektir + +::: + +### Stake kaldırma (Unstake) {#unstaking} + +Fon stake etmiş olan adresler, stake kaldırma işlemini sadece **stake etmiş oldukları fonların tümünü unstake ederek yapabilirler**. + +Stake kaldırma, Staking Akıllı Sözleşmesi üzerinde `unstake` yöntemi çağrılarak yapılabilir: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +Adresler fonlarını unstake ettikten sonra Staking Akıllı Sözleşmesi üzerindeki doğrulayıcı kümesinden çıkarılırlar ve +bir sonraki dönem için doğrulayıcı olarak kabul edilmezler. + +## Dönem Blokları {#epoch-blocks} + +**Dönem Blokları**, Polygon Edge için IBFT'nin PoS uygulamasında ortaya çıkarılmış bir kavramdır. + +Temel olarak, dönem blokları **hiçbir işlem** içermeyen ve sadece **bir dönemin sonunda** meydana gelen özel bloklardır. +Örneğin, **epo boyutu** bloklar olarak ayarlanırsa, epo blokları `50`blok olarak kabul `50`edilir, `100``150`ve bunun gibi. + +Bunlar olağan blok üretimi sırasında oluşmaması gereken ek mantığı gerçekleştirmek için kullanılırlar. + +En önemlisi, bunlar düğüm için Staking Akıllı Sözleşmesi'nden **en güncel doğrulayıcı kümesi** bilgisini +alması gerektiğine dair bir göstergedir. + +Dönem blokunda doğrulayıcı kümesini güncelledikten sonra, doğrulayıcı kümesi (değişmiş veya değişmemiş) +sonraki `epochSize - 1` blokları için kullanılır, ta ki Staking Akıllı Sözleşmesi'nden en yeni bilgiyi alarak +tekrar güncellenene kadar. + +Dönem uzunlukları (blok cinsinden) genesis dosyası oluşturulurken `--epoch-size` özel bayrağı kullanılarak değiştirilebilir: + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +Polygon Edge üzerinde bir dönemin varsayılan boyutu `100000` bloktur. + +## Sözleşmenin önceden devreye alınması {#contract-pre-deployment} + +Polygon Edge _önceden devreye alma işleminde_; +[Staking Akıllı Sözleşmesi](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol), +**genesis oluşturma** sırasında `0x0000000000000000000000000000000000001001` adresinde önceden devreye alınır. + +Bu, bir EVM çalıştırılmadan, Akıllı Sözleşme'nin blok zinciri durumu doğrudan değiştirilerek, +genesis komutuna geçirilen yapılandırma değerleri kullanılarak yapılır. diff --git a/archive/edge/tr-edge/consensus/pos-stake-unstake.md b/archive/edge/tr-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..5f76af1fa7 --- /dev/null +++ b/archive/edge/tr-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,177 @@ +--- +id: pos-stake-unstake +title: Hisse Kanıtı (PoS) yapılandırma ve kullanma +description: "Stake etme, stake kaldırma ve staking ile ilgili diğer talimatlar." +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## Genel Bakış {#overview} + +Bu kılavuz Polygon Edge ile bir Hisse Kanıtı ağının nasıl kurulacağını, düğümlerin doğrulayıcı olabilmesi için nasıl fon stake edileceğini +ve fonların stake'inin nasıl kaldırılacağını ayrıntılarıyla ele alır. + +Bu nedenle okumak ve geçmek **için çok teşvik** edilir [Yerel Kurulum](/docs/edge/get-started/set-up-ibft-locally) +[Bulut Kurulumu](/docs/edge/get-started/set-up-ibft-on-the-cloud) kısımlarının +okunmasıdır. Bu kısımlar Polygon Edge ile bir Yetki Kanıtı (PoA) kümesi başlatmak için gerekli +adımları özetler. + +Şu anda, Staking Akıllı Sözleşmesi üzerinde fon stake edebilecek doğrulayıcı sayısı için herhangi bir limit bulunmamaktadır. + +## Staking Akıllı Sözleşmesi {#staking-smart-contract} + +Staking Akıllı Sözleşmesi için bilgi deposu [burada](https://github.com/0xPolygon/staking-contracts) bulunur. + +Gerekli test komut dizilerini, ABI dosyalarını ve en önemlisi Staking Akıllı Sözleşmesi'nin kendisini içerir. + +## N düğümlü bir küme yapılandırma {#setting-up-an-n-node-cluster} + +Polygon Edge ile bir ağ kurulumu +[Yerel Kurulum](/docs/edge/get-started/set-up-ibft-locally) +/ [Bulut Kurulumu](/docs/edge/get-started/set-up-ibft-on-the-cloud) kısımlarında yer almaktadır. + +PoS ve PoA kümelerinin kurulumu arasındaki **tek fark**, genesis oluşturma kısmındadır. + +**Bir PoS kümesi için genesis dosyası oluştururken, ek bir bayrak gereklidir `--pos`**: + +```bash +polygon-edge genesis --pos ... +``` + +## Bir dönemin uzunluğunu ayarlama {#setting-the-length-of-an-epoch} + +Dönemler [Dönem Blokları](/docs/edge/consensus/pos-concepts#epoch-blocks) kısmında ayrıntılı olarak ele alınmaktadır. + +Genesis dosyası oluştururken bir kümenin (blok cinsinden) boyunu ayarlamak için ek bir bayrak +belirlenir `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +Bu değer genesis dosyası içinde dönem boyutunun `50` blok olması gerektiğini belirtir. + +Bir dönemin boyutunun (blok cinsinden) varsayılan değeri `100000` olarak belirlenmiştir. + +:::info Dönem uzunluğunu kısaltma + +[Dönem Blokları](/docs/edge/consensus/pos-concepts#epoch-blocks) bölümünde özetlendiği gibi, +dönem blokları düğümler için doğrulayıcı kümelerini güncellemek için kullanılır. + +Blok cinsinden varsayılan dönem uzunluğu (`100000`) doğrulayıcı kümesi güncellemeleri için uzun bir bekleme süresi olabilir. Yeni blokların +yaklaşık 2 saniyede eklendiği göz önüne alındığında, doğrulayıcı kümesinin değişmesi hâlinde değişim süresi yaklaşık 55,5 saat olur. + +Dönem uzunluğu için daha düşük bir değer ayarlamak, doğrulayıcı kümesinin daha sık güncellenmesini sağlar. + +::: + +## Staking Akıllı Sözleşmesi betiklerini kullanma {#using-the-staking-smart-contract-scripts} + +### Ön Koşullar {#prerequisites} + +Staking Akıllı Sözleşme bilgi deposu bir Hardhat projesidir ve NPM gerektirir. + +Doğru bir şekilde başlatmak için, ana dizinde şunu çalıştırın: + +```bash +npm install +```` + +### Sağlanan yardımcı komut dosyalarını yapılandırma {#setting-up-the-provided-helper-scripts} + +Devreye alınan Staking Akıllı Sözleşmesi ile etkileşim için kullanılacak komut dizileri, +[Staking Akıllı Sözleşmesi bilgi deposunda](https://github.com/0xPolygon/staking-contracts) bulunur. + +Akıllı Sözleşmeler bilgi deposu konumunda aşağıdaki parametrelere sahip bir `.env` dosyası oluşturun: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +Parametreler şu şekilde olmalıdır: + +* **JSONRPC_URL** - çalışan düğüm için JSON-RPC uç noktası +* **PRIVATE_KEYS** - stake eden adresin özel anahtarları. +* **STAKING_CONTRACT_ADDRESS** - stake eden akıllı sözleşme adresi ( +varsayılan `0x0000000000000000000000000000000000001001`) +* **BLS_PUBLIC_KEY** - stake edenin BLS genel anahtarı. Sadece ağ BLS ile çalışıyorsa ihtiyaç duyulur + +### Fon stake etme {#staking-funds} + +:::info Stake eden adres + +Staking Akıllı Sözleşmesi +`0x0000000000000000000000000000000000001001` adresi üzerinde önceden devreye alınır. + +Staking mekanizması ile her türlü etkileşim, belirlenen adreste Staking Akıllı Sözleşmesi üzerinden yapılır. + +Staking Akıllı Sözleşmesi hakkında daha fazla bilgi edinmek için lütfen ziyaret edin: +**[Staking Smart](/docs/edge/consensus/pos-concepts#contract-pre-deployment)** Sözleşmesi kısmı. + +::: + +Doğrulayıcı kümesinin bir parçası olmak için, adresin belli bir eşiğin üzerinde bir miktar fonu stake etmesi gerekir. + +Şu anda, doğrulayıcı kümesinin bir parçası olmak için varsayılan eşik `1 ETH` olarak belirlenmiştir. + +Stake etme, Staking Akıllı Sözleşmesinin `stake` yöntemini çağırarak ve `>= 1 ETH` değerini belirleyerek başlatılabilir. + +`.env` dosyası +[önceki kısımda](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) belirtildiği şekilde yapılandırıldıktan sonra ve bir +zincir PoS modunda başlatıldıktan sonra, Staking Akıllı Sözleşmesi bilgi deposunda bulunan aşağıdaki komut ile staking yapılabilir: + +```bash +npm run stake +``` + +`stake` Hardhat betiği, varsayılan `1 ETH` miktarı kadar stake eder; bu değer `scripts/stake.ts` dosyası modifiye edilerek +değiştirilebilir. + +Stake edilen fonlar `>= 1 ETH` ise, Staking Akıllı Sözleşmesi üzerinde belirlenen doğrulayıcı güncellenir ve adres +bir sonraki dönemden başlayarak doğrulayıcı kümesinin bir parçası olur. + +:::info BLS anahtarlarını kaydetme + +Ağ BLS modunda çalışıyorsa, düğümlerin doğrulayıcı olmak için staking sonrasında BLS genel anahtarlarını kaydetmeleri gerekir + +Bu aşağıdaki komutla yapılabilir: + +```bash +npm run register-blskey +``` +::: + +### Fonların stake'ini kaldırma {#unstaking-funds} + +Stake eden adresler, stake kaldırma işlemini **sadece tüm fonlarını bir kerede unstake ederek** yapabilirler. + +`.env` dosyası +[önceki bölümde](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) +bahsedilen şekilde yapılandırıldıktan sonra ve PoS modunda zincir başlatıldıktan sonra, stake kaldırma işlemi +Staking Akıllı Sözleşmesi bilgi deposunda bulunan aşağıdaki komutla yapılabilir: + +```bash +npm run unstake +``` + +### Stake edenlerin listesini alma {#fetching-the-list-of-stakers} + +Stake eden tüm adresler, Staking Akıllı Sözleşmesine kaydedilir. + +`.env` dosyası +[önceki bölümde](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) +bahsedilen şekilde yapılandırıldıktan sonra ve PoS modunda bir zincir başlatıldıktan sonra, doğrulayıcı listesini alma işlemi +Staking Akıllı Sözleşmesi bilgi deposunda bulunan aşağıdaki komutla yapılabilir: + +```bash +npm run info +``` diff --git a/archive/edge/tr-edge/faq/Contracts.md b/archive/edge/tr-edge/faq/Contracts.md new file mode 100644 index 0000000000..a40087923b --- /dev/null +++ b/archive/edge/tr-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: Akıllı Sözleşmeler SSS +description: "Polygon Edge Akıllı Sözleşmeleri için SSS" +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## Polygon Edge Akıllı Sözleşmeleri destekler mi? {#does-polygon-edge-support-smart-contracts} + +Evet. Polygon Edge ağları Ethereum uyumlu blok zincirleridir, yani Ethereum üzerinde devreye alınabilen akıllı sözleşmeler Polygon Edge zincirlerinde de devreye alınabilir. + +## PoS için staking sözleşme mantığını, devreye alındıktan sonra güncelleyebilir misiniz? {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +Şimdilik PoS ağını başlattıktan sonra staking sözleşme mantığını değiştiremezsiniz; çünkü bu genesis dosyasının bir parçasıdır. Bu nedenle, örneğin, minimum/maksimum doğrulayıcı sayısını değiştirmeniz mümkün değildir. Yapabileceğiniz şey, doğrulayıcıları eklemek veya kaldırmak için stake etmek veya stake kaldırmaktır. + + + diff --git a/archive/edge/tr-edge/faq/Gas.md b/archive/edge/tr-edge/faq/Gas.md new file mode 100644 index 0000000000..da305ba064 --- /dev/null +++ b/archive/edge/tr-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: Gaz SSS +description: "Polygon Edge için Gaz SSS" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Minimum gaz fiyatı nasıl uygulanır? {#how-to-enforce-a-minimum-gas-price} +Sunucu komutunda sağlanan `--price-limit` bayrağını kullanabilirsiniz. Bunu yapmak, düğümünüzün yalnızca belirlediğiniz fiyat limitinin üzerinde veya limite eşit olan gaz içeren işlemleri kabul etmesini sağlayacaktır. Tüm ağ üzerinde uygulandığından emin olmak için tüm düğümlerin aynı fiyat limitine sahip olduğundan emin olmanız gerekir. + + +## 0 gaz ücreti içeren işlemleriniz olabilir mi? {#can-you-have-transactions-with-0-gas-fees} +Evet, olabilir. Düğümlerin uyguladığı varsayılan fiyat limiti `0` olarak belirlenmiştir; yani düğümler gaz fiyatı `0` olarak ayarlanmış işlemleri kabul edecektir. + +## Gaz (yerel) token için toplam arz nasıl ayarlanır? {#how-to-set-the-gas-native-token-total-supply} + +Hesaplara (adreslere) önceden mine edilmiş bir bakiye ayarlamak için `--premine flag` kullanabilirsiniz. Lütfen bunun genesis dosyasından gelen bir yapılandırma olduğunu ve daha sonra değiştirilemeyeceğini unutmayın. + +`--premine flag` kullanımına bir örnek: + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +Bu işlem 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862 adresine önceden mine edilmiş 1000 ETH'lik bir bakiye ayarlar (argümandaki miktar wei cinsindendir). + +Gaz token'ı için önceden mine edilmiş miktar, toplam arz olacaktır. Bundan sonra hiçbir miktarda yerel para birimi (gaz token'ı) mint edilemez. + +## Edge gaz token'ı olarak ERC-20'yi destekler mi? {#does-edge-support-erc-20-as-a-gas-token} + +Edge, gaz token'ı olarak ERC-20 token'ları desteklemez. Gaz için yalnızca yerel Edge para birimi desteklenir. + +## Gaz limiti nasıl artırılır? {#how-to-increase-the-gas-limit} + +Polygon Edge içinde gaz limitini artırmak için iki seçenek vardır: +1. Zinciri silmek ve genesis dosyasında maksimum uint64 değerine `block-gas-limit`yükseltme +2. Tüm düğümlerin gaz limitini artırmak için `--block-gas-target`bayrağı yüksek bir değere sahip kullanın. Bu durum düğüm yeniden başlatma gerektirir. Detaylı açıklama [burada](/docs/edge/architecture/modules/txpool/#block-gas-target). \ No newline at end of file diff --git a/archive/edge/tr-edge/faq/Tokens.md b/archive/edge/tr-edge/faq/Tokens.md new file mode 100644 index 0000000000..d8e4ab3f74 --- /dev/null +++ b/archive/edge/tr-edge/faq/Tokens.md @@ -0,0 +1,23 @@ +--- +id: tokens +title: Token'lar SSS +description: "Polygon Edge token'ları için SSS" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## Polygon Edge EIP-1559'u destekler mi? {#does-polygon-edge-support-eip-1559} +Şu anda, Polygon Edge EIP-1559'u desteklememektedir. + +## Para birimi (token) sembolü nasıl ayarlanır? {#how-to-set-the-currency-token-symbol} + +Token sembolü sadece kullanıcı arabirimi ile ilgilidir, bu nedenle ağda herhangi bir yerde yapılandırılamaz veya kodla sabitlenemez. +Ancak, ağı örneğin Metamask gibi bir cüzdana eklerken değiştirebilirsiniz. + +## Bir zincir durduğunda işlemlere ne olur? {#what-happens-to-transactions-when-a-chain-halts} + +İşlemi gerçekleştirilmeyen tüm işlemler TxPool'un (sıralı veya terfi edilen sıra) içindedir. Eğer zincir durursa (tüm blok üretimi durur), bu işlemler asla bloklara girmeyecektir.
Bu durum sadece zincir durduğunda geçerli değildir. Düğümler durdurulur veya yeniden başlatılırsa, yürütülmemiş ve hala TxPool'da bulunan tüm işlemler sessizce kaldırılacaktır.
Aynı şey bir kırılma değişikliği ile karşılaşıldığında işlemlerde de gerçekleşecektir, çünkü düğümlerin yeniden başlatılması için gerekli olan budur. diff --git a/archive/edge/tr-edge/faq/Validators.md b/archive/edge/tr-edge/faq/Validators.md new file mode 100644 index 0000000000..0d9eb59a6b --- /dev/null +++ b/archive/edge/tr-edge/faq/Validators.md @@ -0,0 +1,85 @@ +--- +id: validators +title: Doğrulayıcılar SSS +description: "Polygon Edge doğrulayıcıları için SSS" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Doğrulayıcı nasıl eklenir/kaldırılır? {#how-to-add-remove-a-validator} + +### PoA {#poa} +Doğrulayıcıların eklenmesi/kaldırılması oylama ile yapılır. [Burada](/docs/edge/consensus/poa) bununla ilgili tam bir kılavuz bulabilirsiniz. + +### PoS {#pos} +Bir düğümün doğrulayıcı olabilmesi için fonların nasıl stake edileceği ve nasıl unstake edileceği (doğrulayıcıyı kaldırma) hakkında [burada](/docs/edge/consensus/pos-stake-unstake) bir kılavuz bulabilirsiniz. + +Lütfen dikkat edin: +- Doğrulayıcı kümesine katılabilecek maksimum sayıda stake eden ayarlamak için `--max-validator-count` genesis bayrağını kullanabilirsiniz. +- Doğrulayıcı kümesine katılabilecek minimum stake eden sayısını ayarlamak için `--min-validator-count ` genesis bayrağını kullanabilirsiniz (varsayılan olarak `1`). +- Maksimum doğrulayıcı sayısı karşılandığında, mevcut bir doğrulayıcıyı kümeden kaldırana kadar başka bir doğrulayıcı ekleyemezsiniz (yeni doğrulayıcının stake miktarının daha yüksek olup olmadığı önemli değildir). Bir doğrulayıcıyı kaldırırsanız, kalan doğrulayıcıların sayısı en az `--min-validator-count` olmalıdır. +- Doğrulayıcı olmak için varsayılan olarak `1` birim yerel ağ (gaz) para birimi eşiği vardır. + + + +## Bir doğrulayıcı için ne kadar disk alanı önerilir? {#how-much-disk-space-is-recommended-for-a-validator} + +İhtiyatlı bir şekilde tahmin edilen bir yol olarak 100G ile başlamanızı ve daha sonra diski ölçeklemenin mümkün olduğundan emin olmanızı öneririz. + + +## Doğrulayıcı sayısı için bir limit var mı? {#is-there-a-limit-to-the-number-of-validators} + +Teknik limitlerden bahsetmek gerekirse, Polygon Edge, bir ağ üzerinde sahip olabileceğiniz düğüm sayısı konusunda açık bir sınıra sahip değildir. Bağlantı sınırlarını (gelen / giden bağlantı sayısı) düğüm bazında ayarlayabilirsiniz. + +Pratik limitlerden bahsetmek gerekirse, 100 düğümlü bir kümede, 10 düğümlü bir kümeye göre daha düşük bir performans göreceksiniz. Kümenizdeki düğüm sayısını artırarak, iletişim karmaşıklığını ve yalnızca genel olarak ağ oluşturma yükünü artırırsınız. Her şey ne tür bir ağda çalıştığınıza ve ne tür bir ağ topolojisine sahip olduğunuza bağlıdır. + +## PoA'dan PoS'a nasıl geçiş yapılır? {#how-to-switch-from-poa-to-pos} + +PoA, varsayılan konsensüs mekanizmasıdır. Yeni bir küme için PoS'a geçmek için, genesis dosyasını oluştururken `--pos` bayrağını eklemeniz gerekir. Çalışan bir kümeniz varsa, [burada](/docs/edge/consensus/migration-to-pos) geçişin nasıl yapılacağını bulabilirsiniz. Konsensüs mekanizmalarımız ve kurulumumuz hakkında ihtiyacınız olan tüm bilgiler, [konsensüs bölümümüzde](/docs/edge/consensus/poa) bulunabilir. + +## Bozucu bir değişiklik olduğunda düğümlerimi nasıl güncelleyebilirim? {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +Bu prosedürün nasıl yapılacağı hakkında ayrıntılı bir kılavuzu [burada](/docs/edge/validator-hosting#update) bulabilirsiniz. + +## PoS Edge için minimum staking miktarı yapılandırılabilir mi? {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +Varsayılan olarak minimum staking miktarı `1 ETH`'dir ve yapılandırılamaz. + +## JSON RPC komutları `eth_getBlockByNumber`ve `eth_getBlockByHash` neden madencinin adresini geri döndürmüyor? {#not-return-the-miner-s-address} + +Şu anda Polygon Edge'de kullanılan konsensüs, Clique PoA: [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225)'te açıklanan oylama mekanizması üzerine kurulu olan IBFT 2.0'dır. + +EIP-225'e (Clique PoA) baktığımızda, `miner`'in (diğer adıyla `beneficiary`) ne için kullanıldığını açıklayan ilgili bölüm şudur: + +
+ethash başlık alanlarını aşağıdaki gibi yeniden tasarlıyoruz: +
    +
  • yararlanıcı/madenci: Yetkili imzalayanların listesinin değiştirilmesinin önerileceği adres.
  • +
      +
    • Normalde sıfırlarla doldurulmalı, yalnızca oylama yapılırken değiştirilmelidir.
    • +
    • Bununla birlikte, oylama mekanikleriyle ilgili uygulamalarda ekstra karmaşıklığı önlemek için rastgele değerlere (imzalamayanlara oy vermek gibi anlamsız olanlara bile) izin verilir.
    • +
    • Denetim noktası (yani dönem geçişi) bloklarında sıfırlarla doldurulmalıdır.
    • +
    + +
+ +
+ +Bu nedenle `miner` alanı, blok teklif sahibini göstermek için değil, belirli bir adres için oylama teklif etmek için kullanılır. + +Blok teklif sahibi ile ilgili bilgiler, blok başlıklarındaki RLP kodlanmış İstanbul ekstra veri alanının Mühür alanından genel anahtar kurtarılarak bulunabilir. + +## Genesis'in hangi parçaları ve değerleri güvenle değiştirilebilir? {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +Lütfen düzenleme girişiminde bulunmadan önce mevcut genesis.json dosyasının manuel bir kopyasını oluşturduğunuzdan emin olun. Ayrıca, genesis.json dosyasını düzenlemeden önce tüm zincirin durdurulması gerekir. Genesis dosyası değiştirildikten sonra, bunun daha yeni sürümünün tüm doğrulayıcı olmayan ve valdiator düğümleri üzerinden dağıtılması gerekir. + +::: + +**Sadece genesis dosyasının önyükleme bölümü güvenli bir şekilde değiştirilebilir;** burada listeden bootnodes ekleyebilir veya kaldırabilirsiniz. \ No newline at end of file diff --git a/archive/edge/tr-edge/get-started/cli-commands.md b/archive/edge/tr-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..07fd84bfdb --- /dev/null +++ b/archive/edge/tr-edge/get-started/cli-commands.md @@ -0,0 +1,2221 @@ +--- +id: cli-commands +title: CLI Komutları +description: "Polygon Edge için CLI komutları ve komut bayrakları listesi." +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +Bu bölüm Polygon Edge'deki mevcut komutları, komut bayraklarını ve nasıl kullanıldıklarını ayrıntılarıyla açıklar. + +:::tip JSON çıktı desteği + +`--json` bayrağı bazı komutlarda desteklenir. Bu bayrak, komuta JSON formatında çıktı yazdırma talimatı verir + +::: + +## Başlangıç Komutları {#startup-commands} + +| **Komut** | **Açıklama** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| sunucu | Tüm modüllerin önyüklemesini birlikte yaparak blok zinciri istemcisini çalıştıran varsayılan komut | +| genesis | İstemciyi başlatmadan önce, önceden belirlenmiş bir zincir durumu ayarlamak için kullanılan bir *genesis.json* dosyası oluşturur. Genesis dosyasının yapısı aşağıda açıklanmaktadır | +| genesis predeploy | Taze ağlar için Akıllı Sözleşme hazırlar | + +### sunucu bayrakları {#server-flags} + + +| **Tüm sunucu bayrakları** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [prometheus](/docs/edge/get-started/cli-commands#prometheus) | [block-gas-target](/docs/edge/get-started/cli-commands#block-gas-target) | +| [max-peers](/docs/edge/get-started/cli-commands#max-peers) | [max-inbound-peers](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [max-outbound-peers](/docs/edge/get-started/cli-commands#max-outbound-peers) | [max-enqueued](/docs/edge/get-started/cli-commands#max-enqueued) | +| [log-level](/docs/edge/get-started/cli-commands#log-level) | [log-to](/docs/edge/get-started/cli-commands#log-to) | +| [chain](/docs/edge/get-started/cli-commands#chain) | [join](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [price-limit](/docs/edge/get-started/cli-commands#price-limit) | [max-slots](/docs/edge/get-started/cli-commands#max-slots) | +| [config](/docs/edge/get-started/cli-commands#config) | [secrets-config](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-interval](/docs/edge/get-started/cli-commands#dev-interval) | +| [no-discover](/docs/edge/get-started/cli-commands#no-discover) | [restore](/docs/edge/get-started/cli-commands#restore) | +| [block-time](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +Polygon Edge istemci verisini depolamak için kullanılacak veri dizinini belirtmekte kullanılır. Varsayılan: `./test-chain`. + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +JSON-RPC hizmeti için adresi ve portu ayarlar `address:port`. +Tanımlanan tek port `:10001` ise, tüm arabirimlere bağlanacaktır `0.0.0.0:10001`. +Belirlenmezse, hizmet varsayılan `address:port` ile bağlanacaktır. +Varsayılan adres: `0.0.0.0:8545`. + +--- + +####

json-rpc-block-range-limit + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +Json-rpc istekleri için en fazla blok aralığını ayarlar ve bu istekleri (örneğin eth_getLogs) ile de içeren blok/toBlock değerlerini (örneğin eth_getLogs) içerir. Bu limit değeri ayarlayarak tamamen devre dışı `0`bırakılabilir. Varsayılan: `1000`. + +--- + +####

json-rpc-batch-request-limit + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +Json-rpc toplu istekleri ile ilgili olarak düşünülecek maksimum uzunluğu ayarlar. Bu limit değeri ayarlayarak tamamen devre dışı `0`bırakılabilir. Varsayılan: `20`. + +--- + +####

grpc + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +gRPC hizmeti için adresi ve portu ayarlar `address:port`. Varsayılan adres: `127.0.0.1:9632`. + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +libp2p hizmeti için adres ve portu ayarlar `address:port`. Varsayılan adres: `127.0.0.1:1478`. + +--- + +####

prometheus + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +Prometheus sunucusu için adres ve portu ayarlar `address:port`. +Yalnızca `:5001` portu tanımlandıysa, hizmet tüm arabirimlere bağlanacaktır `0.0.0.0:5001`. +Göz ardı edilirse, hizmet başlamayacaktır. + +--- + +####

block-gas-target + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +Zincir için hedef blok gaz limitini ayarlar. Varsayılan (zorlanmayan): `0`. + +Blok gaz hedefi hakkında daha ayrıntılı bir açıklama [TxPool kısmında](/docs/edge/architecture/modules/txpool#block-gas-target) bulunabilir. + +--- + +####

max-peers + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +İstemcinin maksimum eş sayısını ayarlar. Varsayılan: `40`. + +Eş limiti `max-peers` veya `max-inbound/outbound-peers` bayrağı kullanılarak belirtilmelidir. + +--- + +####

max-inbound-peers + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +İstemcinin maksimum gelen eş sayısını ayarlar. Eğer `max-peers`olarak ayarlandıysa, max-inbound-peer limiti aşağıdaki formüller kullanılarak hesaplanır. + +`InboundRatio` değerinin `0.8` olduğu yerde `max-inbound-peer = InboundRatio * max-peers`. + +--- + +####

max-outbound-peers + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +İstemcinin maksimum giden eş sayısını ayarlar. `max-peers` olarak ayarlandıysa, max-outbound-peer sayısı aşağıdaki formüller kullanılarak hesaplanır. + +`OutboundRatio` değerinin `0.2` olduğu yerde `max-outbound-peer = OutboundRatio * max-peers`. + +--- + +####

max-enqueued + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +Hesap başına kuyruğa alınan maksimum işlem sayısını ayarlar. Varsayılan: `128`. + +--- + +####

log-level + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +Konsol çıktısı için günlük seviyesini ayarlar. Varsayılan: `INFO`. + +--- + +####

log-to + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +Sunucu komutundan gelen tüm günlük çıktısını tutacak günlük dosya adını tanımlar. +Varsayılan olarak tüm sunucu günlüklerinin çıktısı konsola (stdout) verilecektir, +ancak bayrak ayarlandıysa, sunucu komutunu çalıştırırken konsola hiçbir çıktı olmayacaktır. + +--- + +####

chain + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +Zinciri başlatmak için kullanılan genesis dosyasını belirtir. Varsayılan: `./genesis.json`. + +--- + +####

join + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Katılınması gereken eşin adresini belirtir. + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +Harici IP adresini, port olmadan, eşler tarafından görüneceği şekliyle ayarlar. + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +Ana bilgisayar DNS adresini ayarlar. Harici bir DNS yayını yapmak için kullanılabilir. `dns4`, `dns`, `dns6` destekler. + +--- + +####

price-limit + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +Havuza kabul edilmek için minimum gaz fiyatı limitini ayarlar. Varsayılan: `1`. + +--- + +####

max-slots + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +Havuzdaki maksimum slotu ayarlar. Varsayılan: `4096`. + +--- + +####

Yapılandırma + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +CLI yapılandırması için dizini belirtir. `.json` destekler. + +--- + +####

secrets-config + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +SecretsManager yapılandırma dosyası için dizini belirler. Hashicorp Vault, AWS SSM ve GCP Secrets Manager için kullanılır. Göz ardı edilirse, yerel FS sır yöneticisi kullanılır. + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +İstemciyi geliştirici moduna ayarlar. Varsayılan `false`: Dev modunda eşlerin keşfi varsayılan olarak devre dışı bırakılır. + +--- + +####

dev-interval + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +İstemcinin dev bildirim aralığını saniye cinsinden ayarlar. Varsayılan: `0`. + +--- + +####

no-discover + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +İstemcinin diğer eşleri keşfetmesini önler. Varsayılan: `false`. + +--- + +####

restore + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +Belirtilen arşiv dosyasından blokları geri yükler + +--- + +####

block-time + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +Blok üretim zamanını saniye cinsinden ayarlar. Varsayılan: `2` + +--- + +####

access-control-allow-origins + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +JSON-RPC isteklerinden gelen yanıtları paylaşabilmek için yetkili alan adlarını ayarlar. +Çoklu alan adlarını yetkilendirmek için çoklu bayrak `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"` ekler. +Göz ardı edilirse, Access-Control-Allow-Origins başlığı `*` olarak ayarlanır ve tüm alan adları yetkilendirilir. + +--- + +### genesis bayrakları {#genesis-flags} +| **Tüm genesis bayrakları** | +|---------------------------------------|---------------------------------------------| +| [dir](/docs/edge/get-started/cli-commands#dir) | [name](/docs/edge/get-started/cli-commands#name) | +| [pos](/docs/edge/get-started/cli-commands#pos) | [epoch-size](/docs/edge/get-started/cli-commands#epoch-size) | +| [premine](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [ibft-validator-type](/docs/edge/get-started/cli-commands#ibft-validator-type) | [ibft-validators-prefix-path](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [ibft-validator](/docs/edge/get-started/cli-commands#ibft-validator) | [block-gas-limit](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [consensus](/docs/edge/get-started/cli-commands#consensus) | [bootnode](/docs/edge/get-started/cli-commands#bootnode) | +| [max-validator-count](/docs/edge/get-started/cli-commands#max-validator-count) | [min-validator-count](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

dir + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +Polygon Edge genesis verisi için dizini ayarlar. Varsayılan: `./genesis.json`. + +--- + +####

Ad + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +Zincirin adını ayarlar. Varsayılan: `polygon-edge`. + +--- + +####

pos + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +İstemcinin Hisse Kanıtı IBFT kullanması gerektiğini belirten bayrağı ayarlar. +Belirlenmediyse veya `false` ise varsayılan olarak Yetki Kanıtı ayarlar. + +--- + +####

epoch-size + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +Zincir için dönem boyutunu ayarlar. Varsayılan `100000`. + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +Önceden mine edilmiş hesapları ve bakiyeleri `address:amount` formatında ayarlar. +Miktar ondalık veya hex cinsinden olabilir. +Varsayılan önceden belirlenmiş bakiye: `0xD3C21BCECCEDA1000000`(1 milyon yerel para birimi belirteçi). + +--- + +####

chainid + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +Zincirin kimliğini ayarlar. Varsayılan: `100`. + +--- + +####

ibft-validator-type + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +Blok başlıklarının doğrulama modunu belirtir. Olası değerler: `[ecdsa, bls]`. Varsayılan: `bls`. + +--- + +####

ibft-validators-prefix-path + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +Doğrulayıcı klasör dizini için ön ek yolu. `ibft-validator` bayrağı göz ardı edilirse, mevcut olmalıdır. + +--- + +####

ibft-validator + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Geçilen adresleri IBFT doğrulayıcıları olarak belirler. `ibft-validators-prefix-path` bayrağı göz ardı edilirse, mevcut olmalıdır. +1. Ağ ECDSA ile çalışıyorsa, format `--ibft-validator [ADDRESS]` şeklindedir. +2. Ağ BLS ile çalışıyorsa, format `--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]` şeklindedir. + +--- + +####

block-gas-limit + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +Bir blok içindeki tüm operasyonlar tarafından kullanılan gaz miktarına karşılık gelir. Varsayılan: `5242880`. + +--- + +####

consensus + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +Konsensüs protokolünü ayarlar. Varsayılan: `pow`. + +--- + +####

bootnode + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +p2p keşif önyüklemesi için Multiaddr URL'sidir. Bu bayrak çok kez kullanılabilir. +Bir IP adresi yerine, bootnode'un DNS adresi sağlanabilir. + +--- + +####

max-validator-count + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +Bir PoS konsensüsü içinde ayarlanan doğrulayıcı kümesine katılabilecek maksimum staker sayısını belirler. +Bu sayı MAX_SAFE_INTEGER (2^53 - 2) değerini aşamaz. + +--- + +####

min-validator-count + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +Bir PoS konsensüsü içinde ayarlanan doğrulayıcı kümesine katılmak için gereken minimum staker sayısını belirtir. +Bu sayı max-validator-count değerini aşamaz. +Varsayılan olarak 1 değerini alır. + +--- + +### genesis önceden dağıtılmış bayraklar {#genesis-predeploy-flags} + +

artifacts-path

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +JSON ile ilgili sözleşme eserlerine giden yolu ayarlar ve `bytecode`bu işlemi `abi`içerir.`deployedBytecode` + +--- + +

chain

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +Güncellenmesi gereken `genesis.json`dosyanın yolunu ayarlar. Varsayılan `./genesis.json`. + +--- + +

constructor-args

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +Eğer varsa Akıllı Sözleşme yapıcı argümanlarını ayarlar. Bu argümanların nasıl görünmesi gerektiği konusunda ayrıntılı bir kılavuz için lütfen [ön dağıtım](/docs/edge/additional-features/predeployment) makalesine başvurun. + +--- + +

predeploy-address

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +Bu adrese önceden dağıtılmak için adresi ayarlar. Varsayılan `0x0000000000000000000000000000000000001100`. + +--- + + +## Operatör Komutları {#operator-commands} + +### Eş Komutları {#peer-commands} + +| **Komut** | **Açıklama** | +|------------------------|-------------------------------------------------------------------------------------| +| peers add | libp2p adresini kullanarak yeni bir eş ekler | +| peers list | istemcinin libp2p aracılığıyla bağlandığı tüm eşleri listeler | +| peers status | libp2p adresini kullanarak eşler listesinden belirli bir eşin durumunu getirir | + +

peers add bayrakları

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Eşin multiaddr biçiminde libp2p adresi. + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +gRPC API adresidir. Varsayılan: `127.0.0.1:9632`. + +

peers list bayrakları

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +gRPC API adresidir. Varsayılan: `127.0.0.1:9632`. + +

peers status bayrakları

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +p2p ağı içinde belirli bir eşin Libp2p düğüm kimliğidir. + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +gRPC API adresidir. Varsayılan: `127.0.0.1:9632`. + +### IBFT Komutları {#ibft-commands} + +| **Komut** | **Açıklama** | +|------------------------|-------------------------------------------------------------------------------------| +| ibft snapshot | IBFT anlık görüntüsünü getirir | +| ibft candidates | Önerilen mevcut aday kümesini ve henüz dâhil edilmemiş adayları sorgular | +| ibft propose | Doğrulayıcı kümesi için eklenecek/çıkarılacak yeni bir aday önerir | +| ibft status | IBFT istemcisinin genel durumunu getirir | +| ibft switch | IBFT türünü değiştirmek için genesis.json dosyası içine çatal yapılandırmaları ekler | +| ibft quorum | Blok numarasını belirtir ve bunun ardından optimal quorum boyutu yöntemi konsensüse varmak için kullanılır | + + +

ibft snapshot bayrakları

+ +

number

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +Anlık görüntü için blok yüksekliği (sayı). + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +gRPC API adresidir. Varsayılan: `127.0.0.1:9632`. + +

ibft candidates bayrakları

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +gRPC API adresidir. Varsayılan: `127.0.0.1:9632`. + +

ibft propose bayrakları

+ +

vote

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +Doğrulayıcı kümesinde bir değişiklik önerir. Olası değerler: `[auth, drop]`. + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +Oylanacak hesabın adresidir. + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +Oylanacak hesap için BLS genel anahtarıdır, yalnızca BLS modunda gereklidir. + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +gRPC API adresidir. Varsayılan: `127.0.0.1:9632`. + +

ibft status bayrakları

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +gRPC API adresidir. Varsayılan: `127.0.0.1:9632`. + +

ibft switch bayrakları

+ +

chain

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +Güncellenecek genesis dosyasını belirtir. Varsayılan: `./genesis.json`. + +--- + +

Tip

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +Değiştirilecek IBFT türünü belirtir. Olası değerler: `[PoA, PoS]`. + +--- + +

deployment

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +Sözleşme devreye alımının yüksekliğini belirtir. Sadece PoS ile kullanılabilir. + +--- + +

from

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +Blok başlıklarının doğrulama modunu belirtir. Olası değerler: `[ecdsa, bls]`. Varsayılan: `bls`. + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +Yeni doğrulayıcıların dizinleri için ön ek yoludur. `ibft-validator` bayrağı göz ardı edilirse, mevcut olmalıdır. Sadece IBFT modu PoA olduğunda kullanılabilir (`--pos` bayrağı göz ardı edilir). + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Geçirilen adresleri çatal sonrasında kullanılan IBFT doğrulayıcıları olarak ayarlar. `ibft-validators-prefix-path` bayrağı göz ardı edilirse, mevcut olmalıdır. Sadece PoA modunda kullanılabilir. +1. Ağ ECDSA ile çalışıyorsa, format `--ibft-validator [ADDRESS]` şeklindedir. +2. Ağ BLS ile çalışıyorsa, format `--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]` şeklindedir. + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +Bir PoS konsensüsü içinde ayarlanan doğrulayıcı kümesine katılabilecek maksimum staker sayısını belirler. +Bu sayı MAX_SAFE_INTEGER (2^53 - 2) değerini aşamaz. + +--- + +

min-validator-count

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +Bir PoS konsensüsü içinde ayarlanan doğrulayıcı kümesine katılmak için gereken minimum staker sayısını belirtir. +Bu sayı max-validator-count değerini aşamaz. +Varsayılan olarak 1 değerini alır. + +Çatalın başlangıç yüksekliğini belirtir. + +--- + +

ibft quorum bayrakları

+ +

from

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +Quorum hesaplamasını QuorumOptimal olarak değiştirecek yüksekliktir; bu hesaplamada `(2/3 * N)` formülü kullanılır ve `N` doğrulayıcı düğümlerin sayısıdır. Lütfen bunun geriye dönük uyumluluk için olduğunu; yani yalnızca belli bir blok yüksekliğine kadar eski Quorum hesaplamasını kullanan zincirler için olduğunu unutmayın. + +--- + +

chain

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +Güncellenecek genesis dosyasını belirtir. Varsayılan: `./genesis.json`. + +### İşlem Havuzu Komutları {#transaction-pool-commands} + +| **Komut** | **Açıklama** | +|------------------------|--------------------------------------------------------------------------------------| +| txpool status | Havuzdaki işlem sayısını getirir | +| txpool subscribe | İşlem havuzundaki olaylara abone olur | + +

txpool status bayrakları

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +gRPC API adresidir. Varsayılan: `127.0.0.1:9632`. + +

txpool subscribe bayrakları

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +gRPC API adresidir. Varsayılan: `127.0.0.1:9632`. + +--- + +

promoted

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +TxPool içinde yükseltilen işlem olaylarına abone olur. + +--- + +

dropped

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +TxPool içinde düşürülen işlem olaylarına abone olur. + +--- + +

demoted

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +TxPool içinde alçaltılan işlem olaylarına abone olur. + +--- + +

added

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +TxPool'a eklenen işlem olaylarına abone olur. + +--- + +

enqueued

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +Hesap kuyruklarında sıralanan işlem olaylarına abone olur. + + +--- + +### Blok zinciri komutları {#blockchain-commands} + +| **Komut** | **Açıklama** | +|------------------------|-------------------------------------------------------------------------------------| +| status | İstemcinin durumunu getirir. Ayrıntılı yanıt aşağıda bulunabilir | +| monitor | Bir blok zinciri olay akışına abone olur. Ayrıntılı yanıt aşağıda bulunabilir | +| version | İstemcinin güncel sürümünü getirir | + +

status bayrakları

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +gRPC API adresidir. Varsayılan: `127.0.0.1:9632`. + +

monitor bayrakları

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +gRPC API adresidir. Varsayılan: `127.0.0.1:9632`. + +--- +

version komutu

+ + + + + + version + + + + +Bu görüntüler, sürüm sürümü, git şubesi, hash işlemesi ve zaman oluşturma + +## Sır Komutları {#secrets-commands} + +| **Komut** | **Açıklama** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| secrets init | İlgili sır yöneticisi için özel anahtarları başlatır | +| secrets generate | Polygon Edge tarafından ayrıştırılabilecek bir sır yöneticisi yapılandırma dosyası oluşturur | +| sırlar çıktı | BLS genel anahtar adresi, doğrulayıcı genel anahtar adresini ve referans için düğüm kimliğini yazdırır | + +### secrets init bayrakları {#secrets-init-flags} + +

Yapılandırma

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +SecretsManager yapılandırma dosyası için dizini belirler. Hashicorp Vault için kullanılır. Göz ardı edilirse, yerel FS sır yöneticisi kullanılır. + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +Yerel FS kullanılıyorsa, Polygon Edge verisi için dizini ayarlar. + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +ECDSA anahtarı oluşturup oluşturulmayacağını belirten bayrağı ayarlar. Varsayılan: `true`. + +--- + +

network

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +Bir Libp2p Ağ anahtarı oluşturulup oluşturumayacağını belirten bayrağı ayarlar. Varsayılan: `true`. + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +Bir BLS anahtarı oluşturulup oluşturulmayacağını belirten bayrağı ayarlar. Varsayılan: `true`. + +### secrets generate bayrakları {#secrets-generate-flags} + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +Sır yöneticisi yapılandırma dosyası için dizini ayarlar; Varsayılan: `./secretsManagerConfig.json` + +--- + +

Tip

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +Sır yöneticisinin türünü belirtir [`hashicorp-vault`]. Varsayılan: `hashicorp-vault` + +--- + +

token

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +Hizmet için erişim token'ını belirtir + +--- + +

server-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +Hizmet için sunucu URL'sini belirtir + +--- + +

Ad

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +Hizmet içi kayıt tutma için düğüm adını belirtir. Varsayılan: `polygon-edge-node` + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Hashicorp Vault sır yöneticisi için kullanılan ad alanını belirtir. Varsayılan: `admin` + +### sırlar çıkış bayrakları {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +BLS genel anahtarını yalnızca çıkarıp çıkarmayacağını belirten bayrağı ayarlar. Varsayılan: `true` + +--- + +

Yapılandırma

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +SecretsManager yapılandırma dosyası için dizini belirler. Göz ardı edilirse, yerel FS sır yöneticisi kullanılır. + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +Yerel FS kullanılıyorsa, Polygon Edge verisi için dizini ayarlar. + +--- + +

node-id

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +Bu bayrağı ayarlar, ağ düğüm kimliğini yalnızca çıkarıp çıkarmayacağını gösterir. Varsayılan: `true` + +--- + +

Doğrulayıcı

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +Bu bayrağı yalnızca doğrulayıcı adresini çıkarıp çıkarmayacağını gösteren bir şekilde ayarlar. Varsayılan: `true` + +--- + +## Yanıtlar {#responses} + +### Durum Yanıtı {#status-response} + +Yanıt nesnesi, Protokol Arabellekleri kullanılarak tanımlanır. +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### İzleme Yanıtı {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## Yardımcı Programlar {#utilities} + +### beyaz liste (whitelist) komutları {#whitelist-commands} + +| **Komut** | **Açıklama** | +|------------------------|-------------------------------------------------------------------------------------| +| whitelist show | Beyaz liste bilgilerini görüntüler | +| whitelist deployment | Akıllı sözleşme devreye alma beyaz listesini günceller | + +

whitelist show

+ + + + + whitelist show + + + + +Beyaz liste bilgilerini görüntüler. + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +Güncellenecek genesis dosyasını belirtir. Varsayılan: `./genesis.json`. + +--- + +

whitelist deployment

+ +

chain

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +Güncellenecek genesis dosyasını belirtir. Varsayılan: `./genesis.json`. + +--- + +

add

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Sözleşme devreye alma beyaz listesine yeni bir adres ekler. Sadece sözleşme devreye alma beyaz listesindeki adresler sözleşmeleri devreye alabilir. Boş bırakılırsa, herhangi bir adres sözleşmeyi devreye alma işlemini gerçekleştirebilir + +--- + +

remove

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Bir adresi sözleşme devreye alma beyaz listesinden kaldırır. Sadece sözleşme devreye alma beyaz listesindeki adresler sözleşmeleri devreye alabilir. Boş bırakılırsa, herhangi bir adres sözleşmeyi devreye alma işlemini gerçekleştirebilir + +--- + +### yedekleme bayrakları {#backup-flags} + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +gRPC API adresidir. Varsayılan: `127.0.0.1:9632`. + +--- + +

out

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +Kaydedilecek arşiv dosya dizinidir. + +--- + +

from

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +Arşivdeki blokların başlangıç yüksekliğidir. Varsayılan: 0. + +--- + +

to

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +Arşivdeki blokların son yüksekliğidir. + +--- + +## Genesis Şablonu {#genesis-template} +Genesis dosyası blok zincirinin başlangıç durumunu ayarlamak için kullanılmalıdır (ör., bazı hesaplarda bakiye bulunması gerekiyorsa). + +Aşağıdaki *./genesis.json* dosyası oluşturulur: +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### Veri Dizini {#data-directory} + +*Data-dir* bayrağını çalıştırırken, bir **test zinciri** klasörü oluşturulur. +Klasör yapısı aşağıdaki alt klasörlerden oluşur: +* **blockchain** - Blok zinciri nesneleri için LevelDB'yi depolar +* **trie** - Merkle ağaçları için LevelDB'yi depolar +* **keystore** - İstemci için özel anahtarları depolar. Buna libp2p özel anahtarı mühürleme/doğrulama özel anahtarı dâhildir +* **consensus** - İstemcinin çalışırken ihtiyaç duyabileceği tüm konsensüs bilgisini depolar + +## Kaynaklar {#resources} +* **[Protokol Arabellekleri](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/tr-edge/get-started/installation.md b/archive/edge/tr-edge/get-started/installation.md new file mode 100644 index 0000000000..8730deeb83 --- /dev/null +++ b/archive/edge/tr-edge/get-started/installation.md @@ -0,0 +1,54 @@ +--- +id: installation +title: Kurulum +description: "Polygon Edge nasıl kurulur?" +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +Lütfen sizin için daha uygun olan kurulum yöntemine bakın. + +Önerimiz, önceden oluşturulmuş sürümleri kullanmak ve sağlanan dosya özetlerini doğrulamaktır. + +## Önceden oluşturulmuş sürümler {#pre-built-releases} + +Sürümlerin listesi için lütfen [GitHub Sürümleri](https://github.com/0xPolygon/polygon-edge/releases) sayfasına başvurun. + +Polygon Edge, Darwin ve Linux için çapraz derlenmiş AMD64/ARM64 ikili dosyaları ile birlikte gelir. + +--- + +## Docker görüntüsü {#docker-image} + +Resmî Docker görüntüleri, [hub.docker.com kayıt defteri](https://hub.docker.com/r/0xpolygon/polygon-edge) altında barındırılır. + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## Kaynaktan oluşturma {#building-from-source} + +Kullanmadan önce `go install`Go'nun yüklü olduğundan`>=1.18` ve doğru bir şekilde yapılandırıldığından emin olun. + +Kararlı şube en son sürümün dalıdır. + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## `go install` Kullanımı + +Kullanmadan önce `go install`Go'nun yüklü olduğundan`>=1.17` ve doğru bir şekilde yapılandırıldığından emin olun. + +`go install github.com/0xPolygon/polygon-edge@release/` + +İkili `GOBIN`çevrenizde mevcut olacak ve en son sürümden gelen değişiklikleri içerecektir. Hangisinin en son olduğunu öğrenmek için [GitHub Releases](https://github.com/0xPolygon/polygon-edge/releases) çıkışını kontrol edebilirsiniz. diff --git a/archive/edge/tr-edge/get-started/set-up-ibft-locally.md b/archive/edge/tr-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..009cfb89f0 --- /dev/null +++ b/archive/edge/tr-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,367 @@ +--- +id: set-up-ibft-locally +title: Yerel Kurulum +description: "Adım adım yerel kurulum kılavuzu." +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution Bu kılavuz yalnızca test amaçlıdır + +Aşağıdaki kılavuz size yerel makinenizde test ve geliştirme için bir Polygon Edge ağı kurma talimatlarını +sunacaktır. + +Bu prosedür Polygon Edge ağınI gerçek bir kullanım senaryosu için bulut sağlayıcı üzerinde kurmaktan +bir bulut sağlayıcısı: **[Cloud Setup](/docs/edge/get-started/set-up-ibft-on-the-cloud)** + +::: + + +## Gereksinimler {#requirements} + +Polygon Edge kurmak için [Kurulum](/docs/edge/get-started/installation) kısmına göz atın. + +## Genel Bakış {#overview} + +![Yerel Kurulum](/img/edge/ibft-setup/local.svg) + +Bu kılavuzda amacımız, [IBFT konsensüs protokolü](https://github.com/ethereum/EIPs/issues/650) ile çalışan işlevsel bir `polygon-edge` blok zinciri ağı oluşturmaktır. +Blok zinciri ağı 4 düğümden oluşacaktır ve bu düğümlerin her biri doğrulayıcı düğüm olacak, dolayısıyla hem blok teklif etmek hem de diğer teklifçilerden gelen blokları doğrulamak için yetkili olacaktır. +4 düğümün her biri aynı makinede çalışacaktır; çünkü bu kılavuzun amacı size mümkün olan en kısa zamanda tam işlevsel bir IBFT kümesi sunmaktır. + +Bunu başarmak için size 4 kolay adımda rehberlik edeceğiz: + +1. Veri dizinlerini başlatmak, 4 düğümün her biri için doğrulayıcı anahtarlarını oluşturacak ve blok zinciri veri dizinlerini başlatacaktır. Doğrulayıcı anahtarları, genesis blokunun önyüklemesini bu anahtarları kullanan başlangıç doğrulayıcı kümesiyle yapmamız gerektiği için önemlidir. +2. Bootnode için bağlantı dizesi hazırlığı, çalıştıracağımız her düğüm için ilk kez başlarken hangi düğüme bağlanacağına dair en önemli bilgi olacaktır. +3. `genesis.json` dosyasını oluşturmak için; genesis bloğunda ağın ilk doğrulayıcılarını belirlemek için kullanılan **adım 1**'de oluşturulmuş doğrulayıcı anahtarları ve **adım 2**'deki bootnode bağlantı dizesi girdi olarak gerekli olacaktır. +4. Bu kılavuzun nihai amacı tüm düğümleri çalıştırmaktır ve bu tamamlayacağımız son adım olacaktır. Düğümlere hangi veri dizininin kullanılacağını ve başlangıç ağ durumunun önyüklemesini yapacak olan `genesis.json` dosyasının nerede bulunacağını öğreteceğiz. + +Dört düğümün tümü localhost üzerinde çalışacağı için, kurulum işlemi sırasında tüm veri dizinlerinin +her bir düğüm için aynı ana dizinde bulunması beklenmektedir. + +:::info Doğrulayıcı sayısı + +Bir kümedeki düğüm sayısı için belirlenmiş minimum bir sayı yoktur; bu da yalnızca 1 doğrulayıcı düğümü içeren kümeler olabileceği anlamına gelir. +Bununla birlikte, _tek_ düğümden oluşan bir kümede **bir çökme toleransı bulunmadığını** ve **BFT garantisi olmadığını** unutmayın. + +BFT garantisi sağlamak için önerilen minimum düğüm sayısı 4'tür; çünkü 4 düğümlü bir kümede +1 düğümün başarısızlığı kalan 3'ünün normal olarak çalışmaya devam etmesi ile tolere edilebilir. + +::: + +## Adım 1: IBFT için veri klasörlerini başlatın ve doğrulayıcı anahtarlarını oluşturun {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +IBFT'yi doğru bir şekilde yapılandırmak ve çalıştırmak için veri klasörlerini +her düğüm için bir tane olacak şekilde başlatmalısınız: + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +Bu komutların her biri doğrulayıcı anahtarını, bls genel anahtarını ve [düğüm kimliğini](https://docs.libp2p.io/concepts/peer-id/) çıktı olarak verecektir. Bir sonraki adım için ilk düğümün Düğüm Kimliği'ne ihtiyacınız olacaktır. + +### Sırları Outputting {#outputting-secrets} +Sır çıktısı tekrar alınabilir ve gerekirse + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## Adım 2: Bootnode için multiaddr bağlantı dizesini hazırlayın {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Bir düğümün başarılı bir şekilde bağlantı kurabilmesi için hangi `bootnode` sunucusuna bağlanacağını bilmesi gerekir; +bu şekilde ağdaki diğer düğümlerin tümünden bilgi alabilir. P2p jargonunda `bootnode`, bazen `rendezvous` olarak da bilinir. + +`bootnode` , polygon-edge düğümünün özel bir örneği değildir. Her polygon-edge düğümü bir `bootnode` olarak görev yapabilir; ancak +her polygon-edge düğümünün belirtilmiş bir bootnode kümesine sahip olması gerekir. Ağdaki diğer tüm düğümler ile nasıl +bağlantı kurulacağının bilgisini almak için bu küme ile iletişim kurulacaktır. + +Bootnode'u belirten bağlantı dizesini oluşturmak için, +[multiaddr formatına](https://docs.libp2p.io/concepts/addressing/) uymamız gerekir: +``` +/ip4//tcp//p2p/ +``` + +Bu kılavuzda birinci ve ikinci düğümleri diğer tüm düğümler için bootnode olarak ele alacağız. Bu senaryoda olacak şey şu şekildedir: +`node 1` veya `node 2` ile bağlantı kuran düğümler, birbiriyle nasıl bağlantı kuracağının bilgisini karşılıklı +iletişim kurulan bootnode üzerinden alacaktır. + +:::info Bir düğüm başlatmak için en az bir bootnode belirtmeniz gerekir + +En az **bir** bootnode gereklidir, böylece ağ içindeki diğer düğümler birbirlerini keşfedebilir. Daha fazla bootnode tavsiye edilir çünkü +kesinti durumlarına karşı ağ için dayanıklılık/koruma sağlarlar. +Bu kılavuzda iki düğüm listeleyeceğiz; ancak bu, çalışma esnasında `genesis.json` dosyasının geçerliliği üzerinde hiçbir etki yaratmadan değiştirilebilir. + +::: + +Localhost üzerinde çalıştığımızdan, `` değerinin `127.0.0.1` olduğunu varsaymak makuldür. + +`` için `10001` değerini kullanacağız çünkü `node 1` için libp2p sunucusunu bu port üzerinden dinleyecek şekilde yapılandıracağız. + +Son olarak, `` değerine ihtiyacımız var; bunu da daha önce çalıştırılan `polygon-edge secrets init --data-dir test-chain-1` komutunun (`node1` için anahtarları ve veri dizinlerini oluşturmak için kullanılmıştı) çıktısından alabiliriz + +Birleştirdikten sonra, bootnode olarak kullanacağımız `node 1` için multiaddr bağlantı dizesi şu şekilde görünecektir (yalnızca sondaki `` farklı olacaktır): +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Benzer şekilde, aşağıda gösterildiği gibi ikinci bootnode için multiaddr oluşturacağız +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info IP'ler yerine DNS ana bilgisayar adları + +Polygon Edge düğüm yapılandırması için DNS ana bilgisayar adları kullanımını destekler. Düğümün IP'si çeşitli nedenlerle değişebileceği için, bu, bulut tabanlı devreye alma sırasında çok kullanışlı bir özelliktir. + +DNS ana bilgisayar adlarını kullanırken uygulanacak bağlantı dizesi multiaddr formatı aşağıdaki gibidir: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## Adım 3: Doğrulayıcı olarak 4 düğümlü genesis dosyasını oluşturun {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +Bu komutun yaptığı şey: + +* `--ibft-validators-prefix-path`, ön ek klasör dizinini Polygon Edge'de IBFT'nin kullanabileceği belirlenmiş olan dizin olarak +ayarlar. Bu dizin, doğrulayıcının özel anahtarının tutulduğu `consensus/` klasörünü barındırmak için kullanılır. Doğrulayıcının +genel anahtarı, önyükleme düğümlerinin başlangıç listesi olan genesis dosyasını oluşturmak için gereklidir. +Bu bayrak yalnızca localhost üzerinde ağ kurarken mantıklıdır çünkü gerçek senaryoda tüm düğümlerin veri dizinlerinin +genel anahtarlarını kolayca okuyabileceğimiz aynı dosya sisteminde olmasını bekleyemeyiz. +* `--bootnode`, düğümlerin birbirlerini bulmasını sağlayacak bootnode adresini ayarlar. +**Adım 2**'de belirtildiği gibi, `node 1` için belirlenen multiaddr dizesini kullanacağız. + +Bu komutun sonucu, yeni blok zincirimizin genesis blokunu içeren `genesis.json` dosyasıdır. Bu dosya, önceden tanımlanmış doğrulayıcı kümesini ve bağlantı kurabilmek için ilk olarak iletişim kurulacak düğüm bilgisini içerir. + +:::info ECDSA'ya geçiş + +BLS blok başlıklarının varsayılan doğrulama modudur. Zincirinizin ECDSA modunda çalışmasını istiyorsanız, şu argümanla birlikte `—ibft-validator-type`bayrağı `ecdsa`kullanabilirsiniz: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info Hesap bakiyelerini önceden mine etmek + +Blok zinciri ağınızı "önceden mine edilmiş" bakiyeye sahip bazı hesaplarla yapılandırmak isteyebilirsiniz. + +Bunu başarmak için, blok zinciri üzerinde belli bir bakiye ile başlatılmasını istediğiniz adres başına istediğiniz kadar `--premine` bayrağı +girin. + +Örneğin, genesis blokumuz içindeki `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` adresine 1000 ETH önceden mine etmek istiyorsak, aşağıdaki argümanı sağlamamız gerekir: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Önceden mine edilecek miktarın ETH değil, WEI cinsinden olduğunu unutmayın.** + +::: + +:::info Blok gaz limitini ayarlayın + +Her blok için varsayılan gaz limiti `5242880` olarak belirlenmiştir. Bu değer genesis dosyasına yazılmıştır ama bunu +artırmak/azaltmak isteyebilirsiniz. + +Bunu yapmak için, aşağıda gösterildiği gibi `--block-gas-limit` bayrağını kullanıp ardından istenen değeri ekleyebilirsiniz: + +```shell +--block-gas-limit 1000000000 +``` +::: + +:::info Sistem dosya tanımlayıcı limitini ayarlayın + +Varsayılan dosya tanımlayıcı limiti (en fazla açık dosya sayısı) düşük ve Linux üzerinde her şey bir dosyadır. Düğümlerin yüksek bir verim elde etmesi bekleniyorsa, bu limiti arttırmayı düşünebilirsiniz. Daha fazla ayrıntı için linux of resmi dokümanlarını kontrol edin. + +#### Geçerli işletim sistemi limitlerini kontrol edin ( açık dosyalar ) {#check-current-os-limits-open-files} +```shell title="ulimit -n" +1024 # Ubuntu default +``` + +#### Açık dosya limitini artırın {#increase-open-files-limit} +- Ön planda `polygon-edge`koşmak (kabuk) + ```shell title="Set FD limit for the current session" + ulimit -n 65535 # affects only current session, limit won't persist after logging out + ``` + + ```shell title="Edit /etc/security/limits.conf" + # add the following lines to the end of the file to modify FD limits + * soft nofile 65535 # sets FD soft limit for all users + * hard nofile 65535 # sets FD hard limit for all users + + # End of file + ``` +Dosyayı kaydedin ve sistemi yeniden başlatın. + +- Arka planda hizmet olarak `polygon-edge`çalışan + +Sistem servisi olarak `polygon-edge`çalıştırılırsa, aracı , `systemd`dosya tanımlayıcı limitleri gibi kullanarak Kullanılarak `systemd`yönetilmelidir. + ```shell title="Edit /etc/systemd/system/polygon-edge.service" + [Service] + ... + LimitNOFILE=65535 + ``` + +### Sorun Giderme {#troubleshooting} +```shell title="Watch FD limits of polygon edge running process" +watch -n 1 "ls /proc/$(pidof polygon-edge)/fd | wc -l" +``` + +```shell title="Check max FD limits for polygon-edge running process" +cat /proc/$(pidof polygon-edge)/limits +``` +::: + + +## Adım 4: Tüm istemcileri çalıştırın {#step-4-run-all-the-clients} + +Aynı makinede 4 düğümden oluşan bir Polygon Edge ağı çalıştırmayı denediğimiz için, +port çakışmalarını önlemeye dikkat etmeliyiz. Bu nedenle, bir düğümün her sunucusundaki dinleme portlarını belirlemek için aşağıdaki mantığı kullanacağız: + +- `node 1` gRPC sunucusu için `10000`, `node 2` gRPC sunucusu için `20000`, vb. +- `node 1` libp2p sunucusu için `10001`, `node 2` libp2p sunucusu için `20001`, vb. +- `node 1` JSON-RPC sunucusu için `10002`, `node 2` JSON-RPC sunucusu için `20002`, vb. + +**İlk** istemciyi çalıştırmak için (`10001` portuna dikkat edin çünkü **adım 2**'de düğüm 1'in Düğüm Kimliği yanında libp2p multiaddr'ın bir parçası olarak kullanılmıştı): + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +**İkinci** istemciyi çalıştırmak için: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +**Üçüncü** istemciyi çalıştırmak için: + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +**Dördüncü** istemciyi çalıştırmak için: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +Şimdiye kadar yapılanları kısaca gözden geçirmek gerekirse: + +* İstemci verisi için dizin, **./test-chain-\*** olarak belirtilmiştir +* GRPC sunucuları her düğüm için sırasıyla **10000**, **20000**, **30000** ve **40000** portlarında başlatılmıştır +* libp2p sunucuları her düğüm için sırasıyla **10001**, **20001**, **30001** ve **40001** portlarında başlatılmıştır +* JSON-RPC sunucuları her düğüm için sırasıyla **10002**, **20002**, **30002** ve **40002** portlarında başlatılmıştır +* *seal* bayrağı, başlatılan düğümün blok mühürlemeye katılacağı anlamına gelir +* *chain* bayrağı, zincir yapılandırması için hangi genesis dosyasının kullanılması gerektiğini belirtir + +Genesis dosyasının yapısı [CLI Komutları](/docs/edge/get-started/cli-commands) bölümünde ele alınmıştır. + +Önceki komutları çalıştırdıktan sonra, blokları mühürleyebilen ve düğüm arızasından kurtulabilecek 4 düğümlü bir Polygon Edge +ağı kurmuş oldunuz. + +:::info Yapılandırma dosyasını kullanarak istemciyi başlatın + +Tüm yapılandırma parametrelerini CLI argümanları olarak belirtmek yerine, İstemci aşağıdaki komutu çalıştırarak bir yapılandırma dosyası kullanarak da başlatılabilir: + +````bash +polygon-edge server --config +```` +Örnek: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Şu anda, biz destek `yaml`ve `json`tabanlı yapılandırma dosyaları, örnek yapılandırma dosyaları **[burada](/docs/edge/configuration/sample-config)** bulunabilir + +::: + +:::info Doğrulayıcı olmayan bir düğüm çalıştırma adımları + +Doğrulayıcı olmayan bir düğüm, her zaman, doğrulayıcı düğümden alınan en son blokları eşitleyecektir (senkronizasyon). Aşağıdaki komutu çalıştırarak doğrulayıcı olmayan bir düğümü başlatabilirsiniz. + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +Örneğin, aşağıdaki komutu çalıştırarak **beşinci** Doğrulayıcı Olmayan istemciyi ekleyebilirsiniz : + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info Fiyat limitini belirleyin + +Bir Polygon Edge düğümü, gelen işlemler için belirlenmiş bir **fiyat limiti** ile başlatılabilir. + +Fiyat limitinin birimi `wei`'dir. + +Bir fiyat limiti belirlemek, mevcut düğüm tarafından işlenen herhangi bir işlemin belirlenen fiyat limitinden **daha yüksek** bir gaz fiyatı +olması gerektiği, aksi halde işlemin bloka eklenmeyeceği anlamına gelir. + +Düğümlerin çoğunluğunun belli bir fiyat limitine uyması, ağ üzerindeki işlemlerin +belli bir fiyat eşiğinin altında olmaması kuralını uygulamaya koyar. + +Fiyat limiti için varsayılan değer `0` olarak belirlenmiştir, yani varsayılan olarak limit uygulanmamaktadır. + +`--price-limit` bayrağının kullanım örneği: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Fiyat limitlerinin **yalnızca yerel olmayan işlemlerde uygulandığına** dikkat etmek gerekir, yani +fiyat limiti düğümde yerel olarak eklenen işlemlere uygulanmaz. + +::: + +:::info WebSocket URL'si + +Polygon Edge çalıştırdığınızda, varsayılan olarak zincir konumuna göre bir WebSocket URL'si oluşturur. +HTTPS bağlantıları için `wss://` ve HTTP için `ws://` URL yöntemi kullanılır. + +Localhost WebSocket URL: +````bash +ws://localhost:10002/ws +```` +Port sayısının düğüm için seçilen JSON-RPC portuna bağlı olduğunu unutmayın. + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## Adım 5: Polygon-edge ağı ile etkileşim kurun {#step-5-interact-with-the-polygon-edge-network} + +Artık en az 1 istemci kurduğunuza göre, yukarıda önceden mine ettiğiniz hesabı kullanarak +ve 4 düğümden herhangi birinde JSON-RPC URL'sini belirterek blok zinciri ile etkileşim kurabilirsiniz: +- Düğüm 1: `http://localhost:10002` +- Düğüm 2: `http://localhost:20002` +- Düğüm 3: `http://localhost:30002` +- Düğüm 4: `http://localhost:40002` + +Yeni oluşturulmuş kümeye operatör komutları yayımlamak için bu kılavuzu takip edin: [Operatör bilgisi nasıl sorgulanır?](/docs/edge/working-with-node/query-operator-info) (Oluşturduğumuz kümenin GRPC portları, her düğüm için sırasıyla `10000`/`20000`/`30000`/`40000` şeklindedir) diff --git a/archive/edge/tr-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/tr-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..7e6e2dd673 --- /dev/null +++ b/archive/edge/tr-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,387 @@ +--- +id: set-up-ibft-on-the-cloud +title: Bulut Kurulumu +description: "Adım adım bulut kurulum kılavuzu." +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info Bu kılavuz, mainnet veya testnet kurulumları içindir + +Aşağıdaki kılavuzda, testnet'inizin veya mainnet'inizin bir üretim ortamında kurulumu için, bir bulut sağlayıcı üzerinde Polygon Edge ağının nasıl kurulacağını açıklayan talimatlar bulunmaktadır. + +Üretim ortamı benzeri bir kurulum yapmadan önce, hızlıca `polygon-edge` testi yapmak için yerel bir Polygon Edge ağı kurmak istiyorsanız, şuraya bakın +**[Yerel Kurulum](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## Gereksinimler {#requirements} + +Polygon Edge kurmak için [Kurulum](/docs/edge/get-started/installation) kısmına göz atın. + +### VM bağlantısı kurulumu {#setting-up-the-vm-connectivity} + +Bulut sağlayıcı seçiminize bağlı olarak, VM'ler arasında bağlantı ve kuralları oluştururken, bir güvenlik duvarı, +güvenlik grupları veya erişim kontrol listeleri kullanabilirsiniz. + +Diğer VM'lere açık kalması gereken tek `polygon-edge` parçası, libp2p sunucusu olduğundan +VM'ler arasındaki tüm haberleşmeye, varsayılan libp2p portu `1478` üzerinde izin vermek yeterli olacaktır. + +## Genel Bakış {#overview} + +![Bulut kurulumu](/img/edge/ibft-setup/cloud.svg) + +Bu kılavuzda amacımız, [IBFT konsensüs protokolü](https://github.com/ethereum/EIPs/issues/650) ile çalışan işlevsel bir `polygon-edge` blok zinciri ağı oluşturmaktır. +Blok zinciri ağı 4 düğümden oluşacaktır ve bu düğümlerin dördü de doğrulayıcı düğüm olacak, dolayısıyla hem blok teklif etmek hem de diğer teklifçilerden gelen blokları doğrulamak için yetkili olacaktır. +4 düğümün her biri kendi VM'si üzerinde çalışacaktır; çünkü bu kılavuzun amacı, size, güven gerektirmeyen (trustless) bir ağ kurulumu sağlamak için doğrulayıcı anahtarlarının özel (private) tutulduğu tam işlevli bir Polygon Edge ağı sunmaktır. + +Bunu başarmak için size 4 kolay adımla rehberlik edeceğiz: + +0. Yukarıdaki **Gereksinimler** listesine bir göz atın +1. Doğrulayıcıların her biri için özel anahtarları üretin ve veri dizinini ilklendirin +2. Paylaşılmış `genesis.json` içine konulacak bootnode için bağlantı dizesini (string) hazırlayın +3. Yerel makinenizde `genesis.json` oluşturun ve bunu düğümlerin her birine gönderin/aktarın +4. Tüm düğümleri başlatın + +:::info Doğrulayıcı sayısı + +Bir kümedeki düğüm sayısı için belirlenmiş minimum bir sayı yoktur; bu da yalnızca 1 doğrulayıcı düğümü içeren kümeler olabileceği anlamına gelir. +Bununla birlikte, _tek_ düğümden oluşan bir kümede **bir çökme toleransı bulunmadığını** ve **BFT garantisi olmadığını** unutmayın. + +BFT garantisi sağlamak için önerilen minimum düğüm sayısı 4'tür; çünkü 4 düğümlü bir kümede +1 düğümün başarısızlığı kalan 3'ünün normal olarak çalışmaya devam etmesi ile tolere edilebilir. + +::: + +## Adım 1: Veri klasörlerini ilklendirin ve doğrulayıcı anahtarlarını oluşturun {#step-1-initialize-data-folders-and-generate-validator-keys} + +Polygon Edge'i hazırlayıp çalıştırabilmek için, her düğüm üzerindeki veri klasörlerini ilklendirmeniz gerekir: + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +Bu komutların her biri doğrulayıcı anahtarını, bls genel anahtarını ve [düğüm kimliğini](https://docs.libp2p.io/concepts/peer-id/) çıktı olarak verecektir. Bir sonraki adım için ilk düğümün Düğüm Kimliği'ne ihtiyacınız olacaktır. + +### Sırları Outputting {#outputting-secrets} +Sır çıktısı tekrar alınabilir ve gerekirse + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning Veri dizininizin erişim ve kontrolü yalnızca size ait olmalıdır! + +Yukarıdaki veri dizini oluşturma işlemleri, blok zinciri durumunu tutmak için kullanılan dizinleri ilklendirmenin yanı sıra, doğrulayıcınızın özel anahtarlarını da oluşturacaktır. +**Bu anahtar gizli tutulmalıdır; çünkü çalınırsa, başka birinin ağ içinde sizin yerinize kendisini doğrulayıcı olarak göstermesine olanak sağlar!** + +::: + +## Adım 2: Bootnode için multiaddr bağlantı dizesini hazırlayın {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Bir düğümün başarılı bir şekilde bağlantı kurabilmesi için hangi `bootnode` sunucusuna bağlanacağını bilmesi gerekir; +bu şekilde ağdaki diğer düğümlerin tümünden bilgi alabilir. P2p jargonunda `bootnode`, bazen `rendezvous` olarak da bilinir. + +`bootnode`, bir Polygon Edge düğümünün özel bir örneği değildir. Her Polygon Edge düğümü bir `bootnode` görevi görebilir ve +her Polygon Edge düğümünün belirtilen bir bootnode kümesine sahip olması gerekir; ağda geriye kalan tüm düğümlerle nasıl +bağlantı kurulacağının bilgisini almak için bu küme ile iletişim kurulacaktır. + +Bootnode'u belirten bağlantı dizesini oluşturmak için, +[multiaddr formatına](https://docs.libp2p.io/concepts/addressing/) uymamız gerekir: +``` +/ip4//tcp//p2p/ +``` + +Bu kılavuzda birinci ve ikinci düğümleri diğer tüm düğümler için bootnode olarak ele alacağız. Bu senaryoda olacak şey şu şekildedir: +`node 1` veya `node 2` ile bağlantı kuran düğümler, birbiriyle nasıl bağlantı kuracağının bilgisini karşılıklı +iletişim kurulan bootnode üzerinden alacaktır. + +:::info Bir düğüm başlatmak için en az bir bootnode belirtmeniz gerekir + +En az **bir** bootnode gereklidir, böylece ağ içindeki diğer düğümler birbirlerini keşfedebilir. Daha fazla bootnode tavsiye edilir çünkü +kesinti durumlarına karşı ağ için dayanıklılık/koruma sağlarlar. +Bu kılavuzda iki düğüm listeleyeceğiz; ancak bu, çalışma esnasında `genesis.json` dosyasının geçerliliği üzerinde hiçbir etki yaratmadan değiştirilebilir. + +::: + +Multiaddr bağlantı dizesinin ilk kısmı `` olduğundan, burada IP adresini diğer düğümler tarafından erişilebilecek şekilde girmeniz gerekecektir; kurulumunuza bağlı olarak bu, `127.0.0.1` değil özel veya genel bir IP adresi olabilir. + +`` için, varsayılan libp2p portu olması nedeniyle `1478` kullanacağız. + +Son olarak, `` değerine ihtiyacımız var; bunu da daha önce çalıştırılan `polygon-edge secrets init --data-dir data-dir` komutunun (`node 1` için anahtarları ve veri dizinlerini oluşturmak için kullanılmıştı) çıktısından alabiliriz + +Birleştirdikten sonra, bootnode olarak kullanacağımız `node 1` için multiaddr bağlantı dizesi şu şekilde görünecektir (yalnızca sondaki `` farklı olacaktır): +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Benzer şekilde, aşağıda gösterildiği gibi ikinci bootnode için multiaddr oluşturacağız +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info IP'ler yerine DNS ana bilgisayar adları + +Polygon Edge düğüm yapılandırması için DNS ana bilgisayar adları kullanımını destekler. Düğümün IP'si çeşitli nedenlerle değişebileceği için, bu, bulut tabanlı devreye alma sırasında çok kullanışlı bir özelliktir. + +DNS ana bilgisayar adlarını kullanırken uygulanacak bağlantı dizesi multiaddr formatı aşağıdaki gibidir: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## Adım 3: Doğrulayıcı olarak 4 düğümlü genesis dosyasını oluşturun {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +Bu adım yerel makinenizde çalıştırılabilir ancak 4 doğrulayıcının her biri için genel doğrulayıcı anahtarlarına ihtiyacınız olacaktır. + +Doğrulayıcılar güvenli bir şekilde `Public key (address)`'i paylaşabilir (aşağıda kendi `secrets init` komutlarının çıktısı olarak gösterilmiştir); bu sayede +genel anahtarları ile tanımlanan ilk doğrulayıcı kümesindeki bu doğrulayıcılar ile genesis.json dosyasını güvenli bir şekilde oluşturabilirsiniz: + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +4 doğrulayıcı genel anahtarının tamamını aldığınızda, `genesis.json` oluşturmak için aşağıdaki komutu çalıştırabilirsiniz + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +Bu komutun yaptığı şey: + +* `--ibft-validator`, genesis bloğu içindeki ilk doğrulayıcı kümesinde yer alması gereken doğrulayıcının genel anahtarını belirler. Birden fazla ilk doğrulayıcı olabilir. +* `--bootnode`, düğümlerin birbirlerini bulmasını sağlayacak bootnode adresini ayarlar. +`node 1`'in multiaddr dizesini kullanacağız (**adım 2**'de de belirtilen şekilde); ancak yukarıda gösterildiği gibi istediğiniz kadar bootnode ekleyebilirsiniz. + +:::info ECDSA'ya geçiş + +BLS blok başlıklarının varsayılan doğrulama modudur. Zincirinizin ECDSA modunda çalışmasını istiyorsanız, şu argümanla birlikte `—ibft-validator-type`bayrağı `ecdsa`kullanabilirsiniz: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info Hesap bakiyelerini önceden mine etmek + +Blok zinciri ağınızı "önceden mine edilmiş" bakiyeye sahip bazı hesaplarla yapılandırmak isteyebilirsiniz. + +Bunu başarmak için, blok zinciri üzerinde belli bir bakiye ile başlatılmasını istediğiniz adres başına istediğiniz kadar `--premine` bayrağı +girin. + +Örneğin, genesis blokumuz içindeki `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` adresine 1000 ETH önceden mine etmek istiyorsak, aşağıdaki argümanı sağlamamız gerekir: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Önceden mine edilecek miktarın ETH değil, WEI cinsinden olduğunu unutmayın.** + +::: + +:::info Blok gaz limitini ayarlayın + +Her blok için varsayılan gaz limiti `5242880` olarak belirlenmiştir. Bu değer genesis dosyasına yazılmıştır ama bunu +artırmak/azaltmak isteyebilirsiniz. + +Bunu yapmak için, aşağıda gösterildiği gibi `--block-gas-limit` bayrağını kullanıp ardından istenen değeri ekleyebilirsiniz: + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Sistem dosya tanımlayıcı limitini ayarlayın + +Varsayılan dosya tanımlayıcı limiti (en fazla açık dosya sayısı) düşük ve Linux üzerinde her şey bir dosyadır. Düğümlerin yüksek bir verim elde etmesi bekleniyorsa, bu limiti arttırmayı düşünebilirsiniz. Daha fazla ayrıntı için linux of resmi dokümanlarını kontrol edin. + +#### Geçerli işletim sistemi limitlerini kontrol edin ( açık dosyalar ) {#check-current-os-limits-open-files} +```shell title="ulimit -n" +1024 # Ubuntu default +``` + +#### Açık dosya limitini artırın {#increase-open-files-limit} +- Ön planda `polygon-edge`koşmak (kabuk) + ```shell title="Set FD limit for the current session" + ulimit -n 65535 # affects only current session, limit won't persist after logging out + ``` + + ```shell title="Edit /etc/security/limits.conf" + # add the following lines to the end of the file to modify FD limits + * soft nofile 65535 # sets FD soft limit for all users + * hard nofile 65535 # sets FD hard limit for all users + + # End of file + ``` +Dosyayı kaydedin ve sistemi yeniden başlatın. + +- Arka planda hizmet olarak `polygon-edge`çalışan + +Sistem servisi olarak `polygon-edge`çalıştırılırsa, aracı , `systemd`dosya tanımlayıcı limitleri gibi kullanarak Kullanılarak `systemd`yönetilmelidir. + ```shell title="Edit /etc/systemd/system/polygon-edge.service" + [Service] + ... + LimitNOFILE=65535 + ``` + +### Sorun Giderme {#troubleshooting} +```shell title="Watch FD limits of polygon edge running process" +watch -n 1 "ls /proc/$(pidof polygon-edge)/fd | wc -l" +``` + +```shell title="Check max FD limits for polygon-edge running process" +cat /proc/$(pidof polygon-edge)/limits +``` +::: + +Şunları belirttikten sonra: +1. Genesis bloğu içine doğrulayıcı kümesi olarak eklenecek doğrulayıcıların genel anahtarları +2. Bootnode multiaddr bağlantı dizeleri +3. Genesis blok içine eklenecek önceden mine edilmiş hesaplar ve bakiyeler + +ve `genesis.json` dosyası oluşturulduğunda, bu dosyayı ağ içindeki tüm VM'lere kopyalamanız gerekir. Kurulumunuza bağlı olarak bunu +kopyala/yapıştır yapabilir, düğüm operatörüne gönderebilir veya basitçe SCP/FTP kullanabilirsiniz. + +Genesis dosyasının yapısı [CLI Komutları](/docs/edge/get-started/cli-commands) bölümünde ele alınmıştır. + +## Adım 4: Tüm istemcileri çalıştırın {#step-4-run-all-the-clients} + +:::note Bulut sağlayıcıları üzerinde ağ oluşturma + +Çoğu bulut sağlayıcı IP adreslerini (özellikle genel olanları), VM'nizde doğrudan bir ağ arayüzü olarak açmaz (expose etmez); bunun yerine görünmez bir NAT proxy kurar. + + +Bu durumda düğümlerin birbirine bağlanmasını sağlamak için tüm arayüzlerde bağlanılacak `0.0.0.0` IP adresini dinlemeniz gerekir; ancak yine de diğer düğümlerin sizin düğümünüze bağlanmak için kullanabileceği IP adresini veya DNS adresini belirtmeniz gerekir. Bu, `--nat` veya `--dns` kullanılarak gerçekleştirilir ve burada sırasıyla harici IP veya DNS adresinizi belirtirsiniz. + +#### Örnek {#example} + +Dinleme yapmak istediğiniz ilişkili IP adresi `192.0.2.1`; fakat bu adres, ağ arayüzlerinizden hiçbirine doğrudan bağlı değil. + +Düğümlerin bağlanmasına izin vermek için aşağıdaki parametreleri göndermeniz gerekecektir: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +Veya bir DNS adresi `dns/example.io` belirtmek istiyorsanız, aşağıdaki parametreleri girebilirsiniz: + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +Bu, düğümünüzün tüm arayüzlerde dinleme yapmasını sağlayacaktır; aynı zamanda istemcilerin bu adrese belirtilen `--nat` veya `--dns` adresi üzerinden bağlandığını da düğümünüze bildirecektir. + +::: + +**Birinci** istemciyi çalıştırmak için: + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +**İkinci** istemciyi çalıştırmak için: + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +**Üçüncü** istemciyi çalıştırmak için: + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +**Dördüncü** istemciyi çalıştırmak için: + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Önceki komutları çalıştırdıktan sonra, blokları mühürleyebilen ve düğüm arızasından kurtulabilecek 4 düğümlü bir Polygon Edge +ağı kurmuş oldunuz. + +:::info Yapılandırma dosyasını kullanarak istemciyi başlatın + +Tüm yapılandırma parametrelerini CLI argümanları olarak belirtmek yerine, İstemci aşağıdaki komutu çalıştırarak bir yapılandırma dosyası kullanarak da başlatılabilir: + +````bash +polygon-edge server --config +```` +Örnek : + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Şu anda, yalnızca `json`tabanlı yapılandırma dosyasını destekliyoruz, örnek yapılandırma dosyası **[burada](/docs/edge/configuration/sample-config)** bulunabilir + +::: + +:::info Doğrulayıcı olmayan bir düğüm çalıştırma adımları + +Doğrulayıcı olmayan bir düğüm, her zaman, doğrulayıcı düğümden alınan en son blokları eşitleyecektir (senkronizasyon). Aşağıdaki komutu çalıştırarak doğrulayıcı olmayan bir düğümü başlatabilirsiniz. + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +Örneğin, aşağıdaki komutu çalıştırarak **beşinci** Doğrulayıcı Olmayan istemciyi ekleyebilirsiniz : + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info Fiyat limitini belirleyin + +Bir Polygon Edge düğümü, gelen işlemler için belirlenmiş bir **fiyat limiti** ile başlatılabilir. + +Fiyat limitinin birimi `wei`'dir. + +Bir fiyat limiti belirlemek, mevcut düğüm tarafından işlenen herhangi bir işlemin belirlenen fiyat limitinden **daha yüksek** bir gaz fiyatına +sahip olması gerektiği anlamına gelir; aksi takdirde işlem bir bloğa eklenmeyecektir. + +Düğümlerin çoğunluğunun belli bir fiyat limitine uyması, ağ üzerindeki işlemlerin +belli bir fiyat eşiğinin altında olmaması kuralını uygulamaya koyar. + +Fiyat limiti için varsayılan değer `0` olarak belirlenmiştir, yani varsayılan olarak limit uygulanmamaktadır. + +`--price-limit` bayrağının kullanım örneği: +````bash +polygon-edge server --price-limit 100000 ... +```` + +Fiyat limitlerinin **yalnızca yerel olmayan işlemlerde uygulandığına** dikkat etmek gerekir, yani +fiyat limiti düğümde yerel olarak eklenen işlemlere uygulanmaz. + +::: + +:::info WebSocket URL'si + +Polygon Edge çalıştırdığınızda, varsayılan olarak zincir konumuna göre bir WebSocket URL'si oluşturur. +HTTPS bağlantıları için `wss://` ve HTTP için `ws://` URL yöntemi kullanılır. + +Localhost WebSocket URL: +````bash +ws://localhost:10002/ws +```` +Port sayısının düğüm için seçilen JSON-RPC portuna bağlı olduğunu unutmayın. + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/tr-edge/get-started/terraform-aws-deployment.md b/archive/edge/tr-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..d35766aba9 --- /dev/null +++ b/archive/edge/tr-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,177 @@ +--- +id: terraform-aws-deployment +title: Terraform AWS ile Devreye Alma +description: "Terraform kullanarak AWS bulut sağlayıcı üzerinde Polygon Edge ağını devreye alın" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info Üretim devreye alma kılavuzu + +Bu kılavuz resmî, üretime hazır, tamamen otomatik, AWS devreye alma kılavuzudur. + +Test için ve/veya bulut sağlayıcınızın AWS olmaması hâlinde ***[Bulut](set-up-ibft-on-the-cloud)*** veya ***[Yerel](set-up-ibft-locally)*** +için manuel devreye alma tavsiye edilir. + +::: + +:::info + +Bu devreye alma işlemi yalnızca PoA içindir. +PoS mekanizmasına ihtiyaç duyuluyorsa, PoA'dan PoS'a geçiş yapmak için bu ***[kılavuzu](/docs/edge/consensus/migration-to-pos)*** takip etmeniz yeterlidir. + +::: + +Bu kılavuz, doğrulayıcı düğümler birden çok kullanılabilirlik bölgesine yayıldığından üretime hazır olan bir Polygon Edge blok zinciri ağını +AWS bulut sağlayıcısında devreye alma işlemini ayrıntılı olarak açıklayacaktır. + +## Ön Koşullar {#prerequisites} + +### Sistem araçları {#system-tools} +* [terraform](https://www.terraform.io/) +* [aws cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [aws erişim anahtarı kimliği ve gizli erişim anahtarı](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Terraform değişkenleri {#terraform-variables} +Dağıtımı çalıştırmadan önce sağlanması gereken iki değişken: + +* `alb_ssl_certificate`- https protokolü için ALB tarafından kullanılacak olan AWS Sertifika Yöneticisi'nin sertifikasının ARN'si. + Sertifika, devreye alma işlemine başlamadan önce oluşturulmalı ve **Çıkarıldı** durumuna sahip olmalıdır +* `premine` - önceden mine edilmiş yerel para birimini alacak hesap. +Değer, resmî [CLI](/docs/edge/get-started/cli-commands#genesis-flags) bayrağındaki teknik özelliklere uygun olmalıdır + +## Devreye alma bilgileri {#deployment-information} +### Devreye alınan kaynaklar {#deployed-resources} +Devreye alınacak kaynaklara ilişkin üst düzey genel bakış: + +* Adanmış VPC +* 4 doğrulayıcı düğüm (aynı zamanda önyükleme düğümleri) +* Düğümlerin giden internet trafiğine izin vermek için 4 NAT ağ geçidi +* İlk (genesis) bloku oluşturmak ve zinciri başlatmak için kullanılan Lambda işlevi +* Özel güvenlik grupları ve IAM rolleri +* genesis.json dosyasını saklamak için kullanılan S3 bucket +* JSON-RPC uç noktasını göstermek için kullanılan Uygulama Yük Dengeleyici + +### Hata toleransı {#fault-tolerance} + +Bu devreye alma işlemi için yalnızca 4 kullanılabilirlik bölgesine sahip bölgeler gereklidir. Her bir düğüm tek bir AZ'de devreye alınır. + +Her düğüm tek bir AZ'ye yerleştirildiğinde, tüm blok zinciri kümesi tek bir düğüm (AZ) hatasına karşı hataya dayanıklı hale gelir çünkü Polygon Edge, +4 doğrulayıcı düğümlü bir kümede tek bir düğümün başarısız olmasına izin veren IBFT konsensüsünü uygulamaktadır. + +### Komut satırı erişimi {#command-line-access} + +Doğrulayıcı düğümler hiçbir şekilde genel internete açık değildir (JSON-PRC'ye yalnızca ALB üzerinden erişilir) +ve onlara bağlı genel IP adresleri bile yoktur. +Düğüm komut satırı erişimi yalnızca [AWS Sistem Yöneticisi - Oturum Yöneticisi](https://aws.amazon.com/systems-manager/features/) üzerinden mümkündür. + +### Temel AMI yükseltme {#base-ami-upgrade} + +Bu devreye alma işlemi `ubuntu-focal-20.04-amd64-server` AWS AMI kullanır. AWS AMI güncellenirse EC2 *yeniden devreye alma işlemini* **tetiklemez**. + +Herhangi bir nedenle temel AMI'nin güncellenmesi gerekiyorsa, +Her bir örnek için `terraform apply`'den önce için `terraform taint` komutu çalıştırılarak gerçekleştirilebilir. +Örnekler, +`terraform taint module.instances[].aws_instance.polygon_edge_instance` komutu çalıştırılarak elde edilebilir. + +Örnek: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info + +Bir üretim ortamında, blok zinciri ağını işlevsel tutmak için `terraform taint` tek tek çalıştırılmalıdır. + +::: + +## Dağıtım prosedürü {#deployment-procedure} + +### Önceden devreye alma adımları {#pre-deployment-steps} +* [polygon-technology-edge](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) terraform kayıt defteri benioku (readme) dosyasını okuyun +* modüllerin benioku sayfasında yer alan *provizyon talimatlarını* kullanarak `polygon-technology-edge`modülünü `main.tf` dosyasına ekleyin +* gerekli tüm Terraform bağımlılıklarını kurmak için `terraform init` komutunu çalıştırın +* [AWS Sertifika Yöneticisi](https://aws.amazon.com/certificate-manager/)'nde yeni bir sertifika sağlayın +* sağlanan sertifikanın **Çıkarıldı** durumunda olduğundan emin olun ve sertifikanın **ARN**'sini not edin +* modüllerin çıktısını cli'de almak için çıktı ifadenizi ayarlayın + +#### `main.tf` örnek {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### `terraform.tfvars` örnek {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### Devreye alma adımları {#deployment-steps} +* `terraform.tfvars` dosyasını oluşturun +* (yukarda açıklandığı gibi) bu dosya içindeki gerekli terraform değişkenlerini ayarlayın. +:::info + +Bu dağıtımı tamamen özelleştirebilecek zorunlu olmayan başka değişkenler de vardır. +Kendi değerlerinizi `terraform.tfvars` dosyasına yazarak varsayılan değerleri geçersiz kılabilirsiniz. + + Mevcut tüm değişkenlerin teknik özellikleri, modüllerin Terraform ***[kayıt defterinde](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)***bulunabilir. + +::: +* `aws s3 ls` çalıştırarak bir aws cli kimlik doğrulamasını doğru bir şekilde kurduğunuzdan emin olun; hiçbir hata olmamalıdır +* `terraform apply` altyapısını devreye alın + +### Devreye alma sonrası adımlar {#post-deployment-steps} +* Devreye alma tamamlandıktan sonra, cli'de yazdırılan `json_rpc_dns_name` değişken değerini not edin +* Alan adınızı, sağlanan `json_rpc_dns_name` değerine yönlendiren genel bir dns cname kaydı oluşturun. Örneğin: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* cname kaydı yayıldıktan sonra, JSON-PRC uç noktanızı çağırarak zincirin düzgün çalışıp çalışmadığını denetleyin. + Yukarıdaki örnekte: + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## İmha prosedürü {#destroy-procedure} +:::warning + +Aşağıdaki prosedür, bu terraform komut dosyalarıyla devreye alınan tüm altyapınızı kalıcı olarak silecektir. +Doğru [blok zinciri veri yedeklemelerine](docs/edge/working-with-node/backup-restore) sahip olduğunuzdan ve/veya bir test ortamıyla çalıştığınızdan emin olun. + +::: + +Tüm altyapıyı kaldırmanız gerekiyorsa, aşağıdaki `terraform destroy` komutunu çalıştırın. +Ek olarak, devreye alma işleminin gerçekleştiği bölge için AWS [Parametre Store](https://aws.amazon.com/systems-manager/features/)'da saklanan + sırları manuel olarak kaldırmanız gerekir. diff --git a/archive/edge/tr-edge/overview.md b/archive/edge/tr-edge/overview.md new file mode 100644 index 0000000000..e8f7c1cbfc --- /dev/null +++ b/archive/edge/tr-edge/overview.md @@ -0,0 +1,36 @@ +--- +id: overview +title: Polygon Edge +sidebar_label: What is Edge +description: "Polygon Edge'e giriş." +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +Polygon Edge, Ethereum uyumlu blok zinciri ağları, yan zincirleri ve genel ölçekleme çözümleri oluşturmak için modüler ve genişletilebilir bir çerçevedir. + +Birincil kullanımı, Ethereum akıllı sözleşmeleri ve işlemleriyle tam uyumluluk sağlarken, yeni bir blok zinciri ağına ön yükleme yapmaktır. [PoA (yetki kanıtı)](/docs/edge/consensus/poa) ve [PoS (hisse kanıtı)](/docs/edge/consensus/pos-stake-unstake) olmak üzere iki şekilde desteklenen IBFT (İstanbul Bizans Hata Toleransı) konsensüs mekanizmasını kullanır. + +Polygon Edge aynı zamanda [merkezî köprü çözümünü](/docs/edge/additional-features/chainbridge/overview) kullanarak hem [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) hem de [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) token'larının aktarılmasını sağlayan çoklu blok zinciri ağı ile iletişimi de destekler. + +Endüstri standardı cüzdanlar, [JSON-RPC](/docs/edge/working-with-node/query-json-rpc) uç noktaları üzerinden Polygon Edge ile etkileşim kurmak için kullanılabilir ve düğüm operatörleri, [gRPC](/docs/edge/working-with-node/query-operator-info) protokolü üzerinden düğümler üzerinde çeşitli eylemler gerçekleştirebilir. + +Polygon hakkında daha fazla bilgi edinmek için [resmi web sitesini](https://polygon.technology) ziyaret edin. + +**[GitHub deposu](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +Bu devam eden bir çalışma olduğu için gelecekte mimari değişiklikler olabilir. Kod henüz denetlenmemiştir +bu nedenle üretimde kullanmak isterseniz lütfen Polygon ekibi ile iletişime geçin. + +::: + + + +Bir `polygon-edge` ağını yerel olarak çalıştırmaya başlamak için lütfen okuyun: [Kurulum](/docs/edge/get-started/installation) ve [Yerel Kurulum](/docs/edge/get-started/set-up-ibft-locally). diff --git a/archive/edge/tr-edge/performance-reports/overview.md b/archive/edge/tr-edge/performance-reports/overview.md new file mode 100644 index 0000000000..f1953847f0 --- /dev/null +++ b/archive/edge/tr-edge/performance-reports/overview.md @@ -0,0 +1,32 @@ +--- +id: overview +title: Genel Bakış +description: "Polygon Edge testine giriş." +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +Bu testleri gerçekleştirmek için kullanılan `loadbot`bizim için kullanılan bizim artık amortisman olduğunu unutmayın. +::: + +| Tip | Değer | Test etmek için bağlantı | +| ---- | ----- | ------------ | +| Düzenli Transferler | 1428 tps | [4 Temmuz 2022](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| ERC-20 Transferleri | 1111 tps | [4 Temmuz 2022](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| NFT Mint Etme | 714 tps | [4 Temmuz 2022](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +Amacımız, yüksek performanslı, özellik açısından zengin ve kurulumu ve bakımı kolay bir blok zinciri istemci yazılımı yapmaktır. +Tüm testler Polygon Edge Loadbot kullanılarak yapılmıştır. +Bu bölüm içinde bulacağınız her performans raporu doğru bir şekilde tarihlenmiştir, ortamı açıkça tanımlanmıştır ve test yöntemi açıkça belirtilmiştir. + +Bu performans testlerinin amacı, Polygon Edge blok zinciri ağının gerçek dünyadaki performansını göstermektir. +Loadbot'umuzu kullanan herkes, aynı ortamda, burada yayımlanan sonuçların aynısını elde edebilmelidir. + +Performans testlerinin tamamı, AWS platformunda EC2 bulut sunucusu düğümlerinden oluşan bir zincir üzerinde gerçekleştirilmiştir. \ No newline at end of file diff --git a/archive/edge/tr-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/tr-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..b61af66757 --- /dev/null +++ b/archive/edge/tr-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,132 @@ +--- +id: test-2022-01-21 +title: 21 Ocak 2022 +description: "21 Ocak tarihli performans testi." +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## 21 Ocak 2022 {#january-21st-2022} + +### Özet {#summary} + +:::caution +Bu testleri gerçekleştirmek için kullanılan `loadbot`bizim için kullanılan bizim artık amortisman olduğunu unutmayın. +::: + +Bu test, performansı önemli ölçüde artıran TxPool yeniden düzenlemesi sonrasında yapılmıştır ([v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0)'da çıkarılmıştır). + +Amaç, aktif katılan 30 doğrulayıcıdan oluşan geniş bir ağ kurmak ve böylece +tüm işlemler tek bir düğümün JSON-RPC'sine gönderildiğinde konsensüs ile TxPool işlemlerinin iletişimine doğru bir şekilde stres testi uygulamaktır. + +Amacımız, saniye başına mümkün olan en yüksek işlem sayısına ulaşmak değildir; çünkü ağ boyutu performansı olumsuz yönde etkilemektedir, +ayrıca blok gaz limiti ve blok süresi fazla sistem kaynağı tüketmeyen makul değerler olarak ayarlanmıştır ve bu da işlemin yaygın bulunan donanım üzerinde çalışmasına izin vermektedir. + +### Sonuçlar {#results} + +| Ölçüm | Değer | +| ------ | ----- | +| Saniye başına işlem | 344 | +| Başarısız olan işlemler | 0 | +| Başarılı olan işlemler | 10000 | +| Toplam çalışma süresi | 30s | + +### Ortam {#environment} + +
+ Ana Bilgisayar Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Bulut sağlayıcısıAWS
Oturum büyüklüğüt2.xlarge
Ağ oluşturmaözel alt ağ
İşletim sistemiLinux Ubuntu 20.04 LTS - Focal Fossa
Dosya tanımlayıcı limiti65535
Maks kullanıcı işlemi sayısı65535
+
+
+
+
+ +
+ Blok Zinciri Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge sürümüGeliştirme dalında 8377162281d1a2e4342ae27cd4e5367c4364aee2 taahhüdü
Doğrulayıcı düğümler30
Doğrulayıcı olmayan düğümler0
KonsensüsIBFT PoA
Blok süresi2000ms
Blok gaz limiti5242880
+
+
+
+
+ +
+ Loadbot Yapılandırması +
+
+ + + + + + + + + + + + + +
Toplam İşlem10000
Saniye başına gönderilen işlem400
İşlem türüEOA'dan EOA'ya aktarımlar
+
+
+
+
diff --git a/archive/edge/tr-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/tr-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..afaab6e225 --- /dev/null +++ b/archive/edge/tr-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,390 @@ +--- +id: test-2022-03-02 +title: 2 Mart 2022 +description: "2 Mart tarihli performans testi." +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### Özet {#summary} + +:::caution +Bu testleri gerçekleştirmek için kullanılan `loadbot`bizim için kullanılan bizim artık amortisman olduğunu unutmayın. +::: + +Bu test, ağır yük altında SC ERC20 token aktarımlarını ve SC ERC721 token mint etme işlevselliği ile işlemlerin hızını ölçmek için yapıldı. + +Amaç, ağır yükler altındayken her şeyin beklendiği gibi çalışıp çalışmadığını kontrol etmekti. Bu aynı zamanda loadbot çıktısında gaz ölçümleri yapmamızın da nedeniydi. Bu ölçümler blokların işlemlerle düzgün olarak doldurulup doldurulmadığını bize gösteriyor. + +Tüm işlemler GRPC API üzerinden tek düğüme gönderildi ve alındıları JSON-RPC API üzerinden alındı. Tüm işlemler tamamlandıktan sonra, gaz bilgisi her blok üzerinden eth_getBlockByNumber JSON-RPC yöntemi kullanılarak okundu. + +Amacımız mümkün olan en yüksek saniye başına işleme ulaşmak değildi +çünkü blok gaz limiti ve blok süresi fazla sistem kaynağı tüketmeyen makul değerler olarak ayarlanmıştı ve bu işlemin yaygın bulunan donanım üzerinde çalışmasına izin veriyordu. + +### Sonuçlar ERC20 {#results-erc20} + +| Ölçüm | Değer | +| ------ | ----- | +| İşlem türü | ERC20 | +| Saniye başına işlem | 65 | +| Başarısız olan işlemler | 0 | +| Başarılı olan işlemler | 5000 | +| ERC20 işlemi yürütme süresi | 76,681690s | +| SC Devreye alma süresi | 4,048250s | + +### Sonuçlar ERC721 {#results-erc721} + +| Ölçüm | Değer | +| ------ | ----- | +| İşlem türü | ERC721 | +| Saniye başına işlem | 20 | +| Başarısız olan işlemler | 0 | +| Başarılı olan işlemler | 2000 | +| ERC721 işlemi yürütme süresi | 97,239920s | +| SC Devreye alma süresi | 3,048970s | + +### Ortam ERC20 {#environment-erc20} + +
+ Ana Bilgisayar Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Bulut sağlayıcısıAWS
Oturum büyüklüğüt2.micro
Ağ oluşturmaözel alt ağ
İşletim sistemiLinux Ubuntu 20.04 LTS - Focal Fossa
Dosya tanımlayıcı limiti65535
Maks kullanıcı işlemi sayısı65535
+
+
+
+
+ +
+ Blok Zinciri Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge sürümüGeliştirme dalında 8a033aa1afb191abdac04636d318f83f32511f3c taahhüdü
Doğrulayıcı düğümler6
Doğrulayıcı olmayan düğümler0
KonsensüsIBFT PoA
Blok süresi2s
Blok gaz limiti5242880
Ortalama blok kullanımı%95
+
+
+
+
+ +
+ Loadbot Yapılandırması +
+
+ + + + + + + + + + + + + +
Toplam İşlem5000
Saniye başına gönderilen işlem200
İşlem türüERC20'den ERC20'ye aktarımlar
+
+
+
+
+ +
+ Loadbot günlüğü + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### Ortam ERC721 {#environment-erc721} + +
+ Ana Bilgisayar Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Bulut sağlayıcısıAWS
Oturum büyüklüğüt2.micro
Ağ oluşturmaözel alt ağ
İşletim sistemiLinux Ubuntu 20.04 LTS - Focal Fossa
Dosya tanımlayıcı limiti65535
Maks kullanıcı işlemi sayısı65535
+
+
+
+
+ +
+ Blok Zinciri Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge sürümüGeliştirme dalında 8a033aa1afb191abdac04636d318f83f32511f3c taahhüdü
Doğrulayıcı düğümler6
Doğrulayıcı olmayan düğümler0
KonsensüsIBFT PoA
Blok süresi2s
Blok gaz limiti5242880
Ortalama blok kullanımı%94
+
+
+
+
+ +
+ Loadbot Yapılandırması +
+
+ + + + + + + + + + + + + +
Toplam İşlem2000
Saniye başına gönderilen işlem200
İşlem türüERC721 token mint
+
+
+
+
+ +
+ Loadbot günlüğü + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/tr-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/tr-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..dddf43ef4e --- /dev/null +++ b/archive/edge/tr-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,960 @@ +--- +id: test-2022-03-23 +title: 23 Mart 2022 +description: "23 Mart tarihli performans testi." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### Özet {#summary} + +:::caution +Bu testleri gerçekleştirmek için kullanılan `loadbot`bizim için kullanılan bizim artık amortisman olduğunu unutmayın. +::: + +Bu test, daha yüksek donanım kaynaklarına sahip düğümlerdeki SC ERC20 token aktarımlarını, SC ERC721 token mint'lemeyi ve EOA'dan EOA'ya ağır yükle aktarım işlevlerini ve işlemlerin hızını ölçmek için yapıldı. + +Amaç, ağır yükler altındayken her şeyin beklendiği gibi çalışıp çalışmadığını kontrol etmekti. Bu aynı zamanda loadbot çıktısında gaz ölçümleri yapmamızın da nedeniydi. Bu ölçümler blokların işlemlerle düzgün olarak doldurulup doldurulmadığını bize gösteriyor. + +Tüm işlemler GRPC API üzerinden tek düğüme gönderildi ve alındı bilgileri JSON-RPC API üzerinden alındı. Tüm işlemler tamamlandıktan sonra, gaz bilgisi her blok üzerinden eth_getBlockByNumber JSON-RPC yöntemi kullanılarak okundu. + +Amacımız, mevcut donanım kaynakları üzerinde mümkün olan en yüksek saniye başına işleme erişmeye çalışmaktı. +Bunu başarmak için, blok gaz limiti ve blok süresi parametrelerini en iyi saniye başına işlem sonuçlarını verecek ve sistem bütünlüğü ile kararlılığını koruyacak şekilde değiştirdik. + +:::info Blok Gaz Limiti + +İşlemlerin yürütülmesi için çok fazla gaz kullanılıyorsa, blok gaz limiti nispeten yüksek bir sayıya çıkarılabilir. +Aşağıda belirtilen örnekte ERC721 token mint'leme işlemleri, blok gaz limiti 80.000.000 olarak belirlendiğinde (20 Mil. yerine) daha hızlı çalışmıştır ancak 80 Mil. blok gaz limitli ERC20 token aktarımlarında sunucu çökmüştür. + +::: + +:::info Üretim Ortamları + +Bir üretim ortamını yapılandırırken, zincirin yüksek performans göstermesini sağlamaya çalışıyorsanız dikkatli olmanız gerekir. +Blok gaz limiti parametresi yüksek bir değer olarak ayarlanmışsa, blok süresi 1s ise ve tek bir düğümde yüksek bir işlem yükü varsa, o düğüm çok fazla (hatta belki tüm) RAM kaynağını tüketecektir ve sunucu çökmesine neden olabilecektir. +Her şeyi kapsamlı bir şekilde test etmek için loadbot kullanın, sistem kaynak kullanımını izleyin ve yapılandırma parametrelerinizi buna göre ayarlayın. + +::: + +:::info Yetersiz Bellek Hataları + +Bazı linux dağıtımları sistem kararlılığını korumak için çok yüksek RAM kullanımına sahip işlemi otomatik olarak sonlandıracaktır (OOM hatası). +Bu OOM hatasının günlük çıktısı aşağıdaki gibidir. +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### EOA'dan EOA'ya aktarım sonuçları {#results-of-eoa-to-eoa-transfers} +| Ölçüm | Değer | +| ------ | ----- | +| İşlem türü | EOA'dan EOA'ya | +| Saniye başına işlem | 689 | +| Başarısız olan işlemler | 0 | +| Başarılı olan işlemler | 20000 | +| Kullanılan blok toplamı | 25 | +| Toplam çalışma süresi | 29,921110s | + +### ERC20 token aktarımın sonuçları {#results-of-erc20-token-transfers} + +| Ölçüm | Değer | +| ------ | ----- | +| İşlem türü | ERC20 | +| Saniye başına işlem | 500 | +| Başarısız olan işlemler | 0 | +| Başarılı olan işlemler | 20000 | +| Kullanılan blok toplamı | 33 | +| ERC20 işlem çalışma süresi | 40,402900s | +| SC Devreye alma süresi | 2,004140s | + +### ERC721 token mint sonuçları {#results-of-erc721-token-minting} + +| Ölçüm | Değer | +| ------ | ----- | +| İşlem türü | ERC721 | +| Saniye başına işlem | 157 | +| Başarısız olan işlemler | 0 | +| Başarılı olan işlemler | 20000 | +| Kullanılan blok toplamı | 124 | +| ERC721 işlem çalışma süresi | 127,537340s | +| SC Devreye alma süresi | 2,004420s | + + +### Çok yüksek blok gaz limiti (80 Mil.) ile ERC721 token mint sonuçları {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| Ölçüm | Değer | +| ------ | ----- | +| İşlem türü | ERC721 | +| Saniye başına işlem | 487 | +| Başarısız olan işlemler | 0 | +| Başarılı olan işlemler | 20000 | +| Kullanılan blok toplamı | 34 | +| ERC721 işlem çalışma süresi | 41,098410s | +| SC Devreye alma süresi | 2,004300s | + + +### Ortam EOA'dan EOA'ya {#environment-eoa-to-eoa} +
+ Ana Bilgisayar Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Bulut sağlayıcısıAWS
Oturum büyüklüğüc5.2xlarge
Ağ oluşturmaözel alt ağ
İşletim sistemiAmazon Linux 2 AMI (HVM) - Kernel 5.10
Dosya tanımlayıcı limiti65535
Maks kullanıcı işlemi sayısı65535
+
+
+
+
+ +
+ Blok Zinciri Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge sürümüGeliştirme dalı üzerinde 06e11eac8da98c79c938fc53dda2da3318cfbe04 taahhüdü
Doğrulayıcı düğümler4
Doğrulayıcı olmayan düğümler0
KonsensüsIBFT PoA
Blok süresi1s
Blok gaz limiti20000000
Maks slot sayısı1000000
Ortalama blok kullanımı%84,00
+
+
+
+
+ +
+ Loadbot Yapılandırması +
+
+ + + + + + + + + + + + + +
Toplam İşlem20000
Saniye başına gönderilen işlem689
İşlem türüEOA'dan EOA'ya aktarımlar
+
+
+
+
+ +
+ Loadbot günlüğü + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### Ortam ERC20 {#environment-erc20} +
+ Ana Bilgisayar Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Bulut sağlayıcısıAWS
Oturum büyüklüğüc5.2xlarge
Ağ oluşturmaözel alt ağ
İşletim sistemiAmazon Linux 2 AMI (HVM) - Kernel 5.10
Dosya tanımlayıcı limiti65535
Maks kullanıcı işlemi sayısı65535
+
+
+
+
+ +
+ Blok Zinciri Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge sürümüGeliştirme dalı üzerinde 06e11eac8da98c79c938fc53dda2da3318cfbe04 taahhüdü
Doğrulayıcı düğümler4
Doğrulayıcı olmayan düğümler0
KonsensüsIBFT PoA
Blok süresi1s
Blok gaz limiti20000000
Maks slot sayısı1000000
Ortalama blok kullanımı%88,38
+
+
+
+
+ +
+ Loadbot Yapılandırması +
+
+ + + + + + + + + + + + + +
Toplam İşlem20000
Saniye başına gönderilen işlem500
İşlem türüERC20'den ERC20'ye aktarımlar
+
+
+
+
+ +
+ Loadbot günlüğü + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### Ortam ERC721 {#environment-erc721} +
+ Ana Bilgisayar Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Bulut sağlayıcısıAWS
Oturum büyüklüğüc5.2xlarge
Ağ oluşturmaözel alt ağ
İşletim sistemiAmazon Linux 2 AMI (HVM) - Kernel 5.10
Dosya tanımlayıcı limiti65535
Maks kullanıcı işlemi sayısı65535
+
+
+
+
+ +
+ Blok Zinciri Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge sürümüGeliştirme dalı üzerinde 06e11eac8da98c79c938fc53dda2da3318cfbe04 taahhüdü
Doğrulayıcı düğümler4
Doğrulayıcı olmayan düğümler0
KonsensüsIBFT PoA
Blok süresi1s
Blok gaz limiti20000000
Maks slot sayısı1000000
Ortalama blok kullanımı%92,90
+
+
+
+
+ +
+ Loadbot Yapılandırması +
+
+ + + + + + + + + + + + + +
Toplam İşlem20000
Saniye başına gönderilen işlem157
İşlem türüERC721 token mint
+
+
+
+
+ +
+ Loadbot günlüğü + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### Ortam ERC20 - çok yüksek blok gaz limiti {#environment-erc20-very-high-block-gas-limit} +
+ Ana Bilgisayar Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Bulut sağlayıcısıAWS
Oturum büyüklüğüc5.2xlarge
Ağ oluşturmaözel alt ağ
İşletim sistemiAmazon Linux 2 AMI (HVM) - Kernel 5.10
Dosya tanımlayıcı limiti65535
Maks kullanıcı işlemi sayısı65535
+
+
+
+
+ +
+ Blok Zinciri Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge sürümüGeliştirme dalı üzerinde 06e11eac8da98c79c938fc53dda2da3318cfbe04 taahhüdü
Doğrulayıcı düğümler4
Doğrulayıcı olmayan düğümler0
KonsensüsIBFT PoA
Blok süresi1s
Blok gaz limiti80000000
Maks slot sayısı1000000
Ortalama blok kullanımı---
+
+
+
+
+ +
+ Loadbot Yapılandırması +
+
+ + + + + + + + + + + + + +
Toplam İşlem20000
Saniye başına gönderilen işlem---
İşlem türüERC20'den ERC20'ye aktarımlar
+
+
+
+
+ +
+ OOM Hata günlüğü + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### Ortam ERC721 - çok yüksek blok gaz limiti {#environment-erc721-very-high-block-gas-limit} +
+ Ana Bilgisayar Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Bulut sağlayıcısıAWS
Oturum büyüklüğüc5.2xlarge
Ağ oluşturmaözel alt ağ
İşletim sistemiAmazon Linux 2 AMI (HVM) - Kernel 5.10
Dosya tanımlayıcı limiti65535
Maks kullanıcı işlemi sayısı65535
+
+
+
+
+ +
+ Blok Zinciri Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge sürümüGeliştirme dalı üzerinde 06e11eac8da98c79c938fc53dda2da3318cfbe04 taahhüdü
Doğrulayıcı düğümler4
Doğrulayıcı olmayan düğümler0
KonsensüsIBFT PoA
Blok süresi1s
Blok gaz limiti80000000
Maks slot sayısı1000000
Ortalama blok kullanımı%84,68
+
+
+
+
+ +
+ Loadbot Yapılandırması +
+
+ + + + + + + + + + + + + +
Toplam İşlem20000
Saniye başına gönderilen işlem487
İşlem türüERC721 token mint
+
+
+
+
+ +
+ Loadbot günlüğü + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/tr-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/tr-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..bda46c2b63 --- /dev/null +++ b/archive/edge/tr-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,568 @@ +--- +id: test-2022-07-04 +title: 4 Temmuz 2022 +description: "4 Temmuz tarihinden performans testi." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### Özet {#summary} + +:::caution +Bu testleri gerçekleştirmek için kullanılan `loadbot`bizim için kullanılan bizim artık amortisman olduğunu unutmayın. +::: + +Bu test, daha yüksek donanım kaynaklarına sahip düğümlerdeki SC ERC20 token aktarımlarını, SC ERC721 token mint'lemeyi ve EOA'dan EOA'ya ağır yükle aktarım işlevlerini ve işlemlerin hızını ölçmek için yapıldı. + +Amaç, ağır yükler altındayken her şeyin beklendiği gibi çalışıp çalışmadığını kontrol etmekti. Bu aynı zamanda loadbot çıktısında gaz ölçümleri yapmamızın da nedeniydi. Bu ölçümler blokların işlemlerle düzgün olarak doldurulup doldurulmadığını bize gösteriyor. + +Tüm işlemler GRPC API üzerinden tek düğüme gönderildi ve alındı bilgileri JSON-RPC API üzerinden alındı. Tüm işlemler tamamlandıktan sonra, gaz bilgisi her blok üzerinden eth_getBlockByNumber JSON-RPC yöntemi kullanılarak okundu. + +Amacımız, mevcut donanım kaynakları üzerinde mümkün olan en yüksek saniye başına işleme erişmeye çalışmaktı. +Bunu başarmak için, blok gaz limiti ve blok süresi parametrelerini en iyi saniye başına işlem sonuçlarını verecek ve sistem bütünlüğü ile kararlılığını koruyacak şekilde değiştirdik. + + +:::info Üretim Ortamları + +Bir üretim ortamını yapılandırırken, zincirin yüksek performans göstermesini sağlamaya çalışıyorsanız dikkatli olmanız gerekir. +Blok gaz limiti parametresi yüksek bir değer olarak ayarlanmışsa, blok süresi 1s ise ve tek bir düğümde yüksek bir işlem yükü varsa, o düğüm çok fazla (hatta belki tüm) RAM kaynağını tüketecektir ve sunucu çökmesine neden olabilecektir. +Her şeyi kapsamlı bir şekilde test etmek için loadbot kullanın, sistem kaynak kullanımını izleyin ve yapılandırma parametrelerinizi buna göre ayarlayın. + +::: + + + +### EOA'dan EOA'ya aktarım sonuçları {#results-of-eoa-to-eoa-transfers} +| Ölçüm | Değer | +| ------ | ----- | +| İşlem türü | EOA'dan EOA'ya | +| Saniye başına işlem | 1428 | +| Başarısız olan işlemler | 0 | +| Başarılı olan işlemler | 30000 | +| Kullanılan blok toplamı | 15 | +| Toplam çalışma süresi | 21,374620s | + +### ERC20 token aktarımın sonuçları {#results-of-erc20-token-transfers} + +| Ölçüm | Değer | +| ------ | ----- | +| İşlem türü | ERC20 | +| Saniye başına işlem | 1111 | +| Başarısız olan işlemler | 0 | +| Başarılı olan işlemler | 50000 | +| Kullanılan blok toplamı | 38 | +| ERC20 işlem çalışma süresi | 45,906450s | +| SC Devreye alma süresi | 2,006580s | + +### ERC721 token mint sonuçları {#results-of-erc721-token-minting} + +| Ölçüm | Değer | +| ------ | ----- | +| İşlem türü | ERC721 | +| Saniye başına işlem | 714 | +| Başarısız olan işlemler | 0 | +| Başarılı olan işlemler | 30000 | +| Kullanılan blok toplamı | 39 | +| ERC721 işlem çalışma süresi | 42,864140s | +| SC Devreye alma süresi | 2,005500s | + + + + +### Ortam EOA'dan EOA'ya {#environment-eoa-to-eoa} +
+ Ana Bilgisayar Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Bulut sağlayıcısıAWS EC2
Oturum büyüklüğüc6a.48xlarge
Ağ oluşturmaözel alt ağ
İşletim sistemiLinux Ubuntu 20.04 LTS - Focal Fossa
Dosya tanımlayıcı limiti65535
Maks kullanıcı işlemi sayısı65535
+
+
+
+
+ +
+ Blok Zinciri Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge versiyonuSürüm v0.4.1
Doğrulayıcı düğümler4
Doğrulayıcı olmayan düğümler0
KonsensüsIBFT PoA
Blok süresi1s
Blok gaz limiti70778880
Maks slot sayısı276480
Ortalama blok kullanımı%59,34
+
+
+
+
+ +
+ Loadbot Yapılandırması +
+
+ + + + + + + + + + + + + +
Toplam İşlem30000
Saniye başına gönderilen işlem1428
İşlem türüEOA'dan EOA'ya aktarımlar
+
+
+
+
+ +
+ Loadbot günlüğü + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### Ortam ERC20 {#environment-erc20} +
+ Ana Bilgisayar Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Bulut sağlayıcısıAWS EC2
Oturum büyüklüğüc6a.48xlarge
Ağ oluşturmaözel alt ağ
İşletim sistemiLinux Ubuntu 20.04 LTS - Focal Fossa
Dosya tanımlayıcı limiti65535
Maks kullanıcı işlemi sayısı65535
+
+
+
+
+ +
+ Blok Zinciri Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge versiyonuSürüm v0.4.1
Doğrulayıcı düğümler4
Doğrulayıcı olmayan düğümler0
KonsensüsIBFT PoA
Blok süresi1s
Blok gaz limiti47185920
Maks slot sayısı184320
Ortalama blok kullanımı%81,29
+
+
+
+
+ +
+ Loadbot Yapılandırması +
+
+ + + + + + + + + + + + + +
Toplam İşlem50000
Saniye başına gönderilen işlem1111
İşlem türüERC20'den ERC20'ye aktarımlar
+
+
+
+
+ +
+ Loadbot günlüğü + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### Ortam ERC721 {#environment-erc721} +
+ Ana Bilgisayar Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Bulut sağlayıcısıAWS EC2
Oturum büyüklüğüc6a.48xlarge
Ağ oluşturmaözel alt ağ
İşletim sistemiLinux Ubuntu 20.04 LTS - Focal Fossa
Dosya tanımlayıcı limiti65535
Maks kullanıcı işlemi sayısı65535
+
+
+
+
+ +
+ Blok Zinciri Yapılandırması +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Polygon Edge versiyonuSürüm v0.4.1
Doğrulayıcı düğümler4
Doğrulayıcı olmayan düğümler0
KonsensüsIBFT PoA
Blok süresi1s
Blok gaz limiti94371840
Maks slot sayısı1000000
Ortalama blok kullanımı%93,88
+
+
+
+
+ +
+ Loadbot Yapılandırması +
+
+ + + + + + + + + + + + + +
Toplam İşlem30000
Saniye başına gönderilen işlem714
İşlem türüERC721 token mint
+
+
+
+
+ +
+ Loadbot günlüğü + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/tr-edge/troubleshooting.md b/archive/edge/tr-edge/troubleshooting.md new file mode 100644 index 0000000000..21e28f497e --- /dev/null +++ b/archive/edge/tr-edge/troubleshooting.md @@ -0,0 +1,71 @@ +--- +id: troubleshooting +title: Sorun Giderme +description: "Polygon Edge için Sorun Giderme bölümü" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# Sorun Giderme {#troubleshooting} + +## `method=eth_call err="invalid signature"` hatası {#error} + +Polygon Edge ile işlem yapmak için bir cüzdan kullanıyorsanız, cüzdanınızın yerel ağ kurulumunda şunlara dikkat edin: + +1. `chainID` doğru olmalıdır. Edge için varsayılan `chainID`, `100` şeklindedir; fakat `--chain-id` genesis bayrağı kullanılarak özelleştirilebilir. + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. “RPC URL” alanında, bağlandığınız düğümün JSON RPC portunu kullandığınızdan emin olun. + + +## WebSocket URL'si nasıl alınır? {#how-to-get-a-websocket-url} + +Polygon Edge çalıştırdığınızda, varsayılan olarak zincir konumuna göre bir WebSocket uç noktasını açığa çıkarır. +HTTPS bağlantıları için `wss://`, HTTP için `ws://` URL şeması kullanılır. + +Localhost WebSocket URL: +````bash +ws://:/ws +```` +Port sayısının düğüm için seçilen JSON-RPC portuna bağlı olduğunu unutmayın. + +Edgenet WebSocket URL: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## Bir sözleşmeyi devreye almaya çalışırken alınan `insufficient funds` hatası {#error-when-trying-to-deploy-a-contract} + +Bu hatayı alıyorsanız, istenen adres üzerinde yeterince fon bulundurduğunuzdan ve kullanılan adresin doğru olduğundan emin olun.
+Önceden mine edilen bakiyeyi ayarlamak için, genesis dosyasını oluştururken `genesis [--premine ADDRESS:VALUE]` genesis bayrağını kullanabilirsiniz. +Bu bayrağı kullanma örneği: +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +Bunu yapmak 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862 üzerinde 1000000000000000000000 WEI'yi önceden mine eder. + + +## Chainbridge kullanılırken serbest bırakılmayan ERC20 token'ları {#erc20-tokens-not-released-while-using-chainbridge} + +Polygon POS ve yerel bir Edge ağı arasında ERC20 token'larını aktarmaya çalışıyorsanız ve ERC20 token'larınız yatırıldıysa, teklif de yönlendiricide yürütüldüyse ancak token'larınız Edge ağınızda serbest bırakılmıyorsa, Polygon Edge zincirindeki ERC20 İşleyicisinin serbest bırakacak yeterince token'ı olduğundan emin olun.
+Hedef zincir içindeki İşleyici sözleşmesi, kilit kaldırma modu için serbest bırakacak yeterince token'a sahip olmalıdır. Yerel Edge ağınızın ERC20 İşleyicisinde ERC20 token'ınız yoksa, yeni token mint edin ve ERC20 İşleyici'ye aktarın. + +## Chainbridge kullanılırken alınan `Incorrect fee supplied` hatası {#error-when-using-chainbridge} + +Bu hatayı Mumbai Polygon POS zinciri ve yerel bir Polygon Edge kurulumu arasında ERC20 token'larını aktarmaya çalışırken alabilirsiniz. Bu hata, `--fee` bayrağını kullanarak dağıtım ücretini ayarladığınız ancak fon yatırma işleminde aynı değeri ayarlamadığınız zaman ortaya çıkar. +Ücreti değiştirmek için aşağıdaki komutu kullanabilirsiniz: +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +Bu bayrak hakkında daha fazla bilgiyi [buradan](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md) bulabilirsiniz. + + + + + diff --git a/archive/edge/tr-edge/validator-hosting.md b/archive/edge/tr-edge/validator-hosting.md new file mode 100644 index 0000000000..9798305775 --- /dev/null +++ b/archive/edge/tr-edge/validator-hosting.md @@ -0,0 +1,265 @@ +--- +id: validator-hosting +title: Doğrulayıcı Barındırma +description: "Polygon Edge için barındırma gereksinimleri" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +Aşağıda bir Polygon Edge ağında bir doğrulayıcı düğümünü doğru şekilde barındırmak için öneriler verilmiştir. Lütfen aşağıda listelenen tüm maddelere dikkat ederek +doğrulayıcı kurulumunuzun güvenli, kararlı ve yüksek performanslı olacak şekilde doğru yapılandırıldığından emin olun. + +## Bilgi tabanı {#knowledge-base} + +Doğrulayıcı düğümü çalıştırmaya başlamadan önce, lütfen bu dokümanı dikkatle okuyun. +Yardımcı olabilecek ilave dokümanlar şunlardır: + +- [Kurulum](get-started/installation) +- [Bulut kurulumu](get-started/set-up-ibft-on-the-cloud) +- [CLI komutları](get-started/cli-commands) +- [Sunucu yapılandırma (config) dosyası](configuration/sample-config) +- [Özel anahtarlar](configuration/manage-private-keys) +- [Prometheus ölçümleri](configuration/prometheus-metrics) +- [Gizli bilgi yöneticileri](/docs/category/secret-managers) +- [Yedekleme/Geri Yükleme](working-with-node/backup-restore) + +## Asgari sistem gereksinimleri {#minimum-system-requirements} + +| Tür | Değer | Etkileyenler | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 2 çekirdek |
  • JSON-RPC sorgularının sayısı
  • Blok zinciri durum boyutu
  • Blok gaz limiti
  • Blok süresi
| +| RAM | 2 GB |
  • JSON-RPC sorgularının sayısı
  • Blok zinciri durum boyutu
  • Blok gaz limiti
| +| Disk |
  • 10 GB kök bölümü
  • Disk genişletme için LVM ile 30 GB kök bölümü
|
  • Blok zinciri durum boyutu
| + + +## Hizmet yapılandırması {#service-configuration} + +`polygon-edge` binary dosyası, ağ bağlantısı kurulduğunda otomatik olarak bir sistem hizmeti olarak çalışmalıdır ve başlatma / durdurma / yeniden başlatma işlevlerine +sahip olmalıdır `systemd.` gibi bir hizmet yöneticisi kullanmanızı öneririz + +Örnek `systemd` sistem yapılandırma dosyası: +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### Binary dosya {#binary} + +Production iş yüklerinde `polygon-edge` binary dosyası, yalnızca önceden oluşturulmuş (pre-built) GitHub sürümü binary dosyalarından devreye alınmalıdır; manuel derleme kullanılmamalıdır. +:::info + +`develop` GitHub dallanmasını manuel olarak derlediğinizde, ortamınıza breaking (çalışmanın kesilmesine neden olabilecek) değişiklikler ekleyebilirsiniz. +Bu nedenle, Polygon Edge binary dosyasını yalnızca sürümlerden devreye almanız önerilir; çünkü +sürümlerde, breaking (çalışmanın kesilmesine neden olabilecek) değişiklikler ve bunların nasıl çözüleceği bilgileri yer alır. + +::: + +Kurulum yönteminin tam bir genel özeti için lütfen [Kurulum](/docs/edge/get-started/installation) bölümüne bakın. + +### Veri depolama {#data-storage} + +Blok zinciri durumunun tamamını içeren `data/` klasörü, buna ayrılmış bir diske / disk bölümüne mount edilerek +otomatik disk yedeklemelerine, disk bölümü genişletmeye ve isteğe bağlı olarak arıza durumunda diskin/disk bölümünün başka bir kuruluma (instance) mount edilmesine olanak sağlanmalıdır. + + +### Günlük dosyaları {#log-files} + +Günlük dosyalarının (`logrotate` gibi bir araç kullanılarak) her gün yenilenmesi (rotation) gerekir. +:::warning + +Günlük yenilemesi (rotation) olmadan yapılandırma yapılırsa, günlük dosyaları kullanılabilir disk alanının tamamını doldurarak doğrulayıcının çalışır kalma süresini (uptime) düşürebilir. + +::: + +Örnek `logrotate` yapılandırması: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +Günlüklerin saklanması hakkındaki öneriler için aşağıdaki [Günlükleme](#logging) bölümüne bakın. + +### Ek bağımlılıklar {#additional-dependencies} + +`polygon-edge` statik olarak derlenir ve ek ana makine (host) OS bağımlılığı gerekmez. + +## Bakım {#maintenance} + +Polygon Edge ağının bir doğrulayıcı düğümünün çalışmasını sürdürmek için en iyi uygulamalar aşağıda verilmiştir. + +### Yedekleme {#backup} + +Polygon Edge düğümleri için önerilen iki tür yedekleme prosedürü vardır. + +Önerimiz, mümkün olduğunda her ikisini de kullanarak Polygon Edge yedeklemesini her zaman ulaşılabilir bir seçenek olarak tutmaktır. + +* ***Disk bölümü yedekleme*** + Polygon Edge düğümünün bulunduğu `data/` disk bölümünün veya mümkünse tüm VM'nin günlük bazda artımlı olarak yedeklemesi. + + +* ***Polygon Edge yedeklemesi***: + Polygon Edge düzenli yedeklemeleri yapan ve `.dat` dosyalarını uzaktaki bir konuma veya güvenli bir bulut nesne depolamasına taşıyan, günlük çalıştırılan CRON görevi (CRON job) önerilir. + +Polygon Edge yedeklemesi ve yukarıda açıklanan Disk Bölümü yedeklemesi tercihen birbiriyle çakışmamalıdır. + +Polygon Edge yedeklemelerinin nasıl yapılacağına dair talimatlar için [Düğüm kurulumunun yedeklenmesi/geri yüklenmesi](working-with-node/backup-restore) bölümüne bakın. + +### Günlükleme {#logging} + +Polygon Edge düğümleri tarafından oluşturulan günlükler: +- dizinleme ve arama imkanları olan harici bir veri deposuna gönderilmelidir; +- 30 günlük bir günlük saklama süresine sahip olmalıdır. + +Polygon Edge doğrulayıcı kurulumunu ilk kez yapıyorsanız, düğümü başlatırken +`--log-level=DEBUG` seçeneğini kullanmanızı öneririz; bu sayede, karşılaşabileceğiniz sorunları hızlı bir şekilde giderebilirsiniz (debug). + +:::info + +`--log-level=DEBUG`, düğümün günlük çıktısını olabildiğince ayrıntılı yapar. +Hata giderme günlükleri, günlük dosya boyutlarını büyük ölçüde artıracaktır; bu durum günlük yenileme çözümü kurulurken +dikkate alınmalıdır. + +::: +### OS güvenlik yamaları {#os-security-patches} + +Yöneticiler, her ay en az bir kez güncelleme yaparak, doğrulayıcı OS'nin her zaman en son yamalarla güncel kalmasını sağlamalıdır. + +## Ölçümler {#metrics} + +### Sistem ölçümleri {#system-metrics} + +Yöneticiler bir çeşit sistem ölçümleri izleyicisi kurmalıdır, (ör. Telegraf + InfluxDB + Grafana veya bir üçüncü taraf SaaS). + +İzlenmesi ve hakkında alarm bildirimleri kurulması gereken ölçümler şunlardır: + +| Ölçüm adı | Alarm eşiği | +|-----------------------|-------------------------------| +| CPU kullanımı (%) | 5 dakikadan fazla %90 üzerinde kalması | +| RAM kullanımı (%) | 5 dakikadan fazla %90 üzerinde kalması | +| Kök disk kullanımı | > %90 | +| Veri diski kullanımı | > %90 | + +### Doğrulayıcı ölçümleri {#validator-metrics} + +Blok zinciri performansını izleyebilmek için, yöneticiler tarafından, Polygon Edge'in Prometheus API ölçümlerinin +toplanmasının ayarlanması gerekir. + +Hangi ölçümlerin okunmaya açık olduğunu ve Prometheus ölçümlerin toplanmasının nasıl ayarlanacağını öğrenmek için [Prometheus ölçümlerine](configuration/prometheus-metrics) bakın. + + +Aşağıdaki ölçümlere özellikle dikkat edilmesi gerekir: +- ***Blok üretim süresi*** - Blok üretim süresi normalden daha yüksekse, ağda bir sorun olması muhtemeldir +- ***Konsensüs roundlarının sayısı*** - Round sayısı birden fazlaysa, ağdaki doğrulayıcı kümesinde bir sorun olması muhtemeldir +- ***Eşlerin (peers) sayısı*** - Eşlerin sayısı düşerse, ağda bir bağlantı sorunu vardır + +## Güvenlik {#security} + +Polygon Edge ağının bir doğrulayıcı düğümünün güvenliğini sağlamak için en iyi uygulamalar aşağıda verilmiştir. + +### API hizmetleri {#api-services} + +- ***JSON-RPC*** - +Genele açık olması gereken tek API hizmetidir ( yük dengeleyici üzerinden veya doğrudan ). +Bu API, tüm arayüzler üzerinde veya belirli bir IP adresinde çalışmalıdır ( ör. `--json-rpc 0.0.0.0:8545` veya `--json-prc 192.168.1.1:8545` ). +:::info + +Genele açık bir API olduğundan, güvenliği sağlamak ve hızı sınırlamak için önünde bir yük dengeleyici / tersine proxy olması önerilir. + +::: + + +- ***LibP2P*** - +Bu, eşlerin haberleşmesi için düğümler tarafından kullanılan ağ API'sidir. Tüm arayüzlerde veya belirli bir IP adresinde çalışması gerekir +( `--libp2p 0.0.0.0:1478` veya `--libp2p 192.168.1.1:1478` ). Bu API, genelin kullanımına açık olmamalıdır +ama diğer tüm düğümler tarafından erişilebilir olmalıdır. +:::info + +Bir yerel ana makine (localhost) üzerinde çalıştırılırsa ( `--libp2p 127.0.0.1:1478` ) diğer düğümler bağlanamayacaktır. + +::: + + +- ***GRPC*** - +Bu API sadece ve sadece operatör komutlarını çalıştırmak için kullanılır. Bu nedenle yalnızca localhost ( `--grpc-address 127.0.0.1:9632` ) üzerinde çalıştırılmalıdır. + +### Polygon Edge gizli bilgileri {#polygon-edge-secrets} + +Polygon Edge gizli bilgileri ( `ibft` ve `libp2p` anahtarları ), yerel dosya sistemi üzerinde saklanmamalıdır. +Bunun yerine, desteklenen bir [Gizli Bilgi Yöneticisi](configuration/secret-managers/set-up-aws-ssm) kullanılmalıdır. +Gizli bilgilerin yerel dosya sisteminde saklanması, yalnızca production dışı ortamlarda yapılabilir. + +## Güncelleme {#update} + +Aşağıda, doğrulayıcı düğümleri için önerilen güncelleme prosedürü adım adım talimatlar hâlinde verilmiştir. + +### Güncelleme prosedürü {#update-procedure} + +- Resmî GitHub [sürümlerinden](https://github.com/0xPolygon/polygon-edge/releases) en son Polygon Edge binary dosyasını indirin +- Polygon Edge hizmetini durdurun ( ör. `sudo systemctl stop polygon-edge.service` ) +- Mevcut `polygon-edge` binary dosyasını, indirdiğiniz dosya ile değiştirin ( ör. `sudo mv polygon-edge /usr/local/bin/` ) +- Doğru `polygon-edge` versiyonunun çalıştığını kontrol etmek için `polygon-edge version` komutunu çalıştırın - sürüm versiyonu ile aynı olmalıdır +- `polygon-edge` hizmetini başlatmadan önce, yapılması gereken geriye dönük uyumluluk adımları olup olmadığını görmek için sürüm dokümantasyonunu kontrol edin +- `polygon-edge` hizmetini başlatın ( ör. `sudo systemctl start polygon-edge.service` ) +- Son olarak `polygon-edge` günlük çıktılarını kontrol edin ve `[ERROR]` günlüğü olmadan her şeyin çalıştığından emin olun + +:::warning + +Bir breaking (çalışmanın kesilmesine neden olabilecek) sürüm varsa, tüm düğümler üzerinde bu güncelleme prosedürü gerçekleştirilmelidir, çünkü +o anda çalışmakta olan binary dosya, yeni sürüm ile uyumlu değildir. + +Bu, zincirin (`polygon-edge` binary dosyaları yenileriyle değiştirilene ve hizmet yeniden başlatılana kadar ) kısa bir süre durdurulması gerektiği anlamına gelir, +dolayısıyla buna göre planlama yapılmalıdır. + +Verimli şekilde güncelleme yapmak ve zincirin çalışmama süresini (downtime) en aza indirmek için **[Ansible](https://www.ansible.com/)** gibi araçları +veya özel hazırlanmış bir script kullanabilirsiniz. + +::: + +## Başlatma prosedürü {#startup-procedure} + +Aşağıda Polygon Edge doğrulayıcı için önerilen başlatma prosedürü akışı verilmiştir + +- [Bilgi Tabanı](#knowledge-base) bölümünde listelenen dokümanları dikkatle okuyun +- En son OS yamalarını doğrulayıcı düğümü üzerinde uygulayın +- En son `polygon-edge` dosyasını, resmi GitHub [sürümlerinden](https://github.com/0xPolygon/polygon-edge/releases) indirin ve bu dosyayı, yerel kurulum `PATH`'a taşıyın +- Desteklenen [gizli bilgi yöneticilerinden](/docs/category/secret-managers) birini başlatmak için `polygon-edge secrets generate` CLI komutunu kullanın +- `polygon-edge secrets init` [CLI komutunu](/docs/edge/get-started/cli-commands#secrets-init-flags) kullanarak gizli bilgileri üretin ve kaydedin +- `NodeID` ve `Public key (address)` değerlerini ayrı bir yere not edin +- `genesis.json` dosyasını, [bulut kurulumunda](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators) açıklandığı gibi `polygon-edge genesis` [CLI komutunu](/docs/edge/get-started/cli-commands#genesis-flags) kullanarak oluşturun +- `polygon-edge server export` [CLI komutunu](/docs/edge/configuration/sample-config) kullanarak varsayılan yapılandırma (config) dosyasını oluşturun +- Yerel doğrulayıcı düğümü ortamını ( dosya yolları vb. ) içerecek şekilde `default-config.yaml` dosyasını düzenleyin +- Bir Polygon Edge hizmeti ( `systemd` veya benzeri ) oluşturun, burada `polygon-edge` binary dosyası, sunucuyu bir `default-config.yaml` dosyasından çalıştırır +- Hizmeti başlatarak Polygon Edge sunucusunu başlatın ( ör. `systemctl start polygon-edge` ) +- `polygon-edge` günlüğü çıktılarını kontrol edin; blokların üretildiğinden ve hiç `[ERROR]` günlüğü olmadığından emin olun +- [`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid) gibi bir JSON-RPC yöntemi çalıştırarak zincirin işlevselliğini kontrol edin diff --git a/archive/edge/tr-edge/working-with-node/backup-restore.md b/archive/edge/tr-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..823342b106 --- /dev/null +++ b/archive/edge/tr-edge/working-with-node/backup-restore.md @@ -0,0 +1,93 @@ +--- +id: backup-restore +title: Düğüm örneğini yedekleme/geri yükleme +description: "Polygon Edge düğüm örneği nasıl yedeklenir ve geri yüklenir?" +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## Genel Bakış {#overview} + +Bu kılavuz bir Polygon Edge düğüm örneğinin nasıl yedekleneceği ve geri yükleneceği hakkında ayrıntılı bilgi verir. +Başarılı bir yedekleme ve geri yükleme için hangi dosyaların kritik olduğunun yanı sıra ana dizinleri ve içeriklerini kapsar. + +## Ana dizinler {#base-folders} + +Polygon Edge, depolama motoru olarak LevelDB'yi kullanır. +Bir Polygon Edge düğümü başlatılırken, belirtilen çalışma dizininde aşağıdaki alt klasörler oluşturulur: +* **blokchain** - Blok zinciri verilerini depolar +* **trie** - Merkle ağaçlarını depolar (dünya durum verisi) +* **keystore** - İstemci için özel anahtarları depolar. Buna libp2p özel anahtarı ve mühürleyici/doğrulayıcı özel anahtarı dâhildir +* **consensus** - İstemcinin çalışırken ihtiyaç duyabileceği tüm konsensüs bilgilerini depolar. Şimdilik, düğümün *özel doğrulayıcı anahtarını* depolar + +Polygon Edge örneğinin sorunsuz çalışması için bu klasörlerin korunması kritik önem taşır. + +## Çalışan bir düğümün yedeklenmesi ve yeni düğüm için geri yüklenmesi {#create-backup-from-a-running-node-and-restore-for-new-node} + +Bu bölüm, çalışan bir düğümde blok zincirinin arşiv verilerini oluşturma ve başka bir örnekte geri yükleme konusunda size rehberlik eder. + +### Yedekleme {#backup} + +`backup`komutu, gRPC ile çalışan bir düğümün bloklarını getirir ve bir arşiv dosyası oluşturur. Komutta `--from` ve `--to` belirtilmemişse, bu komut genesis'ten son bloğa kadar tüm blokları getirir. + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### Geri yükleme {#restore} + +Bir sunucu, `--restore` bayrağı ile başlarken, başlangıçta bir arşivden blokları içe aktarır. Lütfen yeni düğüm için bir anahtar bulunduğundan emin olun. Anahtarların içe aktarılması veya üretilmesi hakkında daha fazla bilgi edinmek için [Gizli Yöneticiler bölümünü](/docs/edge/configuration/secret-managers/set-up-aws-ssm) ziyaret edin. + +```bash +$ polygon-edge server --restore archive.dat +``` + +## Tüm veriyi Yedekleme/Geri yükleme {#back-up-restore-whole-data} + +Bu bölüm, durum verisi ve anahtar dâhil olmak üzere verilerin yedeklenmesi ve yeni örneğe geri yüklenmesi konusunda size rehberlik eder. + +### Adım 1: Çalışan istemcinin durdurulması {#step-1-stop-the-running-client} + +Polygon Edge, veri depolama için **LevelDB** kullandığı için düğümün yedekleme süresi boyunca durdurulması gerekir +çünkü **LevelDB** veri tabanı dosyalarına eş zamanlı erişime izin vermez. + +Ek olarak, Polygon Edge, kapanışta veri senkronizasyonu da yapar. + +İlk adım, çalışan istemciyi durdurmayı içerir (bir hizmet yöneticisi veya işleme SIGINT sinyali gönderen başka bir mekanizma aracılığıyla), +böylece doğal bir şekilde kapanırken 2 olayı tetikleyebilir: +* Diskte veri senkronizasyonu yapma +* LevelDB tarafından kilitlenen DB dosyalarının serbest bırakılması + +### Adım 2: Dizini yedekleme {#step-2-backup-the-directory} + +Artık istemci çalışmadığına göre, veri dizini başka bir ortama yedeklenebilir. +`.key`uzantısına sahip dosyaların, geçerli düğümün taklit edilmesi için kullanılabilecek özel anahtar verilerini içerdiğini +ve bunların asla üçüncü/bilinmeyen bir tarafla paylaşılmaması gerektiğini unutmayın. + +:::info + +Geri yüklenen düğümün tamamen çalışır durumda olması için lütfen oluşturulan `genesis` dosyasını manuel olarak yedekleyin ve geri yükleyin. + +::: + +## Geri yükleme {#restore-1} + +### Adım 1: Çalışan istemcinin durdurulması {#step-1-stop-the-running-client-1} + +Polygon Edge'in çalışan herhangi bir örneği varsa, 2. adımın başarılı olması için durdurulması gerekir. + +### Adım 2: Yedeklenen veri dizininin istenen klasöre kopyalanması {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +İstemci çalışmadığında, daha önce yedeklenmiş olan veri dizini, istenen klasöre kopyalanabilir. +Ek olarak, daha önce kopyalanan `genesis` dosyasını geri yükleyin. + +### Adım 3: Doğru veri dizinini belirterek Polygon Edge istemcisini çalıştırma {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +Polygon Edge'in geri yüklenen veri dizinini kullanması için, kullanıcının başlangıç esnasında veri dizinine giden yolu belirtmesi +gerekir. Lütfen `data-dir` bayrağı hakkındaki bilgiler için [CLI Komutları](/docs/edge/get-started/cli-commands) bölümüne danışın. diff --git a/archive/edge/tr-edge/working-with-node/query-json-rpc.md b/archive/edge/tr-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..3f2ce8debc --- /dev/null +++ b/archive/edge/tr-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,93 @@ +--- +id: query-json-rpc +title: JSON RPC uç noktalarına sorgu gönderme +description: "Veriyi sorgulayın ve zinciri önceden mine edilmiş (premined) bir hesap ile başlatın." +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## Genel Bakış {#overview} + +Polygon Edge'in JSON-RPC katmanı, geliştiricilere blok zinciri ile kolayca HTTP talepleri yoluyla etkileşim kurabilme +işlevselliği sağlar. + +Bu örnek, bilgiyi sorgulamak için **curl** gibi araçları kullanmayı ve zinciri önceden mine edilmiş bir hesap ile başlatma ile +işlem göndermeyi kapsar. + +## Adım 1: Önceden mine edilmiş bir hesap ile bir genesis dosyası oluşturma {#step-1-create-a-genesis-file-with-a-premined-account} + +Bir genesis dosyası oluşturmak için aşağıdaki komutu çalıştırın: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +**Premine** bayrağı, **genesis** dosyası içinde bir başlangıç bakiyesi ile dâhil edilmesi gereken adresi ayarlar.
+Bu durumda, `0x1010101010101010101010101010101010101010` adresi başlangıçta **varsayılan bakiye** olarak +`0xD3C21BCECCEDA1000000` içerecektir (1 milyon yerel para birimi belirteçi). + +Bir bakiye belirtmek istersek, bakiye ile adresi bir `:` kullanarak şu şekilde ayırabiliriz: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +Bakiye bir `hex` veya `uint256` değeri olabilir. + +:::warning Yalnızca özel anahtarına sahip olduğunuz hesapları önceden mine edin! + +Hesapları önceden mine ediyorsanız ve bunlara erişmek için gerekli özel anahtarınız yoksa, kullanılamayacak bir bakiyeyi önceden mine etmiş olursunuz + +::: + +## Adım 2: Polygon Edge'i dev modunda başlatın {#step-2-start-the-polygon-edge-in-dev-mode} + +Polygon Edge'i, [CLI Komutları](/docs/edge/get-started/cli-commands) bölümünde açıklanan geliştirici modunda başlatabilmek için, +aşağıdakileri çalıştırın: +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## Adım 3: Hesap bakiyesini sorgulayın {#step-3-query-the-account-balance} + +Artık istemci çalışıyor ve dev modunda olduğuna göre, **adım 1**'de oluşturulan genesis dosyasını kullanarak +**curl** gibi bir araç ile hesap bakiyesini sorgulayabiliriz: +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +Bu komut aşağıdaki çıktıyı geri döndürmelidir: +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## Adım 4: Bir aktarım işlemi gönderin {#step-4-send-a-transfer-transaction} + +Artık önceden mine edilmiş olarak kurduğumuz hesabın doğru bakiyeye sahip olduğunu onayladığımıza göre, bir miktar ether aktarabiliriz: + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/tr-edge/working-with-node/query-operator-info.md b/archive/edge/tr-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..02ab3979d7 --- /dev/null +++ b/archive/edge/tr-edge/working-with-node/query-operator-info.md @@ -0,0 +1,85 @@ +--- +id: query-operator-info +title: Operatör bilgisi sorgulama +description: "Operatör bilgileri nasıl sorgulanır?" +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## Ön Koşullar {#prerequisites} + +Bu kılavuz, [Yerel Kurulum](/docs/edge/get-started/set-up-ibft-locally)'u veya [bulutta bir IBFT kümesinin nasıl kurulacağına dair kılavuzu takip ettiğinizi varsayar](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +Her türlü operatör bilgisinin sorgulanabilmesi için çalışan bir düğüme ihtiyaç vardır. + +Polygon Edge sayesinde, düğüm operatörleri kontrolü elinde tutar ve işlettikleri düğümün ne yaptığı hakkında bilgilendirilir.
+İstedikleri zaman, gRPC üzerine inşa edilen düğüm bilgi katmanını kullanabilir ve anlamlı bilgiler alabilirler - log inceleme gerekmez. + +:::note + +Düğümünüz `127.0.0.1:8545` üzerinde çalışmıyorsa, bu belgede listelenen komutlara bir `--grpc-address ` bayrağı eklemeniz gerekir. + +::: + +## Eş bilgileri {#peer-information} + +### Eş listesi {#peers-list} + +Bağlı eşlerin (çalışan düğümün kendisi dâhil) tam listesini almak için aşağıdaki komutu çalıştırın: +````bash +polygon-edge peers list +```` + +Bu, çalışan istemcinin mevcut eşleri olan libp2p adreslerinin bir listesini geri döndürür. + +### Eş durumu {#peer-status} + +Belirli bir eşin durumu için şunu çalıştırın: +````bash +polygon-edge peers status --peer-id
+```` +Burada, *adres* parametresi, eşin libp2p adresidir. + +## IBFT bilgisi {#ibft-info} + +Çoğu zaman, operatörler IBFT konsensüsündeki işletim düğümünün durumu hakkında bilgi edinmek isteyebilir. + +Neyse ki, Polygon Edge bu bilgiyi bulmak için kolay bir yol sunuyor. + +### Anlık görüntüler {#snapshots} + +Aşağıdaki komutu çalıştırmak, en son anlık görüntüyü döndürür. +````bash +polygon-edge ibft snapshot +```` +Anlık görüntüyü belirli bir yükseklik için (blok numarası) sorgulamak için, operatör şu komutu çalıştırabilir: +````bash +polygon-edge ibft snapshot --num +```` + +### Adaylar {#candidates} + +Operatör, adaylar hakkında en güncel bilgiyi almak için aşağıdaki komutu çalıştırabilir: +````bash +polygon-edge ibft candidates +```` +Bu komut, önerilen mevcut aday kümesini ve henüz dâhil edilmemiş adayları sorgular + +### Durum {#status} + +Aşağıdaki komut, çalışan IBFT istemcisinin geçerli doğrulayıcı anahtarını döndürür: +````bash +polygon-edge ibft status +```` + +## İşlem havuzu {#transaction-pool} + +İşlem havuzundaki mevcut işlem sayısını bulmak için operatör aşağıdaki komutu çalıştırabilir: +````bash +polygon-edge txpool status +```` diff --git a/archive/edge/vi-edge/additional-features/blockscout.md b/archive/edge/vi-edge/additional-features/blockscout.md new file mode 100644 index 0000000000..49e9791786 --- /dev/null +++ b/archive/edge/vi-edge/additional-features/blockscout.md @@ -0,0 +1,397 @@ +--- +id: blockscout +title: Blockscout +description: Cách thiết lập một phiên bản Blockscout để hoạt động với Polygon Edge. +keywords: + - docs + - polygon + - edge + - blockscout + - deploy + - setup + - instance +--- + +## Tổng quan {#overview} +Hướng dẫn này đi vào chi tiết về cách biên soạn và triển khai thực thể Blockscout để hoạt động với Polygon-Edge. Blockscout có [tài liệu](https://docs.blockscout.com/for-developers/manual-deployment) riêng, nhưng tài liệu này tập trung vào hướng dẫn từng bước đơn giản những chi tiết về cách thiết lập phiên bản Blockscout. + +## Môi trường {#environment} +* Hệ điều hành: [Liên kết tải xuống](https://releases.ubuntu.com/20.04/) Ubuntu Server 20.04 LTS với các quyền sudo +* Phần cứng máy chủ: 8CPU / 16GB RAM / 50GB HDD (LVM) +* Máy chủ cơ sở dữ liệu: Máy chủ chuyên dụng với 2 CPU / 4GB RAM / 100GB SSD / PostgreSQL 13.4 + +### Máy chủ DB {#db-server} +Yêu cầu để làm theo hướng dẫn này là phải có sẵn một máy chủ cơ sở dữ liệu, cơ sở dữ liệu và người dùng db được định cấu hình. Hướng dẫn này sẽ không đi vào chi tiết về cách triển khai và cấu hình máy chủ PostgreSQL. Hiện giờ có rất nhiều hướng dẫn để thực hiện việc này, ví dụ như [Hướng dẫn DigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart) + +:::info TUYÊN BỐ MIỄN TRỪ + +Hướng dẫn này chỉ nhằm giúp bạn thiết lập và chạy Blockscout trên một phiên bản duy nhất không phải là thiết lập sản xuất lý tưởng. Đối với sản xuất, có thể bạn sẽ muốn đưa proxy ngược, bộ cân bằng tải, các tùy chọn khả năng mở rộng, v.v. vào kiến trúc. + +::: + +# Quy trình triển khai Blockscout {#blockscout-deployment-procedure} + +## Phần 1 - cài đặt các phụ thuộc {#part-1-install-dependencies} +Trước khi bắt đầu, chúng ta cần đảm bảo rằng chúng ta đã cài đặt tất cả các tệp nhị phân mà Blockcout phụ thuộc vào. + +### Cập nhật & nâng cấp hệ thống {#update-upgrade-system} +```bash +sudo apt -y update && sudo apt -y upgrade +``` + +### Thêm kho lưu trữ Erlang {#add-erlang-repos} +```bash +# go to your home dir +cd ~ +# download deb +wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb +# download key +wget https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc +# install repo +sudo dpkg -i erlang-solutions_2.0_all.deb +# install key +sudo apt-key add erlang_solutions.asc +# remove deb +rm erlang-solutions_2.0_all.deb +# remove key +rm erlang_solutions.asc +``` + +### Thêm kho lưu trữ NodeJS {#add-nodejs-repo} +```bash +sudo curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - +``` + +### Cài đặt Rust {#install-rust} +```bash +sudo curl https://sh.rustup.rs -sSf | sh -s -- -y +``` + +### Cài đặt phiên bản ErLang cần thiết {#install-required-version-of-erlang} +```bash +sudo apt -y install esl-erlang=1:24.* +``` + +### Cài đặt phiên bản Elixir cần thiết {#install-required-version-of-elixir} +Phải là phiên bản Elixir `1.13`. Nếu cố cài đặt phiên bản này từ kho lưu trữ chính thức, phiên bản `erlang` sẽ cập nhật thành `Erlang/OTP 25` và chúng ta không muốn thế. Do đó, chúng ta cần cài đặt phiên bản `elixir` cụ thể được biên dịch trước từ trang phát hành GitHub. + +```bash +cd ~ +mkdir /usr/local/elixir +wget https://github.com/elixir-lang/elixir/releases/download/v1.13.4/Precompiled.zip +sudo unzip -d /usr/local/elixir/ Precompiled.zip +rm Precompiled.zip +``` + +Bây giờ chúng ta cần thiết lập mã nhị phân `exlixir`hệ thống đúng cách. +```bash +sudo ln -s /usr/local/elixir/bin/elixir /usr/local/bin/elixir +sudo ln -s /usr/local/elixir/bin/mix /usr/local/bin/mix +sudo ln -s /usr/local/elixir/bin/iex /usr/local/bin/iex +sudo ln -s /usr/local/elixir/bin/elixirc /usr/local/bin/elixirc +``` + +Kiểm tra xem `elixir` và `erlang` có được cài đặt đúng cách hay không bằng cách chạy `elixir -v`. Đây sẽ là kết quả: +```bash +Erlang/OTP 24 [erts-12.3.1] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [jit] + +Elixir 1.13.4 (compiled with Erlang/OTP 22) +``` + +:::warning + +`Erlang/OTP` phải là phiên bản `24` và `Elixir` phải là phiên bản `1.13.*`. +Nếu không đúng như vậy, bạn sẽ gặp phải sự cố khi biên dịch Blockscout và/hoặc chạy nó. + +::: +:::info + +Xem ***[trang yêu cầu Blockscout chính thức](https://docs.blockscout.com/for-developers/information-and-settings/requirements)*** + +::: + +### Cài đặt NodeJS {#install-nodejs} +```bash +sudo apt -y install nodejs +``` + +### Cài đặt Cargo {#install-cargo} +```bash +sudo apt -y install cargo +``` + +### Cài đặt các mục phụ thuộc khác {#install-other-dependencies} +```bash +sudo apt -y install automake libtool inotify-tools gcc libgmp-dev make g++ git +``` + +### Tùy chọn cài đặt ứng dụng khách postgresql để kiểm tra kết nối db của bạn {#optionally-install-postgresql-client-to-check-your-db-connection} +```bash +sudo apt install -y postgresql-client +``` + +## Phần 2 - thiết lập biến môi trường {#part-2-set-environment-variables} +Chúng ta cần thiết lập các biến môi trường, trước khi bắt đầu biên dịch Blockscout. Trong hướng dẫn này, chúng tôi sẽ chỉ đặt mức tối thiểu cơ bản để nó hoạt động. +Bạn có thể tìm thấy [tại đây](https://docs.blockscout.com/for-developers/information-and-settings/env-variables) danh sách đầy đủ của các biến có thể thiết lập + +### Đặt kết nối cơ sở dữ liệu làm biến môi trường {#set-database-connection-as-environment-variable} +```bash +# postgresql connection example: DATABASE_URL=postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout +export DATABASE_URL=postgresql://:@:/ # db_name does not have to be existing database + +# we set these env vars to test the db connection with psql +export PGPASSWORD=Passw0Rd +export PGUSER=blockscout +export PGHOST=db.instance.local +export PGDATABASE=postgres # on AWS RDS postgres database is always created +``` + +Bây giờ hãy kiểm tra kết nối DB của bạn với các tham số được cung cấp. Vì bạn đã cung cấp PG env vars, bạn chỉ có thể kết nối với cơ sở dữ liệu bằng cách chạy: +```bash +psql +``` + +Nếu cơ sở dữ liệu được định cấu hình chính xác, bạn sẽ thấy lời nhắc psql: +```bash +psql (12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)) +SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) +Type "help" for help. + +blockscout=> +``` + +Nếu không, bạn có thể thấy lỗi như thế này: +```bash +psql: error: FATAL: password authentication failed for user "blockscout" +FATAL: password authentication failed for user "blockscout" +``` +Nếu vậy, [những tài liệu](https://ubuntu.com/server/docs/databases-postgresql) này có thể giúp bạn. + +:::info Kết nối DB + +Đảm bảo rằng bạn đã sắp xếp tất cả các vấn đề kết nối db trước khi chuyển sang phần tiếp theo. Bạn sẽ cần cung cấp các đặc quyền siêu người dùng cho người dùng Blockscout. + +::: +```bash +postgres@ubuntu:~$ createuser --interactive +Enter name of role to add: blockscout +Shall the new role be a superuser? (y/n) y +``` + +## Phần 3 - nhân bản và biên dịch Blockscout {#part-3-clone-and-compile-blockscout} +Bây giờ cuối cùng chúng ta cũng bắt đầu cài đặt Blockscout. + +### Nhân bản kho lưu trữ Blockscout {#clone-blockscout-repo} +```bash +cd ~ +git clone https://github.com/Trapesys/blockscout +``` + +### Tạo cơ sở khóa bí mật để bảo vệ quá trình sản xuất {#generate-secret-key-base-to-protect-production-build} +```bash +cd blockscout +mix deps.get +mix local.rebar --force +mix phx.gen.secret +``` +Ở dòng cuối cùng, bạn sẽ thấy một chuỗi dài các ký tự ngẫu nhiên. Mục này nên được đặt làm biến môi trường `SECRET_KEY_BASE`của bạn, trước bước tiếp theo. Ví dụ: +```bash +export SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" +``` + +### Thiết lập chế độ sản xuất {#set-production-mode} +```bash +export MIX_ENV=prod +``` + +### Biên dịch {#compile} +Cd vào thư mục nhân bản và bắt đầu biên dịch + +```bash +cd blockcout +mix local.hex --force +mix do deps.get, local.rebar --force, deps.compile, compile +``` + +:::info + +Nếu bạn đã triển khai trước đó, hãy xóa nội dung tĩnh khỏi bản dựng ***mix phx.digest.clean trước đó.***. +::: + +### Di chuyển cơ sở dữ liệu {#migrate-databases} +:::info + +Phần này sẽ không thành công nếu bạn không thiết lập kết nối DB đúng cách, bạn không cung cấp, hoặc bạn đã xác định sai tham số tại biến môi trường DATABASE_URL. Người dùng cơ sở dữ liệu cần có các đặc quyền của người dùng siêu cấp. +::: +```bash +mix do ecto.create, ecto.migrate +``` + +Nếu bạn cần thả cơ sở dữ liệu trước, hãy chạy +```bash +mix do ecto.drop, ecto.create, ecto.migrate +``` + +### Cài đặt phần phụ thuộc npm và biên dịch nội dung giao diện người dùng {#install-npm-dependencies-and-compile-frontend-assets} +Bạn cần thay đổi thư mục thành thư mục chứa nội dung giao diện người dùng. + +```bash +cd apps/block_scout_web/assets +sudo npm install +sudo node_modules/webpack/bin/webpack.js --mode production +``` + +:::info Hãy kiên nhẫn + +Quá trình tổng hợp các nội dung này có thể mất vài phút và có thể sẽ không hiển thị kết quả. Có thể có vẻ như quá trình này đang bị kẹt, nhưng chỉ cần kiên nhẫn. Khi quá trình biên dịch kết thúc, một kết quả sẽ xuất ra như: `webpack 5.69.1 compiled with 3 warnings in 104942 ms` +::: + +### Xây dựng tài nguyên tĩnh {#build-static-assets} +Đối với bước này, bạn cần quay lại thư mục gốc của thư mục bản sao Blockscout. +```bash +cd ~/blockscout +sudo mix phx.digest +``` + +### Khởi tạo chứng chỉ tự ký {#generate-self-signed-certificates} +:::info + +Bạn có thể bỏ qua bước này nếu không sử dụng `https`. + +::: +```bash +cd apps/block_scout_web +mix phx.gen.cert blockscout blockscout.local +``` + +## Phần 4 - tạo và chạy dịch vụ Blockscout {#part-4-create-and-run-blockscout-service} +Trong phần này, chúng ta cần thiết lập một dịch vụ hệ thống vì chúng ta muốn Blockscout chạy ở chế độ nền và tồn tại sau khi khởi động lại hệ thống. + +### Tạo tệp tin dịch vụ {#create-service-file} +```bash +sudo touch /etc/systemd/system/explorer.service +``` + +### Chỉnh tệp tin dịch vụ {#edit-service-file} +Sử dụng trình biên soạn linux yêu thích của bạn để chỉnh sửa tệp tin này và cấu hình dịch vụ. +```bash +sudo vi /etc/systemd/system/explorer.service +``` +Nội dung của tệp tin explorer.service sẽ giống như sau: +```bash +[Unit] +Description=BlockScout Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=1 +User=root +StandardOutput=syslog +StandardError=syslog +WorkingDirectory=/usr/local/blockscout +ExecStart=/usr/local/bin/mix phx.server +EnvironmentFile=/usr/local/blockscout/env_vars.env + +[Install] +WantedBy=multi-user.target +``` + +### Bật dịch vụ khởi động khi khởi động hệ thống {#enable-starting-service-on-system-boot} +```bash +sudo systemctl daemon-reload +sudo systemctl enable explorer.service +``` + +### Di chuyển thư mục nhân bản Blockscout của bạn đến vị trí trên toàn hệ thống {#move-your-blockscout-clone-folder-to-system-wide-location} +Dịch vụ Blockscout cần có quyền truy cập vào thư mục bạn đã nhân bản từ kho Blockscout và biên dịch tất cả các nội dung. +```bash +sudo mv ~/blockscout /usr/local +``` + +### Tạo tệp env vars sẽ được sử dụng bởi dịch vụ Blockscout {#create-env-vars-file-which-will-be-used-by-blockscout-service} + +```bash +sudo touch /usr/local/blockscout/env_vars.env +# use your favorite text editor +sudo vi /usr/local/blockscout/env_vars.env + +# env_vars.env file should hold these values ( adjusted for your environment ) +ETHEREUM_JSONRPC_HTTP_URL="localhost:8545" # json-rpc API of the chain +ETHEREUM_JSONRPC_TRACE_URL="localhost:8545" # same as json-rpc API +DATABASE_URL='postgresql://blockscout:Passw0Rd@db.instance.local:5432/blockscout' # database connection from Step 2 +SECRET_KEY_BASE="912X3UlQ9p9yFEBD0JU+g27v43HLAYl38nQzJGvnQsir2pMlcGYtSeRY0sSdLkV/" # secret key base +ETHEREUM_JSONRPC_WS_URL="ws://localhost:8545/ws" # websocket API of the chain +CHAIN_ID=93201 # chain id +HEART_COMMAND="systemctl restart explorer" # command used by blockscout to restart it self in case of failure +SUBNETWORK="Supertestnet PoA" # this will be in html title +LOGO="/images/polygon_edge_logo.svg" # logo location +LOGO_FOOTER="/images/polygon_edge_logo.svg" # footer logo location +COIN="EDGE" # coin +COIN_NAME="EDGE Coin" # name of the coin +INDEXER_DISABLE_BLOCK_REWARD_FETCHER="true" # disable block reward indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER="true" # disable pending transactions indexer as Polygon Edge doesn't support tracing +INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER="true" # disable internal transactions indexer as Polygon Edge doesn't support tracing +MIX_ENV="prod" # run in production mode +BLOCKSCOUT_PROTOCOL="http" # protocol to run blockscout web service on +PORT=4000 # port to run blockscout service on +DISABLE_EXCHANGE_RATES="true" # disable fetching of exchange rates +POOL_SIZE=200 # the number of database connections +POOL_SIZE_API=300 # the number of read-only database connections +ECTO_USE_SSL="false" # if protocol is set to http this should be false +HEART_BEAT_TIMEOUT=60 # run HEARTH_COMMAND if heartbeat missing for this amount of seconds +INDEXER_MEMORY_LIMIT="10Gb" # soft memory limit for indexer - depending on the size of the chain and the amount of RAM the server has +FETCH_REWARDS_WAY="manual" # disable trace_block query +INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 # sanitize empty block in this batch size +``` +:::info + +Sử dụng `SECRET_KEY_BASE` bạn đã tạo trong Phần 3. + +::: +Lưu tập tin và thoát. + +### Cuối cùng, khởi động dịch vụ Blockscout {#finally-start-blockscout-service} +```bash +sudo systemctl start explorer.service +``` + +## Phần 5 - kiểm tra chức năng của phiên bản Blockscout của bạn {#part-5-test-out-the-functionality-of-your-blockscout-instance} +Bây giờ tất cả những gì còn lại cần làm là kiểm tra xem dịch vụ Blockscout có đang chạy hay không. Kiểm tra trạng thái dịch vụ với: +```bash +sudo systemctl status explorer.service +``` + +Kiểm tra kết quả dịch vụ: +```bash +sudo journalctl -u explorer.service -f +``` + +Bạn có thể kiểm tra xem có một số cổng nghe mới không: +```bash +# if netstat is not installed +sudo apt install net-tools +sudo netstat -tulpn +``` + +Bạn sẽ nhận được một danh sách các cổng nghe và trong danh sách phải có một cái gì đó như sau: +``` +tcp 0 0 0.0.0.0:5432 0.0.0.0:* LISTEN 28142/postgres +tcp 0 0 0.0.0.0:4000 0.0.0.0:* LISTEN 42148/beam.smp +``` + +Dịch vụ web Blockscout chạy cổng và giao thức được xác định trong tệp env. Trong ví dụ này, nó chạy trên `4000`(http) . +Nếu mọi thứ đều ổn, bạn sẽ có thể truy cập vào cổng web Blockscout với `http://:4000`. + +## Xem xét {#considerations} +Để có hiệu suất tốt nhất, bạn nên có một nút không xác thực toàn bộ kho lưu trữ cục bộ / chuyên dụng`polygon-edge` +sẽ được sử dụng riêng cho các truy vấn ·Blockscout. +`json-rpc`API của nút này, không cần phải được hiển thị công khai, vì Blockscout chạy tất cả các truy vấn từ phần sau (backend). + + +## Suy nghĩ cuối cùng {#final-thoughts} +Chúng tôi vừa triển khai một phiên bản Blockscout duy nhất, hoạt động tốt, nhưng để sản xuất, bạn nên cân nhắc đặt phiên bản này sau proxy ngược như Nginx. Bạn cũng nên nghĩ về khả năng mở rộng cơ sở dữ liệu và thực thể, tùy thuộc vào trường hợp sử dụng của bạn. + +Bạn chắc chắn nên xem [tài liệu Blockscout](https://docs.blockscout.com/) chính thức vì có rất nhiều tùy chọn tùy chỉnh. \ No newline at end of file diff --git a/archive/edge/vi-edge/additional-features/chainbridge/definitions.md b/archive/edge/vi-edge/additional-features/chainbridge/definitions.md new file mode 100644 index 0000000000..630a8453b2 --- /dev/null +++ b/archive/edge/vi-edge/additional-features/chainbridge/definitions.md @@ -0,0 +1,259 @@ +--- +id: definitions +title: Các định nghĩa chung +description: Các định nghĩa chung về thuật ngữ sử dụng trong chainBridge + +keywords: + - docs + - polygon + - edge + - Bridge +--- + + +## Trình chuyển tiếp {#relayer} +Chainbridge là một cầu nối trình chuyển tiếp. Vai trò của trình chuyển tiếp là bỏ phiếu về việc thực thi một yêu cầu (ví dụ: đốt/phát hành bao nhiêu token). + Trình này giám sát các sự kiện từ mọi chuỗi và bỏ phiếu cho đề xuất trong hợp đồng Bridge của chuỗi đích khi nhận sự kiện `Deposit` từ chuỗi. + Trình chuyển tiếp sẽ triển khai một phương pháp trong hợp đồng Brigde để thực thi đề xuất sau khi đã có đủ số phiếu yêu cầu. + Cầu nối sẽ ủy quyền việc thực thi hợp đồng Handler. + + + +## Các loại hợp đồng {#types-of-contracts} +Trong ChainBridge, có ba loại hợp đồng trên mỗi chuỗi, được gọi là Bridge/Handler/Target. + +| **Loại** | **Mô tả** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Hợp đồng Bridge | Hợp đồng Bridge quản lý các yêu cầu, phiếu bầu, hoạt động thực thi sẽ được triển khai trong mỗi chuỗi. + Người dùng sẽ gọi `deposit` trong hợp đồng Bridge để bắt đầu chuyển nhượng, hợp đồng Bridge sẽ ủy quyền quá trình cho hợp đồng Handler tương ứng với hợp đồng Target. + Khi hợp đồng Handler gọi thành công hợp đồng Target, hợp đồng Bridge sẽ tạo sự kiện `Deposit` để thông báo cho các trình chuyển tiếp. + | +| Hợp đồng Handler | Hợp đồng này tương tác với hợp đồng Target để thực thi ký quỹ hoặc đề xuất. + Hợp đồng này sẽ xác thực yêu cầu của người dùng, gọi hợp đồng Target và trợ giúp một số cài đặt cho hợp đồng Target. + Có một số hợp đồng Handler nhất định để gọi từng hợp đồng Target có giao diện khác biệt. + Các lệnh gọi gián tiếp của hợp đồng Handler giúp tạo cầu nối cho phép chuyển nhượng mọi loại tài sản hoặc dữ liệu. Hiện tại, có ba loại hợp đồng Handler được ChainBridge thực thi: ERC20Handler, ERC721Handler và GenericHandler. + | +| Hợp đồng Target | Là hợp đồng quản lý các tài sản được trao đổi hoặc các thông điệp được chuyển tiếp giữa các chuỗi. + Tương tác với hợp đồng này sẽ được thực hiện từ mỗi bên của cầu nối. + | + +
+ +![Kiến trúc ChainBridge](/img/edge/chainbridge/architecture.svg) *Kiến trúc ChainBridge* + +
+ +
+ +![Quy trình chuyển nhượng token ERC20](/img/edge/chainbridge/erc20-workflow.svg) + *Ví dụ: Quy trình chuyển nhượng token ERC20* + +
+ +## Các loại tài khoản {#types-of-accounts} + +Hãy đảm bảo các tài khoản có đủ token gốc để tạo giao dịch trước khi bắt đầu. + Trong Polygon Edge, bạn có thể gán số dư định trước cho các tài khoản khi tạo khối gốc. + + +| **Loại** | **Mô tả** | +|----------|-------------------------------------------------------------------------------------------------------------------------------| +| Quản trị viên | Tài khoản này sẽ được trao vai trò quản trị viên như mặc định. + | +| Người dùng | Tài khoản người gửi/người nhận thực hiện gửi/nhận tài sản. + Tài khoản người gửi thanh toán phí gas khi phê duyệt giao dịch chuyển nhượng token và gọi ký quỹ quy định trong hợp đồng Bridge để bắt đầu chuyển nhượng. + | + +:::info Vai trò quản trị viên +Một số thao tác nhất định chỉ có thể được thực hiện bằng tài khoản quản trị viên. + Theo mặc định, nhà phát triển của hợp đồng Bridge sẽ giữ vai trò quản trị viên. Phía dưới sẽ có hướng dẫn chỉ định/gỡ bỏ vai trò quản trị viên cho tài khoản khác. + + +### Thêm vai trò quản trị viên {#add-admin-role} + +Thêm với tư cách quản trị viên + +```bash +# Grant admin role +$ cb-sol-cli admin add-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` +### Thu hồi vai trò quản trị viên {#revoke-admin-role} + +Xóa bỏ quản trị viên + +```bash +# Revoke admin role +$ cb-sol-cli admin remove-admin \ + --url [JSON_RPC_URL] \ + --privateKey [PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --admin "[NEW_ACCOUNT_ADDRESS]" +``` + +## Các thao tác vận hành được cấp phép bởi tài khoản `admin` được nêu dưới đây. {#account-are-as-below} + +### Thiết lập tài nguyên {#set-resource} + +Đăng ký ID tài nguyên cùng địa chỉ hợp đồng cho trình xử lý. + + +```bash +# Register new resource +$ cb-sol-cli bridge register-resource \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Đảm bảo hợp đồng có thể được đốt/mint {#make-contract-burnable-mintable} + +Chuyển hợp đồng token thành có thể đốt/mint trong trình xử lý. + +```bash +# Let contract burnable/mintable +$ cb-sol-cli bridge set-burn \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[TARGET_CONTRACT_ADDRESS]" +``` + +### Hủy đề xuất {#cancel-proposal} + +Hủy đề xuất thực thi + +```bash +# Cancel ongoing proposal +$ cb-sol-cli bridge cancel-proposal \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "[RESOURCE_ID]" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --chainId "[CHAIN_ID_OF_SOURCE_CHAIN]" \ + --depositNonce "[NONCE]" +``` + +### Tạm dừng/Tiếp tục {#pause-unpause} + +Tạm dừng ký quỹ, tạo đề xuất, bỏ phiếu và thực hiện ký quỹ. + + +```bash +# Pause +$ cb-sol-cli admin pause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" + +# Unpause +$ cb-sol-cli admin unpause \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" +``` + +### Thay đổi phí {#change-fee} + +Thay đổi phí thanh toán cho hợp đồng Bridge + +```bash +# Change fee for execution +$ cb-sol-cli admin set-fee \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --fee [FEE_IN_WEI] +``` + +### Thêm/Gỡ bỏ trình chuyển tiếp {#add-remove-a-relayer} + +Chỉ định tài khoản làm trình chuyển tiếp mới hoặc gỡ bỏ tài khoản khỏi trình chuyển tiếp + + +```bash +# Add relayer +$ cb-sol-cli admin add-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[NEW_RELAYER_ADDRESS]" + +# Remove relayer +$ cb-sol-cli admin remove-relayer \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --relayer "[RELAYER_ADDRESS]" +``` + +### Thay đổi ngưỡng của trình chuyển tiếp + {#change-relayer-threshold} + +Thay đổi số lượng phiếu bầu cần thiết để thực hiện đề xuất + + +```bash +# Remove relayer +$ cb-sol-cli admin set-threshold \ + --url [JSON_RPC_URL] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --threshold [THRESHOLD] +``` +::: + +## ID Chuỗi {#chain-id} + +Chainbridge `chainId`là một giá trị tùy ý được sử dụng trong cầu nối để phân biệt các mạng blockchain, giá trị này phải nằm trong phạm vi uint8. + Không được nhầm lẫn với ID chuỗi của mạng lưới, chúng không giống nhau. + Giá trị này phải là duy nhất và không nhất thiết phải giống với ID của mạng lưới. + + +Ví dụ, chúng tôi đặt `99`trong `chainId`, vì chuỗi ID của mạng thử nghiệm Mumbai là `80001`, vốn không thể được biểu diễn bằng uint8. + + +## ID tài nguyên {#resource-id} + +ID tài nguyên là một giá trị 32 byte duy nhất trong môi trường chuỗi chéo, được liên kết với một tài sản (tài nguyên) nhất định đang được chuyển nhượng giữa các mạng lưới. + + +ID tài nguyên là tùy ý, nhưng theo quy ước, sẽ là byte đứng cuối cùng chứa ID chuỗi của chuỗi nguồn (mạng khởi nguồn của tài sản). + + +## URL JSON-RPC dành cho Polygon PoS + {#json-rpc-url-for-polygon-pos} + +Trong hướng dẫn này, chúng tôi sẽ dùng https://rpc-mumbai.matic.today, một URL JSON-RPC công khai do Polygon cung cấp, có thể có giới hạn lưu lượng truy cập hoặc tỷ lệ. + URL này sẽ chỉ được sử dụng để kết nối với mạng thử nghiệm Polygon Mumbai. + Chúng tôi khuyến nghị nên nhận URL JSON-RPC qua một dịch vụ bên ngoài như Infura vì việc triển khai hợp đồng sẽ gửi nhiều truy vấn/yêu cầu đến JSON-RPC. + + +## Các cách xử lý chuyển nhượng token {#ways-of-processing-the-transfer-of-tokens} +Khi chuyển nhượng token ERC20 giữa các chuỗi, chúng có thể được xử lý theo hai chế độ khác nhau: + + +### Chế độ khóa/phát hành {#lock-release-mode} +Chuỗi nguồn: Các token bạn đang gửi sẽ được khóa trong Hợp đồng Handler.
+Chuỗi đích: Lượng token bạn đã gửi vào chuỗi nguồn sẽ được mở khóa và chuyển từ hợp đồng Handler sang tài khoản người nhận tại chuỗi đích. + +### Chế độ đốt/mint {#burn-mint-mode} +Chuỗi nguồn: Các token bạn đang gửi sẽ bị đốt.
Chuỗi đích: Lượng token bạn đã gửi và đốt trên chuỗi nguồn sẽ được mint trên chuỗi đích và gửi đến tài tài khoản người nhận. + +Bạn có thể dùng các chế độ khác nhau trên mỗi chuỗi. Nghĩa là, bạn có thể khóa token trên chuỗi chính trong quá trình mint token trên chuỗi con để chuyển nhượng. + Ví dụ: Nên khóa/phát hành token nếu tổng nguồn cung hoặc lịch mint token bị kiểm soát. + Token sẽ được mint/đốt nếu hợp đồng trong chuỗi con phải tuân thủ theo nguồn cung của chuỗi chính. + + +Chế độ mặc định là khóa/phát hành. Nếu bạn muốn chuyển Token về trạng thái có thể mint/đốt, bạn cần triển khai phương thức `adminSetBurnable`. + Nếu bạn muốn mint token trong quá trình thực thi, bạn sẽ cần chỉ định vai trò `minter` cho hợp đồng ERC20 Handler. + + + diff --git a/archive/edge/vi-edge/additional-features/chainbridge/overview.md b/archive/edge/vi-edge/additional-features/chainbridge/overview.md new file mode 100644 index 0000000000..2acb2e594c --- /dev/null +++ b/archive/edge/vi-edge/additional-features/chainbridge/overview.md @@ -0,0 +1,45 @@ +--- +id: overview +title: Tổng quan +description: Tổng quan về ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## ChainBridge là gì? {#what-is-chainbridge} + +ChainBridge là một cầu nối blockchain đa hướng dạng mô-đun, hỗ trợ các chuỗi tương thích EVM và Substrate, do ChainSafe xây dựng. + ChainBridge cho phép người dùng chuyển nhượng mọi loại tài sản hoặc thông điệp giữa hai chuỗi khác nhau. + + +Để tìm hiểu thêm về ChainBridge, tham khảo các [tài liệu chính thức](https://chainbridge.chainsafe.io/) do nhà phát triển cung cấp. + + +Hướng dẫn này nhằm giúp tích hợp Chainbridge vào Polygon Edge. + Hướng dẫn này đi vào việc thiết lập cầu nối giữa Polygon PoS (mạng thử nghiệm Mumbai) và mạng Polygon Edge cục bộ. + + +## Yêu cầu {#requirements} + +Trong hướng dẫn này, bạn sẽ chạy các nút Polygon Edge, một trình chuyển tiếp ChainBridge (xem thông tin chi tiết [tại đây](/docs/edge/additional-features/chainbridge/definitions)) cùng công cụ cb-sol-cli, một công cụ CLI dùng để triển khai các hợp đồng cục bộ, đăng ký tài nguyên và thay đổi cài đặt cho cầu nối (bạn cũng có thể xem thêm [tại đây](https://chainbridge.chainsafe.io/cli-options/#cli-options)). + Cần đảm bảo các môi trường sau đây khi cài đặt: + +* Go: >= 1.17 +* Node.js >= 16.13.0 +* Git + + +Ngoài ra, bạn sẽ cần sao chép các kho lưu trữ sau với các phiên bản để chạy một số ứng dụng. + + +* [Polygon Edge](https://github.com/0xPolygon/polygon-edge): trên nhánh `develop` +* [ChainBridge](https://github.com/ChainSafe/ChainBridge): v1.1.5 +* [Công cụ triển khai ChainBridge](https://github.com/ChainSafe/chainbridge-deploy): `f2aa093`trên nhánh +`main` + + +Bạn cần thiết lập mạng Polygon Edge trước khi chuyển sang phần tiếp theo. + Vui lòng kiểm tra phần [Cài đặt cục bộ](/docs/edge/get-started/set-up-ibft-locally) hoặc [Cài đặt đám mây](/docs/edge/get-started/set-up-ibft-on-the-cloud) để biết thêm chi tiết. diff --git a/archive/edge/vi-edge/additional-features/chainbridge/setup-erc20-transfer.md b/archive/edge/vi-edge/additional-features/chainbridge/setup-erc20-transfer.md new file mode 100644 index 0000000000..e49be78287 --- /dev/null +++ b/archive/edge/vi-edge/additional-features/chainbridge/setup-erc20-transfer.md @@ -0,0 +1,156 @@ +--- +id: setup-erc20-transfer +title: Chuyển nhượng Token ERC20 +description: Cách thiết lập giao dịch ERC-20 trên ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Hiện tại, chúng ta đã thiết lập cầu nối để trao đổi tài sản/dữ liệu giữa chuỗi Polygon PoS và Polygon Edge. + Phần này sẽ hướng dẫn bạn thiết lập cầu nối ERC20 và gửi token giữa các blockchain khác nhau. + + +## Bước 1: Đăng ký ID tài nguyên + {#step-1-register-resource-id} + +Đầu tiên, bạn cần đăng ký một ID tài nguyên có liên kết với các tài nguyên trong môi trường chuỗi chéo. + ID tài nguyên là một giá trị 32 byte duy nhất, gắn với tài nguyên mà chúng ta chuyển giữa các blockchain này. + Các ID tài nguyên là tùy ý, nhưng theo quy ước, chúng thường chứa ID chuỗi gốc của byte cuối cùng (chuỗi gốc là mạng lưới khởi nguồn của các tài nguyên này). + + +Để đăng ký ID tài nguyên, bạn có thể sử dụng lệnh `cb-sol-cli bridge register-resource`. Bạn sẽ cần cung cấp khóa riêng tư của tài tài khoản `admin`. + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC20 + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## (Không bắt buộc) Đưa hợp đồng về trạng thái có thể đốt/mint + {#optional-make-contracts-mintable-burnable} + + +```bash +# Let ERC20 contract burn on source chain and mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" + +# Grant minter role to ERC20 Handler contract +$ cb-sol-cli erc20 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --minter "[ERC20_HANDLER_CONTRACT_ADDRESS]" +``` + +## Bước 2: Chuyển nhượng Token ERC20 {#step-2-transfer-erc20-token} + +Chúng ta sẽ gửi Token ERC20 từ chuỗi Polygon PoS đến chuỗi Polygon Edge. + + +Đầu tiên, bạn sẽ nhận được token nhờ quá trình mint. + Tài khoản có vai trò `minter` có thể mint các token mới. + Tài khoản đã triển khai hợp đồng ERC20 sẽ giữ vai trò `minter` theo mặc định. + Để chỉ định vai trò thành viên của `minter` cho tài khoản khác, bạn cần chạy lệnh `cb-sol-cli erc20 add-minter`. + + +```bash +# Mint ERC20 tokens +$ cb-sol-cli erc20 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --amount 1000 +``` + +Để kiểm tra số dư hiện tại, bạn có thể sử dụng lệnh `cb-sol-cli erc20 balance`. + +```bash +# Check ERC20 token balance +$ cb-sol-cli erc20 balance \ + --url https://rpc-mumbai.matic.today \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 1000.0 +``` + +Tiếp theo, bạn cần phê duyệt việc chuyển token ERC20 từ tài khoản bằng ERC20 Handler + + +```bash +# Approve transfer from the account by ERC20 Handler +$ cb-sol-cli erc20 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [USER_ACCOUNT_ADDRESS] \ + --gasPrice [GAS_PRICE] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --recipient "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --amount 500 +``` + +Để chuyển token sang chuỗi Polygon Edge, bạn cần triển khai `deposit`. + + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Sau khi giao dịch ký quỹ được thực hiện thành công, trình chuyển tiếp sẽ nhận được sự kiện và tiến hành bỏ phiếu cho đề xuất. Trình chuyển tiếp sẽ thực thi một giao dịch để gửi token đến tài khoản người nhận trong chuỗi Polygon Edge sau khi có đủ số lượng phiếu bầu cần thiết. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Khi giao dịch được thực thi thành công, bạn sẽ nhận được token trong chuỗi Polygon Edge. + +```bash +# Check the ERC20 balance in Polygon Edge chain +$ cb-sol-cli erc20 balance \ + --url https://localhost:10002 \ + --privateKey [PRIVATE_KEY] \ + --erc20Address "[ERC20_CONTRACT_ADDRESS]" \ + --address "[ACCOUNT_ADDRESS]" + +[erc20/balance] Account has a balance of 10.0 +``` diff --git a/archive/edge/vi-edge/additional-features/chainbridge/setup-erc721-transfer.md b/archive/edge/vi-edge/additional-features/chainbridge/setup-erc721-transfer.md new file mode 100644 index 0000000000..8a5ea803db --- /dev/null +++ b/archive/edge/vi-edge/additional-features/chainbridge/setup-erc721-transfer.md @@ -0,0 +1,141 @@ +--- +id: setup-erc721-transfer +title: Giao dịch NFT ERC721 +description: Cách thiết lập giao dịch ERC721 trên ChainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +Phần này sẽ hướng dẫn bạn cách thiết lập cầu nối ERC721 và gửi NFT giữa các mạng blockchain. + + +## Bước 1: Đăng ký ID tài nguyên + {#step-1-register-resource-id} + +Trước tiên, bạn sẽ cần đăng ký ID tài nguyên dành cho token ERC721 trong Hợp đồng Bridge trên cả hai chuỗi. + + +```bash +# For Polygon PoS chain +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" + +# For Polygon Edge chain +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set ResourceID for ERC721 Token + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## (Không bắt buộc): Đưa hợp đồng về trạng thái có thể đốt/mint + {#optional-make-contracts-mintable-burnable} + +Để đưa hợp đồng về trạng thái có thể đốt/mint, bạn cần gọi các lệnh sau: + +```bash +# Let ERC721 contract burn on source chain or mint on destination chain +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" + +# Grant minter role to ERC721 Handler contract (Only if you want to mint) +$ cb-sol-cli erc721 add-minter \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --minter "[ERC721_HANDLER_CONTRACT_ADDRESS]" +``` + +## Bước 2: Giao dịch NFT {#step-2-transfer-nft} + +Trước tiên, bạn tiến hành mint một NFT nếu cần. + + +```bash +# Mint NFT 0x50 +$ cb-sol-cli erc721 mint \ + --url https://rpc-mumbai.matic.today \ + --privateKey [MINTER_ROLE_ACCOUNT] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Để kiểm tra chủ sở hữu NFT, bạn có thể sử dụng `cb-sol-cli erc721 owner` + +```bash +# Check the current owner of NFT +$ cb-sol-cli erc721 owner \ + --url https://rpc-mumbai.matic.today \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Sau đó, bạn cần phê duyệt giao dịch NFT bằng ERC721 Handler + + +```bash +# Approve transfer of the NFT 0x50 by ERC721 Handler +$ cb-sol-cli erc721 approve \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --recipient "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --id 0x50 +``` + +Cuối cùng, bạn bắt đầu tiến hành giao dịch + +```bash +# Start transfer from Polygon PoS to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --id 0x50 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" +``` + +Lớp chuyển tiếp sẽ nhận sự kiện và bỏ phiếu cho đề xuất. + Lớp chuyển tiếp sẽ thực thi một giao dịch để gửi NFT đến tài khoản người nhận trong chuỗi Polygon Edge sau khi có đủ số phiếu bầu cần thiết. + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Bạn có thể kiểm tra chủ sở hữu NFT trên mạng Polygon Edge sau khi hoàn tất quá trình thực thi. + +```bash +# Check the owner of NFT 0x50 in Polygon Edge chain +$ cb-sol-cli erc721 owner \ + --url http://localhost:10002 \ + --erc721Address "[ERC721_CONTRACT_ADDRESS]" \ + --id 0x50 +``` diff --git a/archive/edge/vi-edge/additional-features/chainbridge/setup.md b/archive/edge/vi-edge/additional-features/chainbridge/setup.md new file mode 100644 index 0000000000..cdc8a5f7c2 --- /dev/null +++ b/archive/edge/vi-edge/additional-features/chainbridge/setup.md @@ -0,0 +1,197 @@ +--- +id: setup +title: Thiết lập +description: Cách thiết lập chainBridge +keywords: + - docs + - polygon + - edge + - Bridge +--- + +## Triển khai hợp đồng {#contracts-deployment} + +Trong phần này, bạn sẽ triển khai các hợp đồng bắt buộc đối với chuỗi Polygon PoS và Polygon Edge bằng `cb-sol-cli`. + +```bash +# Setup for cb-sol-cli command +$ git clone https://github.com/ChainSafe/chainbridge-deploy.git +$ cd chainbridge-deploy/cb-sol-cli +$ make install +``` + +Đầu tiên, chúng ta sẽ triển khai các hợp đồng cho chuỗi Polygon PoS bằng lệnh `cb-sol-cli deploy`. Cờ `--all` tạo lệnh triển khai tất cả các hợp đồng, bao gồm Bridge, ERC20 Handler, ERC721 Handler, Generic Handler, ERC20 và ERC721. Ngoài ra, nó sẽ thiết lập địa chỉ tài khoản trình chuyển tiếp mặc định và ngưỡng + +```bash +# Deploy all required contracts into Polygon PoS chain +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + + +Tìm hiểu về URL chainID và JSON-RPC [tại đây](/docs/edge/additional-features/chainbridge/definitions) + +:::caution + +Giá gas mặc định trong `cb-sol-cli` là `20000000` (`0.02 Gwei`). Để thiết lập giá gas thích hợp cho giao dịch, vui lòng đặt giá trị bằng cách sử dụng đối số `--gasPrice`. + +```bash +$ cb-sol-cli deploy --all --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 \ + # Set gas price to 5 Gwei + --gasPrice 5000000000 +``` + +::: + +:::caution + +Hợp đồng Bridge mất khoảng 0x3f97b8 (4167608) gas để triển khai. Hãy đảm bảo rằng các khối được tạo có đủ giới hạn gas khối để chứa giao dịch tạo hợp đồng. Để tìm hiểu thêm về cách thay đổi giới hạn gas khối trong Polygon Edge, vui lòng truy cập mục [Thiết lập cục bộ](/docs/edge/get-started/set-up-ibft-locally) + +::: + +Khi các hợp đồng được triển khai, bạn sẽ nhận được kết quả sau: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed +✓ ERC721Handler contract deployed +✓ GenericHandler contract deployed +✓ ERC20 contract deployed +WARNING: Multiple definitions for safeTransferFrom +✓ ERC721 contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: +---------------------------------------------------------------- +Erc20: +---------------------------------------------------------------- +Erc721: +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +Giờ chúng ta có thể triển khai các hợp đồng đến chuỗi Polygon Edge. + +```bash +# Deploy all required contracts into Polygon Edge chain +$ cb-sol-cli deploy --all --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Lưu kết quả đầu cuối bằng các địa chỉ hợp đồng thông minh đã triển khai vì chúng ta sẽ cần chúng cho bước tiếp theo. + +## Thiết lập trình chuyển tiếp {#relayer-setup} + +Trong phần này, bạn sẽ khởi động một trình chuyển tiếp để trao đổi dữ liệu giữa 2 chuỗi. + +Đầu tiên, chúng ta cần nhân bản và xây dựng kho lưu trữ ChainBridge. + +```bash +$ git clone https://github.com/ChainSafe/ChainBridge.git +$ cd chainBridge && make install +``` + +Tiếp theo, bạn cần tạo `config.json`và thiết lập các URL JSON-RPC, địa chỉ trình chuyển tiếp và địa chỉ hợp đồng cho mỗi chuỗi. + +```json +{ + "chains": [ + { + "name": "mumbai", + "type": "ethereum", + "id": "99", + "endpoint": "https://rpc-mumbai.matic.today", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + }, + { + "name": "polygon-edge", + "type": "ethereum", + "id": "100", + "endpoint": "http://localhost:10002", + "from": "", + "opts": { + "bridge": "", + "erc20Handler": "", + "erc721Handler": "", + "genericHandler": "", + "minGasPrice": "1", + "http": "true" + } + } + ] +} +``` + +Để khởi động trình chuyển tiếp, bạn cần nhập khóa riêng tương ứng với địa chỉ tài khoản của trình chuyển tiếp. Bạn sẽ cần nhập mật khẩu khi nhập khóa riêng tư. Sau khi nhập thành công, khóa sẽ được lưu trữ trong `keys/
.key`. + +```bash +# Import private key and store to local with encryption +$ chainbridge accounts import --privateKey [RELAYER_ACCOUNT_PRIVATE_KEY] + +INFO[11-19|07:09:01] Importing key... +Enter password to encrypt keystore file: +> [PASSWORD_TO_ENCRYPT_KEY] +INFO[11-19|07:09:05] private key imported address= file=.../keys/.key +``` + +Sau đó, bạn có thể bắt đầu trình chuyển tiếp. Bạn sẽ cần phải nhập cùng một mật khẩu mà bạn đã chọn để lưu trữ khóa lúc đầu. + +```bash +# Start relayer +$ chainbridge --config config.json --latest + +INFO[11-19|07:15:19] Starting ChainBridge... +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:25] Connecting to ethereum chain... chain=mumbai url= +Enter password for key ./keys/.key: +> [PASSWORD_TO_DECRYPT_KEY] +INFO[11-19|07:15:31] Connecting to ethereum chain... chain=polygon-edge url= +``` + +Khi trình chuyển tiếp đã chạy, nó sẽ bắt đầu theo dõi các khối mới trên mỗi chuỗi. diff --git a/archive/edge/vi-edge/additional-features/chainbridge/use-case-erc20-bridge.md b/archive/edge/vi-edge/additional-features/chainbridge/use-case-erc20-bridge.md new file mode 100644 index 0000000000..26bee2806c --- /dev/null +++ b/archive/edge/vi-edge/additional-features/chainbridge/use-case-erc20-bridge.md @@ -0,0 +1,256 @@ +--- +id: use-case-erc20-bridge +title: Trường hợp sử dụng - Bridge ERC20 +description: Ví dụ để bắc cầu hợp đồng ERC20 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC20 +--- + +Phần này nhằm mục đích cung cấp cho bạn quy trình thiết lập của Bridge ERC20 cho tình huống sử dụng thực tế. + +Trong hướng dẫn này, bạn sẽ sử dụng mạng thử nghiệm Polygon PoS Mumbai và chuỗi cục bộ Polygon Edge. Hãy đảm bảo bạn có điểm cuối JSON-RPC dành cho Mumbai và bạn đã thiết lập Polygon Edge trong môi trường cục bộ. Vui lòng tham khảo [Thiết lập cục bộ](/docs/edge/get-started/set-up-ibft-locally) hoặc [Thiết lập đám mây](/docs/edge/get-started/set-up-ibft-on-the-cloud) để biết thêm chi tiết. + +## Tình huống {#scenario} + +Tình huống này là thiết lập Bridge cho token ERC20 đã được triển khai trong chuỗi công khai (Polygon PoS) để cho phép quá trình chuyển nhượng chi phí thấp trong chuỗi riêng (Polygon Edge) dành cho người dùng trong tình huống thông thường. Trong trường hợp đó, tổng nguồn cung token đã được xác định trong chuỗi công khai và chỉ số lượng token đã được chuyển từ chuỗi công khai sang chuỗi riêng phải tồn tại trong chuỗi riêng. Vì vậy, bạn sẽ cần sử dụng chế độ khóa/phát hành trong chuỗi công khai và chế độ đốt/mint trong chuỗi riêng tư. + +Khi gửi token từ chuỗi công khai sang chuỗi riêng, token sẽ bị khóa theo hợp đồng ERC20 Handler của chuỗi công khai và lượng token tương ứng sẽ được mint trong chuỗi riêng. Mặt khác, trong trường hợp chuyển nhượng từ chuỗi riêng sang chuỗi công khai, token trong chuỗi riêng sẽ bị đốt và lượng token tương ứng sẽ được phát hành từ hợp đồng ERC20 Handler trong chuỗi công khai. + +## Hợp đồng {#contracts} + +Giải thích bằng hợp đồng ERC20 đơn giản thay vì hợp đồng do ChainBridge phát triển. Đối với chế độ đốt/mint, hợp đồng ERC20 phải có phương thức `mint` và `burnFrom` ngoài các phương pháp cho ERC20 như thế này: + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; + +contract SampleToken is ERC20, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + constructor(string memory name, string memory symbol) ERC20(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + } + + function mint(address recipient, uint256 amount) + external + onlyRole(MINTER_ROLE) + { + _mint(recipient, amount); + } + + function burnFrom(address owner, uint256 amount) + external + onlyRole(BURNER_ROLE) + { + _burn(owner, amount); + } +} +``` + +Tất cả các mã và tập lệnh đều có trong Github Repo [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Bước 1: Triển khai Bridge và các hợp đồng ERC20 Handler {#step1-deploy-bridge-and-erc20-handler-contracts} + +Đầu tiên, bạn sẽ triển khai các hợp đồng Bridge và ERC20 Handler bằng `cb-sol-cli` trong cả hai chuỗi. + +```bash +# Deploy Bridge and ERC20 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC20 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc20Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Bạn sẽ nhận được các địa chỉ hợp đồng Bridge và ERC20Handler như sau: + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC20Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: +---------------------------------------------------------------- +Erc721 Handler: Not Deployed +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Bước 2: Triển khai hợp đồng ERC20 của bạn {#step2-deploy-your-erc20-contract} + +Bạn sẽ triển khai hợp đồng ERC20 của mình. Ví dụ này sẽ hướng dẫn bạn về dự án hardhat [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Vui lòng tạo tệp `.env` và thiết lập các giá trị sau. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Tiếp theo, bạn sẽ cần triển khai hợp đồng ERC20 trong cả hai chuỗi. + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc20 --name --symbol --network edge +``` + +Sau khi triển khai thành công, bạn sẽ nhận địa chỉ hợp đồng như sau: + +```bash +ERC20 contract has been deployed +Address: +Name: +Symbol: +``` + +## Bước 3: Đăng ký ID tài nguyên trong Bridge {#step3-register-resource-id-in-bridge} + +Bạn sẽ cần đăng ký một ID tài nguyên liên kết với tài nguyên trong môi trường chuỗi chéo. Bạn cần thiết lập cùng một ID tài nguyên trong cả hai chuỗi. + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC20_CONTRACT_ADDRESS]" +``` + +## Bước 4: Thiết lập chế độ Mint/Đốt cho cầu nối ERC20 của Edge {#step4-set-mint-burn-mode-in-erc20-bridge-of-the-edge} + +Bridge mong muốn hoạt động như chế độ đốt/mint trong Polygon Edge. Bàn sẽ thiết lập chế độ đốt/mint bằng `cb-sol-cli`. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC20_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC20_CONTRACT_ADDRESS]" +``` + +Và bạn cần cấp vai trò mint và đốt cho hợp đồng ERC20 Handler. + +```bash +$ npx hardhat grant --role mint --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Bước 5: Mint token {#step5-mint-token} + +Bạn sẽ mint token ERC20 mới trong chuỗi Mumbai. + +```bash +$ npx hardhat mint --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --amount 100000000000000000000 --network mumbai # 100 Token +``` + +Sau khi giao dịch thành công, tài khoản sẽ có token được mint. + +## Bước 6: Bắt đầu chuyển nhượng ERC20 {#step6-start-erc20-transfer} + +Trước khi bắt đầu bước này, vui lòng đảm bảo rằng bạn đã khởi động trình chuyển tiếp. Vui lòng kiểm tra mục [Thiết lập](/docs/edge/additional-features/chainbridge/setup) để biết thêm chi tiết. + +Trong quá trình chuyển token từ Mumbai sang Edge, hợp đồng ERC20 Handler ở Mumbai sẽ rút token từ tài khoản của bạn. Bạn sẽ gọi mục phê duyệt trước khi chuyển nhượng. + +```bash +$ npx hardhat approve --type erc20 --contract [ERC20_CONTRACT_ADDRESS] --address [ERC20_HANDLER_CONTRACT_ADDRESS] --amount 10000000000000000000 --network mumbai # 10 Token +``` + +Cuối cùng, bạn sẽ bắt đầu chuyển token từ Mumbai sang Edge bằng `cb-sol-cli`. + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc20 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --amount 10 \ + # ChainID of Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00" +``` + +Sau khi giao dịch nạp tiền thành công, trình chuyển tiếp sẽ nhận được sự kiện và bỏ phiếu cho đề xuất. Nó thực thi một giao dịch để gửi token đến tài khoản người nhận trong chuỗi Polygon Edge sau khi đã nộp đủ số phiếu bầu cần thiết. + +```bash +INFO[11-19|08:15:58] Handling fungible deposit event chain=mumbai dest=100 nonce=1 +INFO[11-19|08:15:59] Attempting to resolve message chain=polygon-edge type=FungibleTransfer src=99 dst=100 nonce=1 rId=000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00 +INFO[11-19|08:15:59] Creating erc20 proposal chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Watching for finalization event chain=polygon-edge src=99 nonce=1 +INFO[11-19|08:15:59] Submitted proposal vote chain=polygon-edge tx=0x67a97849951cdf0480e24a95f59adc65ae75da23d00b4ab22e917a2ad2fa940d src=99 depositNonce=1 gasPrice=1 +INFO[11-19|08:16:24] Submitted proposal execution chain=polygon-edge tx=0x63615a775a55fcb00676a40e3c9025eeefec94d0c32ee14548891b71f8d1aad1 src=99 dst=100 nonce=1 gasPrice=5 +``` + +Khi giao dịch thực thi thành công, bạn sẽ nhận được các token trong chuỗi Polygon Edge. diff --git a/archive/edge/vi-edge/additional-features/chainbridge/use-case-erc721-bridge.md b/archive/edge/vi-edge/additional-features/chainbridge/use-case-erc721-bridge.md new file mode 100644 index 0000000000..130ba5ac66 --- /dev/null +++ b/archive/edge/vi-edge/additional-features/chainbridge/use-case-erc721-bridge.md @@ -0,0 +1,325 @@ +--- +id: use-case-erc721-bridge +title: Trường hợp sử dụng - Cầu nối ERC721 +description: Ví dụ về Hợp đồng Cầu nối ERC721 +keywords: + - docs + - polygon + - edge + - Bridge + - ERC721 +--- + +Phần này nhằm hướng dẫn quy trình thiết lập của Cầu nối ERC721 trong thực tế. + +Trong hướng dẫn này, bạn sẽ sử dụng mạng thử nghiệm Polygon PoS Mumbai và chuỗi cục bộ Polygon Edge. Hãy đảm bảo bạn có điểm cuối JSON-RPC dành cho Mumbai và bạn đã thiết lập Polygon Edge trong môi trường cục bộ. Vui lòng tham khảo [Thiết lập cục bộ](/docs/edge/get-started/set-up-ibft-locally) hoặc [Thiết lập đám mây](/docs/edge/get-started/set-up-ibft-on-the-cloud) để biết thêm chi tiết. + +## Tình huống {#scenario} + +Tình huống này đề cập đến việc thiết lập Cầu nối cho NFT ERC721, vốn được triển khai trong chuỗi công khai (Polygon PoS), nhằm hỗ trợ chuyển nhượng chi phí thấp trong chuỗi riêng (Polygon Edge) dành cho người dùng trong trường hợp thông thường. + Trong trường hợp này, siêu dữ liệu ban đầu đã được xác định trong chuỗi công khai và chỉ các NFT được chuyển nhượng từ chuỗi Công khai có thể tồn tại trong chuỗi riêng. + Vì vậy, bạn sẽ cần sẽ cần sử dụng chế độ khóa/phát hành trong chuỗi công khai và chế độ đốt/mint trong chuỗi riêng. + + +Khi gửi NFT từ chuỗi công khai sang chuỗi riêng, NFT sẽ bị khóa theo Hợp đồng ERC721 Handler trong chuỗi công khai và NFT tương ứng sẽ được mint trong chuỗi riêng. + Mặt khác, trong trường hợp chuyển nhượng từ chuỗi riêng sang chuỗi công khai, NFT trong chuỗi riêng sẽ bị đốt và NFT tương ứng sẽ được phát hành từ hợp đồng ERC721 Handler trong chuỗi công khai. + + +## Hợp đồng {#contracts} + +Giải thích bằng hợp đồng ERC721 đơn giản thay vì hợp đồng do ChainBridge phát triển. + Đối với chế độ đốt/mint, ngoài các phương thức được định nghĩa trong ERC721, hợp đồng ERC721 phải có phương thức `mint`và `burn`như sau: + + +```sol +pragma solidity ^0.8.14; + +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; +import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; + +contract SampleNFT is ERC721, ERC721Burnable, ERC721URIStorage, AccessControl { + bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); + bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); + + string public baseURI; + + constructor( + string memory name, + string memory symbol, + string memory baseURI + ) ERC721(name, symbol) { + _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); + _setupRole(MINTER_ROLE, _msgSender()); + _setupRole(BURNER_ROLE, _msgSender()); + + _setBaseURI(baseURI); + } + + function mint( + address recipient, + uint256 tokenID, + string memory data + ) public onlyRole(MINTER_ROLE) { + _mint(recipient, tokenID); + _setTokenURI(tokenID, data); + } + + function burn(uint256 tokenID) + public + override(ERC721Burnable) + onlyRole(BURNER_ROLE) + { + _burn(tokenID); + } + + function tokenURI(uint256 tokenId) + public + view + virtual + override(ERC721, ERC721URIStorage) + returns (string memory) + { + return super.tokenURI(tokenId); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(ERC721, AccessControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } + + function _burn(uint256 tokenId) + internal + virtual + override(ERC721, ERC721URIStorage) + { + super._burn(tokenId); + } + + function _setBaseURI(string memory baseURI_) internal { + baseURI = baseURI_; + } + + function _baseURI() internal view virtual override returns (string memory) { + return baseURI; + } +} +``` + +Tất cả các mã và tập lệnh đều có trong Github Repo [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + +## Bước 1: Triển khai các hợp đồng Bridge và ERC721 Handler {#step1-deploy-bridge-and-erc721-handler-contracts} + +Đầu tiên, bạn sẽ triển khai các hợp đồng Bridge và ERC721 Handler bằng `cb-sol-cli`trong cả hai chuỗi. + +```bash +# Deploy Bridge and ERC721 contracts in Polygon PoS chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 99 \ + --url https://rpc-mumbai.matic.today \ + --gasPrice [GAS_PRICE] \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +```bash +# Deploy Bridge and ERC721 contracts in Polygon Edge chain +$ cb-sol-cli deploy --bridge --erc721Handler --chainId 100 \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --relayers [RELAYER_ACCOUNT_ADDRESS] \ + --relayerThreshold 1 +``` + +Bạn sẽ nhận được các địa chỉ hợp đồng Bridge và ERC721 Handler như sau: + + +```bash +Deploying contracts... +✓ Bridge contract deployed +✓ ERC721Handler contract deployed + +================================================================ +Url: https://rpc-mumbai.matic.today +Deployer: +Gas Limit: 8000000 +Gas Price: 20000000 +Deploy Cost: 0.00029065308 + +Options +======= +Chain Id: +Threshold: +Relayers: +Bridge Fee: 0 +Expiry: 100 + +Contract Addresses +================================================================ +Bridge: +---------------------------------------------------------------- +Erc20 Handler: Not Deployed +---------------------------------------------------------------- +Erc721 Handler: +---------------------------------------------------------------- +Generic Handler: Not Deployed +---------------------------------------------------------------- +Erc20: Not Deployed +---------------------------------------------------------------- +Erc721: Not Deployed +---------------------------------------------------------------- +Centrifuge Asset: Not Deployed +---------------------------------------------------------------- +WETC: Not Deployed +================================================================ +``` + +## Bước 2: Triển khai Hợp đồng ERC721 của bạn {#step2-deploy-your-erc721-contract} + +Bạn sẽ triển khai Hợp đồng ERC721. Ví dụ này sẽ hướng dẫn bạn về dự án hardhat [Trapesys/chainbridge-example](https://github.com/Trapesys/chainbridge-example). + + +```bash +$ git clone https://github.com/Trapesys/chainbridge-example.git +$ cd chainbridge-example +$ npm i +``` + +Hãy tạo tệp `.env` và thiết lập các giá trị sau. + +```.env +PRIVATE_KEYS=0x... +MUMBAI_JSONRPC_URL=https://rpc-mumbai.matic.today +EDGE_JSONRPC_URL=http://localhost:10002 +``` + +Tiếp theo, bạn sẽ triển khai hợp đồng ERC721 trong cả hai chuỗi. + + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network mumbai +``` + +```bash +$ npx hardhat deploy --contract erc721 --name --symbol --uri --network edge +``` + +Sau khi triển khai thành công, bạn sẽ nhận địa chỉ hợp đồng như sau: + +```bash +ERC721 contract has been deployed +Address: +Name: +Symbol: +Base URI: +``` + +## Bước 3: Đăng ký ID tài nguyên trong Bridge {#step3-register-resource-id-in-bridge} + +Bạn sẽ đăng ký một ID tài nguyên liên kết với các tài nguyên trong môi trường chuỗi chéo. + + +```bash +$ cb-sol-cli bridge register-resource \ + --url https://rpc-mumbai.matic.today \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +```bash +$ cb-sol-cli bridge register-resource \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + # Set Resource ID for ERC721 + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --targetContract "[ERC721_CONTRACT_ADDRESS]" +``` + +## Bước 4: Thiết lập chế độ Đúc/Mint cho cầu nối ERC721 của Edge {#step4-set-mint-burn-mode-in-erc721-bridge-of-the-edge} + +Bridge dự kiến ​​sẽ hoạt động ở chế độ đốt/mint trong Edge. + Bạn sẽ thiết lập chế độ đốt/mint. + +```bash +$ cb-sol-cli bridge set-burn \ + --url http://localhost:10002 \ + --privateKey [ADMIN_ACCOUNT_PRIVATE_KEY] \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --handler "[ERC721_HANDLER_CONTRACT_ADDRESS]" \ + --tokenContract "[ERC721_CONTRACT_ADDRESS]" +``` + +Và bạn cần cấp quyền mint và đốt cho hợp đồng ERC721 Handler. + + +```bash +$ npx hardhat grant --role mint --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +$ npx hardhat grant --role burn --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --network edge +``` + +## Bước 5: Mint NFT {#step5-mint-nft} + +Bạn sẽ tiến hành mint NFT ERC721 mới trong chuỗi Mumbai. + + +```bash +$ npx hardhat mint --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ACCOUNT_ADDRESS] --id 0x50 --data hello.json --network mumbai +``` + +Sau khi giao dịch thành công, tài khoản sẽ nhận được NFT đã mint. + +## Bước 6: Bắt đầu giao dịch ERC721 {#step6-start-erc721-transfer} + +Trước khi bắt đầu bước này, hãy đảm bảo rằng bạn đã kích hoạt trình chuyển tiếp. + Vui lòng kiểm tra mục [Thiết lập](/docs/edge/additional-features/chainbridge/setup) để biết thêm chi tiết. + +Trong quá trình chuyển NFT từ Mumbai sang Edge, hợp đồng ERC721 Hanlder ở Mumbai sẽ rút NFT khỏi tài khoản của bạn. + Bạn sẽ gọi mục phê duyệt trước khi chuyển nhượng. + +```bash +$ npx hardhat approve --type erc721 --contract [ERC721_CONTRACT_ADDRESS] --address [ERC721_HANDLER_CONTRACT_ADDRESS] --id 0x50 --network mumbai +``` + +Cuối cùng, bạn tiến hành chuyển NFT từ Mumbai sang Edge. + + +```bash +# Start transfer from Mumbai to Polygon Edge chain +$ cb-sol-cli erc721 deposit \ + --url https://rpc-mumbai.matic.today \ + --privateKey [PRIVATE_KEY] \ + --gasPrice [GAS_PRICE] \ + --id 0x50 \ + # ChainID for Polygon Edge chain + --dest 100 \ + --bridge "[BRIDGE_CONTRACT_ADDRESS]" \ + --recipient "[RECIPIENT_ADDRESS_IN_POLYGON_EDGE_CHAIN]" \ + --resourceId "0x000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501" +``` + +Sau khi giao dịch nạp tiền thành công, trình chuyển tiếp sẽ nhận được sự kiện và bỏ phiếu cho đề xuất. Trình chuyển tiếp sẽ thực thi một giao dịch để gửi NFT đến tài khoản người nhận trong chuỗi Polygon Edge sau khi nộp đủ số lượng phiếu bầu cần thiết. + + +```bash +INFO[11-19|09:07:50] Handling nonfungible deposit event chain=mumbai +INFO[11-19|09:07:50] Attempting to resolve message chain=polygon-edge type=NonFungibleTransfer src=99 dst=100 nonce=2 rId=000000000000000000000000000000e389d61c11e5fe32ec1735b3cd38c69501 +INFO[11-19|09:07:50] Creating erc721 proposal chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Watching for finalization event chain=polygon-edge src=99 nonce=2 +INFO[11-19|09:07:50] Submitted proposal vote chain=polygon-edge tx=0x58a22d84a08269ad2e8d52d8dc038621f1a21109d11c7b6e0d32d5bf21ea8505 src=99 depositNonce=2 gasPrice=1 +INFO[11-19|09:08:15] Submitted proposal execution chain=polygon-edge tx=0x57419844881a07531e31667c609421662d94d21d0709e64fb728138309267e68 src=99 dst=100 nonce=2 gasPrice=3 +``` + +Sau khi thực thi giao dịch thành công, bạn sẽ nhận được NFT trong chuỗi Polygon Edge. diff --git a/archive/edge/vi-edge/additional-features/permission-contract-deployment.md b/archive/edge/vi-edge/additional-features/permission-contract-deployment.md new file mode 100644 index 0000000000..942a1c4fec --- /dev/null +++ b/archive/edge/vi-edge/additional-features/permission-contract-deployment.md @@ -0,0 +1,97 @@ +--- +id: permission-contract-deployment +title: Quyền triển khai hợp đồng thông minh + +description: Cách thêm quyền triển khai hợp đồng thông minh. + +keywords: + - docs + - polygon + - edge + - smart contract + - permission + - deployment +--- + +## Tổng quan {#overview} + +Hướng dẫn này đi vào chi tiết về cách lập danh sách trắng cho các địa chỉ có thể triển khai hợp đồng thông minh. + Đôi khi các trình vận hành mạng sẽ ngăn người dùng triển khai các hợp đồng thông minh nếu không liên quan đến mục đích của mạng. + Trình vận hành mạng có thể: + +1. Đưa các địa chỉ vào danh sách trắng để triển khai Hợp đồng thông minh + +2. Xóa địa chỉ khỏi danh sách trắng triển khai Hợp đồng thông minh + + +## Trình soạn tin Video {#video-presentation} + +[![Việc triển khai hợp đồng cho phép - video](https://img.youtube.com/vi/yPOkINpf7hg/0.jpg)](https://www.youtube.com/watch?v=yPOkINpf7hg) + +## Cách sử dụng? {#how-to-use-it} + + +Bạn có thể tìm thấy tất cả các lệnh cli liên quan đến danh sách trắng triển khai trong trang [Lệnh CLI](/docs/edge/get-started/cli-commands#whitelist-commands). + +* `whitelist show`: Hiển thị thông tin danh sách trắng +* `whitelist deployment --add`: Thêm một địa chỉ mới vào danh sách trắng triển khai hợp đồng +* `whitelist deployment --remove`: Xóa một địa chỉ mới khỏi danh sách trắng triển khai hợp đồng + +#### Hiển thị tất cả các địa chỉ trong danh sách trắng triển khai {#show-all-addresses-in-the-deployment-whitelist} + +Có 2 cách để tìm địa chỉ trong danh sách trắng triển khai. +1. Tìm trong `genesis.json`, nơi lưu danh sách trắng +2. Triển khai `whitelist show`, giúp in thông tin của tất cả các danh sách trắng được Polygon Edge hỗ trợ + + +```bash + +./polygon-edge whitelist show + +[WHITELISTS] + +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d], + + +``` + +#### Thêm địa chỉ vào danh sách trắng triển khai {#add-an-address-to-the-deployment-whitelist} + +Để thêm một địa chỉ mới vào danh sách trắng triển khai, thực thi lệnh CLI `whitelist deployment --add [ADDRESS]`. Số lượng địa chỉ trong danh sách trắng là không giới hạn. Chỉ có địa chỉ nằm trong danh sách trắng triển khai hợp đồng mới có thể triển khai hợp đồng. + Nếu danh sách trắng trống, bất kỳ địa chỉ nào cũng có thể thực hiện quá trình triển khai + + +```bash + +./polygon-edge whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --add 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Added addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], + + + +``` + +#### Xóa một địa chỉ khỏi danh sách trắng triển khai + {#remove-an-address-from-the-deployment-whitelist} + +Để xóa bỏ địa chỉ khỏi danh sách trắng triển khai, thực thi lệnh CLI `whitelist deployment --remove [ADDRESS]`. Chỉ có địa chỉ nằm trong danh sách trắng triển khai hợp đồng mới có thể triển khai hợp đồng. + Nếu danh sách trắng trống, bất kỳ địa chỉ nào cũng có thể thực hiện quá trình triển khai + + +```bash + +./polygon-edge whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d --remove 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF + + +[CONTRACT DEPLOYMENT WHITELIST] + +Removed addresses: [0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d 0x30ea4435167Ee91f9f874b5a894F3282A956C3FF], +Contract deployment whitelist : [], + + + +``` diff --git a/archive/edge/vi-edge/architecture/modules/blockchain.md b/archive/edge/vi-edge/architecture/modules/blockchain.md new file mode 100644 index 0000000000..125974b9ac --- /dev/null +++ b/archive/edge/vi-edge/architecture/modules/blockchain.md @@ -0,0 +1,156 @@ +--- +id: blockchain +title: Blockchain +description: Giải thích về các mô-đun blockchain và trạng thái của Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - blockchain + - state +--- + +## Tổng quan {#overview} + +Một trong những mô-đun chính của Polygon Edge là **Blockchain** và **State**.
+ +**Blockchain** là công cụ xử lý các tổ chức lại khối. Điều này có nghĩa là nó xử lý tất cả các logic xảy ra khi một khối mới được đưa vào blockchain. + +**State** biểu diễn đối tượng *chuyển tiếp trạng thái*. Nó xử lý cách trạng thái thay đổi khi một khối mới được đưa vào.
Trong số những thứ khác, **State** xử lý: +* Thực thi các giao dịch +* Thực thi EVM +* Thay đổi các Merkle Trie +* Thông tin chi tiết được đề cập trong phần **State** tương ứng 🙂 + +Điểm mấu chốt là 2 phần này kết nối và phối hợp chặt chẽ với nhau để máy khách hoạt động.
Ví dụ, khi lớp **Blockchain** nhận được một khối mới (và không có sự sắp xếp lại xảy ra), nó sẽ gọi **State** để thực hiện chuyển tiếp trạng thái. + +**Blockchain** cũng phải xử lý một số phần liên quan đến sự đồng thuận (ví dụ: *ethHash này có đúng không?*, *PoW này có đúng không?*).
Tóm lại, blockchain **là cốt lõi chính của logic mà thông qua đó, tất cả các khối được kết hợp**. + +## *WriteBlocks* + +Một trong những phần quan trọng nhất liên quan đến lớp **Blockchain** là phương phức *WriteBlocks*: + +````go title="blockchain/blockchain.go" +// WriteBlocks writes a batch of blocks +func (b *Blockchain) WriteBlocks(blocks []*types.Block) error { + if len(blocks) == 0 { + return fmt.Errorf("no headers found to insert") + } + + parent, ok := b.readHeader(blocks[0].ParentHash()) + if !ok { + return fmt.Errorf("parent of %s (%d) not found: %s", blocks[0].Hash().String(), blocks[0].Number(), blocks[0].ParentHash()) + } + + // validate chain + for i := 0; i < len(blocks); i++ { + block := blocks[i] + + if block.Number()-1 != parent.Number { + return fmt.Errorf("number sequence not correct at %d, %d and %d", i, block.Number(), parent.Number) + } + if block.ParentHash() != parent.Hash { + return fmt.Errorf("parent hash not correct") + } + if err := b.consensus.VerifyHeader(parent, block.Header, false, true); err != nil { + return fmt.Errorf("failed to verify the header: %v", err) + } + + // verify body data + if hash := buildroot.CalculateUncleRoot(block.Uncles); hash != block.Header.Sha3Uncles { + return fmt.Errorf("uncle root hash mismatch: have %s, want %s", hash, block.Header.Sha3Uncles) + } + + if hash := buildroot.CalculateTransactionsRoot(block.Transactions); hash != block.Header.TxRoot { + return fmt.Errorf("transaction root hash mismatch: have %s, want %s", hash, block.Header.TxRoot) + } + parent = block.Header + } + + // Write chain + for indx, block := range blocks { + header := block.Header + + body := block.Body() + if err := b.db.WriteBody(header.Hash, block.Body()); err != nil { + return err + } + b.bodiesCache.Add(header.Hash, body) + + // Verify uncles. It requires to have the bodies on memory + if err := b.VerifyUncles(block); err != nil { + return err + } + // Process and validate the block + if err := b.processBlock(blocks[indx]); err != nil { + return err + } + + // Write the header to the chain + evnt := &Event{} + if err := b.writeHeaderImpl(evnt, header); err != nil { + return err + } + b.dispatchEvent(evnt) + + // Update the average gas price + b.UpdateGasPriceAvg(new(big.Int).SetUint64(header.GasUsed)) + } + + return nil +} +```` +Phương thức *WriteBlocks* là điểm vào để ghi các khối vào blockchain. Là một tham số, nó hiện diện trong một loạt các khối.
Đầu tiên, các khối được xác thực. Sau đó, chúng được ghi vào chuỗi. + +Quá trình *chuyển tiếp trạng thái* thực tế được thực hiện bằng cách gọi phương thức *processBlock* trong *WriteBlocks*. + +Điều đáng nói là vì đây là điểm đầu vào để ghi các khối vào blockchain, các mô-đun khác (chẳng hạn như **Sealer**) sử dụng phương pháp này. + +## Đăng ký Blockchain {#blockchain-subscriptions} + +Cần phải có một cách để theo dõi các thay đổi liên quan đến blockchain.
Đây là lúc cần đến **Subscriptions**. + +Đăng ký là một cách để khai thác các luồng sự kiện blockchain và ngay lập tức nhận được dữ liệu có ý nghĩa. + +````go title="blockchain/subscription.go" +type Subscription interface { + // Returns a Blockchain Event channel + GetEventCh() chan *Event + + // Returns the latest event (blocking) + GetEvent() *Event + + // Closes the subscription + Close() +} +```` + +**Sự kiện Blockchain** chứa thông tin liên quan đến bất kỳ thay đổi nào được thực hiện trên chuỗi thực tế. Điều này bao gồm các tổ chức lại, cũng như các khối mới: + +````go title="blockchain/subscription.go" +type Event struct { + // Old chain removed if there was a reorg + OldChain []*types.Header + + // New part of the chain (or a fork) + NewChain []*types.Header + + // Difficulty is the new difficulty created with this event + Difficulty *big.Int + + // Type is the type of event + Type EventType + + // Source is the source that generated the blocks for the event + // right now it can be either the Sealer or the Syncer. TODO + Source string +} +```` + +:::tip Ôn tập +Bạn có nhớ khi chúng tôi đề cập đến lệnh ***giám sát*** trong [Lệnh CLI](/docs/edge/get-started/cli-commands) không? + +Sự kiện Blockchain là những sự kiện ban đầu xảy ra trong Polygon Edge và sau đó chúng được ánh xạ tới định dạng thông báo Bộ đệm giao thức để dễ dàng chuyển giao. +::: \ No newline at end of file diff --git a/archive/edge/vi-edge/architecture/modules/consensus.md b/archive/edge/vi-edge/architecture/modules/consensus.md new file mode 100644 index 0000000000..589919d0e7 --- /dev/null +++ b/archive/edge/vi-edge/architecture/modules/consensus.md @@ -0,0 +1,493 @@ +--- +id: consensus +title: Đồng thuận +description: Giải thích về mô-đun đồng thuận của Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - consensus + - ibft +--- + +## Tổng quan {#overview} + +Mô-đun **Consensus** (Đồng thuận) cung cấp giao diện cho các cơ chế đồng thuận. + +Hiện tại, có sẵn các công cụ đồng thuận sau: +* **IBFT PoA** +* **IBFT PoS** + +Polygon Edge muốn duy trì trạng thái mô-đun và khả năng cắm thêm.
Đây là lý do logic đồng thuận cốt lõi đã bị trừu tượng hóa, nên các cơ chế đồng thuận mới có thể được xây dựng trên cơ sở đó mà không ảnh hưởng đến khả năng sử dụng và dễ sử dụng. + +## Giao diện Consensus {#consensus-interface} + +````go title="consensus/consensus.go" +// Consensus is the interface for consensus +type Consensus interface { + // VerifyHeader verifies the header is correct + VerifyHeader(parent, header *types.Header) error + + // Start starts the consensus + Start() error + + // Close closes the connection + Close() error +} +```` + +Giao diện ***Consensus*** là cốt lõi của sự trừu tượng được đề cập.
+* Phương thức **VerifyHeader** đại diện cho chức năng của trình trợ giúp mà lớp đồng thuận hiển thị cho lớp **blockchain** Nó ở đó để xử lý xác minh tiêu đề +* Phương thức **Start** chỉ đơn giản là bắt đầu quá trình đồng thuận và mọi thứ liên quan đến nó. Điều này gồm quá trình đồng bộ, niêm phong và thực hiện mọi thứ cần thiết +* Phương thức **Close** đóng kết nối đồng thuận + +## Cấu hình đồng thuận {#consensus-configuration} + +````go title="consensus/consensus.go" +// Config is the configuration for the consensus +type Config struct { + // Logger to be used by the backend + Logger *log.Logger + + // Params are the params of the chain and the consensus + Params *chain.Params + + // Specific configuration parameters for the backend + Config map[string]interface{} + + // Path for the consensus protocol to store information + Path string +} +```` + +Đôi khi bạn có thể muốn chuyển đến một vị trí tùy chỉnh để giao thức đồng thuận lưu trữ dữ liệu hoặc có thể một bản đồ khóa-giá trị tùy chỉnh mà bạn muốn cơ chế đồng thuận sử dụng. Có thể đạt được điều này thông qua cấu trúc ***Config***, được đọc khi một phiên bản đồng thuận mới được tạo. + +## IBFT {#ibft} + +### ExtraData {#extradata} + +Đối tượng tiêu đề blockchain, trong số các trường khác, có một trường được gọi là **ExtraData**. + +IBFT sử dụng trường bổ sung này để lưu trữ thông tin vận hành liên quan đến khối, trả lời các câu hỏi như: +* "Ai ký khối này?" +* "Ai là người xác thực cho khối này?" + +Các trường bổ sung cho IBFT này được định nghĩa như sau: +````go title="consensus/ibft/extra.go" +type IstanbulExtra struct { + Validators []types.Address + Seal []byte + CommittedSeal [][]byte +} +```` + +### Dữ liệu ký {#signing-data} + +Để nút ký thông tin trong IBFT, nó sử dụng phương thức *signHash*: +````go title="consensus/ibft/sign.go" +func signHash(h *types.Header) ([]byte, error) { + //hash := istambulHeaderHash(h) + //return hash.Bytes(), nil + + h = h.Copy() // make a copy since we update the extra field + + arena := fastrlp.DefaultArenaPool.Get() + defer fastrlp.DefaultArenaPool.Put(arena) + + // when hashign the block for signing we have to remove from + // the extra field the seal and commitedseal items + extra, err := getIbftExtra(h) + if err != nil { + return nil, err + } + putIbftExtraValidators(h, extra.Validators) + + vv := arena.NewArray() + vv.Set(arena.NewBytes(h.ParentHash.Bytes())) + vv.Set(arena.NewBytes(h.Sha3Uncles.Bytes())) + vv.Set(arena.NewBytes(h.Miner.Bytes())) + vv.Set(arena.NewBytes(h.StateRoot.Bytes())) + vv.Set(arena.NewBytes(h.TxRoot.Bytes())) + vv.Set(arena.NewBytes(h.ReceiptsRoot.Bytes())) + vv.Set(arena.NewBytes(h.LogsBloom[:])) + vv.Set(arena.NewUint(h.Difficulty)) + vv.Set(arena.NewUint(h.Number)) + vv.Set(arena.NewUint(h.GasLimit)) + vv.Set(arena.NewUint(h.GasUsed)) + vv.Set(arena.NewUint(h.Timestamp)) + vv.Set(arena.NewCopyBytes(h.ExtraData)) + + buf := keccak.Keccak256Rlp(nil, vv) + return buf, nil +} +```` +Một phương thức đáng chú ý khác là phương thức *VerifyComiledFields*, xác minh rằng các con dấu đã cam kết là từ các trình xác thực hợp lệ: +````go title="consensus/ibft/sign.go +func verifyCommitedFields(snap *Snapshot, header *types.Header) error { + extra, err := getIbftExtra(header) + if err != nil { + return err + } + if len(extra.CommittedSeal) == 0 { + return fmt.Errorf("empty committed seals") + } + + // get the message that needs to be signed + signMsg, err := signHash(header) + if err != nil { + return err + } + signMsg = commitMsg(signMsg) + + visited := map[types.Address]struct{}{} + for _, seal := range extra.CommittedSeal { + addr, err := ecrecoverImpl(seal, signMsg) + if err != nil { + return err + } + + if _, ok := visited[addr]; ok { + return fmt.Errorf("repeated seal") + } else { + if !snap.Set.Includes(addr) { + return fmt.Errorf("signed by non validator") + } + visited[addr] = struct{}{} + } + } + + validSeals := len(visited) + if validSeals <= 2*snap.Set.MinFaultyNodes() { + return fmt.Errorf("not enough seals to seal block") + } + return nil +} +```` + +### Snapshot {#snapshots} + +*Snapshot*, như tên gọi của nó, có ở đó để cung cấp ảnh chụp nhanh hoặc *trạng thái* của hệ thống ở bất kỳ chiều cao khối (số) nào. + +Ảnh chụp nhanh chứa một tập hợp các nút là người xác thực, cũng như thông tin biểu quyết (người xác thực này có thể bỏ phiếu cho người xác thực khác). Trình xác thực gồm thông tin biểu quyết trong tiêu đề **Miner** và thay đổi giá trị của **nonce**: +* Nonce sẽ **toàn số 1** nếu nút muốn xóa trình xác thực +* Nonce sẽ **toàn số 0** nếu nút muốn thêm trình xác thực + +Ảnh chụp nhanh được đếm bằng phương thức ***processHeaders***: + +````go title="consensus/ibft/snapshot.go" +func (i *Ibft) processHeaders(headers []*types.Header) error { + if len(headers) == 0 { + return nil + } + + parentSnap, err := i.getSnapshot(headers[0].Number - 1) + if err != nil { + return err + } + snap := parentSnap.Copy() + + saveSnap := func(h *types.Header) error { + if snap.Equal(parentSnap) { + return nil + } + + snap.Number = h.Number + snap.Hash = h.Hash.String() + + i.store.add(snap) + + parentSnap = snap + snap = parentSnap.Copy() + return nil + } + + for _, h := range headers { + number := h.Number + + validator, err := ecrecoverFromHeader(h) + if err != nil { + return err + } + if !snap.Set.Includes(validator) { + return fmt.Errorf("unauthroized validator") + } + + if number%i.epochSize == 0 { + // during a checkpoint block, we reset the voles + // and there cannot be any proposals + snap.Votes = nil + if err := saveSnap(h); err != nil { + return err + } + + // remove in-memory snaphots from two epochs before this one + epoch := int(number/i.epochSize) - 2 + if epoch > 0 { + purgeBlock := uint64(epoch) * i.epochSize + i.store.deleteLower(purgeBlock) + } + continue + } + + // if we have a miner address, this might be a vote + if h.Miner == types.ZeroAddress { + continue + } + + // the nonce selects the action + var authorize bool + if h.Nonce == nonceAuthVote { + authorize = true + } else if h.Nonce == nonceDropVote { + authorize = false + } else { + return fmt.Errorf("incorrect vote nonce") + } + + // validate the vote + if authorize { + // we can only authorize if they are not on the validators list + if snap.Set.Includes(h.Miner) { + continue + } + } else { + // we can only remove if they are part of the validators list + if !snap.Set.Includes(h.Miner) { + continue + } + } + + count := snap.Count(func(v *Vote) bool { + return v.Validator == validator && v.Address == h.Miner + }) + if count > 1 { + // there can only be one vote per validator per address + return fmt.Errorf("more than one proposal per validator per address found") + } + if count == 0 { + // cast the new vote since there is no one yet + snap.Votes = append(snap.Votes, &Vote{ + Validator: validator, + Address: h.Miner, + Authorize: authorize, + }) + } + + // check the tally for the proposed validator + tally := snap.Count(func(v *Vote) bool { + return v.Address == h.Miner + }) + + if tally > snap.Set.Len()/2 { + if authorize { + // add the proposal to the validator list + snap.Set.Add(h.Miner) + } else { + // remove the proposal from the validators list + snap.Set.Del(h.Miner) + + // remove any votes casted by the removed validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Validator == h.Miner + }) + } + + // remove all the votes that promoted this validator + snap.RemoveVotes(func(v *Vote) bool { + return v.Address == h.Miner + }) + } + + if err := saveSnap(h); err != nil { + return nil + } + } + + // update the metadata + i.store.updateLastBlock(headers[len(headers)-1].Number) + return nil +} +```` + +Phương thức này thường được gọi với 1 tiêu đề, nhưng luồng vẫn giống nhau ngay cả với nhiều tiêu đề.
Với mỗi tiêu đề được chuyển vào, IBFT cần xác minh rằng người đề xuất tiêu đề là người xác thực. Có thể dễ dàng thực hiện điều này bằng cách lấy ảnh chụp nhanh mới nhất và kiểm tra xem nút có nằm trong tập hợp trình xác thực hay không. + +Tiếp theo, nonce được kiểm tra. Phiếu bầu được đưa vào và đánh dấu - nếu có đủ phiếu bầu, một nút sẽ được thêm/xóa khỏi tập hợp trình xác thực, sau đó ảnh chụp nhanh mới sẽ được lưu. + +#### Snapshot Store {#snapshot-store} + +Dịch vụ snapshot quản lý và cập nhật một thực thể được gọi là **snapshotStore**, nơi lưu trữ danh sách của tất cả snapshot có sẵn. Sử dụng nó, dịch vụ có thể nhanh chóng tìm ra ảnh chụp nhanh nào được liên kết với chiều cao khối (số lượng) nào. +````go title="consensus/ibft/snapshot.go" +type snapshotStore struct { + lastNumber uint64 + lock sync.Mutex + list snapshotSortedList +} +```` + +### Khởi động IBFT {#ibft-startup} + +Để khởi động IBFT, trước tiên Polygon Edge cần thiết lập truyền tải IBFT: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) setupTransport() error { + // use a gossip protocol + topic, err := i.network.NewTopic(ibftProto, &proto.MessageReq{}) + if err != nil { + return err + } + + err = topic.Subscribe(func(obj interface{}) { + msg := obj.(*proto.MessageReq) + + if !i.isSealing() { + // if we are not sealing we do not care about the messages + // but we need to subscribe to propagate the messages + return + } + + // decode sender + if err := validateMsg(msg); err != nil { + i.logger.Error("failed to validate msg", "err", err) + return + } + + if msg.From == i.validatorKeyAddr.String() { + // we are the sender, skip this message since we already + // relay our own messages internally. + return + } + i.pushMessage(msg) + }) + if err != nil { + return err + } + + i.transport = &gossipTransport{topic: topic} + return nil +} +```` + +Về cơ bản, nó tạo ra một chủ đề mới bằng giao thức IBFT, với thông báo bộ đệm giao thức mới.
Các thông báo được các trình xác thực sử dụng. Sau đó, Polygon Edge đăng ký chủ đề và xử lý các thông báo tương ứng. + +#### MessageReq {#messagereq} + +Thông báo được trao đổi bằng các trình xác thực: +````go title="consensus/ibft/proto/ibft.proto" +message MessageReq { + // type is the type of the message + Type type = 1; + + // from is the address of the sender + string from = 2; + + // seal is the committed seal if message is commit + string seal = 3; + + // signature is the crypto signature of the message + string signature = 4; + + // view is the view assigned to the message + View view = 5; + + // hash of the locked block + string digest = 6; + + // proposal is the rlp encoded block in preprepare messages + google.protobuf.Any proposal = 7; + + enum Type { + Preprepare = 0; + Prepare = 1; + Commit = 2; + RoundChange = 3; + } +} + +message View { + uint64 round = 1; + uint64 sequence = 2; +} +```` + +Trường **View** trong **MessageReq** đại diện cho vị trí nút hiện tại bên trong chuỗi. Nó có thuộc tính *round* và *sequence*. +* **round** đại diện cho số vòng đồng thuận mà người đề xuất cho chiều cao (số lượng khối) +* **sequence** đại diện cho chiều cao (số lượng khối) của blockchain + +*MsgQueue* được gửi trong quá trình triển khai IBFT nhằm mục đích lưu trữ các yêu cầu thông báo. Nó sắp xếp các thông báo theo *View* (trước tiên là theo trình tự, sau đó theo vòng). Quá trình triển khai IBFT cũng sở hữu các hàng đợi khác nhau cho các trạng thái khác nhau trong hệ thống. + +### Trạng thái IBFT {#ibft-states} + +Sau khi cơ chế đồng thuận được khởi động bằng phương thức **Start**, nó chạy một vòng lặp vô hạn mô phỏng một máy trạng thái: +````go title="consensus/ibft/ibft.go" +func (i *Ibft) start() { + // consensus always starts in SyncState mode in case it needs + // to sync with other nodes. + i.setState(SyncState) + + header := i.blockchain.Header() + i.logger.Debug("current sequence", "sequence", header.Number+1) + + for { + select { + case <-i.closeCh: + return + default: + } + + i.runCycle() + } +} + +func (i *Ibft) runCycle() { + if i.state.view != nil { + i.logger.Debug( + "cycle", + "state", + i.getState(), + "sequence", + i.state.view.Sequence, + "round", + i.state.view.Round, + ) + } + + switch i.getState() { + case AcceptState: + i.runAcceptState() + + case ValidateState: + i.runValidateState() + + case RoundChangeState: + i.runRoundChangeState() + + case SyncState: + i.runSyncState() + } +} +```` + +#### SyncState {#syncstate} + +Tất cả các nút bắt đầu từ trạng thái **Sync**. + +Điều này là vì dữ liệu mới cần được tìm nạp từ blockchain. Máy khách cần tìm hiểu xem đó có phải là trình xác thực hay không, tìm ảnh chụp nhanh hiện tại. Trạng thái này giải quyết mọi khối đang chờ xử lý. + +Sau khi quá trình đồng bộ kết thúc và máy khách xác định nó thực sự là một trình xác thực, nó cần phải chuyển sang **AcceptState**. Nếu máy khách **không** phải là trình xác thực, máy khách sẽ tiếp tục đồng bộ và ở trạng thái **SyncState** + +#### AcceptState {#acceptstate} + +Trạng thái **Accept** luôn kiểm tra ảnh chụp nhanh và tập hợp trình xác thực. Nếu nút hiện tại không nằm trong tập hợp trình xác thực, nó chuyển về trạng thái **Sync**. + +Mặt khác, nếu nút **là** một trình xác thực, nó sẽ tính toán người đề xuất. Nếu nó chỉ ra rằng nút hiện tại là người đề xuất, nó sẽ dựng một khối, và gửi bản chuẩn bị trước và sau đó chuẩn bị thông báo. + +* Preprepare messages - tin nhắn do người đề xuất gửi đến người xác thực nhằm thông báo cho họ về đề xuất +* Prepare messages - thông báo trong đó người xác thực đồng ý về một đề xuất. Tất cả các nút đều nhận được tất cả thông báo chuẩn bị +* Commit messages - tin nhắn chứa thông tin cam kết dành cho đề xuất + +Nếu nút hiện tại **không phải là** trình xác thực, nó sẽ sử dụng phương thức *getNextMessage* để đọc thông báo từ hàng đợi được hiển thị trước đó.
Nó sẽ chờ preprepare messages. Khi đã xác nhận mọi thứ đều đúng, nút sẽ chuyển sang trạng thái **Validate**. + +#### ValidateState {#validatestate} + +Trạng thái **Validate** khá đơn giản - tất cả việc mà các nút làm ở trạng thái này là đọc thông báo và thêm chúng vào trạng thái ảnh chụp nhanh cục bộ của mình. diff --git a/archive/edge/vi-edge/architecture/modules/json-rpc.md b/archive/edge/vi-edge/architecture/modules/json-rpc.md new file mode 100644 index 0000000000..dd618b0d44 --- /dev/null +++ b/archive/edge/vi-edge/architecture/modules/json-rpc.md @@ -0,0 +1,175 @@ +--- +id: json-rpc +title: JSON RPC +description: Giải thích dành cho mô-đun JSON RPC của Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - json-rpc + - endpoints +--- + +## Tổng quan {#overview} + +Mô-đun **JSON RPC** triển khai lớp **API JSON RPC**, một chức năng mà các nhà phát triển dApp sử dụng để tương tác với blockchain. + +Nó bao gồm hỗ trợ cho các **[điểm cuối json-rpc](https://eth.wiki/json-rpc/API)** tiêu chuẩn, cũng như điểm cuối websocket. + +## Giao diện Blockchain {#blockchain-interface} + +Polygon Edge sử dụng ***giao diện blockchain*** để xác định tất cả các phương thức mà mô-đun JSON RPC cần sử dụng, để cung cấp các điểm cuối của nó. + +Giao diện blockchain được thực hiện bằng máy chủ **[Minimal](/docs/edge/architecture/modules/minimal)**. Đây là quá trình triển khai cơ sở được chuyển vào lớp JSON RPC. + +````go title="jsonrpc/blockchain.go" +type blockchainInterface interface { + // Header returns the current header of the chain (genesis if empty) + Header() *types.Header + + // GetReceiptsByHash returns the receipts for a hash + GetReceiptsByHash(hash types.Hash) ([]*types.Receipt, error) + + // Subscribe subscribes for chain head events + SubscribeEvents() blockchain.Subscription + + // GetHeaderByNumber returns the header by number + GetHeaderByNumber(block uint64) (*types.Header, bool) + + // GetAvgGasPrice returns the average gas price + GetAvgGasPrice() *big.Int + + // AddTx adds a new transaction to the tx pool + AddTx(tx *types.Transaction) error + + // State returns a reference to the state + State() state.State + + // BeginTxn starts a transition object + BeginTxn(parentRoot types.Hash, header *types.Header) (*state.Transition, error) + + // GetBlockByHash gets a block using the provided hash + GetBlockByHash(hash types.Hash, full bool) (*types.Block, bool) + + // ApplyTxn applies a transaction object to the blockchain + ApplyTxn(header *types.Header, txn *types.Transaction) ([]byte, bool, error) + + stateHelperInterface +} +```` + +## Điểm cuối ETH {#eth-endpoints} + +Tất cả các điểm cuối JSON RPC tiêu chuẩn được thực hiện trong: + +````bash +jsonrpc/eth_endpoint.go +```` + +## Trình quản lý bộ lọc {#filter-manager} + +**Trình quản lý bộ lọc** là một dịch vụ chạy cùng với máy chủ JSON RPC. + +Trình quản lý bộ lọc hỗ trợ việc lọc các khối trên blockchain.
Cụ thể, chức năng này bao gồm cả **nhật ký** và bộ lọc cấp **khối**. + +Trình quản lý bộ lọc chủ yếu dựa vào Sự kiện đăng ký, được đề cập trong phần [Blockchain](blockchain#blockchain-subscriptions) + +````go title="jsonrpc/filter_manager.go" +type Filter struct { + id string + + // block filter + block *headElem + + // log cache + logs []*Log + + // log filter + logFilter *LogFilter + + // index of the filter in the timer array + index int + + // next time to timeout + timestamp time.Time + + // websocket connection + ws wsConn +} + + +type FilterManager struct { + logger hclog.Logger + + store blockchainInterface + closeCh chan struct{} + + subscription blockchain.Subscription + + filters map[string]*Filter + lock sync.Mutex + + updateCh chan struct{} + timer timeHeapImpl + timeout time.Duration + + blockStream *blockStream +} + +```` + +Các sự kiện của Trình quản lý bộ lọc được gửi đi trong phương thức *Run*: + +````go title="jsonrpc/filter_manager.go" +func (f *FilterManager) Run() { + + // watch for new events in the blockchain + watchCh := make(chan *blockchain.Event) + go func() { + for { + evnt := f.subscription.GetEvent() + if evnt == nil { + return + } + watchCh <- evnt + } + }() + + var timeoutCh <-chan time.Time + for { + // check for the next filter to be removed + filter := f.nextTimeoutFilter() + if filter == nil { + timeoutCh = nil + } else { + timeoutCh = time.After(filter.timestamp.Sub(time.Now())) + } + + select { + case evnt := <-watchCh: + // new blockchain event + if err := f.dispatchEvent(evnt); err != nil { + f.logger.Error("failed to dispatch event", "err", err) + } + + case <-timeoutCh: + // timeout for filter + if !f.Uninstall(filter.id) { + f.logger.Error("failed to uninstall filter", "id", filter.id) + } + + case <-f.updateCh: + // there is a new filter, reset the loop to start the timeout timer + + case <-f.closeCh: + // stop the filter manager + return + } + } +} +```` + +## 📜 Tài nguyên {#resources} +* **[Ethereum JSON-RPC](https://eth.wiki/json-rpc/API)** diff --git a/archive/edge/vi-edge/architecture/modules/minimal.md b/archive/edge/vi-edge/architecture/modules/minimal.md new file mode 100644 index 0000000000..9139c3cc04 --- /dev/null +++ b/archive/edge/vi-edge/architecture/modules/minimal.md @@ -0,0 +1,122 @@ +--- +id: minimal +title: Minimal +description: Giải thích về các loại mô-đun Minimal của Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - minimal +--- + +## Tổng quan {#overview} + +Như đã đề cập, Polygon Edge là một tập hợp các mô-đun, tất cả đều được kết nối với nhau.
+ **Blockchain** được kết nối với **Trạng thái**, ví dụ như **Đồng bộ hóa**, đưa các khối mới vào **Blockchain**. + + +**Minimal** là nền tảng cho các mô-đun liên kết này.
Minimal hoạt động như một trung tâm trung tâm cho tất cả các dịch vụ hoạt động trên Polygon Edge. + + +## Startup Magic {#startup-magic} + +Ngoài ra, Minimal còn chịu trách nhiệm: + +* Thiết lập các thư mục dữ liệu +* Tạo kho khóa cho giao tiếp libp2p + +* Tạo kho +* Thiết lập đồng thuận +* Thiết lập đối tượng blockchain với GRPC, JSON RPC, và Đồng bộ + +````go title="minimal/server.go" +func NewServer(logger hclog.Logger, config *Config) (*Server, error) { + m := &Server{ + logger: logger, + config: config, + chain: config.Chain, + grpcServer: grpc.NewServer(), + } + + m.logger.Info("Data dir", "path", config.DataDir) + + // Generate all the paths in the dataDir + if err := setupDataDir(config.DataDir, dirPaths); err != nil { + return nil, fmt.Errorf("failed to create data directories: %v", err) + } + + // Get the private key for the node + keystore := keystore.NewLocalKeystore(filepath.Join(config.DataDir, "keystore")) + key, err := keystore.Get() + if err != nil { + return nil, fmt.Errorf("failed to read private key: %v", err) + } + m.key = key + + storage, err := leveldb.NewLevelDBStorage(filepath.Join(config.DataDir, "blockchain"), logger) + if err != nil { + return nil, err + } + m.storage = storage + + // Setup consensus + if err := m.setupConsensus(); err != nil { + return nil, err + } + + stateStorage, err := itrie.NewLevelDBStorage(filepath.Join(m.config.DataDir, "trie"), logger) + if err != nil { + return nil, err + } + + st := itrie.NewState(stateStorage) + m.state = st + + executor := state.NewExecutor(config.Chain.Params, st) + executor.SetRuntime(precompiled.NewPrecompiled()) + executor.SetRuntime(evm.NewEVM()) + + // Blockchain object + m.blockchain, err = blockchain.NewBlockchain(logger, storage, config.Chain, m.consensus, executor) + if err != nil { + return nil, err + } + + executor.GetHash = m.blockchain.GetHashHelper + + // Setup sealer + sealerConfig := &sealer.Config{ + Coinbase: crypto.PubKeyToAddress(&m.key.PublicKey), + } + m.Sealer = sealer.NewSealer(sealerConfig, logger, m.blockchain, m.consensus, executor) + m.Sealer.SetEnabled(m.config.Seal) + + // Setup the libp2p server + if err := m.setupLibP2P(); err != nil { + return nil, err + } + + // Setup the GRPC server + if err := m.setupGRPC(); err != nil { + return nil, err + } + + // Setup jsonrpc + if err := m.setupJSONRPC(); err != nil { + return nil, err + } + + // Setup the syncer protocol + m.syncer = protocol.NewSyncer(logger, m.blockchain) + m.syncer.Register(m.libp2pServer.GetGRPCServer()) + m.syncer.Start() + + // Register the libp2p GRPC endpoints + proto.RegisterHandshakeServer(m.libp2pServer.GetGRPCServer(), &handshakeService{s: m}) + + m.libp2pServer.Serve() + return m, nil +} +```` diff --git a/archive/edge/vi-edge/architecture/modules/networking.md b/archive/edge/vi-edge/architecture/modules/networking.md new file mode 100644 index 0000000000..d279ece95f --- /dev/null +++ b/archive/edge/vi-edge/architecture/modules/networking.md @@ -0,0 +1,88 @@ +--- +id: networking +title: Kết nối mạng +description: Giải thích về mô-đun kết nối mạng của Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - networking + - libp2p + - GRPC +--- + +## Tổng quan {#overview} + +Một nút thường phải giao tiếp với các nút khác trên mạng lưới để trao đổi thông tin hữu ích.
+ Để thực hiện nhiệm vụ này, Polygon Edge sử dụng khung **libp2p**, vốn đã được sử dụng rộng rãi. + +Lựa chọn sử dụng **libp2p** chủ yếu là vì: + +* **Tốc độ** - libp2p cải tiến đáng kể về hiệu suất so với devp2p (được sử dụng trong GETH và các máy khách khác) +* **Khả năng mở rộng** - đây là nền tảng tuyệt vời dành cho các tính năng khác của hệ thống + +* **Đặc tính mô-đun** - libp2p bản chất là một mô-đun, giống như Polygon Edge. Điều này mang lại tính linh hoạt cao hơn, đặc biệt khi các phần của Polygon Edge cần được hoán đổi + + +## GRPC {#grpc} + +Ngoài **libp2p**, Polygon Edge còn sử dụng giao thức **GRPC**.
+ Về mặt kỹ thuật, Polygon Edge sử dụng nhiều giao thức GRPC, sẽ được đề cập thêm ở phần sau. + + +Lớp GRPC giúp tóm tắt tất cả các giao thức yêu cầu/phản hồi và đơn giản hóa các giao thức phát trực tuyến cần thiết để Polygon Edge hoạt động. + + +GRPC sử dụng **Bộ đệm giao thức** để xác định các *dịch vụ* và *cấu trúc thông điệp*.
Các dịch vụ và cấu trúc được định nghĩa trong tệp *.proto*, được biên dịch và là ngôn ngữ bất khả tri. + + +Ở phần trên, chúng ta đã đề cập rằng Polygon Edge tận dụng một số giao thức GRPC.
+ Việc này được thực hiện để tăng tốc UX tổng thể dành cho trình vận hành nút, một khía cạnh thường bị các máy khách như GETH và Parity xem nhẹ. + + +Trình vận hành nút sẽ có cái nhìn tổng quan tốt hơn về những hoạt động đang diễn ra trong hệ thống nhờ gọi dịch vụ GRPC thay vì sàng lọc các nhật ký để tìm thông tin cần thiết. + + +### GRPC dành cho các trình vận hành nút + {#grpc-for-node-operators} + +Phần tiếp theo sẽ tương đối quen thuộc vì đã được trình bày qua trong phần [Lệnh CLI](/docs/edge/get-started/cli-commands). + + +Dịch vụ GRPC sẽ được sử dụng bởi **trình vận hành nút** được xác định như sau: + +````go title="minimal/proto/system.proto" +service System { + // GetInfo returns info about the client + rpc GetStatus(google.protobuf.Empty) returns (ServerStatus); + + // PeersAdd adds a new peer + rpc PeersAdd(PeersAddRequest) returns (google.protobuf.Empty); + + // PeersList returns the list of peers + rpc PeersList(google.protobuf.Empty) returns (PeersListResponse); + + // PeersInfo returns the info of a peer + rpc PeersStatus(PeersStatusRequest) returns (Peer); + + // Subscribe subscribes to blockchain events + rpc Subscribe(google.protobuf.Empty) returns (stream BlockchainEvent); +} +```` +:::tip +Các lệnh CLI thực sự gọi các quá trình triển khai các phương thức dịch vụ này. + + +Các phương thức được triển khai qua ***minimal/system_service.go***. +::: + +### GRPC dành cho các nút khác {#grpc-for-other-nodes} + +Polygon Edge cũng triển khai một số phương thức dịch vụ được sử dụng bởi các nút khác trên mạng lưới.
Dịch vụ được đề cập sẽ được mô tả trong phần **[giao thức](docs/edge/architecture/modules/consensus)**. + +## 📜 Tài nguyên {#resources} +* **[Bộ đệm giao thức](https://developers.google.com/protocol-buffers)** +* **[Libp2p](https://libp2p.io/)** +* **[gRPC](https://grpc.io/)** diff --git a/archive/edge/vi-edge/architecture/modules/other-modules.md b/archive/edge/vi-edge/architecture/modules/other-modules.md new file mode 100644 index 0000000000..71bd44757a --- /dev/null +++ b/archive/edge/vi-edge/architecture/modules/other-modules.md @@ -0,0 +1,39 @@ +--- +id: other-modules +title: Các mô-đun khác +description: Giải thích về một số mô-đun của Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modules +--- + +## Crypto {#crypto} + +Mô-đun **Crypto** gồm các chức năng tiện ích của crypto. + +## Chuỗi {#chain} + +Mô-đun **Chuỗi** gồm các thông số chuỗi (các nhánh hoạt động, động cơ đồng thuận, v.v.) + + +* **Chuỗi** - Các cấu hình chuỗi được xác định trước (mainnet, goerli, ibft) + + +## Trình trợ giúp {#helper} + +Mô-đun **Trình trợ giúp** gồm các gói trợ giúp. + +* **dao** - Tiện ích Dao +* **enode** - Chức năng mã hóa/giải mã enode + +* **hex** - Các chức năng mã hóa/giải mã Hex +* **ipc** - Các chức năng kết nối IPC +* **keccak** - Các chức năng Keccak +* **rlputil** - Chức năng trình trợ giúp mã hóa/giải mã Rlp + +## Lệnh {#command} + +Mô-đun **Lệnh** gồm các giao diện dành cho các CLI. \ No newline at end of file diff --git a/archive/edge/vi-edge/architecture/modules/sealer.md b/archive/edge/vi-edge/architecture/modules/sealer.md new file mode 100644 index 0000000000..f972b39b4e --- /dev/null +++ b/archive/edge/vi-edge/architecture/modules/sealer.md @@ -0,0 +1,71 @@ +--- +id: sealer +title: Sealer +description: Giải thích cho mô-đun niêm phong của Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - sealer + - sealing +--- + +## Tổng quan {#overview} + +**Sealer** là một thực thể thu thập các giao dịch và tạo ra một khối mới.
Rồi khối đó được gửi đến mô-đun **Consensus** để niêm phong. + +Logic niêm phong cuối cùng nằm trong mô-đun **Consensus**. + +## Phương pháp chạy {#run-method} + +````go title="sealer/sealer.go" +func (s *Sealer) run(ctx context.Context) { + sub := s.blockchain.SubscribeEvents() + eventCh := sub.GetEventCh() + + for { + if s.config.DevMode { + // In dev-mode we wait for new transactions to seal blocks + select { + case <-s.wakeCh: + case <-ctx.Done(): + return + } + } + + // start sealing + subCtx, cancel := context.WithCancel(ctx) + done := s.sealAsync(subCtx) + + // wait for the sealing to be done + select { + case <-done: + // the sealing process has finished + case <-ctx.Done(): + // the sealing routine has been canceled + case <-eventCh: + // there is a new head, reset sealer + } + + // cancel the sealing process context + cancel() + + if ctx.Err() != nil { + return + } + } +} +```` + +:::caution Đang thực hiện + +Mô-đun **Sealer** và **Consensus** sẽ được kết hợp thành một thực thể duy nhất trong tương lai gần. + +Mô-đun mới sẽ kết hợp logic mô-đun dành cho các loại cơ chế đồng thuận khác nhau, đòi hỏi các quy trình triển khai niêm phong khác nhau: +* **PoS** (Bằng chứng cổ phần) +* **PoA** (Bằng chứng quyền hạn) + +Hiện tại, các mô-đun **Sealer** và **Consensus** hoạt động với PoW (Bằng chứng công việc). +::: \ No newline at end of file diff --git a/archive/edge/vi-edge/architecture/modules/state.md b/archive/edge/vi-edge/architecture/modules/state.md new file mode 100644 index 0000000000..b6fc2e7cbe --- /dev/null +++ b/archive/edge/vi-edge/architecture/modules/state.md @@ -0,0 +1,253 @@ +--- +id: state +title: Trạng thái +description: Giải thích về mô-đun trạng thái của Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - state + - trie +--- + +Để thực sự hiểu cách **Trạng thái** hoạt động, bạn cần hiểu một số khái niệm Ethereum cơ bản.
+ +Bạn nên đọc **[Hướng dẫn về trạng thái trong Ethereum](https://ethereum.github.io/execution-specs/autoapi/ethereum/frontier/state/index.html)**. + +## Tổng quan {#overview} + +Sau khi làm quen với các khái niệm Ethereum cơ bản, phần tổng quan tiếp theo sẽ khá dễ hiểu. + + +Như đã đề cập, **Trạng thái thế giới trie** chứa tất cả các tài khoản Ethereum tồn tại.
Những tài khoản này là nhánh của Merkle Trie. + Mỗi nhánh sẽ mã hóa thông tin **Trạng thái Tài khoản**. + + +Điều này giúp Polygon Edge nhận được một Merkle Trie cụ thể vào thời điểm cụ thể.
Ví dụ, chúng ta có thể lấy băm của trạng thái tại khối 10. + + +Merkle Trie, tại một thời điểm bất kỳ được gọi là ***Snapshot***. + +Chúng ta có thể lấy các ***Snapshot*** của **trạng thái trie** hoặc của **bộ nhớ trie** - chúng về cơ bản là như nhau.
Điểm khác biệt duy nhất là ý nghĩa của nhánh: + +* Đối với bộ nhớ trie, các nhánh chứa một trạng thái tùy ý, chúng ta không thể xử lý và không thể biết có gì trong đó + +* Còn đối với trạng thái trie, các nhánh đại diện cho các tài khoản + +````go title="state/state.go +type State interface { + // Gets a snapshot for a specific hash + NewSnapshotAt(types.Hash) (Snapshot, error) + + // Gets the latest snapshot + NewSnapshot() Snapshot + + // Gets the codeHash + GetCode(hash types.Hash) ([]byte, bool) +} +```` + +Giao diện **Snapshot** được định nghĩa là: + +````go title="state/state.go +type Snapshot interface { + // Gets a specific value for a leaf + Get(k []byte) ([]byte, bool) + + // Commits new information + Commit(objs []*Object) (Snapshot, []byte) +} +```` + +Thông tin có thể cam kết, được xác định bằng *Cấu trúc Đối tượng*: + + +````go title="state/state.go +// Object is the serialization of the radix object +type Object struct { + Address types.Address + CodeHash types.Hash + Balance *big.Int + Root types.Hash + Nonce uint64 + Deleted bool + + DirtyCode bool + Code []byte + + Storage []*StorageObject +} +```` + +Quá trình triển khai Merkle Trie nằm trong thư mục *state/immutable-trie*
. + *state/immutable-trie/state.go* triển khai giao diện **Trạng thái**. + +*state/immutable-trie/trie.go* là đối tượng Merkle Trie chính. Đây được coi là một phiên bản tối ưu của Merkle Trie, sử dụng lại nhiều bộ nhớ nhất có thể. + + +## Trình thực thi {#executor} + +*state/executor.go* chứa tất cả các thông tin cần thiết để Polygon Edge quyết định cách một khối thay đổi trạng thái hiện thời. Quá trình triển khai của *ProcessBlock* nằm ở đây. + + +Phương thức *áp dụng* thực hiện chuyển đổi trạng thái. + Trình thực thi sẽ gọi EVM. + +````go title="state/executor.go" +func (t *Transition) apply(msg *types.Transaction) ([]byte, uint64, bool, error) { + // check if there is enough gas in the pool + if err := t.subGasPool(msg.Gas); err != nil { + return nil, 0, false, err + } + + txn := t.state + s := txn.Snapshot() + + gas, err := t.preCheck(msg) + if err != nil { + return nil, 0, false, err + } + if gas > msg.Gas { + return nil, 0, false, errorVMOutOfGas + } + + gasPrice := new(big.Int).SetBytes(msg.GetGasPrice()) + value := new(big.Int).SetBytes(msg.Value) + + // Set the specific transaction fields in the context + t.ctx.GasPrice = types.BytesToHash(msg.GetGasPrice()) + t.ctx.Origin = msg.From + + var subErr error + var gasLeft uint64 + var returnValue []byte + + if msg.IsContractCreation() { + _, gasLeft, subErr = t.Create2(msg.From, msg.Input, value, gas) + } else { + txn.IncrNonce(msg.From) + returnValue, gasLeft, subErr = t.Call2(msg.From, *msg.To, msg.Input, value, gas) + } + + if subErr != nil { + if subErr == runtime.ErrNotEnoughFunds { + txn.RevertToSnapshot(s) + return nil, 0, false, subErr + } + } + + gasUsed := msg.Gas - gasLeft + refund := gasUsed / 2 + if refund > txn.GetRefund() { + refund = txn.GetRefund() + } + + gasLeft += refund + gasUsed -= refund + + // refund the sender + remaining := new(big.Int).Mul(new(big.Int).SetUint64(gasLeft), gasPrice) + txn.AddBalance(msg.From, remaining) + + // pay the coinbase + coinbaseFee := new(big.Int).Mul(new(big.Int).SetUint64(gasUsed), gasPrice) + txn.AddBalance(t.ctx.Coinbase, coinbaseFee) + + // return gas to the pool + t.addGasPool(gasLeft) + + return returnValue, gasUsed, subErr != nil, nil +} +```` + +## Thời gian chạy {#runtime} + +Khi thực thi chuyển đổi trạng thái, mô-đun chính thực thi việc chuyển đổi trạng thái là EVM (nằm trong + state/runtime/evm). + +**Bảng điều khiển** thực hiện khớp lệnh giữa **opcode** và chỉ dẫn. + + +````go title="state/runtime/evm/dispatch_table.go" +func init() { + // unsigned arithmetic operations + register(STOP, handler{opStop, 0, 0}) + register(ADD, handler{opAdd, 2, 3}) + register(SUB, handler{opSub, 2, 3}) + register(MUL, handler{opMul, 2, 5}) + register(DIV, handler{opDiv, 2, 5}) + register(SDIV, handler{opSDiv, 2, 5}) + register(MOD, handler{opMod, 2, 5}) + register(SMOD, handler{opSMod, 2, 5}) + register(EXP, handler{opExp, 2, 10}) + + ... + + // jumps + register(JUMP, handler{opJump, 1, 8}) + register(JUMPI, handler{opJumpi, 2, 10}) + register(JUMPDEST, handler{opJumpDest, 0, 1}) +} +```` + +Logic cốt lõi cung cấp năng lượng cho EVM là vòng lặp *Run*. +
+ +Đây là điểm nhập chính dành cho EVM. Nó thực hiện vòng lặp và kiểm tra opcode hiện thời, truy xuất hướng dẫn, kiểm tra xem có thể thực hiện, tiêu thụ gas và thực thi lệnh hướng dẫn cho đến khi thất bại hoặc bị dừng. + +````go title="state/runtime/evm/state.go" + +// Run executes the virtual machine +func (c *state) Run() ([]byte, error) { + var vmerr error + + codeSize := len(c.code) + + for !c.stop { + if c.ip >= codeSize { + c.halt() + break + } + + op := OpCode(c.code[c.ip]) + + inst := dispatchTable[op] + + if inst.inst == nil { + c.exit(errOpCodeNotFound) + break + } + + // check if the depth of the stack is enough for the instruction + if c.sp < inst.stack { + c.exit(errStackUnderflow) + break + } + + // consume the gas of the instruction + if !c.consumeGas(inst.gas) { + c.exit(errOutOfGas) + break + } + + // execute the instruction + inst.inst(c) + + // check if stack size exceeds the max size + if c.sp > stackSize { + c.exit(errStackOverflow) + break + } + + c.ip++ + } + + if err := c.err; err != nil { + vmerr = err + } + + return c.ret, vmerr +} +```` diff --git a/archive/edge/vi-edge/architecture/modules/storage.md b/archive/edge/vi-edge/architecture/modules/storage.md new file mode 100644 index 0000000000..d899cc7a37 --- /dev/null +++ b/archive/edge/vi-edge/architecture/modules/storage.md @@ -0,0 +1,116 @@ +--- +id: storage +title: Lưu trữ +description: Giải thích dành cho mô-đun lưu trữ của Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - storage + - LevelDB +--- + +## Tổng quan {#overview} + +Polygon Edge hiện đang sử dụng **LevelDB** để lưu trữ dữ liệu, cũng như lưu trữ dữ liệu **trong bộ nhớ**. + +Trong suốt Polygon Edge, khi các mô-đun cần tương tác với kho dữ liệu cơ sở, chúng không cần biết động cơ hoặc dịch vụ DB nào mà chúng đang đề cập. + +Lớp DB được trừu tượng hóa giữa một mô-đun được gọi là **Lưu trữ**, xuất các giao diện mà mô-đun truy vấn. + +Mỗi lớp DB, hiện chỉ có **LevelDB**, thực hiện các phương thức này một cách riêng biệt, đảm bảo rằng chúng phù hợp với quá trình triển khai. + +````go title="blockchain/storage/storage.go" +// Storage is a generic blockchain storage +type Storage interface { + ReadCanonicalHash(n uint64) (types.Hash, bool) + WriteCanonicalHash(n uint64, hash types.Hash) error + + ReadHeadHash() (types.Hash, bool) + ReadHeadNumber() (uint64, bool) + WriteHeadHash(h types.Hash) error + WriteHeadNumber(uint64) error + + WriteForks(forks []types.Hash) error + ReadForks() ([]types.Hash, error) + + WriteDiff(hash types.Hash, diff *big.Int) error + ReadDiff(hash types.Hash) (*big.Int, bool) + + WriteHeader(h *types.Header) error + ReadHeader(hash types.Hash) (*types.Header, error) + + WriteCanonicalHeader(h *types.Header, diff *big.Int) error + + WriteBody(hash types.Hash, body *types.Body) error + ReadBody(hash types.Hash) (*types.Body, error) + + WriteSnapshot(hash types.Hash, blob []byte) error + ReadSnapshot(hash types.Hash) ([]byte, bool) + + WriteReceipts(hash types.Hash, receipts []*types.Receipt) error + ReadReceipts(hash types.Hash) ([]*types.Receipt, error) + + WriteTxLookup(hash types.Hash, blockHash types.Hash) error + ReadTxLookup(hash types.Hash) (types.Hash, bool) + + Close() error +} +```` + +## LevelDB {#leveldb} + +### Tiền tố {#prefixes} + +Để thực hiện truy vấn bộ lưu trữ LevelDB có tính xác định và để tránh xung đột bộ nhớ khóa, Polygon Edge tận dụng tiền tố và tiền tố con khi lưu trữ dữ liệu + +````go title="blockchain/storage/keyvalue.go" +// Prefixes for the key-value store +var ( + // DIFFICULTY is the difficulty prefix + DIFFICULTY = []byte("d") + + // HEADER is the header prefix + HEADER = []byte("h") + + // HEAD is the chain head prefix + HEAD = []byte("o") + + // FORK is the entry to store forks + FORK = []byte("f") + + // CANONICAL is the prefix for the canonical chain numbers + CANONICAL = []byte("c") + + // BODY is the prefix for bodies + BODY = []byte("b") + + // RECEIPTS is the prefix for receipts + RECEIPTS = []byte("r") + + // SNAPSHOTS is the prefix for snapshots + SNAPSHOTS = []byte("s") + + // TX_LOOKUP_PREFIX is the prefix for transaction lookups + TX_LOOKUP_PREFIX = []byte("l") +) + +// Sub-prefixes +var ( + HASH = []byte("hash") + NUMBER = []byte("number") + EMPTY = []byte("empty") +) +```` + +## Kế hoạch tương lai {#future-plans} + +Kế hoạch cho tương lai gần bao gồm việc bổ sung một số giải pháp DB phổ biến nhất, chẳng hạn như: +* PostgreSQL +* MySQL + + +## 📜 Tài nguyên {#resources} +* **[LevelDB](https://github.com/google/leveldb)** \ No newline at end of file diff --git a/archive/edge/vi-edge/architecture/modules/syncer.md b/archive/edge/vi-edge/architecture/modules/syncer.md new file mode 100644 index 0000000000..7de35b3d40 --- /dev/null +++ b/archive/edge/vi-edge/architecture/modules/syncer.md @@ -0,0 +1,67 @@ +--- +id: syncer +title: Trình đồng bộ +description: Giải thích dành cho mô-đun trình đồng bộ của Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - synchronization +--- + +## Tổng quan {#overview} + +Mô-đun này chứa logic cho giao thức đồng bộ hóa. Nó được sử dụng để đồng bộ một nút mới với mạng đang chạy, hoặc xác thực/chèn các khối mới cho các nút không tham gia vào sự đồng thuận (không có trình xác thực). + +Polygon Edge sử dụng **libp2p** làm lớp mạng và trên đó chạy **gRPC**. + +Về cơ bản có 2 kiểu đồng bộ trong Polygon Edge: +* Bulk Sync - đồng bộ một loạt các khối cùng một lúc +* Watch Sync - đồng bộ trên cơ sở mỗi khối + +### Bulk Sync {#bulk-sync} + +Các bước cho quá trình Đồng bộ hàng loạt (Bulk Syncing) khá đơn giản để đáp ứng mục tiêu của Bulk Sync - đồng bộ càng nhiều khối càng tốt (có sẵn) từ máy ngang hàng khác để bắt kịp càng nhanh càng tốt. + +Dưới đây là luồng công việc của quy trình Bulk Sync: + +1. ** Xác định xem nút có cần Bulk Sync không ** - Trong bước này, nút kiểm tra bản đồ ngang hàng để xem có ai có số lượng khối lớn hơn số lượng khối cục bộ của nút không +2. ** Tìm máy ngang hàng tốt nhất (sử dụng bản đồ máy ngang hàng đồng bộ) ** - Trong bước này, nút tìm máy ngang hàng tốt nhất để đồng bộ theo các tiêu chí được đề cập trong ví dụ trên. +3. ** Mở luồng đồng bộ hàng loạt ** - Trong bước này, nút mở một luồng gRPC cho máy ngang hàng tốt nhất để đồng bộ hàng loạt các khối từ số khối chung +4. ** Máy ngang hàng tốt nhất đóng luồng khi hoàn tất gửi hàng loạt ** - Trong bước này, máy ngang hàng tốt nhất mà nút đang đồng bộ sẽ đóng luồng ngay sau khi gửi tất cả các khối khả dụng mà nó có +5. ** Khi hoàn tất quá trình đồng bộ hàng loạt, hãy kiểm tra xem nút có phải là trình xác thực không ** - Trong bước này, luồng được đóng bằng máy ngang hàng tốt nhất và nút cần kiểm tra xem chúng có phải là trình xác thực sau khi đồng bộ hàng loạt hay không. + * Nếu đúng như vậy, chúng sẽ nhảy ra khỏi trạng thái đồng bộ và bắt đầu tham gia vào quá trình đồng thuận + * Nếu không, chúng sẽ tiếp tục với ** Watch Sync ** + +### Watch Sync {#watch-sync} + +:::info + +Bước cho Đồng bộ trên cơ sở mỗi khối (Watch Syncing) chỉ được thực thi nếu nút không phải là trình xác thực, mà là nút không cần xác thực thông thường trong mạng và chỉ lắng nghe các khối đang đến. +::: + +Hoạt động của Watch Sync khá đơn giản, nút đã được đồng bộ với phần còn lại của mạng và chỉ cần phân tích cú pháp các khối mới sắp xuất hiện. + +Đây là luồng công việc của quy trình Watch Sync: + +1. ** Thêm một khối mới khi trạng thái của máy ngang hàng được cập nhật ** - Trong bước này, các nút lắng nghe các sự kiện khối mới, khi có một khối mới, nó sẽ chạy một lệnh gọi hàm gRPC, lấy khối và cập nhật trạng thái cục bộ. +2. ** Kiểm tra xem nút có phải là trình xác thực hay không sau khi đồng bộ khối mới nhất ** + * Nếu đúng như vậy, hãy ra khỏi trạng thái đồng bộ + * Nếu không thì vẫn tiếp tục nghe các sự kiện khối mới + +## Báo cáo hiệu suất {#perfomance-report} + +:::info + +Hiệu suất được đo trên một máy cục bộ bằng cách đồng bộ ** triệu khối ** + +::: + +| Tên | Kết quả | +|----------------------|----------------| +| Đồng bộ 1M khối | ~ 25 phút | +| Chuyển 1M khối | ~ 1 phút | +| Số lượng lệnh gọi GRPC | 2 | +| Phạm vi thử nghiệm | ~ 93% | \ No newline at end of file diff --git a/archive/edge/vi-edge/architecture/modules/txpool.md b/archive/edge/vi-edge/architecture/modules/txpool.md new file mode 100644 index 0000000000..cf145ae88e --- /dev/null +++ b/archive/edge/vi-edge/architecture/modules/txpool.md @@ -0,0 +1,243 @@ +--- +id: txpool +title: TxPool +description: Giải thích về mô-đun TxPool của Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - TxPool + - transaction + - pool +--- + +## Tổng quan {#overview} + +Mô-đun TxPool đại diện cho quá trình triển khai nhóm giao dịch, nơi các giao dịch được thêm vào từ các phần khác nhau của + hệ thống. Mô-đun cũng cung cấp một số tính năng hữu ích dành cho trình vận hành nút, sẽ được giải thích thêm được bên dưới. + +## Lệnh của trình vận hành {#operator-commands} + +````go title="txpool/proto/operator.proto +service TxnPoolOperator { + // Status returns the current status of the pool + rpc Status(google.protobuf.Empty) returns (TxnPoolStatusResp); + + // AddTxn adds a local transaction to the pool + rpc AddTxn(AddTxnReq) returns (google.protobuf.Empty); + + // Subscribe subscribes for new events in the txpool + rpc Subscribe(google.protobuf.Empty) returns (stream TxPoolEvent); +} + +```` + +Trình vận hành nút có thể truy vấn các điểm điểm cuối của GRPC như mô tả trong phần **[Lệnh CLI](/docs/edge/get-started/cli-commands#transaction-pool-commands)**. + +## Xử lý Giao dịch {#processing-transactions} + +````go title="txpool/txpool.go" +// AddTx adds a new transaction to the pool +func (t *TxPool) AddTx(tx *types.Transaction) error { + if err := t.addImpl("addTxn", tx); err != nil { + return err + } + + // broadcast the transaction only if network is enabled + // and we are not in dev mode + if t.topic != nil && !t.dev { + txn := &proto.Txn{ + Raw: &any.Any{ + Value: tx.MarshalRLP(), + }, + } + if err := t.topic.Publish(txn); err != nil { + t.logger.Error("failed to topic txn", "err", err) + } + } + + if t.NotifyCh != nil { + select { + case t.NotifyCh <- struct{}{}: + default: + } + } + return nil +} + +func (t *TxPool) addImpl(ctx string, txns ...*types.Transaction) error { + if len(txns) == 0 { + return nil + } + + from := txns[0].From + for _, txn := range txns { + // Since this is a single point of inclusion for new transactions both + // to the promoted queue and pending queue we use this point to calculate the hash + txn.ComputeHash() + + err := t.validateTx(txn) + if err != nil { + return err + } + + if txn.From == types.ZeroAddress { + txn.From, err = t.signer.Sender(txn) + if err != nil { + return fmt.Errorf("invalid sender") + } + from = txn.From + } else { + // only if we are in dev mode we can accept + // a transaction without validation + if !t.dev { + return fmt.Errorf("cannot accept non-encrypted txn") + } + } + + t.logger.Debug("add txn", "ctx", ctx, "hash", txn.Hash, "from", from) + } + + txnsQueue, ok := t.queue[from] + if !ok { + stateRoot := t.store.Header().StateRoot + + // initialize the txn queue for the account + txnsQueue = newTxQueue() + txnsQueue.nextNonce = t.store.GetNonce(stateRoot, from) + t.queue[from] = txnsQueue + } + for _, txn := range txns { + txnsQueue.Add(txn) + } + + for _, promoted := range txnsQueue.Promote() { + t.sorted.Push(promoted) + } + return nil +} +```` +Phương pháp ***addImpl*** là nền tảng của mô-đun **TxPool**. Đây là trung tâm nơi các giao dịch được thêm vào hệ hệ thống, được gọi triển khai từ dịch vụ GRPC, điểm cuối JSON RPC, và bất kỳ khi nào máy khách nhận được giao dịch qua giao thức **gossip**. + +Mô-đun nhận giao dịch như một đối số **ctx**, chỉ biểu thị cơ sở mà từ đó các giao dịch được thêm vào (GRPC, JSON RPC...)
. + Tham số khác là danh sách các giao dịch sẽ được thêm vào nhóm. + + +Điều quan trọng cần lưu ý ở đây là kiểm tra trường **Đến từ** trong giao dịch: + +* Nếu trường **Đến từ** bị **bỏ trống**, giao dịch sẽ bị coi là chưa được mã hóa/chưa được ký. + Những giao dịch như vậy sẽ chỉ + được chấp nhận ở chế độ phát triển +* Nếu trường **Đến từ** **không trống**, giao dịch sẽ được coi là đã ký và quá trình xác minh chữ ký sẽ diễn ra + +Sau khi hoàn thành các bước xác thực này, giao dịch sẽ được coi là hợp lệ. + +## Cấu trúc dữ liệu {#data-structures} + +````go title="txpool/txpool.go" +// TxPool is a pool of transactions +type TxPool struct { + logger hclog.Logger + signer signer + + store store + idlePeriod time.Duration + + queue map[types.Address]*txQueue + sorted *txPriceHeap + + // network stack + network *network.Server + topic *network.Topic + + sealing bool + dev bool + NotifyCh chan struct{} + + proto.UnimplementedTxnPoolOperatorServer +} +```` + +Một số trường trong đối tượng TxPool có thể dễ gây nhầm lẫn là danh sách **queue** và **sorted**. + +* **queue** - Thực hiện hàng loạt theo danh sách giao dịch tài khoản được sắp xếp (theo nonce) + +* **sorted** - Danh sách được sắp xếp gồm tất cả giao dịch hiện được ưu đãi (tất cả giao dịch có thể thực thi). + Sắp xếp theo giá gas + +## Quản lý lỗi giới hạn gas {#gas-limit-error-management} + +Mỗi khi bạn nộp một giao dịch, sẽ có ba cách để TxPool xử lý giao dịch đó. + + +1. Tất cả giao dịch đang chờ xử lý có thể phù hợp để đưa vào khối + +2. Một hoặc nhiều giao dịch đang chờ xử lý sẽ không phù hợp để đưa vào khối +3. Một hoặc nhiều giao dịch đang chờ xử lý sẽ không bao giờ phù hợp để đưa vào khối + +Tại đây, từ **_phù hợp_** có nghĩa là giới hạn gas của giao dịch thấp hơn lượng gas còn lại trong TxPool. + + +Trường hợp đầu tiên sẽ không phát sinh lỗi. + +### Trường hợp thứ hai {#second-scenario} + +- Lượng gas còn lại của TxPool được đặt theo giới hạn gas của khối cuối cùng, ví dụ là **5000** + +- Giao dịch đầu tiên được xử lý và tiêu thụ **3000** gas của TxPool + + - Lượng gas còn lại của TxPool hiện giờ là **2000** +- Giao giao dịch thứ hai, tương tự như giao dịch đầu tiên - cũng tiêu thụ 3000 đơn vị gas - được đặt lệnh +- Vì lượng gas còn lại của TxPool **thấp** hơn lượng gas giao dịch cần, giao dịch sẽ không thể xử lý được khối + - Giao dịch sẽ được đưa trở lại danh sách giao dịch chờ xử lý và được xử lý trong khối tiếp theo +- Khối đầu tiên sẽ được hạch toán, hãy tạm gọi là **khối #1** +- Lượng gas còn lại của TxPool được đặt theo khối chính - giới hạn gas **của khối #1** + +- Giao dịch được đưa trở lại danh sách giao dịch chờ xử lý của TxPool giờ sẽ được xử lý và hạch toán vào khối + + - Lượng gas còn của TxPool giờ là **2000** +- Khối thứ hai sẽ được hạch toán +- ... + +![Trường hợp lỗi #1 của TxPool](/img/edge/txpool-error-1.png) + +### Trường hợp thứ ba {#third-scenario} +- Lượng gas còn lại của TxPool được đặt theo giới hạn gas của khối cuối cùng, ví dụ là **5000** + +- Giao dịch đầu tiên được xử lý và tiêu thụ **3000** gas của TxPool + + - Lượng gas còn lại của TxPool hiện giờ là **2000** +- Giao dịch thứ hai, với trường gas được đặt là **6000**, được đặt lệnh +- Vì giới hạn gas của khối **thấp hơn** lượng gas giao dịch nên giao dịch sẽ bị loại bỏ + - Giao dịch này sẽ không bao giờ phù hợp với khối +- Khối đầu tiên sẽ được hạch toán +- ... + + +![Trường hợp lỗi #2 của TxPool](/img/edge/txpool-error-2.png) + +> Điều này sẽ xảy ra bất cứ khi nào bạn gặp lỗi sau: +> ```shell +> 2021-11-04T15:41:07.665+0100 [ERROR] polygon.consensus.dev: failed to write transaction: transaction's gas limit exceeds block gas limit +> ``` + +## Mục tiêu gas khối + {#block-gas-target} + +Sẽ có trường hợp các nút muốn giữ giới hạn gas khối thấp hơn hoặc nằm ở một mức mục tiêu nhất định trên một chuỗi đang chạy. + +Trình vận hành nút có thể đặt mục tiêu giới hạn gas lên một nút cụ thể, nút này sẽ cố gắng áp dụng giới hạn trên cho các khối mới được tạo. + Nếu phần lớn các nút khác cũng có giới hạn gas tương tự (hoặc y hệt) thì giới hạn gas khối sẽ luôn ở quanh mục tiêu gas khối đó và dần tịnh tiến về mục tiêu (tối đa `1/1024 * parent block gas limit`) khi các khối mới được tạo ra. + +### Trường hợp ví dụ {#example-scenario} + +* Trình vận hành nút sẽ đặt giới hạn gas khối cho nút đơn lẻ là `5000` +* Các nút khác cũng được định cấu hình là `5000`, ngoại trừ nút đơn lẻ được định cấu hình là `7000` +* Khi các nút có mục tiêu gas là `5000` trở thành người đề xuất, các nút này sẽ kiểm tra xem giới hạn gas đã đạt mức mục tiêu chưa +* Nếu giới hạn gas không nằm ở mức mục tiêu (cao hơn/thấp hơn), nút người đề xuất sẽ đặt mục tiêu gas của khối lên tối đa (1/1024 * giới hạn gas chính) về hướng mức mục tiêu + 1. Ví dụ: `parentGasLimit = 4500` và `blockGasTarget = 5000`, người đề xuất sẽ tính giới hạn gas cho khối mới là `4504.39453125` ( `4500/1024 + 4500`) + 2. Ví dụ: `parentGasLimit = 5500` và `blockGasTarget = 5000`, người đề xuất sẽ tính giới hạn gas cho khối mới là `5494.62890625` ( `5500 - 5500/1024`) +* Điều này đảm bảo rằng giới hạn gas khối trong chuỗi sẽ được giữ ở mục tiêu, bởi một người đề xuất có mục tiêu được định cấu hình thành `7000` sẽ không thể tăng giới hạn quá nhiều và phần lớn + các nút đã đặt thành `5000`sẽ luôn cố gắng giữ giới hạn ở đó \ No newline at end of file diff --git a/archive/edge/vi-edge/architecture/modules/types.md b/archive/edge/vi-edge/architecture/modules/types.md new file mode 100644 index 0000000000..eab7304cd5 --- /dev/null +++ b/archive/edge/vi-edge/architecture/modules/types.md @@ -0,0 +1,40 @@ +--- +id: types +title: Loại +description: Giải thích dành cho các loại mô-đun của Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - module + - types + - marshaling +--- + +## Tổng quan {#overview} + +Mô-đun **Loại** thực hiện các kiểu đối tượng cốt lõi, chẳng hạn như: + +* **Địa chỉ** +* **Hàm băm** +* **Tiêu đề** +* Rất nhiều chức năng của trình trợ giúp + +## Mã hoá / Giải mã RLP {#rlp-encoding-decoding} + +Không giống như các ứng dụng khách như GETH, Polygon Edge không sử dụng tính năng phản chiếu cho mã hóa.
Ưu tiên không sử dụng tính năng phản chiếu vì nó tạo ra các sự cố mới, chẳng hạn như suy giảm hiệu suất và khó mở rộng quy mô hơn. + +Mô-đun **Loại** cung cấp giao diện dễ sử dụng để marshaling (quá trình chuyển đổi các đối tượng thành chuỗi hoặc dữ liệu) và unmarshalling (quá trình chuyển đổi các chuỗi hoặc dữ liệu thành đối tượng) RLP, bằng cách sử dụng gói FastRLP. + +Marshaling (quá trình chuyển đổi các đối tượng thành chuỗi hoặc dữ liệu) được thực hiện thông qua các phương pháp *MarshalRLPWith* và *MarshalRLPTo*. Phương pháp tương tự tồn tại cho unmarshalling (quá trình chuyển đổi các chuỗi hoặc dữ liệu thành các đối tượng). + +Bằng cách xác định thủ công các phương pháp này, Polygon Edge không cần sử dụng tính năng phản xạ. Trong *rlp_marshal.go*, bạn có thể tìm thấy +phương pháp cho việc chuyển đổi marshaling: + +* **Thân** +* **Khối** +* **Tiêu đề** +* **Biên nhận** +* **Nhật ký** +* **Giao dịch** \ No newline at end of file diff --git a/archive/edge/vi-edge/architecture/overview.md b/archive/edge/vi-edge/architecture/overview.md new file mode 100644 index 0000000000..94ea4dc855 --- /dev/null +++ b/archive/edge/vi-edge/architecture/overview.md @@ -0,0 +1,59 @@ +--- +id: overview +title: Tổng quan kiến trúc +sidebar_label: Overview +description: Giới thiệu kiến trúc Polygon Edge. +keywords: + - docs + - polygon + - edge + - architecture + - modular + - layer + - libp2p + - extensible +--- + +Chúng ta bắt đầu với ý tưởng tạo một phần mềm dạng *mô-đun*. + +Đây là mục hiện diện ở hầu hết các phần của Polygon Edge. Dưới đây, bạn sẽ tìm thấy tổng quan ngắn gọn về kiến trúc xây dựng và sự phân lớp của nó. + +## Phân lớp Polygon Edge {#polygon-edge-layering} + +![Kiến trúc Polygon Edge](/img/edge/Architecture.jpg) + +## Libp2p {#libp2p} + +Tất cả bắt đầu ở lớp mạng cơ sở, sử dụng **libp2p**. Chúng tôi quyết định sử dụng công nghệ này vì nó phù hợp với triết lý thiết kế của Polygon Edge. Libp2p là: + +- Mô-đun +- Khả năng mở rộng +- Nhanh + +Quan trọng nhất là nó cung cấp một nền tảng tuyệt vời cho các tính năng nâng cao hơn, điều chúng tôi sẽ đề cập ở phần sau. + + +## Đồng bộ hóa & Đồng thuận {#synchronization-consensus} +Sự tách biệt giữa các giao thức đồng bộ và đồng thuận cho phép mô-đun hóa và triển khai các cơ chế đồng bộ và đồng thuận **tùy chỉnh** - tùy thuộc vào cách máy thức khách đang được chạy. + +Polygon Edge được thiết kế để cung cấp các thuật toán đồng thuận có thể sẵn sàng được sử dụng. + +Danh sách các thuật toán đồng thuận hiện tại: + +* IBFT PoA +* IBFT PoS + +## Blockchain {#blockchain} +Lớp Blockchain là lớp trung tâm điều phối mọi thứ trong hệ thống Polygon Edge. Mục này sẽ được đề cập sâu trong phần *Mô-đun* tương ứng. + +## Trạng thái {#state} +Lớp bên trong Trạng thái chứa logic chuyển đổi trạng thái. Lớp này giải quyết cách trạng thái thay đổi khi một khối mới được đưa vào. Mục này sẽ được đề cập sâu trong phần *Mô-đun* tương ứng. + +## JSON RPC {#json-rpc} +Lớp JSON RPC là một lớp API mà các nhà phát triển dApp sử dụng để tương tác với blockchain. Mục này sẽ được đề cập sâu trong phần *Mô-đun* tương ứng. + +## TxPool {#txpool} +Lớp TxPool đại diện cho nhóm giao dịch và sẽ được liên kết chặt chẽ với các mô-đun khác trong hệ thống, vì các giao dịch có thể được thêm vào từ nhiều điểm. + +## grpc {#grpc} +gRPC, hoặc Google Remote Proceduture Call, là một khung mã nguồn mở và nguồn gốc mạnh mà Google ban đầu tạo ra để xây dựng một APC có thể và phát triển nhanh. Lớp GRPC rất quan trọng đối với các tương tác của người vận hành. Thông qua đó, các trình vận hành nút có thể dễ dàng tương tác với máy khách, mang đến trải nghiệm người dùng thú vị. diff --git a/archive/edge/vi-edge/community/propose-new-feature.md b/archive/edge/vi-edge/community/propose-new-feature.md new file mode 100644 index 0000000000..05a74e9e02 --- /dev/null +++ b/archive/edge/vi-edge/community/propose-new-feature.md @@ -0,0 +1,66 @@ +--- +id: propose-new-feature +title: Đề xuất tính năng mới +description: "Biểu mẫu PR và hướng dẫn để đề xuất một tính năng mới." +keywords: + - docs + - polygon + - edge + - feature + - PR + - template + - fix +--- + +## Tổng quan {#overview} + +Nếu bạn muốn đề xuất một bản vá hoặc đóng góp vào việc lập trình, chúng tôi rất khuyến khích bạn liên hệ với đội ngũ của chúng tôi.
Polygon Edge sử dụng biểu mẫu đề xuất tính năng tương đối cơ bản, ngắn gọn và trọng tâm. + + +## Biểu mẫu PR {#pr-template} + +### Mô tả {#description} + +Vui lòng cung cấp mô tả chi tiết về những thay đổi được thực hiện theo biểu mẫu PR này + +### Thay đổi bao gồm {#changes-include} + +- [ ] Bugfix (thay nhỏ giúp xử lý một sự cố) +- [ ] Hotfix (thay đổi giúp xử lý sự cố khẩn cấp và cần được chú ý ngay lập tức) + +- [ ] Tính năng mới (thay đổi nhỏ giúp bổ sung chức năng) + +- [ ] Thay đổi lớn (thay đổi không tương thích ngược và/hoặc thay đổi chức năng hiện tại) + + +### Thay đổi lớn {#breaking-changes} + +Vui lòng điền phần này nếu có thay đổi lớn được thực hiện, nếu không hãy xóa nó + +### Danh sách kiểm tra {#checklist} + +- [ ] Tôi tự giao bản PR này cho mình +- [ ] Tôi đã thêm ít nhất 1 người đánh giá + +- [ ] Tôi đã thêm các nhãn liên quan +- [ ] Tôi đã cập nhật tài liệu chính thức +- [ ] Tôi đã thêm đầy đủ tài liệu vào mã + +### Thử nghiệm {#testing} + +- [ ] Tôi đã thử nghiệm mã này với bộ thử nghiệm chính thức + +- [ ] Tôi đã thử nghiệm thủ công mã này + +## Thử nghiệm thủ công {#manual-tests} + +Vui lòng hoàn tất phần này nếu bạn đã chạy thử nghiệm thủ công chức năng này, nếu không hãy xóa nó + +### Cập nhật tài liệu {#documentation-update} + +Vui lòng nhập liên kết cập nhật tài liệu PR trong phần này nếu có, nếu không hãy xóa nó + + +### Nhận xét bổ sung {#additional-comments} + +Vui lòng gửi nhận xét bổ sung trong phần này nếu có, nếu không hãy xóa nó diff --git a/archive/edge/vi-edge/community/report-bug.md b/archive/edge/vi-edge/community/report-bug.md new file mode 100644 index 0000000000..1ece6c1b48 --- /dev/null +++ b/archive/edge/vi-edge/community/report-bug.md @@ -0,0 +1,53 @@ +--- +id: report-bug +title: Báo cáo sự cố +description: Mẫu và hướng dẫn báo cáo sự cố Polygon Edge. +keywords: + - docs + - polygon + - edge + - issue + - bug + - report + - template +--- + +## Tổng quan {#overview} + +Đôi khi vài thứ hư hỏng.
Tốt hơn là để cho đội ngũ biết về bất kỳ sự cố nào mà bạn có thể gặp phải.
Trên trang Polygon Edge GitHub, bạn có thể gửi một sự cố mới và bắt đầu thảo luận với nhóm. + +## Mẫu mẫu báo cáo sự cố {#issue-template} + +## [Đối tượng của sự cố] + +### Mô tả {#description} + +Mô tả sự cố của bạn càng chi tiết càng tốt tại đây + +### Môi trường của bạn {#your-environment} + +* Hệ điều hành và phiên bản +* phiên bản của Polygon Edge +* nhánh gây ra sự cố này + +### Các bước để tái tạo {#steps-to-reproduce} + +* Nói cho chúng tôi biết cách tái tạo sự cố này
+* Sự cố ở đâu, nếu bạn biết
+* Lệnh nào gây ra sự cố, nếu có + +### Hành vi mong đợi {#expected-behaviour} + +Hãy nói cho chúng tôi điều gì nên xảy ra + +### Hành vi thực sự {#actual-behaviour} + +Thay vào đó hãy nói với chúng tôi chuyện gì đã xảy ra + +### Nhật ký {#logs} + +Vui lòng dán bất kỳ nhật ký nào vào đây để minh họa cho sự cố, nếu chúng tồn tại + +### Giải pháp đề xuất {#proposed-solution} + +Nếu bạn có ý tưởng về cách xử lý sự cố, vui lòng viết xuống đây, để chúng ta có thể bắt đầu thảo luận \ No newline at end of file diff --git a/archive/edge/vi-edge/configuration/manage-private-keys.md b/archive/edge/vi-edge/configuration/manage-private-keys.md new file mode 100644 index 0000000000..2b9c01f861 --- /dev/null +++ b/archive/edge/vi-edge/configuration/manage-private-keys.md @@ -0,0 +1,84 @@ +--- +id: manage-private-keys +title: Quản lý khóa riêng tư +description: "Cách quản lý khóa riêng tư và phân loại khóa.\n" +keywords: + - docs + - polygon + - edge + - private + - key + - keystore +--- + +## Tổng quan {#overview} + +Polygon Edge có hai loại khóa riêng tư mà nó trực tiếp quản lý: + + +* **Khóa riêng tư sử dụng cho cơ chế đồng đồng thuận** +* **Khóa riêng tư dùng để kết nối mạng của libp2p** +* **(Không bắt buộc) Khóa riêng tư BLS sử dụng trong cơ chế đồng thuận để tổng hợp chữ ký của trình xác thực** + +Hiện tại, Polygon Edge không hỗ trợ quản lý tài khoản trực tiếp. + +Dựa trên cấu trúc thư mục được nêu trong [Hướng dẫn Phục hồi và Lưu trữ](/docs/edge/working-with-node/backup-restore) +, + Polygon Edge lưu trữ các tệp khóa này trong hai thư mục riêng biệt - **đồng thuận** và **kho khóa**. + + +## Định dạng khóa {#key-format} + +Các khóa riêng tư được lưu trữ ở **định dạng Base64** đơn giản, vì vậy người dùng có thể đọc được và có thể chuyển được. + + +```bash +# Example private key +0802122068a1bdb1c8af5333e58fe586bc0e9fc7aff882da82affb678aef5d9a2b9100c0 +``` + +:::info Loại khóa +Tất cả các tệp khóa riêng tư được tạo và sử dụng trong Polygon Edge đều dựa trên ECDSA và curve [secp256k1](https://en.bitcoin.it/wiki/Secp256k1). + + +Vì curve không được chuẩn hóa, nên không thể được mã hóa và lưu trữ ở bất kỳ định dạng PEM tiêu chuẩn nào. + Không hỗ trợ việc nhập khóa không phù hợp với loại khóa này. + +::: +## Khóa riêng tư đồng thuận {#consensus-private-key} + +Tệp khóa riêng tư được gọi là *khóa riêng tư đồng đồng thuận* còn được gọi là **khóa riêng tư xác thực**. Khóa riêng tư này được sử dụng khi nút đóng vai trò trình xác thực trong mạng lưới và cần ký dữ liệu mới. + +Tệp khóa riêng tư nằm trong `consensus/validator.key` và tuân thủ theo [định dạng khóa](/docs/edge/configuration/manage-private-keys#key-format) đã đề cập. + +:::warning +Khóa riêng tư trình xác thực là duy nhất với mỗi nút trình xác thực. + Khóa sẽ không được chia sẻ cho tất cả các trình xác thực, vì điều này có thể ảnh hưởng đến tính bảo mật của chuỗi. + +::: + +## Khóa riêng tư kết nối mạng {#networking-private-key} + +Tệp khóa riêng tư kết nối mạng đã đề cập được libp2p sử dụng để tạo PeerID tương ứng, cho phép nút tham gia vào mạng lưới. + + +Tệp nằm trong `keystore/libp2p.key` và tuân thủ theo [định dạng khóa](/docs/edge/configuration/manage-private-keys#key-format) đã đề cập. + +## Khóa bí mật BLS {#bls-secret-key} + +Tệp tin khóa bí mật BLS được sử dụng để tổng hợp dấu đồng thuận với lớp đồng thuận. Kích thước của các dấu cam kết được tổng hợp bằng BLS nhỏ hơn chữ ký ECDSA đã cam kết tuần tự. + + +Tính năng BLS là không bắt buộc và bạn có thể chọn sử dụng BLS hoặc không. + Xem thêm [BLS](/docs/edge/consensus/bls) để biết thêm chi tiết. + +## Nhập / Xuất {#import-export} + +Vì các tệp khóa được lưu trữ ở định dạng Base64 đơn giản trên đĩa, chúng có thể được sao lưu hoặc nhập dễ dàng. + + +:::caution Thay đổi tệp khóa +Bất kỳ thay đổi nào được thực hiện đối với các tệp khóa trên một mạng lưới đã thiết lập/chạy đều có thể dẫn đến gián đoạn mạng lưới/đồng thuận nghiêm trọng, vì cơ chế đồng thuận và cơ chế khám phá ngang hàng đều lưu trữ dữ liệu thu được từ các khóa này trong bộ nhớ dành riêng cho từng nút, cũng như sử dụng dữ liệu này để + khởi tạo kết nối và thực hiện logic đồng thuận + +::: \ No newline at end of file diff --git a/archive/edge/vi-edge/configuration/prometheus-metrics.md b/archive/edge/vi-edge/configuration/prometheus-metrics.md new file mode 100644 index 0000000000..56afbac205 --- /dev/null +++ b/archive/edge/vi-edge/configuration/prometheus-metrics.md @@ -0,0 +1,41 @@ +--- +id: prometheus-metrics +title: Số liệu Prometheus + +description: "Cách kích hoạt số liệu Prometheus trên Polygon Edge.\n" +keywords: + - docs + - polygon + - edge + - metrics + - prometheus +--- + +## Tổng quan {#overview} + +Polygon Edge có thể báo cáo và phân phát các số liệu Prometheus, chúng có thể được sử dụng bằng trình thu thập Prometheus. + + +metheus đã bị tắt theo mặc định. Nó có thể được bật bằng cách xác định địa chỉ của người nghe bằng `--prometheus`[cờ](/docs/edge/get-started/cli-commands#prometheus) `Telemetry.prometheus`hoặc trường trong tệp tin cấu hình. Các số liệu sẽ được phân phát dưới dạng `/metrics` trên địa chỉ được chỉ định. + + +## Số liệu có sẵn {#available-metrics} + +Hiện có sẵn các số liệu sau đây: + + +| **Tên** | **Loại** | **Mô tả** | +|-------------------------------------------------|----------|---------------------------------------------| +| edge_txpool_pool_pend_translated by | Gauge | Số lượng giao dịch đang chờ xử lý trong TxPool | +| edge_asufactor | Gauge | Số lượng trình xác thực + | +| edge_deal_cours_cours_courssus | Gauge | Số lượng lượt | +| edge_dealsum_num_txs | Gauge | Số lượng giao dịch trong khối mới nhất | +| edge_econtinuues_block_interview | Gauge | Thời gian giữa khối này và khối gần nhất tính theo giây + | +| edge_nets_peeer | Gauge | Số lượng các số đồng số kết nối | +| edge_neted_nets_outbbed_outbbed_interbbben_outbound_bed_en_e_ed_interbound_e_e_ed_tabbed_intered_ | Gauge | Số lượng kết nối bên ngoài | +| edge_mạng need_inbbbed_inbbound_intered_intereded_inbbbound__e_tabed_intereded_intered_tab_e_intered_intered_intered_comp_e_e_coun | Gauge | Số lượng kết nối bên trong | +| ededed_mạng lưới_pen_inbed_interededed_pen_deed_compe_pen_pen_inbed_e_tabed_e_ededed_pen_e_e_deed_coun_count_ed | Gauge | Số lượng kết nối bên ngoài đang chờ xử lý | +| edge_net_pend_pend_outs_depend_contrump_en, depends_enborn_dep, depend_en, depend_ened | Gauge | Số lượng kết nối bên trong đang chờ xử lý | +| edge_epoch_số edge_ededep_epoch_edge_epededepeep_number | Gauge | Số epoch hiện tại | \ No newline at end of file diff --git a/archive/edge/vi-edge/configuration/sample-config.md b/archive/edge/vi-edge/configuration/sample-config.md new file mode 100644 index 0000000000..eed02e8511 --- /dev/null +++ b/archive/edge/vi-edge/configuration/sample-config.md @@ -0,0 +1,160 @@ +--- +id: sample-config +title: Tệp cấu hình máy chủ +description: "Khởi động máy chủ Polygon Edge bằng tệp cấu hình.\n" +keywords: + - docs + - polygon + - edge + - server + - configuration + - yaml + - jason + +--- +# Tệp cấu hình máy chủ {#server-configuration-file} +Khởi động máy chủ với các tùy chọn cấu hình khác nhau có thể được thực hiện bằng tệp cấu hình thay vì chỉ sử dụng cờ. + Lệnh được dùng để khởi động máy chủ với tệp cấu hình: +`polygon-edge server --config ` + +## Xuất tệp cấu hình với cấu hình mặc định + {#export-config-file-with-default-configuration} +Cấu hình với cài đặt mặc định dành cho máy chủ Polygon Edge có thể được xuất thành tệp cấu hình ở định dạng tệp `yaml` hoặc `json`. + Tệp này có thể được sử dụng làm mẫu cho việc chạy máy chủ bằng tệp cấu hình. + + +### YAML {#yaml} +Để tạo tệp cấu hình theo định dạng `yaml`: +```bash +polygon-edge server export --type yaml +``` +hoặc chỉ +```bash +polygon-edge server export +``` +Tệp cấu hình có tên `default-config.yaml` sẽ được tạo trong cùng thư mục mà lệnh này đã được chạy. + + +Ví dụ về tệp tin: +```yaml +chain_config: ./genesis.json +secrets_config: "" +data_dir: "" +block_gas_target: "0x0" +grpc_addr: "" +jsonrpc_addr: "" +telemetry: + prometheus_addr: "" +network: + no_discover: false + libp2p_addr: 127.0.0.1:1478 + nat_addr: "" + dns_addr: "" + max_peers: -1 + max_outbound_peers: -1 + max_inbound_peers: -1 +seal: true +tx_pool: + price_limit: 0 + max_slots: 4096 +log_level: INFO +restore_file: "" +block_time_s: 2 +headers: + access_control_allow_origins: + - '*' +log_to: "" +``` + +### JSON {#json} +Để tạo tệp cấu hình theo định dạng `json`: +```bash +polygon-edge server export --type json +``` +Tệp cấu hình có tên `default-config.json` sẽ được tạo trong cùng thư mục mà lệnh này đã được chạy. + + +Ví dụ về tệp tin: + +```json +{ + "chain_config": "./genesis.json", + "secrets_config": "", + "data_dir": "", + "block_gas_target": "0x0", + "grpc_addr": "", + "jsonrpc_addr": "", + "telemetry": { + "prometheus_addr": "" + }, + "network": { + "no_discover": false, + "libp2p_addr": "127.0.0.1:1478", + "nat_addr": "", + "dns_addr": "", + "max_peers": -1, + "max_outbound_peers": -1, + "max_inbound_peers": -1 + }, + "seal": true, + "tx_pool": { + "price_limit": 0, + "max_slots": 4096 + }, + "log_level": "INFO", + "restore_file": "", + "block_time_s": 2, + "headers": { + "access_control_allow_origins": [ + "*" + ] + }, + "log_to": "" +} +``` + +Hãy xem phần [Lệnh CLI](/docs/edge/get-started/cli-commands) để biết thông tin về cách sử dụng các tham số này. + + +### Lược đồ TypeScript + {#typescript-schema} + +Sau đây là định dạng mẫu cho tệp cấu hình. Nó được viết bằng TypeScript để trình bày các kiểu thuộc tính (·`string`, `number`, `boolean`), từ đó bạn có thể lấy ra cấu hình của mình. + Lưu ý rằng kiểu `PartialDeep` từ `type-fest` được sử dụng để trình bày rằng tất cả các thuộc tính là không bắt buộc. + + +```typescript +import { PartialDeep } from 'type-fest'; + +type ServerConfig = PartialDeep<{ + chain_config: string; // + secrets_config: string; // + data_dir: string; // + block_gas_target: string; // + grpc_addr: string; // + jsonrpc_addr: string; // + telemetry: { + prometheus_addr: string; // + }; + network: { + no_discover: boolean; // , + libp2p_addr: string; // , + nat_addr: string; // , + dns_addr: string; // , + max_peers: number; // , + max_inbound_peers: number; // , + max_outbound_peers: number; // + }; + seal: boolean; // + txpool: { + price_limit: number; // + max_slots: number; // + }; + log_level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'DPANIC' | 'PANIC' | 'FATAL'; // + restore_file: string; // + block_time_s: number; // + headers: Record; + log_to: string; // +}> +``` + diff --git a/archive/edge/vi-edge/configuration/secret-managers/set-up-aws-ssm.md b/archive/edge/vi-edge/configuration/secret-managers/set-up-aws-ssm.md new file mode 100644 index 0000000000..56060919d1 --- /dev/null +++ b/archive/edge/vi-edge/configuration/secret-managers/set-up-aws-ssm.md @@ -0,0 +1,135 @@ +--- +id: set-up-aws-ssm +title: Thiết lập AWS SSM (Trình quản lý Hệ thống) +description: "Thiết lập AWS SSM (Trình quản lý Hệ thống) cho Polygon Edge." +keywords: + - docs + - polygon + - edge + - aws + - ssm + - secrets + - manager +--- + +## Tổng quan {#overview} + +Hiện tại, Polygon Edge quan tâm đến việc giữ 2 bí mật chính về thời gian chạy: +* **Khóa riêng tư của trình xác thực** được nút sử dụng, nếu nút là trình xác thực +* **Khóa riêng tư của mạng** được libp2p sử dụng để tham gia và giao tiếp với mạng ngang hàng khác + +Để biết thêm thông tin, vui lòng đọc qua [Hướng dẫn Quản lý Khóa Riêng tư](/docs/edge/configuration/manage-private-keys) + +Các mô-đun của Polygon Edge **không cần biết cách giữ bí mật**. Sau cùng, một mô-đun không cần quan tâm nếu + một bí mật được lưu trữ trên một máy chủ ở xa hoặc cục bộ trên ổ cứng của nút. + + +Mọi thứ mà một mô-đun cần biết về việc giữ bí mật là **biết cách sử dụng bí mật**, **biết những bí mật nào cần lấy + hoặc lưu lại**. Các thông tin triển khai quan trọng hơn của các hoạt động này được ủy quyền cho `SecretsManager`, tất nhiên đây chỉ là cách diễn giải trừu tượng. + + +Trình vận hành nút khởi động Polygon Edge hiện có thể chỉ định trình quản lý bí mật nào họ muốn sử dụng và ngay + khi trình quản lý bí mật chính xác được khởi tạo, các mô-đun xử lý các bí mật thông qua giao diện được đề cập - + mà không cần quan tâm các bí mật được lưu trữ trên đĩa hay máy chủ. + + +Bài viết này trình bày chi tiết các bước cần thiết để thiết lập và chạy Polygon Edge với [Cửa hàng thông số trình quản lý hệ thống AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html). + +:::info các hướng dẫn trước đây +Chúng tôi **khuyến nghị** rằng trước khi xem bài viết này, hãy đọc các bài viết về [**Thiết lập Cục bộ**](/docs/edge/get-started/set-up-ibft-locally) + và [**Thiết lập Đám mây**](/docs/edge/get-started/set-up-ibft-on-the-cloud). +::: + + +## Điều kiện tiên quyết {#prerequisites} +### Chính sách IAM {#iam-policy} +Người dùng cần tạo Chính sách IAM cho phép hoạt động đọc/ghi đối với Cửa hàng thông số trình quản lý hệ thống AWS. Sau khi tạo thành công Chính sách IAM, người dùng cần đính kèm nó vào cá thể EC2 đang chạy máy chủ Polygon Edge. Chính sách IAM sẽ trông giống như sau: +```json +{ + "Version": "2012-10-17", + "Statement" : [ + { + "Effect" : "Allow", + "Action" : [ + "ssm:PutParameter", + "ssm:DeleteParameter", + "ssm:GetParameter" + ], + "Resource" : [ + "arn:aws:ssm:::parameter*" + ] + } + ] +} +``` +Bạn có thể tìm thấy thông tin chi tiết về Vai trò AWS SSM IAM trong [tài liệu AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html). + +Thông tin cần có trước khi tiếp tục: +* **Region** (khu vực có chứa Trình quản lý Hệ thống và nút) +* **Parameter Path** (ví dụ: đường dẫn tùy ý mà bí mật sẽ được đặt vào `/polygon-edge/nodes`) + +## Bước 1 - Tạo cấu hình trình quản lý bí mật {#step-1-generate-the-secrets-manager-configuration} + +Để Polygon Edge có thể giao tiếp liền mạch với AWS SSM, cần phân tích cú pháp + tệp cấu hình đã tạo, chứa tất cả thông tin cần thiết để lưu trữ bí mật trên AWS SSM. + +Để tạo cấu hình, hãy chạy lệnh sau: + +```bash +polygon-edge secrets generate --type aws-ssm --dir --name --extra region=,ssm-parameter-path= +``` + +Các tham số hiện tại: +* `PATH`là đường dẫn mà tệp tin cấu hình cần được xuất vào. Mặc định `./secretsManagerConfig.json` +* `NODE_NAME` là tên của nút hiện tại mà cấu hình AWS SSM đang được thiết lập. Nó có thể là một giá giá trị tùy ý. Mặc định `polygon-edge-node` +* `REGION`là vùng trong đó lưu trữ AWS SSM. Đây phải cùng một vùng với nút sử dụng AWS SSM. +* `SSM_PARAM_PATH` là tên của đường dẫn mà bí mật sẽ được lưu trữ trong đó. Ví dụ nếu `--name node1` và `ssm-parameter-path=/polygon-edge/nodes`được chỉ định, bí mật sẽ được lưu trữ như `/polygon-edge/nodes/node1/` + +:::caution Tên nút + +Hãy thận trọng khi chỉ định tên nút. + +Polygon Edge sử dụng tên nút được chỉ định để theo dõi các bí mật mà nó tạo và sử dụng trên AWS SSM. + Việc chỉ định tên nút hiện tại có thể dẫn đến hậu quả là không thể ghi bí mật vào AWS SSM. + +Các bí mật được lưu trữ trên đường dẫn cơ sở sau: `SSM_PARAM_PATH/NODE_NAME` +::: + +## Bước 2 - Khởi tạo khóa bí mật bằng cách sử dụng cấu hình {#step-2-initialize-secret-keys-using-the-configuration} + +Giờ đây, khi đã có tệp cấu hình, chúng ta có thể khởi tạo các khóa bí mật cần thiết với tệp cấu hình + được thiết lập ở bước 1, sử dụng `--config`: + +```bash +polygon-edge secrets init --config +``` + +Tham số `PATH` là vị trí của tham số trình quản lý bí mật đã được tạo trước đó từ bước 1. + + +:::info Chính sách IAM + +Bước này sẽ không thành công nếu Chính sách IAM cho phép hoạt động đọc/ghi không được định cấu hình chính xác và/hoặc không được đính kèm với phiên bản EC2 chạy lệnh này. +::: + +## Bước 3 - Tạo tệp tin khởi nguồn {#step-3-generate-the-genesis-file} + +Tệp tin khởi nguồn phải được tạo theo cách tương tự như hướng dẫn [**Thiết lập Cục bộ**](/docs/edge/get-started/set-up-ibft-locally) + và [**Thiết lập Đám mây**](/docs/edge/get-started/set-up-ibft-on-the-cloud), với một vài thay đổi nhỏ. + +Vì AWS SSM đang được sử dụng thay vì hệ thống tệp cục bộ, nên các địa chỉ của trình xác thực phải được thêm thông qua cờ `--ibft-validator`: +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Bước 4 - Bắt đầu máy khách Polygon Edge {#step-4-start-the-polygon-edge-client} + +Bây giờ khi các khóa đã được thiết lập và tệp khởi nguồn đã được tạo, bước cuối cùng của quá trình là khởi tạo Polygon Edge bằng lệnh `server`. + +Lệnh `server` được sử dụng theo cách tương tự như trong các hướng dẫn đã đề cập trước đó, với một bổ sung nhỏ - cờ `--secrets-config`: + +```bash +polygon-edge server --secrets-config ... +``` + +Tham số `PATH` là vị trí của tham số trình quản lý bí mật đã được tạo trước đó từ bước 1. diff --git a/archive/edge/vi-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md b/archive/edge/vi-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md new file mode 100644 index 0000000000..6cb2d1127f --- /dev/null +++ b/archive/edge/vi-edge/configuration/secret-managers/set-up-gcp-secrets-manager.md @@ -0,0 +1,132 @@ +--- +id: set-up-gcp-secrets-manager +title: Thiết lập Trình quản lý bí mật GCP +description: "Thiết lập Trình quản lý bí mật GCP cho Polygon Edge." +keywords: + - docs + - polygon + - edge + - gcp + - secrets + - manager +--- + +## Tổng quan {#overview} + +Hiện tại, Polygon Edge quan tâm đến việc giữ 2 bí mật chính về thời gian chạy: +* **Khóa riêng tư của trình xác thực** được nút sử dụng, nếu nút là trình xác thực +* **Khóa riêng tư của mạng** được libp2p sử dụng để tham gia và giao tiếp với mạng ngang hàng khác + +Để biết thêm thông tin, vui lòng đọc qua [Hướng dẫn Quản lý Khóa Riêng tư](/docs/edge/configuration/manage-private-keys) + +Các mô-đun của Polygon Edge **không cần biết cách giữ bí mật**. Sau cùng, một mô-đun không cần quan tâm nếu + một bí mật được lưu trữ trên một máy chủ ở xa hoặc cục bộ trên ổ cứng của nút. + + +Mọi thứ mà một mô-đun cần biết về việc giữ bí mật là **biết cách sử dụng bí mật**, **biết những bí mật nào cần lấy + hoặc lưu lại**. Các thông tin triển khai quan trọng hơn của các hoạt động này được ủy quyền cho `SecretsManager`, tất nhiên đây chỉ là cách diễn giải trừu tượng. + + +Trình vận hành nút khởi động Polygon Edge hiện có thể chỉ định trình quản lý bí mật nào họ muốn sử dụng và ngay + khi trình quản lý bí mật chính xác được khởi tạo, các mô-đun xử lý các bí mật thông qua giao diện được đề cập - + mà không cần quan tâm các bí mật được lưu trữ trên đĩa hay máy chủ. + + +Bài viết này trình bày chi tiết các bước cần thiết để thiết lập và chạy Polygon Edge với [Trình quản lý bí mật GCP](https://cloud.google.com/secret-manager). + + +:::info các hướng dẫn trước đây +Chúng tôi **khuyến nghị** rằng trước khi xem bài viết này, hãy đọc các bài viết về [**Thiết lập Cục bộ**](/docs/edge/get-started/set-up-ibft-locally) + và [**Thiết lập Đám mây**](/docs/edge/get-started/set-up-ibft-on-the-cloud). +::: + + +## Điều kiện tiên quyết {#prerequisites} +### Tài khoản thanh toán GCP + {#gcp-billing-account} +Để sử dụng Trình quản lý bí mật GCP, người dùng phải có [Tài khoản thanh toán](https://console.cloud.google.com/) được kích hoạt trên cổng GCP. + Các tài khoản Google mới trên nền tảng GCP được cung cấp một số tiền ban đầu, với tư cách là tài khoản dùng thử miễn phí. + Thông tin thêm có tại [tài liệu GCP](https://cloud.google.com/free) + +### API Trình quản lý bí mật {#secrets-manager-api} + +Người dùng sẽ cần kích hoạt API Trình quản lý bí mật GCP trước khi sử dụng. +Có thể thực hiện việc này thông qua [cổng thông tin API Trình quản lý bí mật](https://console.cloud.google.com/apis/library/secretmanager.googleapis.com). Thông tin thêm: [Cấu hình Trình quản lý bí mật](https://cloud.google.com/secret-manager/docs/configuring-secret-manager) + + +### Thông tin đăng nhập GCP + {#gcp-credentials} +Cuối cùng, người dùng cần tạo thông tin đăng nhập mới để xác thực. + Có thể thực hiện việc này theo chỉ dẫn sau được đăng tải [tại đây](https://cloud.google.com/secret-manager/docs/reference/libraries). Tệp json được tạo có chứa thông tin đăng nhập và sẽ được chuyển đến từng nút cần sử dụng Trình quản lý bí mật GCP. + + +Thông tin cần có trước khi tiếp tục: +* **Project ID** (ID dự án được xác định trên nền tảng GCP) + +* **Credentials File Location** (đường dẫn đến tệp json chứa thông tin đăng nhập) + + +## Bước 1 - Tạo cấu hình trình quản lý bí mật {#step-1-generate-the-secrets-manager-configuration} + +Để Polygon Edge có thể giao tiếp liền mạch với GCP SM, cần phân tích cú pháp + của tệp cấu hình đã tạo, gồm tất cả thông tin cần thiết để lưu trữ bí mật trên GCP SM. + + +Để tạo cấu hình, hãy chạy lệnh sau: + +```bash +polygon-edge secrets generate --type gcp-ssm --dir --name --extra project-id=,gcp-ssm-cred= +``` + +Các tham số hiện tại: +* `PATH`là đường dẫn mà tệp tin cấu hình cần được xuất vào. Mặc định `./secretsManagerConfig.json` +* `NODE_NAME`là tên của nút hiện tại mà cấu hình GCP SM đang được thiết lập. + Nó có thể là một giá giá trị tùy ý. Mặc định `polygon-edge-node` +* `PROJECT_ID` là ID của dự án mà người dùng đã chỉ định trong bảng điều khiển GCP trong quá trình thiết lập tài khoản và kích hoạt API Trình quản lý bí mật. + +* `GCP_CREDS_FILE` là đường dẫn đến tệp tin json chứa thông tin đăng nhập mà sẽ cho phép đọc/ghi vào Trình quản lý Bí mật. + +:::caution Tên nút +Hãy thận trọng khi chỉ định tên nút. + +Polygon Edge sử dụng tên nút được chỉ định để theo dõi các bí mật mà nó tạo và sử dụng trên GCP SM. + Việc chỉ định tên nút hiện tại có thể dẫn đến hậu quả là không thể ghi bí mật vào GCP SM. + + +Các bí mật được lưu trữ trên đường dẫn cơ sở sau: `projects/PROJECT_ID/NODE_NAME` +::: + +## Bước 2 - Khởi tạo khóa bí mật bằng cách sử dụng cấu hình {#step-2-initialize-secret-keys-using-the-configuration} + +Giờ đây, khi đã có tệp cấu hình, chúng ta có thể khởi tạo các khóa bí mật cần thiết với tệp cấu hình + được thiết lập ở bước 1, sử dụng `--config`: + +```bash +polygon-edge secrets init --config +``` + +Tham số `PATH` là vị trí của tham số trình quản lý bí mật đã được tạo trước đó từ bước 1. + + +## Bước 3 - Tạo tệp tin khởi nguồn {#step-3-generate-the-genesis-file} + +Tệp tin khởi nguồn phải được tạo theo cách tương tự như hướng dẫn [**Thiết lập Cục bộ**](/docs/edge/get-started/set-up-ibft-locally) + và [**Thiết lập Đám mây**](/docs/edge/get-started/set-up-ibft-on-the-cloud), với một vài thay đổi nhỏ. + +Vì GCP SM được sử dụng thay vì hệ thống tệp cục bộ, việc các thêm địa chỉ của trình xác thực cần được thực hiện thông qua cờ `--ibft-validator`: + +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Bước 4 - Bắt đầu máy khách Polygon Edge {#step-4-start-the-polygon-edge-client} + +Bây giờ khi các khóa đã được thiết lập và tệp khởi nguồn đã được tạo, bước cuối cùng của quá trình là khởi tạo Polygon Edge bằng lệnh `server`. + +Lệnh `server` được sử dụng theo cách tương tự như trong các hướng dẫn đã đề cập trước đó, với một bổ sung nhỏ - cờ `--secrets-config`: + +```bash +polygon-edge server --secrets-config ... +``` + +Tham số `PATH` là vị trí của tham số trình quản lý bí mật đã được tạo trước đó từ bước 1. diff --git a/archive/edge/vi-edge/configuration/secret-managers/set-up-hashicorp-vault.md b/archive/edge/vi-edge/configuration/secret-managers/set-up-hashicorp-vault.md new file mode 100644 index 0000000000..02cea3ddc9 --- /dev/null +++ b/archive/edge/vi-edge/configuration/secret-managers/set-up-hashicorp-vault.md @@ -0,0 +1,131 @@ +--- +id: set-up-hashicorp-vault +title: Thiết lập Hashicorp Vault + +description: "Thiết lập Hashicorp Vault cho Polygon Edge.\n" +keywords: + - docs + - polygon + - edge + - hashicorp + - vault + - secrets + - manager +--- + +## Tổng quan {#overview} + +Hiện tại, Polygon Edge quan tâm đến việc giữ 2 bí mật chính về thời gian chạy: +* **Khóa riêng tư của trình xác thực** được nút sử dụng, nếu nút là trình xác thực +* **Khóa riêng tư của mạng** được libp2p sử dụng để tham gia và giao tiếp với mạng ngang hàng khác + +:::warning +Khóa riêng tư của trình xác thực là duy nhất với mỗi nút trình xác thực. + Khóa này sẽ không được chia sẻ cho tất cả các trình xác thực, vì điều này có thể ảnh hưởng đến tính bảo mật của chuỗi. + +::: + +Để biết thêm thông tin, vui lòng đọc qua [Hướng dẫn Quản lý Khóa Riêng tư](/docs/edge/configuration/manage-private-keys) + +Các mô-đun của Polygon Edge **không cần biết cách giữ bí mật**. Sau cùng, một mô-đun không cần quan tâm nếu + một bí mật được lưu trữ trên một máy chủ ở xa hoặc cục bộ trên ổ cứng của nút. + + +Mọi thứ mà một mô-đun cần biết về việc giữ bí mật là **biết cách sử dụng bí mật**, **biết những bí mật nào cần lấy + hoặc lưu lại**. Các thông tin triển khai quan trọng hơn của các hoạt động này được ủy quyền cho `SecretsManager`, tất nhiên đây chỉ là cách diễn giải trừu tượng. + + +Trình vận hành nút khởi động Polygon Edge hiện có thể chỉ định trình quản lý bí mật nào họ muốn sử dụng và ngay + khi trình quản lý bí mật chính xác được khởi tạo, các mô-đun xử lý các bí mật thông qua giao diện được đề cập - + mà không cần quan tâm các bí mật được lưu trữ trên đĩa hay máy chủ. + + +Bài viết này trình bày chi tiết các bước cần thiết để thiết lập và chạy Polygon Edge với máy chủ [Hashicorp Vault](https://www.vaultproject.io/) + + +:::info các hướng dẫn trước đây +Chúng tôi **khuyến nghị** rằng trước khi xem bài viết này, hãy đọc các bài viết về [**Thiết lập Cục bộ**](/docs/edge/get-started/set-up-ibft-locally) + và [**Thiết lập Đám mây**](/docs/edge/get-started/set-up-ibft-on-the-cloud). +::: + + +## Điều kiện tiên quyết {#prerequisites} + +Bài viết này, giả định rằng một phiên bản đang hoạt động của máy chủ Hashicorp Vault **đã được thiết lập**. + + +Ngoài ra, máy chủ Hashicorp Vault được sử dụng cho Polygon Edge phải có **bộ lưu trữ KV được kích hoạt** . + + +Thông tin cần có trước khi tiếp tục: +* **URL máy chủ** (URL API của máy chủ Hashicorp Vault) + +* **Token** (token truy cập được sử dụng để truy cập vào công cụ lưu trữ KV) + + +## Bước 1 - Tạo cấu hình trình quản lý bí mật {#step-1-generate-the-secrets-manager-configuration} + +Để Polygon Edge có thể giao tiếp liền mạch với máy chủ Vault, cần có phân tích cú pháp + của tệp cấu hình đã tạo, gồm tất cả thông tin cần thiết để lưu trữ bí mật trên Vault. + + +Để tạo cấu hình, hãy chạy lệnh sau: + +```bash +polygon-edge secrets generate --dir --token --server-url --name +``` + +Các tham số hiện tại: +* `PATH`là đường dẫn mà tệp tin cấu hình cần được xuất vào. Mặc định `./secretsManagerConfig.json` +* `TOKEN`là token truy cập đã được đề cập trước đó trong [phần điều kiện tiên quyết](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) + +* `SERVER_URL`là URL của API máy chủ Vault, cũng được đề cập trong [phần điều kiện tiên quyết](/docs/edge/configuration/secret-managers/set-up-hashicorp-vault#prerequisites) + +* `NODE_NAME` là tên của nút hiện tại mà cấu hình Vault đang được thiết lập. + Nó có thể là một giá giá trị tùy ý. Mặc định `polygon-edge-node` + +:::caution Tên nút + +Hãy thận trọng khi chỉ định tên nút. + +Polygon Edge sử dụng tên nút được chỉ định để theo dõi các bí mật mà nó tạo ra và sử dụng trên Vault. + Việc chỉ định tên nút đã tồn tại có thể dẫn đến hậu quả là dữ liệu bị ghi đè trên máy chủ Vault. + + +Các bí mật được lưu trữ trên đường dẫn cơ sở sau: `secrets/node_name` +::: + +## Bước 2 - Khởi tạo khóa bí mật bằng cách sử dụng cấu hình {#step-2-initialize-secret-keys-using-the-configuration} + +Giờ đây, khi đã có tệp cấu hình, chúng ta có thể khởi tạo các khóa bí mật cần thiết với tệp cấu hình + được thiết lập ở bước 1, sử dụng `--config`: + +```bash +polygon-edge secrets init --config +``` + +Tham số `PATH` là vị trí của tham số trình quản lý bí mật đã được tạo trước đó từ bước 1. + + +## Bước 3 - Tạo tệp tin khởi nguồn {#step-3-generate-the-genesis-file} + +Tệp tin khởi nguồn phải được tạo theo cách tương tự như hướng dẫn [**Thiết lập Cục bộ**](/docs/edge/get-started/set-up-ibft-locally) + và [**Thiết lập Đám mây**](/docs/edge/get-started/set-up-ibft-on-the-cloud), với một vài thay đổi nhỏ. + +Vì Hashicorp Vault được sử dụng thay cho hệ thống tệp cục bộ, nên việc thêm địa chỉ trình xác thực cần được thực hiện qua cờ `--ibft-validator`: + +```bash +polygon-edge genesis --ibft-validator ... +``` + +## Bước 4 - Bắt đầu máy khách Polygon Edge {#step-4-start-the-polygon-edge-client} + +Bây giờ khi các khóa đã được thiết lập và tệp khởi nguồn đã được tạo, bước cuối cùng của quá trình là khởi tạo Polygon Edge bằng lệnh `server`. + +Lệnh `server` được sử dụng theo cách tương tự như trong các hướng dẫn đã đề cập trước đó, với một bổ sung nhỏ - cờ `--secrets-config`: + +```bash +polygon-edge server --secrets-config ... +``` + +Tham số `PATH` là vị trí của tham số trình quản lý bí mật đã được tạo trước đó từ bước 1. diff --git a/archive/edge/vi-edge/consensus/bls.md b/archive/edge/vi-edge/consensus/bls.md new file mode 100644 index 0000000000..93bde2aa75 --- /dev/null +++ b/archive/edge/vi-edge/consensus/bls.md @@ -0,0 +1,141 @@ +--- +id: bls +title: BLS +description: "Giải thích và hướng dẫn liên quan đến chế độ BLS." +keywords: + - docs + - polygon + - edge + - bls +--- + +## Tổng quan {#overview} + +BLS cũng được biết đến với tên Bloneh–Lynn–Shamm (BS)- là một kế hoạch đặc trưng mã hóa cho phép người dùng xác thực rằng một signer là xác thực. Đây là một kế hoạch đặc trưng có thể kết hợp nhiều chữ ký. Trong Polygon Edge, BLS được sử dụng mặc định để cung cấp bảo mật tốt hơn trong chế độ đồng thuận IBFT. BLS có thể tổng hợp các chữ ký thành một mảng byte đơn và giảm kích thước tiêu đề khối. Mỗi chuỗi có thể chọn sử dụng BLS hoặc không. Khóa ECDSA được sử dụng bất kể chế độ BLS có được bật hay không. + +## Trình soạn tin Video {#video-presentation} + +[![bls - video](https://img.youtube.com/vi/HbUmZpALlqo/0.jpg)](https://www.youtube.com/watch?v=HbUmZpALlqo) + +## Cách thiết lập một chuỗi mới bằng BLS {#how-to-setup-a-new-chain-using-bls} + +Tham khảo phần [Thiết lập Cục bộ](/docs/edge/get-started/set-up-ibft-locally) / [Thiết lập Đám mây](/docs/edge/get-started/set-up-ibft-on-the-cloud) để biết hướng dẫn thiết lập chi tiết. + +## Cách chuyển từ chuỗi ECDSA PoA hiện hữu sang chuỗi BLS PoA {#how-to-migrate-from-an-existing-ecdsa-poa-chain-to-bls-poa-chain} + +Phần này mô tả cách sử dụng chế độ BLS trong chuỗi PoA hiện hữu. Các bước sau là bắt buộc để kích hoạt BLS trong chuỗi PoA. + +1. Dừng tất cả các nút +2. Tạo khóa BLS cho các trình xác thực +3. Thêm cài đặt fork vào genesis.json +4. Khởi động lại tất cả các nút + +### 1. Dừng tất cả các nút {#1-stop-all-nodes} + +Chấm dứt tất cả các quy trình của các trình xác thực bằng cách nhấn Ctrl + c (Control + c). Vui lòng ghi nhớ chiều cao khối mới nhất (số thứ tự cao nhất trong nhật ký cam kết khối). + +### 2. Tạo khóa BLS {#2-generate-the-bls-key} + +`secrets init` với `--bls` tạo khóa BLS. Để giữ ECDSA và khóa Mạng hiện hữu và thêm khóa BLS mới, cần vô hiệu hoá `--ecdsa` và `--network`. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Thêm thiết lập fork {#3-add-fork-setting} + +Lệnh `ibft switch` thêm thiết lập fork, cho phép bật BLS trong chuỗi hiện hữu, thành `genesis.json`. + +Đối với mạng PoA, các trình xác thực cần được cho sẵn trong lệnh. Giống như lệnh `genesis`, cờ `--ibft-validators-prefix-path`hoặc `--ibft-validator` có thể được sử dụng để chỉ định trình xác thực. + +Chỉ định độ cao (số lượng khối) mà từ đó chuỗi bắt đầu sử dụng BLS với cờ `--from`. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoA --ibft-validator-type bls --ibft-validators-prefix-path test-chain- --from 100 +``` + +### 4. Khởi động lại tất cả các nút {#4-restart-all-nodes} + +Khởi động lại tất cả các nút bằng lệnh `server`. Sau khi khối ở `from` đã chỉ định trong bước trước được tạo, chuỗi sẽ bật BLS và hiển thị nhật ký như bên dưới: + +```bash +2022-09-02T11:45:24.535+0300 [INFO] polygon.ibft: IBFT validation type switched: old=ecdsa new=bls +``` + +Ngoài ra, các bản ghi cho thấy chế độ xác minh nào được sử dụng để tạo mỗi khối sau khi khối được tạo. + +``` +2022-09-02T11:45:28.728+0300 [INFO] polygon.ibft: block committed: number=101 hash=0x5f33aa8cea4e849807ca5e350cb79f603a0d69a39f792e782f48d3ea57ac46ca validation_type=bls validators=3 committed=3 +``` + +## Cách chuyển từ chuỗi ECDSA PoS hiện hữu sang chuỗi BLS PoS {#how-to-migrate-from-an-existing-ecdsa-pos-chain-to-a-bls-pos-chain} + +Phần này mô tả cách sử dụng chế độ BLS trong chuỗi PoS hiện hữu. Các bước sau là bắt buộc để kích hoạt BLS trong chuỗi PoS. + +1. Dừng tất cả các nút +2. Tạo khóa BLS cho các trình xác thực +3. Thêm cài đặt fork vào genesis.json +4. Gọi hợp đồng góp cổ phần để đăng ký Khóa công khai BLS +5. Khởi động lại tất cả các nút + +### 1. Dừng tất cả các nút {#1-stop-all-nodes-1} + +Chấm dứt tất cả các quy trình của các trình xác thực bằng cách nhấn Ctrl + c (Control + c). Vui lòng ghi nhớ chiều cao khối mới nhất (số thứ tự cao nhất trong nhật ký cam kết khối). + +### 2. Tạo khóa BLS {#2-generate-the-bls-key-1} + +`secrets init` với cờ `--bls` tạo khóa BLS. Để giữ ECDSA và Khóa mạng hiện hữu và thêm khóa BLS mới, cần phải vô hiệu hoá `--ecdsa` và `--network`. + +```bash +polygon-edge secrets init --bls --ecdsa=false --network=false + +[SECRETS INIT] +Public key (address) = 0x... +BLS Public key = 0x... +Node ID = 16... +``` + +### 3. Thêm thiết lập fork {#3-add-fork-setting-1} + +Lệnh `ibft switch` thêm cài đặt fork, cho phép bật BLS từ giữa chuỗi, thành `genesis.json`. + +Chỉ định độ cao (số lượng khối) mà từ đó chuỗi bắt đầu sử dụng chế độ BLS với cờ `from` và độ cao mà hợp đồng được cập nhật với cờ `development`. + +```bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type bls --deployment 50 --from 200 +``` + +### 4. Đăng ký Khóa công khai BLS trong hợp đồng góp cổ phần {#4-register-bls-public-key-in-staking-contract} + +Sau khi fork được thêm vào và các trình xác thực được khởi động lại, mỗi trình xác nhận cần gọi `registerBLSPublicKey` trong hợp đồng góp cổ phần để đăng ký Khóa công khai BLS. Điều này phải được thực hiện sau khi chiều cao được chỉ định trong `--deployment` trước chiều cao được chỉ định trong `--from`. + +Tập lệnh để đăng ký Khóa công khai BLS được định nghĩa trong [ Kho lưu trữ Hợp đồng thông minh góp cổ phần](https://github.com/0xPolygon/staking-contracts). + +Thiết lập `BLS_PUBLIC_KEY` để được đăng ký vào tệp `.env`. Tham khảo mục [pos-stake-unake](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) để biết thêm chi tiết về các thông số khác. + +```env +JSONRPC_URL=http://localhost:10002 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +PRIVATE_KEYS=0x... +BLS_PUBLIC_KEY=0x... +``` + +Lệnh sau đăng ký Khóa công khai BLS đã cho trong `.env` với hợp đồng. + +```bash +npm run register-blskey +``` + +:::warning Các trình xác thực cần đăng ký Khóa công khai BLS theo cách thủ công + +Ở chế độ BLS, các trình xác thực phải có địa chỉ riêng và khóa công khai BLS. Lớp đồng thuận bỏ qua các trình xác thực chưa đăng ký khóa công khai BLS trong hợp đồng khi sự đồng thuận tìm nạp thông tin trình xác thực từ hợp đồng. +::: + +### 5. Khởi động lại tất cả các nút {#5-restart-all-nodes} + +Khởi động lại tất cả các nút bằng lệnh `server`. Chuỗi kích hoạt BLS sau khi khối tại `from` đã chỉ định trong bước trước được tạo. diff --git a/archive/edge/vi-edge/consensus/migration-to-pos.md b/archive/edge/vi-edge/consensus/migration-to-pos.md new file mode 100644 index 0000000000..4197557a65 --- /dev/null +++ b/archive/edge/vi-edge/consensus/migration-to-pos.md @@ -0,0 +1,40 @@ +--- +id: migration-to-pos +title: Di chuyển từ PoA sang PoS +description: "Cách di chuyển từ PoA sang chế độ PoS IBFT và ngược lại." +keywords: + - docs + - polygon + - edge + - migrate + - PoA + - PoS +--- + +## Tổng quan {#overview} + +Phần này hướng dẫn bạn di chuyển từ chế độ PoA sang chế độ PoS IBFT và ngược lại, đối với một cụm đang chạy - mà không cần thiết lập lại blockchain. + +## Cách di chuyển sang PoS {#how-to-migrate-to-pos} + +Bạn sẽ cần dừng tất cả các nút, thêm cấu hình fork vào genesis.json bằng lệnh `ibft switch` và khởi động lại các nút. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --deployment 100 --from 200 +```` +:::caution Chuyển đổi trong khi sử dụng ECDSA +Khi sử dụng ECDSA, `--ibft-validator-type`cờ phải được thêm vào công tắc, đề cập đến ECDSA đã được sử dụng. Nếu không được bao gồm , Edge sẽ tự động chuyển sang BLS. + +````bash +polygon-edge ibft switch --chain ./genesis.json --type PoS --ibft-validator-type ecdsa --deployment 100 --from 200 +```` +:::Để chuyển sang PoS, bạn sẽ cần chỉ định 2 khối độ cao: `deployment``from``deployment`và . Là chiều cao để triển khai hợp đồng giả và `from`là chiều cao của sự khởi đầu của PoS. Hợp đồng đấu giá sẽ được triển khai tại địa chỉ `0x0000000000000000000000000000000000001001`tại `deployment`, giống như trường hợp của hợp đồng triển khai sẵn. + +Vui lòng kiểm tra [Bằng chứng cổ phần](/docs/edge/consensus/pos-concepts) để biết thêm chi tiết về hợp đồng đấu giá. + +:::warning Trình xác thực cần đấu giá theo cách thủ công + +Mỗi trình xác thực cần phải đặt cược sau khi hợp đồng được triển khai tại `deployment` và trước `from` để trở thành người xác thực ở đầu PoS. Mỗi trình xác thực sẽ cập nhật trình xác thực của riêng nó được thiết lập bởi bộ lệnh trong hợp đồng đấu giá ở đầu PoS. + +Để tìm hiểu thêm về Staking, hãy thăm **[Set và sử dụng Proof Stake](/docs/edge/consensus/pos-stake-unstake)**. +::: diff --git a/archive/edge/vi-edge/consensus/poa.md b/archive/edge/vi-edge/consensus/poa.md new file mode 100644 index 0000000000..cc425a29cc --- /dev/null +++ b/archive/edge/vi-edge/consensus/poa.md @@ -0,0 +1,106 @@ +--- +id: poa +title: Bằng chứng Thẩm quyền (PoA) +description: "Giải thích và hướng dẫn liên quan đến Bằng chứng Thẩm quyền." +keywords: + - docs + - polygon + - edge + - PoA + - autorithy +--- + +## Tổng quan {#overview} + +IBFT PoA là cơ chế đồng thuận mặc định trong Polygon Edge. Trong PoA, trình xác thực là các trình sẽ chịu trách nhiệm tạo các khối và thêm chúng vào chuỗi khối. + +Tất cả các trình xác thực tạo thành một tập hợp trình xác thực động, nơi các trình xác thực có thể được thêm vào hoặc xóa khỏi tập hợp bằng cơ chế bỏ phiếu. Điều này có nghĩa là các trình xác thực có thể được bỏ phiếu thuận/chống từ tập hợp trình xác thực nếu đa số (51%) nút xác thực bỏ phiếu để thêm/bỏ một trình xác thực nhất định vào/khỏi tập hợp. Bằng cách này, các trình xác thực độc hại có thể được nhận dạng và xóa khỏi mạng, trong khi các trình xác thực đáng tin cậy mới có thể được thêm vào mạng. + +Tất cả các trình xác thực thay phiên nhau đề xuất khối tiếp theo (round-robin) và để khối được xác thực/chèn vào blockchain, đa số (hơn 2/3) trình xác thực phải chấp thuận khối đã đề cập. + +Bên cạnh trình xác thực, có những trình không xác thực không tham gia vào việc tạo khối nhưng có tham gia vào quá trình xác thực khối. + +## Thêm trình xác thực vào tập hợp trình xác thực {#adding-a-validator-to-the-validator-set} + +Hướng dẫn này mô tả cách thêm một nút trình xác thực mới vào mạng IBFT đang hoạt động với 4 nút trình xác thực. Nếu bạn cần giúp thiết lập mạng đang đề cập đến sự [Thiết lập](/edge/get-started/set-up-ibft-locally.md) Cục bộ / [Cloud](/edge/get-started/set-up-ibft-on-the-cloud.md) September + +### Bước 1: Khởi tạo thư mục dữ liệu cho IBFT và tạo khóa trình xác thực cho nút mới {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys-for-the-new-node} + +Để thiết lập và chạy IBFT trên nút mới, trước tiên bạn cần khởi tạo các thư mục dữ liệu và tạo các khóa: + +````bash +polygon-edge secrets init --data-dir test-chain-5 +```` + +Lệnh này sẽ in khóa của trình xác thực (địa chỉ) và ID nút. Bạn sẽ cần khóa của trình xác thực (địa chỉ) cho bước tiếp theo. + +### Bước 2: Đề xuất một ứng cử viên mới từ các nút trình xác thực khác {#step-2-propose-a-new-candidate-from-other-validator-nodes} + +Để một nút mới trở thành trình xác thực, ít nhất 51% người xác thực cần đề xuất anh ta. + +Ví dụ về cách đề xuất trình xác thực mới (`0x8B15464F8233F718c8605B16eBADA6fc09181fC2`) từ nút trình xác thực hiện có trên địa chỉ grpc: 127.0.0.1:10000: + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote auth +```` + +Cấu trúc của các lệnh IBFT được trình bày trong phần [Lệnh CLI](/docs/edge/get-started/cli-commands). + +:::info Khóa công khai BLS + +Khóa công khai BLS chỉ cần thiết nếu mạng đang chạy với BLS, `--bls`không cần thiết đối với mạng không chạy ở chế độ BLS +::: + +### Bước 3: Chạy nút máy khách {#step-3-run-the-client-node} + +Vì trong ví dụ này, chúng ta đang cố gắng chạy mạng mà tất cả các nút đều nằm trên cùng một máy, chúng ta cần chú ý để tránh xung đột cổng. + +````bash +polygon-edge server --data-dir ./test-chain-5 --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 --seal +```` + +Sau khi tìm nạp tất cả các khối, bên trong bảng điều khiển của bạn, bạn sẽ nhận thấy rằng một nút mới đang tham gia vào quá trình xác thực + +````bash +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=4004 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=5 votes=0 +2021-12-01T14:56:48.369+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0x8B15464F8233F718c8605B16eBADA6fc09181fC2 block=4004 +```` + +:::info Thăng cấp một trình không xác thực thành một trình xác thực + +Đương nhiên, một trình không xác thực có thể trở thành trình xác thực trong quá trình bỏ phiếu, nhưng để được đưa vào tập hợp trình xác thực sau quá trình bỏ phiếu thành công, nút phải được khởi động lại bằng cờ `--seal`. +::: + +## Xóa trình xác thực khỏi tập hợp trình xác thực {#removing-a-validator-from-the-validator-set} + +Thao tác này khá đơn giản. Để xóa một nút trình xác thực khỏi tập hợp trình xác thực, lệnh này cần được thực hiện cho phần lớn các nút trình xác thực. + +````bash +polygon-edge ibft propose --grpc-address 127.0.0.1:10000 --addr 0x8B15464F8233F718c8605B16eBADA6fc09181fC2 --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --vote drop +```` + +:::info Khóa công khai BLS + +Khóa công khai BLS chỉ cần thiết nếu mạng đang chạy với BLS, `--bls`không cần thiết đối với mạng không chạy ở chế độ BLS +::: + +Sau khi các lệnh được thực hiện, hãy quan sát rằng số lượng trình xác thực đã giảm (trong ví dụ nhật ký này từ 4 xuống còn 3). + +````bash +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2399 round=1 +2021-12-15T19:20:51.014+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=4 votes=2 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft.acceptState: we are the proposer: block=2399 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: picked out txns from pool: num=0 remaining=0 +2021-12-15T19:20:51.015+0100 [INFO] polygon.consensus.ibft: build block: number=2399 txns=0 +2021-12-15T19:20:53.002+0100 [INFO] polygon.consensus.ibft: state change: new=ValidateState +2021-12-15T19:20:53.009+0100 [INFO] polygon.consensus.ibft: state change: new=CommitState +2021-12-15T19:20:53.009+0100 [INFO] polygon.blockchain: write block: num=2399 parent=0x768b3bdf26cdc770525e0be549b1fddb3e389429e2d302cb52af1722f85f798c +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new block: number=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 txns=0 generation_time_in_sec=2 +2021-12-15T19:20:53.011+0100 [INFO] polygon.blockchain: new head: hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 number=2399 +2021-12-15T19:20:53.011+0100 [INFO] polygon.consensus.ibft: block committed: sequence=2399 hash=0x6538286881d32dc7722dd9f64b71ec85693ee9576e8a2613987c4d0ab9d83590 validators=4 rounds=1 committed=3 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: state change: new=AcceptState +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft.acceptState: Accept state: sequence=2400 round=1 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: current snapshot: validators=3 votes=0 +2021-12-15T19:20:53.012+0100 [INFO] polygon.consensus.ibft: proposer calculated: proposer=0xea21efC826F4f3Cb5cFc0f986A4d69C095c2838b block=2400 +```` diff --git a/archive/edge/vi-edge/consensus/pos-concepts.md b/archive/edge/vi-edge/consensus/pos-concepts.md new file mode 100644 index 0000000000..d4606edf62 --- /dev/null +++ b/archive/edge/vi-edge/consensus/pos-concepts.md @@ -0,0 +1,101 @@ +--- +id: pos-concepts +title: Bằng chứng Cổ phần +description: "Giải thích và hướng dẫn liên quan đến Bằng chứng Cổ phần." +keywords: + - docs + - polygon + - edge + - PoS + - stake +--- + +## Tổng quan {#overview} + +Phần này nhằm mục đích cung cấp cái nhìn tổng quan hơn về một số khái niệm hiện có trong Bằng chứng Cổ phần (PoS) triển khai Polygon Edge. + +Triển khai Polygon Edge Proof of Stake (PoS) có nghĩa là một sự thay thế cho việc triển khai PoA IBFT hiện có, mang lại cho trình vận hành nút khả năng dễ dàng lựa chọn giữa hai cách khi bắt đầu một chuỗi. + +## Tính năng PoS {#pos-features} + +Logic cốt lõi đằng sau việc triển khai Bằng chứng Cổ phần nằm trong **[Hợp đồng Thông minh Smart](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol)**. + +Hợp đồng này được triển khai trước bất cứ khi nào chuỗi Polygon Edge theo cơ chế PoS được khởi tạo và có sẵn trên địa chỉ +`0x0000000000000000000000000000000000001001` từ khối `0`. + +### Epoch {#epochs} + +Epoch là một khái niệm được giới thiệu kèm việc bổ sung PoS vào Polygon Edge. + +Epoch được coi là một khung thời gian đặc biệt (theo khối) trong đó một tập hợp các trình xác thực nhất định có thể tạo ra các khối. Độ dài của chúng có thể thay đổi được, nghĩa là các nhà vận hành nút có thể định cấu hình độ dài của một epoch trong quá trình tạo genesis. + +Ở cuối mỗi epoch, một _khối epoch_ được tạo và sau sự kiện đó, epoch mới bắt đầu. Để tìm hiểu thêm về khối epoch, hãy xem phần [Khối Epoch](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Các tập hợp trình xác thực được cập nhật ở cuối mỗi epoch. Các nút truy vấn tập hợp trình xác thực từ Hợp đồng Thông minh Góp cổ phần trong quá trình tạo khối epoch và lưu dữ liệu thu được vào bộ nhớ cục bộ. Chu kỳ truy vấn và lưu này được lặp lại vào cuối mỗi epoch. + +Về cơ bản, nó đảm bảo rằng Hợp đồng Thông minh Góp cổ phần có toàn quyền kiểm soát các địa chỉ trong tập hợp trình xác thực và để các nút chỉ có 1 trách nhiệm - truy vấn hợp đồng một lần trong suốt thời gian epoch tìm nạp thông tin tập hợp trình xác thực mới nhất. Điều này làm giảm bớt trách nhiệm từ các nút riêng lẻ khỏi việc chăm sóc các tập hợp trình xác thực. + +### Góp cổ phần {#staking} + +Các địa chỉ có thể góp tiền vào Hợp đồng Thông minh Góp cổ phần bằng cách gọi phương thức `stake` và bằng cách chỉ định giá trị cho số tiền góp cổ phần trong giao dịch: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.stake({value: STAKE_AMOUNT}) +```` + +Bằng cách góp tiền vào Hợp đồng Thông minh Góp cổ phần, các địa chỉ có thể tham gia tập hợp trình xác thực và do đó có thể tham gia vào quy trình sản xuất khối. + +:::info Ngưỡng góp cổ phần + +Hiện tại, ngưỡng tối thiểu để gia nhập tập hợp trình xác thực là góp cổ phần `1 ETH` +::: + +### Huỷ góp cổ phần {#unstaking} + +Các địa chỉ đã góp tiền chỉ có thể **hủy góp cùng một lúc tất cả số tiền đã góp vào của họ**. + +Có thể hủy việc góp cổ phần bằng cách gọi phương thức `unstake` trong Hợp đồng Thông minh Góp cổ phần: + +````js +const StakingContractFactory = await ethers.getContractFactory("Staking"); +let stakingContract = await StakingContractFactory.attach(STAKING_CONTRACT_ADDRESS) +as +Staking; +stakingContract = stakingContract.connect(account); + +const tx = await stakingContract.unstake() +```` + +Sau khi huỷ góp số tiền của mình, các địa chỉ sẽ bị xóa khỏi tập hợp trình xác thực trên Hợp đồng Thông minh Góp cổ phần và sẽ không được coi là trình xác thực trong epoch tiếp theo. + +## Khối Epoch {#epoch-blocks} + +**Khối Epoch** là một khái niệm được giới thiệu trong quá trình triển khai PoS của IBFT trong Polygon Edge. + +Về cơ bản, các khối epoch là các khối đặc biệt **không chứa giao dịch** và chỉ phát sinh ở **cuối một epoch**. Ví dụ, **nếu kích thước epoch** được thiết lập thành khối `50`thì khối epoch sẽ được xem là khối `50``100``150`và như vậy. + +Chúng được sử dụng để thực hiện logic bổ sung không nên xảy ra trong quá trình sản xuất khối thông thường. + +Quan trọng nhất, chúng là dấu hiệu cho nút thấy **nút cần tìm nạp thông tin tập hợp trình xác thực mới nhất** từ Hợp đồng Thông minh Góp cổ phần. + +Sau khi cập nhật tập hợp trình xác thực tại khối epoch, tập hợp trình xác thực (có thể thay đổi hoặc không thay đổi) được sử dụng cho các khối `epochSize - 1` tiếp theo, cho đến khi nó được cập nhật lại bằng cách lấy thông tin mới nhất từ Hợp đồng Thông minh Góp cổ phần. + +Độ dài epoch (theo khối) có thể sửa đổi được khi tạo tệp genesis, bằng cách sử dụng cờ đặc biệt `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 ... +``` + +Kích thước mặc định của một epoch là `100000` khối trong Polygon Edge. + +## Trước khi triển khai hợp đồng {#contract-pre-deployment} + +Polygon Edge _trước khi triển khai_ [Hợp đồng Thông minh Góp cổ phần](https://github.com/0xPolygon/staking-contracts/blob/main/contracts/Staking.sol) trong quá trình **khởi tạo genesis** tới địa chỉ `0x0000000000000000000000000000000000001001`. + +Có thể làm như vậy mà không cần chạy EVM, bằng cách sửa đổi trực tiếp trạng thái blockchain của Hợp đồng Thông minh, sử dụng các giá trị cấu hình được chuyển vào lệnh genesis. diff --git a/archive/edge/vi-edge/consensus/pos-stake-unstake.md b/archive/edge/vi-edge/consensus/pos-stake-unstake.md new file mode 100644 index 0000000000..f530f195cf --- /dev/null +++ b/archive/edge/vi-edge/consensus/pos-stake-unstake.md @@ -0,0 +1,152 @@ +--- +id: pos-stake-unstake +title: Thiết lập và sử dụng Bằng chứng Cổ phần (Proof Stake - PoS) +description: "Góp cổ phần, hủy góp cổ phần và các hướng dẫn khác liên quan đến góp cổ phần." +keywords: + - docs + - polygon + - edge + - stake + - unstake + - validator + - epoch +--- + +## Tổng quan {#overview} + +Hướng dẫn này đi vào chi tiết về cách thiết lập mạng Bằng chứng Cổ phần với Polygon Edge, cách góp cổ phần cho các nút để trở thành các trình xác thực và cách huỷ góp các phần vốn góp. + +Nó được **khuyến khích rất nhiều** khi đọc và xem qua [Thiết lập Cục bộ](/docs/edge/get-started/set-up-ibft-locally) / [Thiết lập Đám mây](/docs/edge/get-started/set-up-ibft-on-the-cloud), trước khi tiến hành theo hướng dẫn PoS này. Các phần này phác thảo các bước cần thiết để bắt đầu một cụm Bằng chứng Thẩm quyền (PoA) với Polygon Edge. + +Hiện tại, không có giới hạn về số lượng người xác thực có thể góp vốn vào Hợp đồng Thông minh Góp cổ phần. + +## Hợp đồng Thông minh Góp cổ phần {#staking-smart-contract} + +Kho lưu trữ dành cho Hợp đồng Thông minh Góp cổ phần được đặt [tại đây](https://github.com/0xPolygon/staking-contracts). + +Nó chứa các tập lệnh thử nghiệm cần thiết, các tệp ABI và quan trọng nhất là bản thân Hợp đồng Thông minh Góp cổ phần. + +## Thiết lập một cụm nút N {#setting-up-an-n-node-cluster} + +Thiết lập mạng với Polygon Edge được đề cập trong phần [Thiết lập Cục bộ](/docs/edge/get-started/set-up-ibft-locally) / [Thiết lập Đám mây](/docs/edge/get-started/set-up-ibft-on-the-cloud). + +Sự **khác biệt duy nhất** giữa việc thiết lập một cụm PoS và PoA là ở phần tạo genesis. + +**Khi tạo tệp genesis cho một cụm PoS, cần có cờ `--pos`** bổ sung: + +```bash +polygon-edge genesis --pos ... +``` + +## Thiết lập độ dài của một epoch {#setting-the-length-of-an-epoch} + +Epoch được đề cập chi tiết trong phần [Khối Epoch](/docs/edge/consensus/pos-concepts#epoch-blocks). + +Để thiết lập kích thước của một epoch cho một cụm (trong các khối), khi tạo tệp genesis, một cờ bổ sung được chỉ định `--epoch-size`: + +```bash +polygon-edge genesis --epoch-size 50 +``` + +Giá trị này được chỉ định trong tệp genesis mà kích thước epoch phải là `50` khối. + +Giá trị mặc định cho kích thước của một epoch (tính bằng khối) là `100000`. + +:::info Giảm độ dài epoch + +Như đã được nêu trong phần [Khối Epoch](/docs/edge/consensus/pos-concepts#epoch-blocks), các khối epoch được sử dụng để cập nhật các tập hợp trình xác thực cho các nút. + +Độ dài epoch mặc định trong các khối (`100000`) có thể là một khoảng thời gian dài để chuẩn bị cho các bản cập nhật tập hợp trình xác thực. Cân nhắc rằng các khối mới được thêm ~ 2 giây, sẽ mất ~ 55,5 giờ để tập hợp trình xác nhận có thể thay đổi. + +Thiết lập giá trị thấp hơn cho độ dài epoch đảm bảo rằng tập hợp trình xác thực được cập nhật thường xuyên hơn. +::: + +## Sử dụng tập lệnh Hợp đồng Thông minh Góp cổ phần {#using-the-staking-smart-contract-scripts} + +### Điều kiện tiên quyết {#prerequisites} + +Kho lưu trữ Hợp đồng Thông minh Góp cổ phần là một dự án Hardhat, cần có NPM. + +Để khởi tạo một cách chính xác, trong thư mục chính, hãy chạy: + +```bash +npm install +```` + +### Thiết lập các tập lệnh trình trợ giúp được cung cấp {#setting-up-the-provided-helper-scripts} + +Các tập lệnh để tương tác với Hợp đồng Thông minh Góp cổ phần đã triển khai được đặt trong kho lưu trữ [Hợp đồng Thông minh Góp cổ phần](https://github.com/0xPolygon/staking-contracts). + +Tạo tệp `.env` với các thông số sau trong vị trí kho lưu trữ Hợp đồng Thông Minh: + +```bash +JSONRPC_URL=http://localhost:10002 +PRIVATE_KEYS=0x0454f3ec51e7d6971fc345998bb2ba483a8d9d30d46ad890434e6f88ecb97544 +STAKING_CONTRACT_ADDRESS=0x0000000000000000000000000000000000001001 +BLS_PUBLIC_KEY=0xa.. +``` + +Trong đó các thông số là: + +* **JSONRPC_URL** - điểm cuối JSON-RPC dành cho nút đang chạy +* **PRIVATE_KEYS** - khóa riêng tư của địa chỉ người góp cổ phần. +* **STAKING_CONTRACT_ADDRESS** - địa chỉ của hợp đồng thông minh góp cổ phần ( mặc định `0x0000000000000000000000000000000000001001`) +* **BLS_PUBLIC_KEY** - Khóa công khai BLS của người góp cổ phần. Chỉ cần thiết nếu mạng đang chạy với BLS + +### Số tiền góp cổ phần {#staking-funds} + +:::info Địa chỉ góp cổ phần + +Hợp đồng Thông minh Góp cổ phần được triển khai trước tại địa chỉ `0x0000000000000000000000000000000000001001`. + +Bất kỳ loại tương tác nào với cơ chế góp cổ phần đều được thực hiện thông qua Hợp đồng Thông minh Góp cổ phần tại địa chỉ được chỉ định. + +Để tìm hiểu thêm về Hợp đồng Thông minh Góp cổ phần, vui lòng xem phần **[Hợp đồng Thông minh Smart Smart](/docs/edge/consensus/pos-concepts#contract-pre-deployment)** . +::: + +Để trở thành một phần của tập hợp trình xác thực, một địa chỉ cần góp vào một số tiền nhất định trên ngưỡng yêu cầu. + +Hiện tại, ngưỡng mặc định để trở thành một phần của tập hợp trình xác thực là `1 ETH`. + +Việc góp cổ phần có thể được bắt đầu bằng cách gọi phương thức `stake` của Hợp đồng Thông minh Góp cổ phần và chỉ định một giá trị `>= 1 ETH`. + +Sau khi tệp `.env` được đề cập trong [phần trước](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) đã được thiết lập và một chuỗi đã được bắt đầu ở chế độ PoS, việc góp cổ phần có thể được thực hiện bằng lệnh sau trong kho lưu trữ Hợp đồng Thông minh Góp cổ phần: + +```bash +npm run stake +``` + +Tập lệnh Hardhat `stake` góp vào một lượng `1 ETH` mặc định, có thể được thay đổi bằng cách sửa đổi tệp `scripts/stake.ts`. + +Nếu số tiền đang được góp vào là `>= 1 ETH`, trình xác thực được đặt trên Hợp đồng Thông minh Góp cổ phần sẽ được cập nhật và địa chỉ sẽ là một phần của tập hợp trình xác thực bắt đầu từ epoch tiếp theo. + +:::info Đăng ký khóa BLS + +Nếu mạng đang chạy ở chế độ BLS, để các nút trở thành trình xác thực, họ cần đăng ký khóa công khai BLS của mình sau khi góp cổ phần + +Việc này có thể được thực hiện bằng lệnh sau: + +```bash +npm run register-blskey +``` +::: + +### Huỷ góp cổ phần {#unstaking-funds} + +Các địa chỉ đã góp cổ phần **chỉ có thể rút tất cả số tiền đã góp** của họ cùng một lúc. + +Sau khi tệp `.env` được đề cập trong [phần trước](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) đã được thiết lập và một chuỗi đã được bắt đầu ở chế độ PoS, việc hủy góp cổ phần có thể thực hiện bằng lệnh sau trong Kho lưu trữ Hợp đồng Thông minh Góp cổ phần: + +```bash +npm run unstake +``` + +### Tìm nạp danh sách những người góp cổ phần {#fetching-the-list-of-stakers} + +Tất cả các địa chỉ góp cổ phần sẽ được lưu vào Hợp đồng Thông minh Góp Cổ phần. + +Sau khi tệp `.env` được đề cập trong [phần trước](/docs/edge/consensus/pos-stake-unstake#setting-up-the-provided-helper-scripts) đã được thiết lập và một chuỗi đã được bắt đầu ở chế độ PoS, việc tìm nạp danh sách trình xác thực có thể được thực hiện bằng lệnh sau trong kho Hợp đồng Thông minh Góp cổ phần: + +```bash +npm run info +``` diff --git a/archive/edge/vi-edge/faq/Contracts.md b/archive/edge/vi-edge/faq/Contracts.md new file mode 100644 index 0000000000..7acc24e393 --- /dev/null +++ b/archive/edge/vi-edge/faq/Contracts.md @@ -0,0 +1,24 @@ +--- +id: contracts +title: Các câu hỏi thường gặp về Hợp đồng Thông minh +description: "Các câu hỏi thường gặp về Hợp đồng Thông minh trong Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - smart + - contracts + +--- + +## Polygon Edge có hỗ trợ Hợp đồng thông minh không? {#does-polygon-edge-support-smart-contracts} + +Có. Mạng Polygon Edge là các blockchain tương thích với Ethereum, vì vậy Hợp đồng Thông minh có thể triển khai trên Ethereum, cũng có thể triển khai trên chuỗi Polygon Edge. + +## Bạn có thể cập nhật logic hợp đồng đấu giá cho PoS sau khi triển khai không? {#can-you-update-the-staking-contract-logic-for-pos-after-deployment} + +Hiện tại, sau khi bạn đã khởi động mạng PoS, bạn không thể thay đổi logic hợp đồng đấu giá, vì nó là một phần của tệp khởi tạo. Vì vậy, bạn không thể thay đổi số lượng trình xác thực tối thiểu/tối đa. Những gì bạn có thể làm là đấu giá hoặc hủy đấu giá, đồng thời thêm hoặc xóa trình xác thực. + + + diff --git a/archive/edge/vi-edge/faq/Gas.md b/archive/edge/vi-edge/faq/Gas.md new file mode 100644 index 0000000000..8c349d04b7 --- /dev/null +++ b/archive/edge/vi-edge/faq/Gas.md @@ -0,0 +1,41 @@ +--- +id: gas +title: Hỏi đáp về Gas +description: "Hỏi đáp về Gas trong Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Cách thức để thực thi giá gas tối thiểu? {#how-to-enforce-a-minimum-gas-price} +Bạn có thể sử dụng cờ `--price-limit` được cung cấp trên lệnh máy chủ. Điều này sẽ buộc nút của bạn chỉ chấp nhận các giao dịch có gas cao hơn hoặc bằng giới hạn giá mà bạn đã thiết lập. Để đảm bảo nó được thực thi trên toàn bộ mạng, bạn cần đảm bảo tất cả các nút có cùng giới hạn giá. + + +## Bạn có thể có các giao dịch với phí gas bằng 0 không? {#can-you-have-transactions-with-0-gas-fees} +Vâng, bạn có thể. Giới hạn giá mặc định mà các nút cần để thực thi là `0`, điều này có nghĩa là các nút sẽ chấp nhận các giao dịch có giá gas được đặt là `0`. + +## Cách thức để đặt tổng cung cho token gas(native)? {#how-to-set-the-gas-native-token-total-supply} + +Bạn có thể thiết lập số dư định trước cho các tài khoản (địa chỉ) bằng cách sử dụng `--premine flag`. Xin lưu ý rằng đây là cấu hình từ tệp genesis và không thể thay đổi về sau. + +Ví dụ về cách sử dụng `--premine flag`: + +`--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000` + +Điều này thiết lập số dư 1000 ETH định trước thành 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862 (số lượng trong đối số tính bằng wei). + +Số tiền định trước của token gas sẽ là tổng nguồn cung. Không có số lượng tiền bản địa nào khác (gas token) có thể được mint sau này. + +## Edge có hỗ trợ ERC-20 như một gas token không? {#does-edge-support-erc-20-as-a-gas-token} + +Edge không hỗ trợ token ERC-20 làm gas token. Chỉ có đơn vị tiền tệ Edge gốc mới được hỗ trợ cho gas. + +## Làm thế nào để tăng giới hạn gas ? {#how-to-increase-the-gas-limit} + +Có hai lựa chọn để tăng giới hạn gas trong Polygon Edge: +1. Việc quét chuỗi và tăng lên `block-gas-limit`giá trị uint64 trong tệp tin genesis +2. Sử `--block-gas-target`dụng cờ với giá trị cao để tăng giới hạn gas của tất cả các nút. Điều này đòi hỏi sự khởi động lại nút Giải thích chi tiết [ở đây](/docs/edge/architecture/modules/txpool/#block-gas-target). \ No newline at end of file diff --git a/archive/edge/vi-edge/faq/Tokens.md b/archive/edge/vi-edge/faq/Tokens.md new file mode 100644 index 0000000000..3349918d9c --- /dev/null +++ b/archive/edge/vi-edge/faq/Tokens.md @@ -0,0 +1,23 @@ +--- +id: tokens +title: Hỏi đáp về token +description: "Hỏi đáp về token Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - tokens +--- + +## Polygon Edge có hỗ trợ EIP-1559 không? {#does-polygon-edge-support-eip-1559} +Hiện tại, Polygon Edge không hỗ trợ EIP-1559. + +## Làm thế nào để thiết lập ký hiệu tiền tệ (token)? {#how-to-set-the-currency-token-symbol} + +Biểu tượng token chỉ là một giao diện người dùng, vì vậy nó không thể được định cấu hình hoặc mã hóa cứng ở bất kỳ đâu trong mạng. +Nhưng bạn có thể thay đổi nó khi thêm mạng vào ví, chẳng hạn như Metamask. + +## Điều gì sẽ xảy ra với giao dịch khi một hời dây chuyền? {#what-happens-to-transactions-when-a-chain-halts} + +Tất cả các giao dịch chưa được xử lý đều nằm trong TxPool(có vẻ là hàng đợi hoặc hàng đợi thăng chức). Nếu chuỗi halts(tất cả blocks production), các giao dịch này sẽ không bao giờ bị kẹt.
Đây không chỉ là trường hợp khi các hời dây chuyền. Nếu các nút bị dừng hoặc khởi động, tất cả các giao dịch chưa thực hiện, và vẫn đang ở TxPool, sẽ im lặng được gỡ bỏ.
Tương tự sẽ xảy ra với giao dịch khi thay đổi đột phá được giới thiệu, vì nó được yêu cầu để các nút được khởi động. diff --git a/archive/edge/vi-edge/faq/Validators.md b/archive/edge/vi-edge/faq/Validators.md new file mode 100644 index 0000000000..6aefbdf3dd --- /dev/null +++ b/archive/edge/vi-edge/faq/Validators.md @@ -0,0 +1,112 @@ +--- +id: validators +title: Hỏi đáp về trình xác thực +description: "Hỏi đáp về trình xác thực của Polygon Edge" +keywords: + - docs + - polygon + - edge + - FAQ + - validators + +--- + +## Cách thức để thêm/gỡ bỏ trình xác thực? {#how-to-add-remove-a-validator} + +### PoA {#poa} +Việc thêm/gỡ bỏ trình xác thực được thực hiện bằng cách bỏ phiếu. Bạn có thể xem hướng dẫn đầy đủ ở [đây](/docs/edge/consensus/poa). + +### PoS {#pos} +Bạn có thể xem hướng dẫn về góp cổ phần tại [đây](/docs/edge/consensus/pos-stake-unstake) (đây là cách để một nút trở thành trình xác thực) và cách hủy bỏ (loại bỏ trình xác thực). + +Vui lòng lưu ý rằng: + +- Bạn có thể sử dụng cờ khởi nguồn `--max-validator-count` để thiết lập số lượng người góp cổ phần tối đa có thể tham gia tập hợp trình xác nhận. + +- Bạn có thể sử dụng cờ khởi nguồn `--min-validator-count ` để thiết lập số lượng người góp cổ phần tối thiểu cần tham gia tập hợp trình xác nhận (theo mặc định là `1`). +- Khi đạt số lượng trình xác thực tối đa, bạn sẽ không thể thêm một trình xác thực khác trừ khi bạn xóa một trình xác thực hiện có khỏi tập hợp (việc số tiền góp cổ phần của trình xác thực mới cao hơn là không quan trọng). + Nếu bạn gỡ bỏ một trình xác thực, số lượng trình xác thực còn lại không được thấp hơn `--min-validator-count`. +- Ngưỡng mặc định là `1` đơn vị tiền tệ mạng (gas) để trở thành trình xác thực. + + + + +## Dung lượng ổ đĩa được khuyến nghị cho trình xác thực là bao nhiêu? + {#how-much-disk-space-is-recommended-for-a-validator} + +Chúng tôi khuyên bạn nên bắt đầu với 100G để dự phòng và cần đảm bảo rằng bạn có thể nâng cấp ổ đĩa về sau. + + + +## Có giới hạn về số lượng trình xác thực không? + {#is-there-a-limit-to-the-number-of-validators} + +Về các giới hạn kỹ thuật, Polygon Edge không có giới hạn rõ ràng về số lượng nút bạn có thể có trong một mạng. + Bạn có thể thiết lập giới hạn kết nối (số lượng kết nối đến/đi) trên cơ sở mỗi nút. + + +Còn về giới hạn thực tế, bạn sẽ thấy hiệu suất bị giảm sút khi so sánh cụm 100 nút với cụm 10 nút. + Khi tăng số lượng các nút trong cụm, bạn sẽ tăng độ phức tạp của giao tiếp và mạng tổng quát nói chung. + Tất cả phụ thuộc vào loại mạng bạn đang chạy và loại cấu trúc liên kết mạng bạn có. + + +## Cách thức để chuyển từ PoA sang PoS? + {#how-to-switch-from-poa-to-pos} + +PoA là cơ chế đồng thuận mặc định. + Đối với một cụm mới, để chuyển sang PoS, bạn sẽ cần thêm cờ `--pos` khi tạo tệp khởi nguồn. + Nếu có một cụm đang hoạt động, bạn có thể tìm hiểu về cách chuyển đổi [tại đây](/docs/edge/consensus/migration-to-pos). Tất cả thông tin bạn cần biết về các cơ chế đồng thuận và thiết lập của chúng tôi đều có thể được tìm thấy trong phần [sự đồng thuận](/docs/edge/consensus/poa). + + +## Cách thức để cập nhật các nút khi có thay đổi đột ngột? + {#how-do-i-update-my-nodes-when-there-s-a-breaking-change} + +Bạn có thể xem hướng dẫn chi tiết về cách thực hiện quy trình này [tại đây](/docs/edge/validator-hosting#update). + + +## Có thể định cấu hình số tiền góp cổ phần tối thiểu trên PoS Edge không? + {#is-the-minimum-staking-amount-configurable-for-pos-edge} + +Số tiền góp cổ phần tối thiểu theo mặc định là `1 ETH` và không thể được định cấu hình. + +## Tại sao các lệnh JSON RPC `eth_getBlockByNumber` và `eth_getBlockByHash` không trả về địa chỉ của người khai thác? + {#not-return-the-miner-s-address} + +Cơ chế đồng thuận hiện được sử dụng trong Polygon Edge là IBFT 2.0, được xây dựng dựa trên cơ chế bỏ phiếu, thông tin thêm tại Clique PoA: [ethereum/EIPs#225](https://github.com/ethereum/EIPs/issues/225). + + +Nói về EIP-225 (Clique PoA), đây là phần giải thích mục đích sử dụng của `miner`(hay còn gọi là `beneficiary`): + + +
Chúng tôi sử dụng lại các trường tiêu đề ethash như sau: +
    +
  • người thụ hưởng / người khai thác: Địa chỉ để đề xuất sửa đổi danh sách người ký được ủy quyền. +
  • +
      +
    • Trường này thường được điền số 0, chỉ được sửa đổi khi biểu quyết. +
    • +
    • Tuy nhiên, các giá trị tùy ý vẫn được cho phép (ngay cả những giá trị vô nghĩa như khi bỏ phiếu loại bỏ người không phải người ký) để tránh thêm phức tạp trong việc triển khai cơ chế bỏ phiếu. +
    • +
    • Các khối điểm kiểm soát phải được điền số 0 (ví dụ: giao dịch epoch). +
    • +
    + +
+ +
+ +Do đó, trường `miner` được sử dụng để đề xuất biểu quyết cho một địa chỉ nhất định, thay vì để hiển thị người đề xuất của khối. + + +Thông tin về người đề xuất của khối có thể được tìm thấy bằng cách khôi phục khóa công khai từ trường Con dấu của trường dữ liệu bổ sung được mã hóa RLP Istanbul trong tiêu đề khối. + + +## Phần nào và giá trị của Genesis có thể được sửa đổi an toàn? {#which-parts-and-values-of-genesis-can-safely-be-modified} + +:::caution + +Vui lòng đảm bảo tạo một bản sao bằng tay của tệp genesis.json trước khi cố gắng sửa nó. Ngoài ra, toàn bộ chuỗi phải được dừng lại trước khi chỉnh lại tệp tin gen.json. Một khi tệp tin genesis được sửa đổi, phiên bản mới hơn của nó sẽ được phát hành trên tất cả các nút không xác thực và nút của người val. + +::: + +**Chỉ phần bootnodes của tệp tin genesis mới có thể được sửa đổi an toàn**, nơi bạn có thể thêm hoặc gỡ bỏ bootnodes khỏi danh sách. \ No newline at end of file diff --git a/archive/edge/vi-edge/get-started/cli-commands.md b/archive/edge/vi-edge/get-started/cli-commands.md new file mode 100644 index 0000000000..739ef99558 --- /dev/null +++ b/archive/edge/vi-edge/get-started/cli-commands.md @@ -0,0 +1,2203 @@ +--- +id: cli-commands +title: Lệnh CLI +description: "Danh sách các lệnh CLI và cờ lệnh cho Polygon Edge." +keywords: + - docs + - polygon + - edge + - cli + - commands + - flags +--- +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +Phần này trình bày chi tiết các lệnh hiện tại, cờ lệnh trong Polygon Edge và cách chúng được sử dụng. + +:::tip Hỗ trợ đầu ra JSON + +Cờ `--json` được hỗ trợ trên một số lệnh. Cờ này chỉ thị lệnh in đầu ra ở định dạng JSON + +::: + +## Lệnh khởi động {#startup-commands} + +| **Lệnh** | **Mô tả** | +|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| server | Lệnh mặc định khởi động ứng dụng máy khách blockchain, bằng cách khởi động tất cả các mô-đun với nhau | +| genesis | Tạo tệp *genesis.json*, được sử dụng để thiết lập trạng thái chuỗi được định sẵn trước khi khởi động máy khách. Cấu trúc của tệp tin genesis được mô bên dưới | +| Khởi động dự báo | Khởi động Hợp đồng Thông minh cho mạng mới | + +### cờ máy chủ {#server-flags} + + +| **Tất cả cờ máy chủ** | +|---------------------------------------|---------------------------------------------| +| [data-dir](/docs/edge/get-started/cli-commands#data-dir) | [jsonrpc](/docs/edge/get-started/cli-commands#jsonrpc) | +| [json-rpc-block-range-limit](/docs/edge/get-started/cli-commands#json-rpc-block-range-limit) | [json-rpc-batch-request-limit](/docs/edge/get-started/cli-commands#json-rpc-batch-request-limit) | +| [grpc](/docs/edge/get-started/cli-commands#grpc) | [libp2p](/docs/edge/get-started/cli-commands#libp2p) | +| [prometheus](/docs/edge/get-started/cli-commands#prometheus) | [block-gas-target](/docs/edge/get-started/cli-commands#block-gas-target) | +| [max-peers](/docs/edge/get-started/cli-commands#max-peers) | [max-inbound-peers](/docs/edge/get-started/cli-commands#max-inbound-peers) | +| [max-outbound-peers](/docs/edge/get-started/cli-commands#max-outbound-peers) | [max-enqueued](/docs/edge/get-started/cli-commands#max-enqueued) | +| [log-level](/docs/edge/get-started/cli-commands#log-level) | [log-to](/docs/edge/get-started/cli-commands#log-to) | +| [chain](/docs/edge/get-started/cli-commands#chain) | [join](/docs/edge/get-started/cli-commands#join) | +| [nat](/docs/edge/get-started/cli-commands#nat) | [dns](/docs/edge/get-started/cli-commands#dns) | +| [Giới hạn giá](/docs/edge/get-started/cli-commands#price-limit) | [Slot max-](/docs/edge/get-started/cli-commands#max-slots) | +| [Cấu hình](/docs/edge/get-started/cli-commands#config) | [secrets-config](/docs/edge/get-started/cli-commands#secrets-config) | +| [dev](/docs/edge/get-started/cli-commands#dev) | [dev-interval](/docs/edge/get-started/cli-commands#dev-interval) | +| [no-discover](/docs/edge/get-started/cli-commands#no-discover) | [restore](/docs/edge/get-started/cli-commands#restore) | +| [block-time](/docs/edge/get-started/cli-commands#block-time) | [access-control-allow-origins](/docs/edge/get-started/cli-commands#access-control-allow-origins) | + + +####

data-dir + + + + + server [--data-dir DATA_DIRECTORY] + + + + + server --data-dir ./example-dir + + + + +Được sử dụng để chỉ định thư mục dữ liệu được sử dụng để lưu trữ dữ liệu máy khách Polygon Edge. Mặc định: `./test-chain`. + +--- + + +####

jsonrpc + + + + + server [--jsonrpc JSONRPC_ADDRESS] + + + + + server --jsonrpc 127.0.0.1:10000 + + + + +Thiết lập địa chỉ và cổng cho dịch vụ `address:port` JSON-RPC. Nếu chỉ có cổng được xác định `:10001`, nó sẽ liên kết với tất cả các giao diện `0.0.0.0:10001`. Nếu lược bỏ dịch vụ sẽ liên kết với `address:port` mặc định. +Địa chỉ mặc định: `0.0.0.0:8545`. + +--- + +####

json-rpc-block-range-limit + + + + + server [--json-rpc-block-range-limit BLOCK_RANGE] + + + + + server --json-rpc-block-range-limit 1500 + + + + +Sets the straight Khối tối đa sẽ được xem xét khi thực thi các yêu cầu json-rpc bao gồm giá trị từ Block/toBlock (ví dụ như: eth_getlogs). Giới hạn này có thể bị tắt hoàn toàn bằng cách thiết lập giá trị cho `0`. Mặc định:`1000`. + +--- + +####

json-rpc-batch-request-limit + + + + + server [--json-rpc-batch-request-limit MAX_LENGTH] + + + + + server --json-rpc-batch-request-limit 50 + + + + +Đặt chiều dài tối đa để được xem xét khi xử lý yêu cầu mẻ json-rpc. Giới hạn này có thể bị tắt hoàn toàn bằng cách thiết lập giá trị cho `0`. Mặc định: `20`. + +--- + +####

grpc + + + + + server [--grpc-address GRPC_ADDRESS] + + + + + server --grpc-address 127.0.0.1:10001 + + + + +Thiết lập địa chỉ và cổng cho dịch vụ gRPC `address:port`. Địa chỉ mặc định: `127.0.0.1:9632`. + +--- + +####

libp2p + + + + + server [--libp2p LIBP2P_ADDRESS] + + + + + server --libp2p 127.0.0.1:10002 + + + + +Thiết lập địa chỉ và cổng cho dịch vụ libp2p `address:port`. Địa chỉ mặc định: `127.0.0.1:1478`. + +--- + +####

prometheus + + + + + server [--prometheus PROMETHEUS_ADDRESS] + + + + + server --prometheus 127.0.0.1:10004 + + + + +Thiết lập địa chỉ và cổng cho máy chủ prometheus `address:port`. Nếu chỉ có cổng được xác định `:5001`, dịch vụ sẽ liên kết với tất cả các giao diện `0.0.0.0:5001` . Nếu lược bỏ, dịch vụ sẽ không được bắt đầu. + +--- + +####

block-gas-target + + + + + server [--block-gas-target BLOCK_GAS_TARGET] + + + + + server --block-gas-target 10000000 + + + + +Thiết lập giới hạn gas khối mục tiêu cho chuỗi. Mặc định (không thực thi): `0`. + +Giải thích chi tiết hơn về mục tiêu gas khối có thể được tìm thấy trong [phần TxPool](/docs/edge/architecture/modules/txpool#block-gas-target). + +--- + +####

max-peers + + + + + server [--max-peers PEER_COUNT] + + + + + server --max-peers 40 + + + + +Thiết lập số lượng ngang hàng tối đa của máy khách. Mặc định: `40`. + +Giới hạn ngang hàng phải được chỉ định bằng `max-peers` hoặc gắn cờ `max-inbound/outbound-peers`. + +--- + +####

max-inbound-peers + + + + + server [--max-inbound-peers PEER_COUNT] + + + + + server --max-inbound-peers 32 + + + + +Thiết lập số lượng ngang hàng gửi vào tối đa trên máy khách. Nếu `max-peers` được thiết lập, giới hạn max-inbound-peer được tính bằng các công thức sau. + +`max-inbound-peer = InboundRatio * max-peers`, trong đó `InboundRatio` là `0.8`. + +--- + +####

max-outbound-peers + + + + + server [--max-outbound-peers PEER_COUNT] + + + + + server --max-outbound-peers 8 + + + + +Thiết lập số lượng ngang hàng gửi đi tối đa trên máy khách. Nếu `max-peers` được thiết lập, giới hạn max-outbound-peer được tính bằng các công thức sau. + +`max-outbound-peer = OutboundRatio * max-peers`, trong đó `OutboundRatio` là `0.2`. + +--- + +####

max-enqueued + + + + + server [--max-enqueued ENQUEUED_TRANSACTIONS] + + + + + server --max-enqueued 210 + + + + +Thiết lập số lượng giao dịch được xếp hàng tối đa cho mỗi tài khoản. Mặc định:`128`. + +--- + +####

log-level + + + + + server [--log-level LOG_LEVEL] + + + + + server --log-level DEBUG + + + + +Thiết lập mức nhật ký cho đầu ra bảng điều khiển. Mặc định: `INFO`. + +--- + +####

log-to + + + + + server [--log-to LOG_FILE] + + + + + server --log-to node.log + + + + +Xác định tên tệp nhật ký sẽ giữ tất cả đầu ra nhật ký từ lệnh máy chủ. Theo mặc định, tất cả nhật ký máy chủ sẽ được xuất ra bảng điều khiển (stdout), nhưng nếu cờ được thiết lập, sẽ không có đầu ra cho bảng điều khiển khi chạy lệnh máy chủ. + +--- + +####

chain + + + + + server [--chain GENESIS_FILE] + + + + + server --chain /home/ubuntu/genesis.json + + + + +Chỉ định tệp gốc được sử dụng để bắt đầu chuỗi. Mặc định: `./genesis.json`. + +--- + +####

join + + + + + server [--join JOIN_ADDRESS] + + + + + server --join /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Chỉ định địa chỉ của mục ngang hàng sẽ được tham gia. + +--- + +####

nat + + + + + server [--nat NAT_ADDRESS] + + + + + server --nat 192.0.2.1 + + + + +Thiết lập địa chỉ IP bên ngoài mà không có cổng, vì nó có thể được máy ngang hàng nhìn thấy. + +--- + +####

dns + + + + + server [--dns DNS_ADDRESS] + + + + + server --dns dns4/example.io + + + + +Thiết lập địa chỉ DNS máy chủ. Mục này có thể được sử dụng để quảng cáo một DNS bên ngoài. Hỗ trợ `dns`, `dns4`, `dns6`. + +--- + +####

Giới hạn giá + + + + + + server [--price-limit PRICE_LIMIT] + + + + + server --price-limit 10000 + + + + +Thiết lập giới hạn giá gas tối thiểu để thực thi để được chấp nhận vào nhóm. Mặc định `1`. + +--- + +####

Slot max- + + + + + server [--max-slots MAX_SLOTS] + + + + + server --max-slots 1024 + + + + +Thiết lập số lượng tối đa trong nhóm. Mặc định: `4096`. + +--- + +####

config + + + + + server [--config CLI_CONFIG_PATH] + + + + + server --config ./myConfig.json + + + + +Chỉ định đường dẫn đến cấu hình CLI. Hỗ trợ `.json`. + +--- + +####

secrets-config + + + + + server [--secrets-config SECRETS_CONFIG] + + + + + server --secrets-config ./secretsManagerConfig.json + + + + +Thiết lập đường dẫn đến tệp cấu hình SecretsManager. Được sử dụng cho Hashicorp Vault, AWS SSM và GCP Secrets Manager. Nếu lược bỏ, trình quản lý bí mật FS cục bộ sẽ được sử dụng. + +--- + +####

dev + + + + + server [--dev DEV_MODE] + + + + + server --dev + + + + +Thiết lập máy khách sang chế độ dev. `false`Lỗi Trong chế độ dev, phát hiện peer bị tắt theo mặc định. + +--- + +####

dev-interval + + + + + server [--dev-interval DEV_INTERVAL] + + + + + server --dev-interval 20 + + + + +Thiết lập khoảng thời gian thông báo dành cho dev của máy khách tính bằng giây. Mặc định: `0`. + +--- + +####

no-discover + + + + + server [--no-discover NO_DISCOVER] + + + + + server --no-discover + + + + +Ngăn không cho máy khách phát hiện ra các máy ngang hàng khác. Mặc định: `false`. + +--- + +####

restore + + + + + server [--restore RESTORE] + + + + + server --restore backup.dat + + + + +Khôi phục các khối từ tệp lưu trữ được chỉ định + +--- + +####

block-time + + + + + server [--block-time BLOCK_TIME] + + + + + server --block-time 1000 + + + + +Thiết lập thời gian sản xuất khối tính bằng giây. Mặc định: `2` + +--- + +####

access-control-allow-origins + + + + server [--access-control-allow-origins ACCESS_CONTROL_ALLOW_ORIGINS] + + + + + server --access-control-allow-origins "https://edge-docs.polygon.technology" + + + + +Thiết lập các miền được ủy quyền để có thể chia sẻ phản hồi từ các yêu cầu JSON-RPC. Thêm nhiều cờ `--access-control-allow-origins "https://example1.com" --access-control-allow-origins "https://example2.com"` để ủy quyền cho nhiều miền. Nếu lược bỏ, tiêu đề Access-Control-Allow-Origins sẽ được đặt thành `*` và tất cả các miền sẽ được ủy quyền. + +--- + +### genesis flags {#genesis-flags} +| **Tất cả cờ genesis** | +|---------------------------------------|---------------------------------------------| +| [dir](/docs/edge/get-started/cli-commands#dir) | [Tên](/docs/edge/get-started/cli-commands#name) | +| [pos](/docs/edge/get-started/cli-commands#pos) | [epoch-size](/docs/edge/get-started/cli-commands#epoch-size) | +| [premine](/docs/edge/get-started/cli-commands#premine) | [chainid](/docs/edge/get-started/cli-commands#chainid) | +| [ibft-validator-type](/docs/edge/get-started/cli-commands#ibft-validator-type) | [ibft-validators-prefix-path](/docs/edge/get-started/cli-commands#ibft-validators-prefix-path) | +| [ibft-validator](/docs/edge/get-started/cli-commands#ibft-validator) | [block-gas-limit](/docs/edge/get-started/cli-commands#block-gas-limit) | +| [consensus](/docs/edge/get-started/cli-commands#consensus) | [bootnode](/docs/edge/get-started/cli-commands#bootnode) | +| [max-validator-count](/docs/edge/get-started/cli-commands#max-validator-count) | [min-validator-count](/docs/edge/get-started/cli-commands#min-validator-count) | + + +####

dir + + + + + genesis [--dir DIRECTORY] + + + + + genesis --dir ./genesis.json + + + + +Thiết lập thư mục cho dữ liệu genesis Polygon Edge. Mặc định: `./genesis.json`. + +--- + +####

Tên + + + + + genesis [--name NAME] + + + + + genesis --name test-chain + + + + +Đặt tên cho chuỗi. Mặc định: `polygon-edge`. + +--- + +####

pos + + + + + genesis [--pos IS_POS] + + + + + genesis --pos + + + + +Đặt cờ chỉ ra rằng máy khách nên sử dụng IBFT Proof of Stake. Mặc định là Bằng chứng Thẩm quyền nếu cờ không được cung cấp hoặc `false`. + +--- + +####

epoch-size + + + + + genesis [--epoch-size EPOCH_SIZE] + + + + + genesis --epoch-size 50 + + + + +Thiết lập kích thước giao đoạn dành cho chuỗi. Mặc định `100000`. + +--- + +####

premine + + + + + genesis [--premine ADDRESS:VALUE] + + + + + genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 + + + + +Thiết lập các tài khoản và số dư định sẵn theo định dạng `address:amount`. +Số tiền có thể ở dạng thập phân hoặc hex. +Số dư được thiết lập mặc định: `0xD3C21BCECCEDA1000000`(1 triệu đồng tiền bản địa). + +--- + +####

chainid + + + + + genesis [--chain-id CHAIN_ID] + + + + + genesis --chain-id 200 + + + + +Thiết lập ID cho chuỗi. Mặc định: `100`. + +--- + +####

ibft-validator-type + + + + + genesis [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + genesis --ibft-validator-type ecdsa + + + + +Chỉ định chế độ xác thực của tiêu đề khối. Các giá trị khả thi: `[ecdsa, bls]`. Mặc định: `bls`. + +--- + +####

ibft-validators-prefix-path + + + + + genesis [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + genesis --ibft-validators-prefix-path test-chain- + + + + +Đường dẫn tiền tố cho thư mục trình xác thực. Cần phải có nếu cờ `ibft-validator` bị lược bỏ. + +--- + +####

ibft-validator + + + + + genesis [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + genesis --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Thiết lập các địa chỉ đã chuyển làm trình xác thực IBFT. Cần phải có nếu cờ `ibft-validators-prefix-path` bị lược bỏ. +1. Nếu mạng đang chạy với ECDSA, định dạng là `--ibft-validator [ADDRESS]`. +2. Nếu mạng đang chạy với BLS, định dạng là `--ibft-validator [ADDRESS]:[BLS_PUBLIC_KEY]`. + +--- + +####

block-gas-limit + + + + + genesis [--block-gas-limit BLOCK_GAS_LIMIT] + + + + + genesis --block-gas-limit 5000000 + + + + +Ám chỉ lượng gas tối đa được sử dụng cho tất cả các hoạt động trong một khối. Mặc định: `5242880`. + +--- + +####

consensus + + + + + genesis [--consensus CONSENSUS_PROTOCOL] + + + + + genesis --consensus ibft + + + + +Thiết lập giao thức đồng thuận Mặc định: `pow`. + +--- + +####

bootnode + + + + + genesis [--bootnode BOOTNODE_URL] + + + + + genesis --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Multiaddr URL cho p2p phát hiện bootstrap. Cờ này có thể được sử dụng nhiều lần. Thay vì địa chỉ IP, địa chỉ DNS của bootnode có thể được cung cấp. + +--- + +####

max-validator-count + + + + + genesis [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + genesis --max-validator-count 42 + + + + +Số lượng trình đặt cược tối đa có thể tham gia trình xác thực được đặt trong chế độ đồng thuận PoS. Số này không thể vượt quá giá trị của MAX_SAFE_INTEGER (2^53 - 2). + +--- + +####

min-validator-count + + + + + genesis [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + genesis --min-validator-count 4 + + + + +Số lượng trình đặt cược tối thiểu cần thiết để tham gia trình xác thực được đặt trong đồng thuận PoS. Số này không thể vượt quá giá trị của max-validator-count. Mặc định là 1. + +--- + +### sgenesis pretriển khai cờ {#genesis-predeploy-flags} + +

path

+ + + + + genesis predeploy [--artifacts-path PATH_TO_ARTIFACTS] + + + + + genesis predeploy --artifacts-path ./ArtifactsData.json + + + + +Đặt đường dẫn đến các hiện vật hợp đồng JSON chứa đựng `abi`, `bytecode`và .`deployedBytecode` + +--- + +

chain

+ + + + + genesis predeploy [--chain PATH_TO_GENESIS] + + + + + genesis predeploy --chain ./genesis.json + + + + +Đặt đường dẫn đến `genesis.json`tệp tin sẽ được cập nhật. Mặc định `./genesis.json`. + +--- + +

structor- arg

+ + + + + genesis predeploy [--constructor-args CONSTRUCTOR_ARGUMENT] + + + + + genesis predeploy --constructor-args 123 + + + + +Thiết lập Hợp đồng Thông minh về việc xây dựng Công ty Thông minh, nếu có. Để có một hướng dẫn chi tiết về các đối số này sẽ giống như thế nào, vui lòng tham khảo [bài báo về sự triển khai trước mắt](/docs/edge/additional-features/predeployment). + +--- + +

Địa chỉ trước

+ + + + + genesis predeploy [--predeploy-address PREDEPLOY_ADDRESS] + + + + + genesis predeploy --predeploy-address 0x5555 + + + + +Đặt địa chỉ để triển khai trước khi. Mặc định `0x0000000000000000000000000000000000001100`. + +--- + + +## Lệnh điều hành {#operator-commands} + +### Lệnh ngang hàng {#peer-commands} + +| **Lệnh** | **Mô tả** | +|------------------------|-------------------------------------------------------------------------------------| +| peers add | Thêm một máy ngang hàng mới bằng cách sử dụng địa chỉ libp2p của họ | +| peers list | Liệt kê tất cả các máy ngang hàng mà máy khách được kết nối thông qua libp2p | +| peers status | Trả về trạng thái của một máy ngang hàng cụ thể từ danh sách ngang hàng, sử dụng địa chỉ libp2p | + +

peers add flags

+ +

addr

+ + + + + peers add --addr PEER_ADDRESS + + + + + peers add --addr /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +Địa chỉ libp2p của máy ngang hàng ở định dạng multiaddr. + +--- + +

grpc-address

+ + + + + peers add [--grpc-address GRPC_ADDRESS] + + + + + peers add --grpc-address 127.0.0.1:10003 + + + + +Địa chỉ của API gRPC. Mặc định: `127.0.0.1:9632`. + +

peers list flags

+ +

grpc-address

+ + + + + peers list [--grpc-address GRPC_ADDRESS] + + + + + peers list --grpc-address 127.0.0.1:10003 + + + + +Địa chỉ của API gRPC. Mặc định: `127.0.0.1:9632`. + +

peers status flags

+ +

peer-id

+ + + + + peers status --peer-id PEER_ID + + + + + peers status --peer-id 16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW + + + + +ID nút Libp2p của một máy ngang hàng cụ thể trong mạng p2p. + +--- + +

grpc-address

+ + + + + peers status [--grpc-address GRPC_ADDRESS] + + + + + peers status --grpc-address 127.0.0.1:10003 + + + + +Địa chỉ của API gRPC. Mặc định: `127.0.0.1:9632`. + +### Lệnh IBFT {#ibft-commands} + +| **Lệnh** | **Mô tả** | +|------------------------|-------------------------------------------------------------------------------------| +| ibft snapshot | Trả về bản chụp IBFT | +| ibft candidates | Truy vấn nhóm ứng viên được đề xuất hiện tại, cũng như các ứng viên chưa được đưa vào | +| ibft propose | Đề xuất một ứng cử viên mới được thêm vào/xóa khỏi tập hợp trình xác thực | +| ibft status | Trả về trạng thái tổng thể của máy khách IBFT | +| ibft switch | Thêm cấu hình fork vào tệp genesis.json để chuyển loại IBFT | +| ibft quorum | Chỉ định số khối mà sau đó phương pháp kích thước số đại biểu tối ưu sẽ được sử dụng để đạt được sự đồng thuận | + + +

ibft snapshot flags

+ +

number

+ + + + + ibft snapshot [--number BLOCK_NUMBER] + + + + + ibft snapshot --number 100 + + + + +Chiều cao khối (số) cho ảnh chụp nhanh. + +--- + +

grpc-address

+ + + + + ibft snapshot [--grpc-address GRPC_ADDRESS] + + + + + ibft snapshot --grpc-address 127.0.0.1:10003 + + + + +Địa chỉ của API gRPC. Mặc định: `127.0.0.1:9632`. + +

ibft candidates flags

+ +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Địa chỉ của API gRPC. Mặc định: `127.0.0.1:9632`. + +

ibft propose flags

+ +

vote

+ + + + + ibft propose --vote VOTE + + + + + ibft propose --vote auth + + + + +Đề xuất thay đổi đối với bộ trình xác thực. Các giá trị khả thi: `[auth, drop]`. + +--- + +

addr

+ + + + + ibft propose --addr ETH_ADDRESS + + + + + ibft propose --addr 0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7 + + + + +Địa chỉ của tài khoản được bình chọn. + +--- + +

bls

+ + + + + ibft propose --bls BLS_PUBLIC_KEY + + + + + ibft propose --bls 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf + + + + +Khóa công khai BLS của tài khoản được bình chọn, chỉ cần thiết trong chế độ BLS. + +--- + +

grpc-address

+ + + + + ibft candidates [--grpc-address GRPC_ADDRESS] + + + + + ibft candidates --grpc-address 127.0.0.1:10003 + + + + +Địa chỉ của API gRPC. Mặc định: `127.0.0.1:9632`. + +

ibft status flags

+ +

grpc-address

+ + + + + ibft status [--grpc-address GRPC_ADDRESS] + + + + + ibft status --grpc-address 127.0.0.1:10003 + + + + +Địa chỉ của API gRPC. Mặc định: `127.0.0.1:9632`. + +

ibft switch flags

+ +

chain

+ + + + + ibft switch [--chain GENESIS_FILE] + + + + + ibft switch --chain genesis.json + + + + +Chỉ định tệp gốc để cập nhật. Mặc định: `./genesis.json`. + +--- + +

Loại

+ + + + + ibft switch [--type TYPE] + + + + + ibft switch --type PoS + + + + +Xác định loại IBFT để chuyển đổi. Các giá trị khả thi: `[PoA, PoS]`. + +--- + +

deployment

+ + + + + ibft switch [--deployment DEPLOYMENT] + + + + + ibft switch --deployment 100 + + + + +Chỉ định độ cao (số lượng khối) của việc triển khai hợp đồng. Chỉ có sẵn với PoS. + +--- + +

from

+ + + + + ibft switch [--from FROM] + + + + + ibft switch --from 200 + + + + +--- + +

ibft-validator-type

+ + + + + ibft switch [--ibft-validator-type IBFT_VALIDATOR_TYPE] + + + + + ibft switch --ibft-validator-type ecdsa + + + + +Chỉ định chế độ xác thực của tiêu đề khối. Các giá trị khả thi: `[ecdsa, bls]`. Mặc định: `bls`. + +--- + +

ibft-validators-prefix-path

+ + + + + ibft switch [--ibft-validators-prefix-path IBFT_VALIDATORS_PREFIX_PATH] + + + + + ibft switch --ibft-validators-prefix-path test-chain- + + + + +Đường dẫn tiền tố dành cho các thư mục của trình xác thực mới. Cần có mặt nếu cờ `ibft-validator` bị lược bỏ. Chỉ khả dụng khi chế độ IBFT là PoA (lược bỏ cờ `--pos`). + +--- + +

ibft-validator

+ + + + + ibft switch [--ibft-validator IBFT_VALIDATOR_LIST] + + + + + ibft switch --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 + + + + +Thiết lập các địa chỉ được chuyển vào làm trình xác thực IBFT được sử dụng sau đợt fork. Cần có mặt nếu cờ `ibft-validators-prefix-path` bị lược bỏ. Chỉ sẵn có trong chế độ PoA. +1. Nếu mạng đang chạy với ECDSA, định dạng là `--ibft-validator [ADDRESS]`. +2. Nếu mạng đang chạy với BLS, định dạng là `--ibft-validator [ADDRESS][BLS_PUBLIC_KEY]`. + +--- + +

max-validator-count

+ + + + + ibft switch [--max-validator-count MAX_VALIDATOR_COUNT] + + + + + ibft switch --max-validator-count 42 + + + + +Số lượng trình đặt cược tối đa có thể tham gia trình xác thực được đặt trong chế độ đồng thuận PoS. Số này không thể vượt quá giá trị của MAX_SAFE_INTEGER (2^53 - 2). + +--- + +

min-validator-count

+ + + + + ibft switch [--min-validator-count MIN_VALIDATOR_COUNT] + + + + + ibft switch --min-validator-count 4 + + + + +Số lượng trình đặt cược tối thiểu cần thiết để tham gia trình xác thực được đặt trong đồng thuận PoS. Số này không thể vượt quá giá trị của max-validator-count. Mặc định là 1. + +Chỉ định chiều cao (số lượng khối) bắt đầu của fork. + +--- + +

ibft quorum flags

+ +

from

+ + + + + ibft quorum [--from your_quorum_switch_block_num] + + + + + ibft quorum --from 350 + + + + +Chiều cao (số lượng khối) để chuyển phép tính số đại biểu thành QuorumOptimal, sử dụng công thức `(2/3 * N)`, trong đó `N` là số lượng nút trình xác thực. Xin lưu ý rằng mục này là để tương thích ngược, tức là chỉ dành cho các chuỗi đã sử dụng phép tính Quorum legacy số lượng tối đa đến một chiều cao (số lượng) khối nhất định. + +--- + +

chain

+ + + + + ibft quorum [--chain GENESIS_FILE] + + + + + ibft quorum --chain genesis.json + + + + +Chỉ định tệp gốc để cập nhật. Mặc định: `./genesis.json`. + +### Lệnh nhóm giao dịch {#transaction-pool-commands} + +| **Lệnh** | **Mô tả** | +|------------------------|--------------------------------------------------------------------------------------| +| txpool status | Trả về số lượng giao dịch trong nhóm | +| txpool subscribe | Đăng ký cho các sự kiện trong nhóm giao dịch | + +

txpool status flags

+ +

grpc-address

+ + + + + txpool status [--grpc-address GRPC_ADDRESS] + + + + + txpool status --grpc-address 127.0.0.1:10003 + + + + +Địa chỉ của API gRPC. Mặc định: `127.0.0.1:9632`. + +

txpool subscribe flags

+ +

grpc-address

+ + + + + txpool subscribe [--grpc-address GRPC_ADDRESS] + + + + + txpool subscribe --grpc-address 127.0.0.1:10003 + + + + +Địa chỉ của API gRPC. Mặc định: `127.0.0.1:9632`. + +--- + +

promoted

+ + + + + txpool subscribe [--promoted LISTEN_PROMOTED] + + + + + txpool subscribe --promoted + + + + +Đăng ký cho các sự kiện tx được đẩy mạnh trong TxPool. + +--- + +

dropped

+ + + + + txpool subscribe [--dropped LISTEN_DROPPED] + + + + + txpool subscribe --dropped + + + + +Đăng ký cho các sự kiện tx bị loại bỏ trong TxPool. + +--- + +

demoted

+ + + + + txpool subscribe [--demoted LISTEN_DEMOTED] + + + + + txpool subscribe --demoted + + + + +Đăng ký cho các sự kiện tx bị giáng cấp trong TxPool. + +--- + +

added

+ + + + + txpool subscribe [--added LISTEN_ADDED] + + + + + txpool subscribe --added + + + + +Đăng ký các sự kiện tx được thêm vào TxPool. + +--- + +

enqueued

+ + + + + txpool subscribe [--enqueued LISTEN_ENQUEUED] + + + + + txpool subscribe --enqueued + + + + +Đăng ký cho các sự kiện tx được xếp hàng trong hàng đợi tài khoản. + +--- + +### Lệnh blockchain {#blockchain-commands} + +| **Lệnh** | **Mô tả** | +|------------------------|-------------------------------------------------------------------------------------| +| status | Trả về trạng thái của máy khách. Có thể tìm thấy phản hồi chi tiết dưới đây | +| monitor | Đăng ký luồng sự kiện blockchain. Có thể tìm thấy phản hồi chi tiết dưới đây | +| version | Trả về phiên bản hiện tại của máy khách | + +

status flags

+ +

grpc-address

+ + + + + status [--grpc-address GRPC_ADDRESS] + + + + + status --grpc-address 127.0.0.1:10003 + + + + +Địa chỉ của API gRPC. Mặc định: `127.0.0.1:9632`. + +

monitor flags

+ +

grpc-address

+ + + + + monitor [--grpc-address GRPC_ADDRESS] + + + + + monitor --grpc-address 127.0.0.1:10003 + + + + +Địa chỉ của API gRPC. Mặc định: `127.0.0.1:9632`. + +--- +

lệnh phiên bản

+ + + + + + version + + + + +Hiển thị phiên bản phát hành, chi nhánh git, cam kết hash, và thời gian xây dựng. + +## Lệnh bí mật {#secrets-commands} + +| **Lệnh** | **Mô tả** | +|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------| +| secrets init | Khởi tạo khóa riêng cho trình quản lý bí mật tương ứng | +| secrets generate | Tạo tệp cấu hình trình quản lý bí mật có thể được phân tích cú pháp bởi Polygon Edge | +| Sản xuất bí mật | In địa chỉ khóa công khai BLS và địa chỉ khóa công khai và nút để tham khảo. | + +### secrets init flags {#secrets-init-flags} + +

config

+ + + + + secrets init [--config SECRETS_CONFIG] + + + + + secrets init --config ./secretsManagerConfig.json + + + + +Thiết lập đường dẫn đến tệp cấu hình SecretsManager. Sử dụng cho Hashicorp Vault. Nếu lược bỏ, trình quản lý bí mật FS cục bộ sẽ được sử dụng. + +--- + +

data-dir

+ + + + + secrets init [--data-dir DATA_DIRECTORY] + + + + + secrets init --data-dir ./example-dir + + + + +Thiết lập thư mục cho dữ liệu Polygon Edge nếu FS cục bộ được sử dụng. + +--- + +

ecdsa

+ + + + + secrets init [--ecdsa FLAG] + + + + + secrets init --ecdsa=false + + + + +Đặt cờ ám chỉ có tạo khóa ECDSA hay không. Mặc định: `true`. + +--- + +

network

+ + + + + secrets init [--network FLAG] + + + + + secrets init --network=false + + + + +Đặt cờ ám chỉ có tạo khóa Mạng Libp2p hay không. Mặc định: `true`. + +--- + +

bls

+ + + + + secrets init [--bls FLAG] + + + + + secrets init --bls + + + + +Đặt cờ ám chỉ có tạo khóa BLS hay không. Mặc định: `true`. + +### secrets generate flags {#secrets-generate-flags} + +

dir

+ + + + + secrets generate [--dir DATA_DIRECTORY] + + + + + secrets generate --dir ./example-dir + + + + +Thiết lập thư mục cho tệp cấu hình trình quản lý bí mật Mặc định: `./secretsManagerConfig.json` + +--- + +

Loại

+ + + + + secrets generate [--type TYPE] + + + + + secrets generate --type hashicorp-vault + + + + +Chỉ định loại trình quản lý bí mật [`hashicorp-vault`]. Mặc định: `hashicorp-vault` + +--- + +

token

+ + + + + secrets generate [--token TOKEN] + + + + + secrets generate --token s.zNrXa9zF9mgrdnClM7PZ19cu + + + + +Chỉ định token truy cập cho dịch vụ + +--- + +

server-url

+ + + + + secrets generate [--server-url SERVER_URL] + + + + + secrets generate --server-url http://127.0.0.1:8200 + + + + +Chỉ định URL máy chủ dành cho dịch vụ + +--- + +

Tên

+ + + + + secrets generate [--name NODE_NAME] + + + + + secrets generate --name node-1 + + + + +Chỉ định tên của nút để lưu trữ hồ sơ tại chỗ. Mặc định: `polygon-edge-node` + +--- + +

namespace

+ + + + + secrets generate [--namespace NAMESPACE] + + + + + secrets generate --namespace my-namespace + + + + +Chỉ định không gian tên được sử dụng cho trình quản lý bí mật Hashicorp Vault. Mặc định: `admin` + +### Cờ xuất bí mật {#secrets-output-flags} + +

bls

+ + + + + secrets output [--bls FLAG] + + + + + secrets output --bls + + + + +Đánh dấu cờ chỉ ra liệu có phải là chỉ ra chìa khóa công khai BLS không. Mặc định: `true` + +--- + +

config

+ + + + + secrets output [--config SECRETS_CONFIG] + + + + + secrets output --config ./secretsManagerConfig.json + + + + +Thiết lập đường dẫn đến tệp cấu hình SecretsManager. Nếu lược bỏ, trình quản lý bí mật FS địa phương sẽ được sử dụng. + +--- + +

data-dir

+ + + + + secrets output [--data-dir DATA_DIRECTORY] + + + + + secrets output --data-dir ./example-dir + + + + +Thiết lập thư mục cho dữ liệu Polygon Edge nếu FS cục bộ được sử dụng. + +--- + +

node-id

+ + + + + secrets output [--node-id FLAG] + + + + + secrets output --node-id + + + + +Đặt cờ chỉ ra sự phát triển của thẻ thông tin về mạng hay không. Mặc định: `true` + +--- + +

Người xác thực

+ + + + + secrets output [--validator FLAG] + + + + + secrets output --validator + + + + +Sets Cờ sẽ chỉ ra địa chỉ xác thực có phải là chỉ ra không. Mặc định: `true` + +--- + +## Phản hồi {#responses} + +### Phản hồi trạng thái {#status-response} + +Đối tượng phản hồi được xác định bằng cách Bộ đệm giao thức. +````go title="minimal/proto/system.proto" +message ServerStatus { + int64 network = 1; + + string genesis = 2; + + Block current = 3; + + string p2pAddr = 4; + + message Block { + int64 number = 1; + string hash = 2; + } +} +```` + +### Theo dõi phản hồi {#monitor-response} +````go title="minimal/proto/system.proto" +message BlockchainEvent { + // The "repeated" keyword indicates an array + repeated Header added = 1; + repeated Header removed = 2; + + message Header { + int64 number = 1; + string hash = 2; + } +} +```` + +## Tiện ích {#utilities} + +### whitelist commands {#whitelist-commands} + +| **Lệnh** | **Mô tả** | +|------------------------|-------------------------------------------------------------------------------------| +| whitelist show | Hiển thị thông tin danh sách trắng | +| whitelist deployment | Cập nhật hợp đồng thông minh triển khai danh sách trắng | + +

whitelist show

+ + + + + whitelist show + + + + +Hiển thị thông tin danh sách trắng. + +--- + + + + + whitelist show [--chain GENESIS_FILE] + + + + + whitelist show --chain genesis.json + + + + +Chỉ định tệp gốc để cập nhật. Mặc định: `./genesis.json`. + +--- + +

whitelist deployment

+ +

chain

+ + + + + whitelist deployment [--chain GENESIS_FILE] + + + + + whitelist deployment --chain genesis.json + + + + +Chỉ định tệp gốc để cập nhật. Mặc định: `./genesis.json`. + +--- + +

add

+ + + + + whitelist deployment [--add ADDRESS] + + + + + whitelist deployment --add 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Thêm địa chỉ mới vào danh sách trắng triển khai hợp đồng. Chỉ các địa chỉ trong danh sách trắng triển khai hợp đồng mới có thể triển khai hợp đồng. Nếu trống, bất kỳ địa chỉ nào cũng có thể thực thi việc triển khai hợp đồng + +--- + +

remove

+ + + + + whitelist deployment [--remove ADDRESS] + + + + + whitelist deployment --remove 0x5383Cb489FaCa92365Bb6f9f1FB40bD032E6365d + + + + +Xóa địa chỉ khỏi danh sách trắng triển khai hợp đồng. Chỉ các địa chỉ trong danh sách trắng triển khai hợp đồng mới có thể triển khai hợp đồng. Nếu trống, bất kỳ địa chỉ nào cũng có thể thực thi việc triển khai hợp đồng + +--- + +### backup flags {#backup-flags} + +

grpc-address

+ + + + + backup [--grpc-address GRPC_ADDRESS] + + + + + backup --grpc-address 127.0.0.1:9632 + + + + +Địa chỉ của API gRPC. Mặc định: `127.0.0.1:9632`. + +--- + +

out

+ + + + + backup [--out OUT] + + + + + backup --out backup.dat + + + + +Đường dẫn của tệp lưu trữ cần lưu. + +--- + +

from

+ + + + + from [--from FROM] + + + + + backup --from 0x0 + + + + +Chiều cao bắt đầu của các khối trong kho lưu trữ. Mặc định: 0. + +--- + +

to

+ + + + + to [--to TO] + + + + + backup --to 0x2710 + + + + +Chiều cao (số lượng) cuối của các khối trong kho lưu trữ. + +--- + +## Biểu mẫu Genesis {#genesis-template} +Tệp genesis nên được sử dụng để thiết lập trạng thái ban đầu của blockchain (ví dụ: nếu một số tài khoản phải có số dư ban đầu). + +Tệp *./genesis.json* sau đây được tạo: +````json +{ + "name": "example", + "genesis": { + "nonce": "0x0000000000000000", + "gasLimit": "0x0000000000001388", + "difficulty": "0x0000000000000001", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x0000000000000000000000000000000000000000", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + }, + "params": { + "forks": {}, + "chainID": 100, + "engine": { + "pow": {} + } + }, + "bootnodes": [] +} +```` + +### Thư mục dữ liệu {#data-directory} + +Khi thực thi cờ *data-dir*, một thư mục **chuỗi thử nghiệm** sẽ được tạo. Cấu trúc thư mục bao gồm các thư mục con sau đây: +* **blockchain** - Lưu trữ LevelDB dành cho các đối tượng blockchain +* **trie** - Lưu trữ LevelDB dành cho Merkle trie +* **keystore** - Lưu trữ khóa riêng dành cho máy khách. Mục này bao gồm khóa riêng tư libp2p và khóa niêm phong/trình xác thực +* **consensus** - Lưu trữ bất kỳ thông tin đồng thuận nào mà khách hàng có thể cần khi làm việc + +## Tài nguyên {#resources} +* **[Bộ đệm giao thức](https://developers.google.com/protocol-buffers)** diff --git a/archive/edge/vi-edge/get-started/installation.md b/archive/edge/vi-edge/get-started/installation.md new file mode 100644 index 0000000000..39ce1a0be0 --- /dev/null +++ b/archive/edge/vi-edge/get-started/installation.md @@ -0,0 +1,63 @@ +--- +id: installation +title: Cài đặt +description: "Cách cài đặt Polygon Edge.\n" +keywords: + - docs + - polygon + - edge + - install + - installation +--- + +Vui lòng tham khảo phương pháp cài đặt phù hợp hơn với bạn. + + +Khuyến nghị của chúng tôi là sử dụng các bản phát hành được tạo sẵn và xác minh các tổng kiểm tra được cấp. + + +## Bản phát hành được tạo sẵn + {#pre-built-releases} + +Vui lòng tham khảo trang [Bản phát hành GitHub](https://github.com/0xPolygon/polygon-edge/releases) để xem danh sách các bản phát hành. + + +Polygon Edge đi kèm các mã nhị phân AMD64/ARM64 được biên dịch chéo cho Darwin và Linux. + + +--- + +## Hình ảnh Docker + {#docker-image} + +Hình ảnh Docker chính thức được lưu trữ trong [hub.docker.com registry](https://hub.docker.com/r/0xpolygon/polygon-edge). + + +`docker pull 0xpolygon/polygon-edge:latest` + +--- + +## Xây dựng từ nguồn {#building-from-source} + +Trước khi sử dụng `go install` hãy đảm bảo rằng bạn đã cài đặt Go `>=1.18` và định cấu hình phù hợp. + + +Chi nhánh ổn định là chi nhánh của sự phát hành mới nhất. + +```shell +git clone https://github.com/0xPolygon/polygon-edge.git +cd polygon-edge/ +go build -o polygon-edge main.go +sudo mv polygon-edge /usr/local/bin +``` + +--- + +## Sử dụng `go install` + +Trước khi sử dụng `go install` hãy đảm bảo rằng bạn đã cài đặt Go `>=1.17` và định cấu hình phù hợp. + + +`go install github.com/0xPolygon/polygon-edge@release/` + +Việc nhị phân sẽ có sẵn trong biến `GOBIN`môi trường của bạn, và sẽ bao gồm sự thay đổi từ sự phát hành mới nhất. Bạn có thể kiểm tra [Github Feleases](https://github.com/0xPolygon/polygon-edge/releases) để tìm ra ai là người mới nhất. diff --git a/archive/edge/vi-edge/get-started/set-up-ibft-locally.md b/archive/edge/vi-edge/get-started/set-up-ibft-locally.md new file mode 100644 index 0000000000..0145331781 --- /dev/null +++ b/archive/edge/vi-edge/get-started/set-up-ibft-locally.md @@ -0,0 +1,350 @@ +--- +id: set-up-ibft-locally +title: Thiết lập Cục bộ +description: "Hướng dẫn từng bước thiết lập cục bộ." +keywords: + - docs + - polygon + - edge + - local + - setup + - genesis +--- + +:::caution Hướng dẫn này chỉ nhằm mục đích thử nghiệm + +Hướng dẫn dưới đây sẽ hướng dẫn bạn cách thiết lập mạng Polygon Edge trên máy cục bộ của bạn cho các mục đích thử nghiệm và phát triển. + +Quy trình này khác rất nhiều so với cách bạn muốn thiết lập mạng Polygon Edge cho một kịch bản sử dụng thực tế trên một nhà cung cấp đám mây: **[Thiết lập Đám mây](/docs/edge/get-started/set-up-ibft-on-the-cloud)** + +::: + + +## Yêu cầu {#requirements} + +Tham khảo mục [Cài đặt](/docs/edge/get-started/installation) để cài đặt Polygon Edge. + +## Tổng quan {#overview} + +![Thiết lập Cục bộ](/img/edge/ibft-setup/local.svg) + +Trong hướng dẫn này, mục tiêu của chúng ta là thiết lập một mạng `polygon-edge`blockchain hoạt động với [Giao thức đồng thuận IBFT](https://github.com/ethereum/EIPs/issues/650). + Mạng blockchain sẽ gồm 4 nút và cả 4 nút đều là nút trình xác thực, đủ điều kiện để đề xuất khối và xác thực các khối đến từ những người đề xuất khác. + Tất cả 4 nút sẽ chạy trên cùng một máy, vì ý tưởng của hướng dẫn này là cung cấp cho bạn một cụm IBFT đầy đủ chức năng trong khoảng thời gian ngắn nhất. + +Để đạt được điều đó, chúng tôi hướng dẫn bạn qua 4 bước dễ dàng: + +1. Việc khởi tạo các thư mục dữ liệu sẽ tạo cả các khóa của trình xác thực cho từng nút trong số 4 nút và khởi tạo các thư mục dữ liệu blockchain trống. Các khóa của trình xác thực rất quan trọng vì chúng ta cần khởi động khối genesis với tập hợp ban đầu gồm các trình xác thực bằng các khóa này. +2. Chuẩn bị chuỗi kết nối dành cho bootnode sẽ là thông tin quan trọng cho mọi nút mà chúng ta sẽ chạy để kết nối với nút nào khi bắt đầu lần đầu tiên. +3. Việc tạo tệp `genesis.json`sẽ yêu cầu nhập cả các khóa của trình xác thực được tạo ở **bước 1** được sử dụng để thiết lập các trình xác thực ban đầu của mạng trong khối genesis và chuỗi kết nối bootnode từ **bước 2**. +4. Chạy tất cả các nút là mục tiêu cuối cùng của hướng dẫn này và sẽ là bước cuối cùng chúng ta thực hiện, chúng tôi sẽ hướng dẫn các nút sử dụng thư mục dữ liệu nào và nơi để tìm `genesis.json`sẽ khởi động trạng thái mạng ban đầu. + +Vì tất cả bốn nút sẽ chạy trên localhost, nên trong quá trình thiết lập, tất cả các thư mục dữ liệu được mong đợi cho mỗi nút nằm trong cùng một thư mục mẹ. + +:::info Số lượng trình xác thực + +Không có quy định về số lượng nút tối thiểu trong một cụm, nghĩa là có thể có các cụm chỉ có 1 nút trình xác thực. + Xin lưu ý rằng cụm với _một_ nút duy nhất sẽ không có **khả năng chống lại sự cố** và **không đảm bảo BFT**. + + +Số lượng nút tối thiểu được đề xuất để đảm bảo BFT là 4 - vì trong một cụm 4 nút, lỗi của + 1 nút có thể được chấp nhận nếu 3 nút còn lại hoạt động bình thường. + +::: + +## Bước 1: Khởi tạo các thư mục dữ liệu dành cho IBFT và tạo các khóa của trình xác thực {#step-1-initialize-data-folders-for-ibft-and-generate-validator-keys} + +Để thiết lập và chạy với IBFT, bạn cần khởi tạo các thư mục dữ liệu, một thư mục cho mỗi nút: + +````bash +polygon-edge secrets init --data-dir test-chain-1 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-2 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-3 +```` + +````bash +polygon-edge secrets init --data-dir test-chain-4 +```` + +Mỗi lệnh này sẽ in khóa của trình xác thực, khóa công khai BLS và [ID nút](https://docs.libp2p.io/concepts/peer-id/). + Bạn sẽ cần Node ID của nút đầu tiên cho bước tiếp theo. + +### Bí mật ngoài khơi {#outputting-secrets} +Kết quả bí mật có thể được lấy lại một lần nữa, nếu cần. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +## Bước 2: Chuẩn bị chuỗi kết nối multiaddr cho bootnode {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Để một nút có thể thiết lập kết nối thành công, nút này cần biết nên kết nối với máy chủ `bootnode` nào để + có thông tin về các nút còn lại trên mạng lưới. `bootnode` đôi khi cũng được gọi là máy chủ `rendezvous` theo thuật ngữ p2p. + +`bootnode` không phải là một phiên bản đặc biệt của nút Polygon Edge. Mỗi nút polygon-edge có thể đóng vai trò là một `bootnode`, nhưng mỗi nút polygon-edge cần phải có một tập hợp các bootnode được chỉ định, chúng sẽ được liên hệ để cung cấp thông tin về cách kết nối với các nút còn lại trong mạng lưới. + +Để tạo chuỗi kết nối và chỉ định bootnode, chúng ta cần tuân thủ [định dạng multiaddr](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +Trong hướng dẫn này, chúng ta sẽ coi nút đầu tiên và nút thứ hai là bootnode cho các nút còn lại. + Điều sẽ xảy ra trong tình huống này chính là các nút kết nối với `node 1` hoặc `node 2`sẽ nhận được thông tin về cách kết nối với nhau thông qua + các bootnode chung. + +:::info Bạn cần chỉ định ít nhất một bootnode để bắt đầu một nút + +Cần có ít nhất **một** bootnode để các nút khác trong mạng có thể phát hiện ra nhau. Nhiều bootnode hơn được khuyến nghị, như chúng cung cấp khả năng phục hồi cho mạng trong trường hợp mất điện. Trong hướng dẫn này, chúng ta sẽ liệt kê hai nút, nhưng có thể thay đổi điều này trong quá trình mà không ảnh hưởng đến tính hợp lệ của tệp `genesis.json`. + +::: + +Vì chúng ta đang chạy trên localhost, nên có thể an toàn khi giả sử rằng `` là `127.0.0.1`. + +Đối với `` mà chúng ta sẽ sử dụng `10001` vì chúng ta sẽ định cấu hình máy chủ libp2p cho `node 1` để nghe trên cổng này sau. + +Và cuối cùng, chúng ta cần `` mà chúng ta có thể lấy từ đầu ra của lệnh đã chạy trước đó `polygon-edge secrets init --data-dir test-chain-1` (được sử dụng để tạo các khóa và thư mục dữ liệu cho `node1`) + +Sau khi liên kết, chuỗi kết nối multiaddr với `node 1` mà chúng ta sẽ sử dụng làm bootnode sẽ trông giống thế này (chỉ có `` ở cuối là khác biệt): +``` +/ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Tương tự, chúng ta sẽ dựng multiaddr cho bootnode thứ hai như hình dưới đây +``` +/ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` + +:::info Tên máy chủ DNS thay vì ips + +Polygon Edge hỗ trợ sử dụng tên máy chủ DNS cho cấu hình các nút. Đây là một tính năng rất hữu ích dành cho các triển khai sử dụng đám mây, vì ip của nút có thể thay đổi vì nhiều lý do khác nhau. + +Định dạng multiaddr cho chuỗi kết nối khi sử dụng tên máy chủ DNS như sau: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + + +## Bước 3: Tạo tệp genesis với 4 nút làm trình xác thực {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +````bash +polygon-edge genesis --consensus ibft --ibft-validators-prefix-path test-chain- --bootnode /ip4/127.0.0.1/tcp/10001/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW --bootnode /ip4/127.0.0.1/tcp/20001/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +```` + +Lệnh này thực hiện: + +* `--ibft-validators-prefix-path` thiết lập đường dẫn thư mục tiền tố thành đường dẫn được chỉ định mà IBFT trong Polygon Edge có thể sử dụng. Thư mục này được sử dụng để chứa thư mục `consensus/`, nơi giữ khóa riêng tư của trình xác thực. Khoá công khai của trình xác thực là cần thiết để dựng tệp genesis - danh sách ban đầu của các nút bootstrap. Cờ này chỉ có ý nghĩa khi thiết lập mạng trên máy chủ cục bộ, vì trong trường hợp thực tế, chúng ta không thể mong đợi tất cả các thư mục dữ liệu của các nút nằm trên cùng một hệ thống tệp mà từ đó chúng ta có thể dễ dàng đọc các khóa công khai của chúng. +* `--bootnode` thiết lập địa chỉ của bootnode để cho phép các nút tìm thấy nhau. + Chúng ta sẽ sử dụng chuỗi multiadr của `node 1`, như đã đề cập trong **bước 2**. + +Kết quả của lệnh này là tệp `genesis.json` chứa khối khởi đầu của chuỗi khối mới của chúng tôi, với bộ xác thực được xác định trước và cấu hình cho nút nào cần liên hệ trước để thiết lập kết nối. + +:::info Chuyển sang ECDSA + +BLS là chế độ xác thực mặc định của người đầu khối Nếu bạn muốn chuỗi của bạn chạy trong chế độ ECDSA, bạn có thể sử dụng cờ `—ibft-validator-type`, bằng sự tranh `ecdsa`luận: + +``` +genesis --ibft-validator-type ecdsa +``` +::: +:::info Số dư tài khoản trước khi khai thác + +Bạn có thể sẽ muốn thiết lập mạng lưới blockchain của mình với một số địa chỉ có số dư "định sẵn". + +Để làm như vậy, hãy tùy ý chuyển cờ `--premine` cho mỗi địa chỉ mà bạn muốn được khởi tạo với số dư nhất định + trên blockchain. + +Ví dụ: nếu chúng ta muốn định trước 1000 ETH để xử lý `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` trong khối khởi đầu của mình, thì chúng ta cần cung cấp đối số sau: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Lưu ý rằng số lượng trước khi đào là WEI, không phải ETH.** + +::: + +:::info Thiết lập giới hạn gas khối + +Giới hạn gas mặc định cho mỗi khối là `5242880`. Giá trị này được ghi trong tệp genesis, nhưng bạn có thể muốn tăng / giảm nó. + +Để làm như vậy, bạn có thể sử dụng cờ `--block-gas-limit`theo sau là giá trị mong muốn như hình dưới đây: + +```shell +--block-gas-limit 1000000000 +``` +::: + +:::info Thiết lập giới hạn trình mô tả tệp hệ thống + +Giới hạn tệp tin mặc định (số lượng tệp tin đã mở) có thể thấp, và trên Linux, mọi thứ đều là tệp. Nếu các nút được dự kiến sẽ có thông lượng cao, bạn có thể cân nhắc việc tăng giới hạn này. Kiểm tra các tiến sĩ chính thức của sự phân tâm linux của bạn để biết thêm chi tiết. + +#### Kiểm tra giới hạn hệ điều hành hiện tại (tệp đang mở) {#check-current-os-limits-open-files} +```shell title="ulimit -n" +1024 # Ubuntu default +``` + +#### Tăng giới hạn tệp đang mở {#increase-open-files-limit} +- Chạy `polygon-edge`trong foreground (vỏ sọc) + ```shell title="Set FD limit for the current session" + ulimit -n 65535 # affects only current session, limit won't persist after logging out + ``` + + ```shell title="Edit /etc/security/limits.conf" + # add the following lines to the end of the file to modify FD limits + * soft nofile 65535 # sets FD soft limit for all users + * hard nofile 65535 # sets FD hard limit for all users + + # End of file + ``` +Lưu tệp tin và khởi động lại hệ thống. + +- Chạy `polygon-edge`trong nền như một dịch vụ + +Nếu được `polygon-edge`chạy như một dịch vụ hệ thống, sử dụng công cụ như , giới hạn mô tả `systemd`tệp tin sẽ được quản lý bằng cách sử dụng `systemd`. + ```shell title="Edit /etc/systemd/system/polygon-edge.service" + [Service] + ... + LimitNOFILE=65535 + ``` + +### Khắc phục sự cố {#troubleshooting} +```shell title="Watch FD limits of polygon edge running process" +watch -n 1 "ls /proc/$(pidof polygon-edge)/fd | wc -l" +``` + +```shell title="Check max FD limits for polygon-edge running process" +cat /proc/$(pidof polygon-edge)/limits +``` +::: + + +## Bước 4: Chạy tất cả máy khách {#step-4-run-all-the-clients} + +Vì chúng ta đang cố gắng chạy một mạng Polygon Edge gồm 4 nút trên cùng một máy, chúng ta cần chú ý để tránh xung đột cổng. Đây là lý do chúng ta sẽ sử dụng lý do sau để xác định các cổng nghe của từng máy chủ của một nút: + +- `10000` cho máy chủ gRPC của `node 1`, `20000` cho máy chủ GRPC của `node 2` v.v. +- `10001` cho máy chủ libp2p của `node 1` , `20001` cho máy chủ libp2p của `node 2` v.v. +- `10002` cho máy chủ JSON-RPC của `node 1`, `20002` cho máy chủ JSON-RPC của `node 2` v.v. + +Để chạy ứng dụng khách **đầu tiên** (lưu ý cổng `10001` vì nó được sử dụng như một phần của multiaddr libp2p ở **bước 2** cùng với ID nút của nút 1): + +````bash +polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :10000 --libp2p :10001 --jsonrpc :10002 --seal +```` + +Để chạy máy khách **thứ hai**: + +````bash +polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :20000 --libp2p :20001 --jsonrpc :20002 --seal +```` + +Để chạy máy khách **thứ ba**: + +````bash +polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :30000 --libp2p :30001 --jsonrpc :30002 --seal +```` + +Để chạy máy khách **thứ tư**: + +````bash +polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :40000 --libp2p :40001 --jsonrpc :40002 --seal +```` + +Để xem qua những gì đã được thực hiện cho đến nay: + +* Thư mục cho dữ liệu máy khách đã được chỉ định là **./test-chain-\*** +* Các máy chủ GRPC đã được khởi động trên các cổng **10000**, **20000**, **30000** và **40000**, cho mỗi nút tương ứng +* Các máy chủ libp2p đã được khởi động trên các cổng **10001**, **20001**, **30001** và **40001**, cho mỗi nút tương ứng +* Các máy chủ JSON-RPC đã được khởi động trên các cổng **10002**, **20002**, **30002** và **40002**, cho mỗi nút tương ứng +* Cờ *flag* có nghĩa là nút đang được khởi động sẽ tham gia vào quá trình niêm phong khối +* Cờ *chain* chỉ định tệp gốc nào sẽ được sử dụng cho cấu hình chuỗi + +Cấu trúc của tệp tin genesis được đề cập trong phần [Lệnh CLI](/docs/edge/get-started/cli-commands). + +Sau khi chạy các lệnh trước đó, bạn đã thiết lập mạng Polygon Edge 4 nút, có khả năng niêm phong các khối và khôi phục từ lỗi nút. + +:::info Khởi động máy khách bằng tệp cấu hình + +Thay vì chỉ định tất cả các tham số cấu hình dưới dạng đối số CLI, Máy khách cũng có thể được khởi động bằng tệp cấu hình bằng cách thực thi lệnh sau: + +````bash +polygon-edge server --config +```` +Ví dụ: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Hiện tại, chúng tôi hỗ trợ `yaml`và tệp tin cấu hình dựa `json`trên đây, có thể tìm thấy tệp tin cấu hình mẫu **[ở đây](/docs/edge/configuration/sample-config)**. + +::: + +:::info Các bước để chạy một nút không xác thực + +Một nút không phải là trình xác thực sẽ luôn đồng bộ các khối mới nhất nhận được từ nút trình xác thực, bạn có thể kích hoạt một nút không phải là trình xác thực bằng cách chạy lệnh sau. + + +````bash +polygon-edge server --data-dir --chain --grpc-address --libp2p --jsonrpc +```` +Ví dụ: bạn có thể thêm máy khách không phải là trình xác thực **thứ năm** bằng cách thực thi lệnh sau: + +````bash +polygon-edge server --data-dir ./test-chain --chain genesis.json --grpc-address :50000 --libp2p :50001 --jsonrpc :50002 +```` +::: + +:::info Chỉ định giới hạn giá + +Một nút Polygon Edge có thể được bắt đầu với **giới hạn giá** đã đặt cho các giao dịch đến. + +Đơn vị dành cho giới hạn giá là `wei`. + + +Thiết lập giới hạn giá nghĩa là bất kỳ giao dịch nào được xử lý bởi nút hiện tại sẽ cần có giá gas **cao hơn +** giới hạn giá đã thiết lập, nếu không, giá sẽ không được đưa vào trong một khối. + +Việc đa số các nút tuân theo một giới hạn giá nhất định sẽ thực thi quy tắc giao dịch trong mạng không được dưới một ngưỡng giá nhất định. + +Giá trị mặc định cho giới hạn giá là `0`, có nghĩa là nó hoàn toàn không được thực thi theo mặc định. + +Ví dụ sử dụng cờ `--price-limit` : +````bash +polygon-edge server --price-limit 100000 ... +```` + +Cần lưu ý rằng giới hạn giá **chỉ được thực thi đối với các giao dịch không cục bộ**, nghĩa là giới hạn giá không áp dụng cho các giao dịch được thêm cục bộ trên nút. +::: + +:::info URL websocket + +Theo mặc định, khi bạn chạy Polygon Edge, nó sẽ tạo một URL WebSocket dựa trên vị trí chuỗi. Lược đồ URL `wss://` được sử dụng cho các liên kết HTTPS và `ws://` cho HTTP. + +URL Localhost Websocket: +````bash +ws://localhost:10002/ws +```` +Vui lòng lưu ý rằng số cổng phụ thuộc vào cổng JSON-RPC đã chọn cho nút. + +URL Websocket Edgenet: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: + + + +## Bước 5: Tương tác với mạng Polygon Edge {#step-5-interact-with-the-polygon-edge-network} + +Bây giờ bạn đã thiết lập ít nhất 1 máy khách đang chạy, bạn có thể tiếp tục và tương tác với blockchain bằng tài khoản bạn đã tạo trước ở trên và bằng cách chỉ định URL JSON-RPC cho bất kỳ nút nào trong số 4 nút: +- Nút 1: `http://localhost:10002` +- Nút 2: `http://localhost:20002` +- Nút 3: `http://localhost:30002` +- Nút 4: `http://localhost:40002` + +Thực hiện theo hướng dẫn này để phát hành lệnh của trình vận hành cho cụm vừa mới dựng: [Cách để truy vấn thông tin trình vận hành](/docs/edge/working-with-node/query-operator-info) (cổng GRPC cho cụm chúng ta mới dựng là `10000`/`20000`/`30000`/`40000` cho mỗi nút tương ứng) diff --git a/archive/edge/vi-edge/get-started/set-up-ibft-on-the-cloud.md b/archive/edge/vi-edge/get-started/set-up-ibft-on-the-cloud.md new file mode 100644 index 0000000000..8c3c1c3237 --- /dev/null +++ b/archive/edge/vi-edge/get-started/set-up-ibft-on-the-cloud.md @@ -0,0 +1,416 @@ +--- +id: set-up-ibft-on-the-cloud +title: Thiết lập Đám mây +description: "Hướng dẫn thiết lập đám mây chi tiết." +keywords: + - docs + - polygon + - edge + - cloud + - setup + - genesis +--- + +:::info Hướng dẫn này dành cho thiết lập mạng lưới chính hoặc mạng thử nghiệm + +Hướng dẫn dưới đây sẽ hỗ trợ bạn cách thiết lập mạng Polygon Edge với nhà cung cấp dịch vụ đám mây để thiết lập vận hành mạng thử nghiệm hoặc mạng lưới chính. + + +Nếu bạn muốn thiết lập cục bộ mạng Polygon Edge để nhanh chóng kiểm tra `polygon-edge` trước khi thực hiện các thiết lập tương tự khi vận hành, vui lòng tham khảo + **[Thiết lập Cục bộ](/docs/edge/get-started/set-up-ibft-locally)** +::: + +## Yêu cầu {#requirements} + +Tham khảo mục [Cài đặt](/docs/edge/get-started/installation) để cài đặt Polygon Edge. + +### Thiết lập kết nối VM + {#setting-up-the-vm-connectivity} + +Tùy thuộc vào lựa chọn nhà cung cấp dịch vụ đám mây, bạn có thể thiết lập kết nối và quy tắc giữa các VM bằng tường lửa, + nhóm bảo mật hoặc danh sách kiểm soát truy cập. + + +Phần duy nhất của `polygon-edge` cần được tiếp xúc với các VM khác là máy chủ libp2p, chỉ cần cho phép + tất cả giao tiếp giữa các VM trên cổng libp2p `1478`mặc định là đủ. + + +## Tổng quan {#overview} + +![Thiết lập đám mây](/img/edge/ibft-setup/cloud.svg) + +Trong hướng dẫn này, mục tiêu của chúng ta là thiết lập một mạng `polygon-edge`blockchain hoạt động với [Giao thức đồng thuận IBFT](https://github.com/ethereum/EIPs/issues/650). + Mạng blockchain sẽ gồm 4 nút và cả 4 nút đều là nút trình xác thực, đủ điều kiện để đề xuất khối và xác thực các khối đến từ những người đề xuất khác. + Mỗi nút trong số 4 nút sẽ chạy trên VM riêng của chúng, vì ý tưởng của hướng dẫn này là xây dựng một mạng Polygon Edge đầy đủ chức năng trong khi vẫn để các khóa của trình xác thực ở chế độ riêng tư để đảm bảo thiết lập mạng không cần tin cậy. + + +Để làm được như vậy, chúng tôi sẽ hướng dẫn bạn qua 4 bước dễ dàng: + +0. Hãy xem danh sách các **Yêu cầu** ở trên + +1. Tạo các khóa riêng tư cho mỗi trình xác thực và khởi tạo thư mục dữ liệu + +2. Chuẩn bị chuỗi kết nối cho bootnode để đưa vào `genesis.json` được chia sẻ + +3. Tạo `genesis.json` trên máy cục bộ của bạn và gửi/chuyển đến từng nút + +4. Kích hoạt tất cả các nút + +:::info Số lượng trình xác thực + +Không có quy định về số lượng nút tối thiểu trong một cụm, nghĩa là có thể có các cụm chỉ có 1 nút trình xác thực. + Xin lưu ý rằng cụm với _một_ nút duy nhất sẽ không có **khả năng chống lại sự cố** và **không đảm bảo BFT**. + + +Số lượng nút tối thiểu được đề xuất để đảm bảo BFT là 4 - vì trong một cụm 4 nút, lỗi của + 1 nút có thể được chấp nhận nếu 3 nút còn lại hoạt động bình thường. + +::: + +## Bước 1: Khởi tạo thư mục dữ liệu và tạo các khóa của trình xác thực + {#step-1-initialize-data-folders-and-generate-validator-keys} + +Để thiết lập và vận hành Polygon Edge, bạn cần khởi tạo các thư mục dữ liệu, trên mỗi nút: + + + +````bash +node-1> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-2> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-3> polygon-edge secrets init --data-dir data-dir +```` + +````bash +node-4> polygon-edge secrets init --data-dir data-dir +```` + +Mỗi lệnh này sẽ in khóa của trình, khóa công khai BLS và [ID nút](https://docs.libp2p.io/concepts/peer-id/). + Bạn sẽ cần Node ID của nút đầu tiên cho bước tiếp theo. + +### Bí mật ngoài khơi {#outputting-secrets} +Kết quả bí mật có thể được lấy lại một lần nữa, nếu cần. + +```bash +polygon-edge secrets output --data-dir test-chain-4 +``` + +:::warning Hãy giữ bảo mật thư mục dữ liệu của bạn! + + +Các thư mục dữ liệu được tạo ở trên, ngoài khởi tạo các thư mục để duy trì trạng thái blockchain, cũng sẽ tạo các khóa riêng tư cho trình xác thực của bạn. + **Khóa này phải được giữ bí mật vì nếu bị đánh cắp, nó sẽ giúp người khác mạo danh bạn làm người xác thực trong mạng lưới!** + +::: + +## Bước 2: Chuẩn bị chuỗi kết nối multiaddr cho bootnode {#step-2-prepare-the-multiaddr-connection-string-for-the-bootnode} + +Để một nút thiết lập kết nối thành công, nút này cần biết nên kết nối với máy chủ `bootnode`chủ nào để + có thông tin về các nút còn lại trên mạng lưới. `bootnode` đôi khi cũng được gọi là máy chủ `rendezvous` theo thuật ngữ p2p. + +`bootnode` không phải là một phiên bản đặc biệt của nút Polygon Edge. Mỗi nút Polygon Edge đều có thể đóng vai trò là `bootnode` và + mỗi nút Polygon Edge cần phải có một tập hợp các bootnode được chỉ định để liên hệ khi cần thông tin về cách kết nối với + các nút còn lại trong mạng lưới. + +Để tạo chuỗi kết nối và chỉ định bootnode, chúng ta cần tuân thủ [định dạng multiaddr](https://docs.libp2p.io/concepts/addressing/): +``` +/ip4//tcp//p2p/ +``` + +Trong hướng dẫn này, chúng ta sẽ coi nút đầu tiên và nút thứ hai là bootnode cho các nút còn lại. + Điều sẽ xảy ra trong tình huống này chính là các nút kết nối với `node 1` hoặc `node 2`sẽ nhận được thông tin về cách kết nối với nhau thông qua + các bootnode chung. + +:::info Bạn cần chỉ định ít nhất một bootnode để bắt đầu một nút + +Cần có ít nhất **một** bootnode để các nút khác trong mạng có thể phát hiện ra nhau. Nhiều bootnode hơn được khuyến nghị, như chúng cung cấp khả năng phục hồi cho mạng trong trường hợp mất điện. Trong hướng dẫn này, chúng ta sẽ liệt kê hai nút, nhưng có thể thay đổi điều này trong quá trình mà không ảnh hưởng đến tính hợp lệ của tệp `genesis.json`. + +::: + +Vì phần đầu tiên của chuỗi kết nối multiaddr là ``, bạn sẽ cần nhập địa chỉ IP mà các nút khác có thể truy cập được, tùy thuộc vào thiết lập của bạn, đây có thể là địa chỉ IP riêng hoặc công khai, không phải `127.0.0.1`. + + +Đối với `` chúng ta sẽ sử dụng `1478`, vì đây là cổng libp2p mặc định. + +Và cuối cùng, chúng ta cần `` mà chúng ta có thể lấy từ đầu ra của lệnh `polygon-edge secrets init --data-dir data-dir` đã chạy trước đó (được sử dụng để tạo các khóa và thư mục dữ liệu cho `node 1`) + + +Sau khi liên kết, chuỗi kết nối multiaddr với `node 1` mà chúng ta sẽ sử dụng làm bootnode sẽ trông giống thế này (chỉ có `` ở cuối là khác biệt): + +``` +/ip4//tcp/1478/p2p/16Uiu2HAmJxxH1tScDX2rLGSU9exnuvZKNM9SoK3v315azp68DLPW +``` +Tương tự, chúng ta xây dựng multiaddr cho bootnode thứ hai như hình dưới đây +``` +/ip4//tcp/1478/p2p/16Uiu2HAmS9Nq4QAaEiogE4ieJFUYsoH28magT7wSvJPpfUGBj3Hq +``` +:::info Tên máy chủ DNS thay vì ips + +Polygon Edge hỗ trợ sử dụng tên máy chủ DNS cho cấu hình các nút. Đây là một tính năng rất hữu ích dành cho các triển khai sử dụng đám mây, vì ip của nút có thể thay đổi vì nhiều lý do khác nhau. + +Định dạng multiaddr cho chuỗi kết nối khi sử dụng tên máy chủ DNS như sau: +`/dns4/sample.hostname.com/tcp//p2p/nodeid` + +::: + +## Bước 3: Tạo tệp genesis với 4 nút làm trình xác thực {#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators} + +Bước này có thể được chạy trên máy cục bộ của bạn, nhưng bạn sẽ cần các khóa xác thực công khai cho từng trình xác thực trong số 4 trình xác thực. + + +Các trình xác thực có thể chia sẻ `Public key (address)` một cách an toàn như hình bên dưới thông qua đầu ra của lệnh `secrets init`, do đó + bạn có thể tạo genesis.json một cách an toàn bằng những trình xác thực đó trong tập hợp trình xác thực ban đầu, xác định bằng khóa công khai: + + +``` +[SECRETS INIT] +Public key (address) = 0xC12bB5d97A35c6919aC77C709d55F6aa60436900 +BLS Public key = 0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf +Node ID = 16Uiu2HAmVZnsqvTwuzC9Jd4iycpdnHdyVZJZTpVC8QuRSKmZdUrf +``` + +Khi bạn đã nhận được đủ 4 khóa công khai của trình xác thực, bạn có thể chạy lệnh sau để tạo +`genesis.json` + +````bash +polygon-edge genesis --consensus ibft --ibft-validator 0xC12bB5d97A35c6919aC77C709d55F6aa60436900:0x9952735ca14734955e114a62e4c26a90bce42b4627a393418372968fa36e73a0ef8db68bba11ea967ff883e429b3bfdf --ibft-validator <2nd validator IBFT public key>:<2nd validator BLS public key> --ibft-validator <3rd validator IBFT public key>:<3rd validator BLS public key> --ibft-validator <4th validator IBFT public key>:<4th validator BLS public key> --bootnode= --bootnode --bootnode +```` + +Lệnh này thực hiện: + +* `--ibft-validator` thiết lập khóa công khai của trình xác thực cần đưa vào trong tập hợp trình xác thực ban đầu của khối genesis. + Có thể có nhiều trình xác thực ban đầu. +* `--bootnode` thiết lập địa chỉ của bootnode nhằm cho phép các nút tìm thấy nhau. + Chúng ta sẽ sử dụng chuỗi multiaddr của `node 1` như đã đề cập trong **bước 2**, mặc dù bạn có thể thêm bao nhiêu bootnode tùy thích, như hiển thị ở trên. + + +:::info Chuyển sang ECDSA + +BLS là chế độ xác thực mặc định của người đầu khối Nếu bạn muốn chuỗi của bạn chạy trong chế độ ECDSA, bạn có thể sử dụng cờ `—ibft-validator-type`, bằng sự tranh `ecdsa`luận: + +``` +genesis --ibft-validator-type ecdsa +``` +::: + +:::info Số dư tài khoản trước khi khai thác + +Bạn có thể sẽ muốn thiết lập mạng lưới blockchain của mình với một số địa chỉ có số dư "định sẵn". + +Để làm như vậy, hãy tùy ý chuyển cờ `--premine` cho mỗi địa chỉ mà bạn muốn được khởi tạo với số dư nhất định + trên blockchain. + +Ví dụ: nếu chúng ta muốn định trước 1000 ETH để xử lý `0x3956E90e632AEbBF34DEB49b71c28A83Bc029862` trong khối khởi đầu của mình, thì chúng ta cần cung cấp đối số sau: + +``` +--premine=0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +``` + +**Lưu ý rằng số lượng trước khi đào là WEI, không phải ETH.** + +::: + +:::info Thiết lập giới hạn gas khối + +Giới hạn gas mặc định cho mỗi khối là `5242880`. Giá trị này được ghi trong tệp genesis, nhưng bạn có thể muốn tăng / giảm nó. + +Để làm như vậy, bạn có thể sử dụng cờ `--block-gas-limit`theo sau là giá trị mong muốn như hình dưới đây: + +```shell +--block-gas-limit 1000000000 +``` + +::: + +:::info Thiết lập giới hạn trình mô tả tệp hệ thống + +Giới hạn tệp tin mặc định (số lượng tệp tin đã mở) có thể thấp, và trên Linux, mọi thứ đều là tệp. Nếu các nút được dự kiến sẽ có thông lượng cao, bạn có thể cân nhắc việc tăng giới hạn này. Kiểm tra các tiến sĩ chính thức của sự phân tâm linux của bạn để biết thêm chi tiết. + +#### Kiểm tra giới hạn hệ điều hành hiện tại (tệp đang mở) {#check-current-os-limits-open-files} +```shell title="ulimit -n" +1024 # Ubuntu default +``` + +#### Tăng giới hạn tệp đang mở {#increase-open-files-limit} +- Chạy `polygon-edge`trong foreground (vỏ sọc) + ```shell title="Set FD limit for the current session" + ulimit -n 65535 # affects only current session, limit won't persist after logging out + ``` + + ```shell title="Edit /etc/security/limits.conf" + # add the following lines to the end of the file to modify FD limits + * soft nofile 65535 # sets FD soft limit for all users + * hard nofile 65535 # sets FD hard limit for all users + + # End of file + ``` +Lưu tệp tin và khởi động lại hệ thống. + +- Chạy `polygon-edge`trong nền như một dịch vụ + +Nếu được `polygon-edge`chạy như một dịch vụ hệ thống, sử dụng công cụ như , giới hạn mô tả `systemd`tệp tin sẽ được quản lý bằng cách sử dụng `systemd`. + ```shell title="Edit /etc/systemd/system/polygon-edge.service" + [Service] + ... + LimitNOFILE=65535 + ``` + +### Khắc phục sự cố {#troubleshooting} +```shell title="Watch FD limits of polygon edge running process" +watch -n 1 "ls /proc/$(pidof polygon-edge)/fd | wc -l" +``` + +```shell title="Check max FD limits for polygon-edge running process" +cat /proc/$(pidof polygon-edge)/limits +``` +::: + +Sau khi chỉ định: +1. Khóa công khai của các trình xác thực sẽ được đưa vào trong khối genesis như tập hợp trình xác nhận + +2. Các chuỗi kết nối Bootnode multiaddr + +3. Các tài khoản và số dư định trước sẽ được đưa vào khối genesis + + +và tạo `genesis.json`, bạn nên sao chép nó vào tất cả VM trong mạng lưới. + Tùy thuộc vào thiết lập, bạn có thể sao chép/dán, gửi nó đến trình vận hành nút, hoặc đơn giản là SCP/FTP nó. + + +Cấu trúc của tệp genesis được đề cập trong phần [Lệnh CLI](/docs/edge/get-started/cli-commands). + +## Bước 4: Chạy tất cả máy khách {#step-4-run-all-the-clients} + +:::note Kết nối mạng lưới với các nhà cung cấp Đám mây + + +Hầu hết các nhà cung cấp dịch vụ đám mây không để lộ địa chỉ IP (đặc biệt là các địa chỉ công khai) dưới dạng giao diện mạng trực tiếp trên MV, thay vào đó, họ thiết lập một proxy NAT ẩn. + + + +Trong trường hợp này, để cho phép các nút kết nối với nhau, bạn sẽ cần nghe `0.0.0.0` trên địa chỉ IP để liên kết trên tất cả các giao diện, nhưng bạn vẫn cần chỉ định địa chỉ IP hoặc địa chỉ DNS mà các nút khác có thể sử dụng để kết nối với phiên của bạn. + Có thể thực hiện việc này bằng đối số `--nat` hoặc `--dns`, nơi bạn có thể chỉ định địa chỉ IP hoặc DNS bên ngoài tương ứng. + + +#### Ví dụ {#example} + +Địa chỉ IP liên kết mà bạn muốn nghe là `192.0.2.1`, nhưng nó không bị ràng buộc trực tiếp với bất kỳ giao diện mạng nào của bạn. + + +Để cho phép các nút kết nối, bạn sẽ chuyển các tham số sau: + + +`polygon-edge ... --libp2p 0.0.0.0:10001 --nat 192.0.2.1` + +Hoặc, nếu bạn muốn chỉ định địa chỉ DNS `dns/example.io`, hãy chuyển các tham số sau: + + +`polygon-edge ... --libp2p 0.0.0.0:10001 --dns dns/example.io` + +Việc này sẽ khiến nút của bạn nghe trên tất cả các giao diện, nhưng cũng làm cho nút biết rằng các máy khách đang kết nối với nó thông qua địa chỉ `--nat`hoặc `--dns` được chỉ định. + + +::: + +Để chạy máy khách **đầu tiên**: + + + +````bash +node-1> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Để chạy máy khách **thứ hai**: + +````bash +node-2> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Để chạy máy khách **thứ ba**: + +````bash +node-3> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Để chạy máy khách **thứ tư**: + +````bash +node-4> polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat --seal +```` + +Sau khi chạy các lệnh trước đó, bạn đã thiết lập mạng Polygon Edge 4 nút, có khả năng niêm phong các khối và khôi phục từ lỗi nút. + +:::info Khởi động máy khách bằng tệp cấu hình + +Thay vì chỉ định tất cả các tham số cấu hình dưới dạng đối số CLI, Máy khách cũng có thể được khởi động bằng tệp cấu hình bằng cách thực thi lệnh sau: + +````bash +polygon-edge server --config +```` +Ví dụ: + +````bash +polygon-edge server --config ./test/config-node1.json +```` +Hiện tại, chúng tôi chỉ hỗ trợ tệp tin cấu hình dựa `json`trên , có thể tìm thấy tệp tin cấu hình mẫu **[ở đây](/docs/edge/configuration/sample-config)**. + +::: + +:::info Các bước để chạy một nút không phải là trình xác thực + +Một nút không phải là trình xác thực sẽ luôn đồng bộ các khối mới nhất nhận được từ nút trình xác thực, bạn có thể kích hoạt một nút không phải là trình xác thực bằng cách chạy lệnh sau. + + +````bash +polygon-edge server --data-dir --chain --libp2p --nat +```` +Ví dụ: bạn có thể thêm máy khách không phải là trình xác thực **thứ năm** bằng cách thực thi lệnh sau: + +````bash +polygon-edge server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat +```` +::: + +:::info Chỉ định giới hạn giá + +Một nút Polygon Edge có thể được bắt đầu với **giới hạn giá** đã đặt cho các giao dịch đến. + +Đơn vị dành cho giới hạn giá là `wei`. + + +Thiết lập giới hạn giá nghĩa là bất kỳ giao dịch nào được xử lý bởi nút hiện tại sẽ cần có giá gas **cao hơn +** so với giới hạn giá đã đặt, nếu không, giá này sẽ không được đưa vào khối. + + +Việc đa số các nút tuân theo một giới hạn giá nhất định sẽ thực thi quy tắc giao dịch trong mạng không được dưới một ngưỡng giá nhất định. + +Giá trị mặc định cho giới hạn giá là `0`, có nghĩa là nó hoàn toàn không được thực thi theo mặc định. + +Ví dụ sử dụng cờ `--price-limit` : +````bash +polygon-edge server --price-limit 100000 ... +```` + +Cần lưu ý rằng giới hạn giá **chỉ được thực thi đối với các giao dịch không cục bộ**, nghĩa là giới hạn giá không áp dụng cho các giao dịch được thêm cục bộ trên nút. +::: + +:::info URL websocket + +Theo mặc định, khi bạn chạy Polygon Edge, nó sẽ tạo một URL WebSocket dựa trên vị trí chuỗi. Lược đồ URL `wss://` được sử dụng cho các liên kết HTTPS và `ws://` cho HTTP. + +URL Localhost Websocket: +````bash +ws://localhost:10002/ws +```` +Vui lòng lưu ý rằng số cổng phụ thuộc vào cổng JSON-RPC đã chọn cho nút. + +URL Websocket Edgenet: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` +::: diff --git a/archive/edge/vi-edge/get-started/terraform-aws-deployment.md b/archive/edge/vi-edge/get-started/terraform-aws-deployment.md new file mode 100644 index 0000000000..67ff444f79 --- /dev/null +++ b/archive/edge/vi-edge/get-started/terraform-aws-deployment.md @@ -0,0 +1,206 @@ +--- +id: terraform-aws-deployment +title: Triển khai Terraform AWS + +description: "Triển khai mạng Polygon Edge qua nhà cung cấp dịch vụ đám mây AWS bằng Terraform\n" +keywords: + - docs + - polygon + - edge + - deployment + - terraform + - aws + - script +--- +:::info Hướng dẫn triển khai vận hành +Đây là hướng dẫn triển khai AWS chính thức, sẵn sàng đưa vào vận hành và hoàn toàn tự động. + + +Triển khai thủ công trên ***[Đám mây](set-up-ibft-on-the-cloud)*** hoặc ***[Cục bộ](set-up-ibft-locally)*** được khuyến nghị cho hoạt động thử nghiệm và/hoặc khi nhà cung cấp dịch vụ đám mây của bạn không phải là AWS. +::: + +:::info +Triển khai này chỉ dành cho PoA. Nếu cơ chế PoS là cần thiết, chỉ cần làm theo ***[hướng dẫn](/docs/edge/consensus/migration-to-pos)*** này để thực hiện chuyển đổi từ PoA sang PoS. + +::: + +Hướng dẫn này sẽ mô tả chi tiết quá trình triển khai mạng blockchain Polygon Edge qua nhà cung cấp dịch đám mây AWS, + đảm bảo sẵn sàng vận hành với các nút trình xác thực được mở rộng trên nhiều vùng khả dụng. + + +## Điều kiện tiên quyết {#prerequisites} + +### Công cụ hệ thống {#system-tools} +* [terraform](https://www.terraform.io/) +* [aws cli](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) +* [ID khóa truy cập aws và khóa truy cập bí mật](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-prereqs.html#getting-started-prereqs-keys) + +### Các biến Terraform + {#terraform-variables} +Hai biến cần được cung cấp, trước khi tiến hành triển triển khai: + +* `alb_ssl_certificate`- ARN của chứng chỉ gửi từ Trình quản lý chứng chỉ AWS, được ALB sử dụng cho giao thức https. + Chứng chỉ phải được tạo trước khi bắt đầu triển khai và phải ở trạng thái **Đã cấp** + +* `premine`- tài khoản sẽ nhận được tiền bản địa đã khai thác sẵn. + Giá trị phải tuân thủ các đặc điểm kỹ thuật của cờ [CLI](/docs/edge/get-started/cli-commands#genesis-flags) chính thức + + +## Thông tin triển khai + {#deployment-information} +### Các tài nguyên đã triển khai + {#deployed-resources} +Tổng quan mức cao về các tài nguyên sẽ được triển khai: + + +* VPC chuyên dụng + +* 4 nút trình xác thực (cũng là nút khởi động) + +* 4 cổng NAT cho phép các nút gửi lưu lượng internet + +* Hàm Lambda được sử dụng để tạo khối (genesis) đầu tiên và bắt đầu chuỗi + +* Các nhóm bảo mật chuyên dụng và vai trò IAM + +* Nhóm S3 được sử dụng để lưu trữ tệp genesis.json + +* Bộ cân bằng tải ứng dụng được sử dụng để hiển thị điểm cuối JSON-RPC + + +### Khả năng chịu lỗi + {#fault-tolerance} + +Chỉ những vùng có 4 vùng khả dụng mới cần thiết cho quá trình triển khai này. + Mỗi nút được triển khai trong một AZ (vùng khả dụng) duy nhất. + + +Bằng cách đặt mỗi nút trong một AZ duy nhất, toàn bộ cụm blockchain sẽ có khả năng chịu lỗi đối với lỗi trên một nút (AZ), vì Polygon Edge đã triển khai + đồng thuận IBFT, cho phép gặp lỗi đối với một nút trong cụm 4 nút trình xác thực. + + +### Truy cập dòng lệnh + {#command-line-access} + +Các nút trình xác thực sẽ không được hiển thị theo bất kỳ cách nào đối với mạng internet công cộng (JSON-PRC chỉ được truy cập qua ALB) + và chúng thậm chí sẽ không được gắn với địa chỉ IP công cộng. + Truy cập dòng lệnh nút chỉ có thể thực hiện được thông qua [AWS Systems Manager - Trình quản lý phiên](https://aws.amazon.com/systems-manager/features/) + + + +### Nâng cấp AMI cơ sở + {#base-ami-upgrade} + +Triển khai này sử dụng `ubuntu-focal-20.04-amd64-server`AWS AMI. + Nó sẽ **không** kích hoạt *triển khai lại* EC2 nếu AWS AMI được cập nhật. + + +Nếu vì lý do nào đó, AMI cơ sở được yêu cầu cập nhật, + bạn có thể thực hiện việc này bằng cách chạy lệnh `terraform taint` từng lần, trước khi `terraform apply`. + Các phiên bản có thể bị nhiễm bẩn khi chạy lệnh `terraform taint module.instances[].aws_instance.polygon_edge_instance` . + +Ví dụ: +```shell +terraform taint module.instances[0].aws_instance.polygon_edge_instance +terraform taint module.instances[1].aws_instance.polygon_edge_instance +terraform taint module.instances[2].aws_instance.polygon_edge_instance +terraform taint module.instances[3].aws_instance.polygon_edge_instance +terraform apply +``` + +:::info +Trong môi trường vận hành, nên chạy từng `terraform taint` để duy trì hoạt động của mạng blockchain. + +::: + +## Quy trình triển khai {#deployment-procedure} + +### Các bước trước + khi triển khai {#pre-deployment-steps} +* xem qua ghi chú đăng ký terraform [polygon-technology-edge](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws) + +* thêm mô-đun `polygon-technology-edge` vào tệp `main.tf` của bạn bằng cách làm theo *hướng dẫn cung cấp* trên trang ghi chú của mô-đun + +* chạy lệnh `terraform init` để cài đặt tất cả các mục phụ thuộc Terraform cần thiết +* cung cấp chứng chỉ mới trong [AWS Certificate Manager](https://aws.amazon.com/certificate-manager/) + +* đảm bảo chứng chỉ được cấp ở trạng thái **Đã cấp** và ghi lại **ARN** của chứng chỉ + +* thiết lập câu lệnh đầu ra của bạn để nhận đầu ra của mô-đun trong cli + + +#### Ví dụ `main.tf` {#example} +```terraform +module "polygon-edge" { + source = "aws-ia/polygon-technology-edge/aws" + version = ">=0.0.1" + + premine = var.premine + alb_ssl_certificate = var.alb_ssl_certificate +} + +output "json_rpc_dns_name" { + value = module.polygon-edge.jsonrpc_dns_name + description = "The dns name for the JSON-RPC API" +} + +variable "premine" { + type = string + description = "Public account that will receive premined native currency" +} + +variable "alb_ssl_certificate" { + type = string + description = "The ARN of SSL certificate that will be placed on JSON-RPC ALB" +} +``` + +#### Ví dụ `terraform.tfvars` {#example-1} +```terraform +premine = "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +alb_ssl_certificate = "arn:aws:acm:us-west-2:123456789:certificate/64c7f117-61f5-435e-878b-83186676a8af" +``` + +### Các bước triển khai {#deployment-steps} +* tạo tệp `terraform.tfvars` +* thiết lập các biến terraform bắt buộc trong tệp này (như đã giải thích ở trên). +:::info +Có các biến không bắt buộc khác có thể hoàn toàn tùy chỉnh triển khai này. + Bạn có thể ghi đè các giá trị mặc định khi thêm giá trị của riêng bạn vào tệp `terraform.tfvars`. + + +Có thể tìm thấy đặc điểm kỹ thuật của tất cả các biến có sẵn trong mục ***[đăng ký](https://registry.terraform.io/modules/aws-ia/polygon-technology-edge/aws)*** Terraform của mô-đun + +::: +* đảm bảo bạn đã thiết lập xác thực cli aws đúng cách bằng cách chạy `aws s3 ls` và đảm bảo không có lỗi phát sinh + +* triển khai cơ sở hạ tầng `terraform apply` + +### Các bước sau khi triển khai + {#post-deployment-steps} +* sau khi hoàn thành việc triển khai, hãy ghi lại giá trị biến `json_rpc_dns_name` được in trong cli + +* tạo một bản ghi dns cname công khai trỏ tên miền của bạn đến giá trị `json_rpc_dns_name` được cung cấp. + Ví dụ: + ```shell + # BIND syntax + # NAME TTL CLASS TYPE CANONICAL NAME + rpc.my-awsome-blockchain.com. IN CNAME jrpc-202208123456879-123456789.us-west-2.elb.amazonaws.com. + ``` +* khi bản ghi cname được truyền đi, hãy kiểm tra xem chuỗi có hoạt động bình thường hay không bằng cách triển khai điểm cuối JSON-PRC của bạn. + Từ ví dụ phía trên: + ```shell + curl https://rpc.my-awsome-blockchain.com -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' + ``` + +## Quy trình hủy + {#destroy-procedure} +:::warning +Quy trình sau sẽ xóa vĩnh viễn toàn bộ cơ sở hạ tầng được triển khai bằng các tập lệnh terraform này. + Đảm bảo rằng bạn có [bản sao lưu dữ liệu blockchain](docs/edge/working-with-node/backup-restore) thích hợp và/hoặc làm việc trên môi trường thử nghiệm. + +::: + +Nếu bạn cần xóa toàn bộ cơ sở hạ tầng, hãy chạy lệnh sau `terraform destroy`. Ngoài ra, bạn sẽ cần xóa thủ công các bí mật được lưu trữ trong [Bộ nhớ Tham số](https://aws.amazon.com/systems-manager/features/) AWS + dành cho khu vực đã diễn ra việc triển khai. + diff --git a/archive/edge/vi-edge/overview.md b/archive/edge/vi-edge/overview.md new file mode 100644 index 0000000000..1119850dff --- /dev/null +++ b/archive/edge/vi-edge/overview.md @@ -0,0 +1,43 @@ +--- +id: overview +title: Polygon Edge +sidebar_label: What is Edge +description: "Giới thiệu về Polygon Edge.\n" +keywords: + - docs + - polygon + - edge + - network + - modular + +--- + +Polygon Edge là một bộ khung dạng mô-đun và có thể mở rộng, giúp xây dựng các mạng blockchain tương thích Ethereum, các chuỗi bên và các giải pháp mở rộng quy mô nói chung. + + +Công dụng chính của nó là khởi động mạng blockchain mới đồng thời cung cấp khả năng tương thích hoàn toàn với các hợp đồng và giao dịch thông minh Ethereum. + Nó sử dụng cơ chế đồng thuận IBFT (Istanbul Byzantine Fault Tolerant), được hỗ trợ trong [PoA (bằng chứng quyền hạn)](/docs/edge/consensus/poa) và [PoS (bằng chứng cổ phần)](/docs/edge/consensus/pos-stake-unstake). + + +Polygon Edge cũng hỗ trợ giao tiếp với nhiều mạng blockchain, cho phép chuyển nhượng cả [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) và [ERC-721](https://ethereum.org/en/developers/docs/standards/tokens/erc-721), bằng cách sử dụng [giải pháp cầu nối tập trung](/docs/edge/additional-features/chainbridge/overview). + + +Các ví đạt tiêu chuẩn của ngành có thể được sử dụng để tương tác với Polygon Edge thông qua các điểm cuối [JSON-RPC](/docs/edge/working-with-node/query-json-rpc), các trình vận hành nút cũng có thể thực hiện nhiều thao tác trên nút thông qua giao thức [gRPC](/docs/edge/working-with-node/query-operator-info). + + +Để tìm hiểu thêm về Polygon, hãy truy cập [trang web chính thức](https://polygon.technology). + + +**[Kho lưu trữ GitHub](https://github.com/0xPolygon/polygon-edge)** + +:::caution + +Mảng này vẫn đang được hoàn thiện nên có thể sẽ có thay đổi về kiến ​​trúc trong tương lai. + Mã lập trình chưa được kiểm tra nên hãy liên lạc với đội ngũ Polygon nếu bạn muốn đưa mảng này vào vận hành. + +::: + + + +Để bắt đầu bằng cách chạy `polygon-edge` trên mạng cục bộ, vui lòng đọc: [Cài đặt](/docs/edge/get-started/installation) và [Cài đặt cục bộ](/docs/edge/get-started/set-up-ibft-locally). + diff --git a/archive/edge/vi-edge/performance-reports/overview.md b/archive/edge/vi-edge/performance-reports/overview.md new file mode 100644 index 0000000000..e5f8d94477 --- /dev/null +++ b/archive/edge/vi-edge/performance-reports/overview.md @@ -0,0 +1,34 @@ +--- +id: overview +title: Tổng quan +description: "Giới thiệu về thử nghiệm Polygon Edge.\n" +keywords: + - docs + - polygon + - edge + - performance + - tests + - loadbot +--- +:::caution +Vui lòng lưu ý rằng `loadbot`chúng tôi đã sử dụng để thực hiện các thử nghiệm này, hiện đang bị giảm giá. +::: + +| Loại | Giá trị | Liên kết tới thử nghiệm + | +| ---- | ----- | ------------ | +| Giao dịch thông thường | 1428 tps | [Ngày 04/07/2022](test-history/test-2022-07-04.md#results-of-eoa-to-eoa-transfers) | +| Giao dịch ERC-20 | 1111 tps | [Ngày 04/07/2022](test-history/test-2022-07-04.md#results-of-erc20-token-transfers) | +| Đúc NFT (NFT Minting) | 714 tps | [Ngày 04/07/2022](test-history/test-2022-07-04.md#results-of-erc721-token-minting) | + +--- + +Mục tiêu của chúng tôi là tạo ra một phần mềm ứng dụng khách blockchain hiệu suất cao, giàu tính năng và dễ dàng thiết lập và bảo trì. + Tất cả các thử nghiệm đều được thực hiện bằng Loadbot của Polygon Edge. Mọi báo cáo hiệu suất bạn tìm thấy trong phần này đều được ghi chép theo đúng ngày tháng, mô tả môi trường rõ ràng và giải thích cụ thể về phương pháp thử nghiệm. + + +Mục tiêu của các bài kiểm tra hiệu suất này là để thể hiện hiệu suất thực tế của mạng blockchain Polygon Edge. + Bất kỳ ai cũng có thể nhận được kết quả tương tự như kết quả đăng tải tại đây, với điều kiện sử dụng cùng môi trường và cùng loadbot của chúng tôi. + + +Tất cả các thử nghiệm hiệu suất đều được thực hiện trên nền tảng AWS bằng một chuỗi chứa các nút EC2. diff --git a/archive/edge/vi-edge/performance-reports/test-history/test-2022-01-21.md b/archive/edge/vi-edge/performance-reports/test-history/test-2022-01-21.md new file mode 100644 index 0000000000..08b3e124ee --- /dev/null +++ b/archive/edge/vi-edge/performance-reports/test-history/test-2022-01-21.md @@ -0,0 +1,130 @@ +--- +id: test-2022-01-21 +title: 21 tháng 1 năm 2022 +description: "Bài kiểm tra hiệu suất từ ngày 21 tháng 1." +keywords: + - docs + - polygon + - edge + - performance + - test + - txpool +--- + +## 21 tháng 1 năm 2022 {#january-21st-2022} + +### Tóm tắt {#summary} + +:::caution +Vui lòng lưu ý rằng `loadbot`chúng tôi đã sử dụng để thực hiện các thử nghiệm này, hiện đang bị giảm giá. +::: + +Bài kiểm tra này được thực hiện sau khi trình cơ cấu lại TxPool đã cải thiện đáng kể hiệu suất (được phát hành trong phiên bản [v0.2.0](https://github.com/0xPolygon/polygon-edge/releases/v0.2.0)). + +Mục tiêu là thiết lập một mạng lưới lớn bao gồm 30 trình xác thực tham gia tích cực để kiểm tra sự đồng thuận và khả năng đồn thổi giữa các giao dịch TxPool một cách chính xác vì tất cả các giao dịch đều được gửi đến JSON-RPC của một nút duy nhất. + +Mục đích của chúng tôi không phải là cố gắng đạt được TPS tối đa có thể, vì quy mô mạng ảnh hưởng tiêu cực đến hiệu suất, và vì giới hạn gas khối & thời gian khối được đặt thành các giá trị lành mạnh không tiêu tốn nhiều tài nguyên hệ thống, việc này sẽ cho phép chúng chạy trên phần cứng thương mại. + +### Kết quả {#results} + +| Phương diện | Giá trị | +| ------ | ----- | +| Số lượng giao dịch mỗi giây | 344 | +| Số lượng giao dịch thất bại | 0 | +| Số lượng giao dịch thành công | 10000 | +| Tổng thời gian chạy | 30s | + +### Môi trường {#environment} + +
+ Cấu hình máy chủ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Nhà cung cấp đám mâyAWS
Kích thước phiên bảnt2.xlarge
Kết nối mạngmạng con riêng
Hệ điều hànhLinux Ubuntu 20.04 LTS - Focal Fossa
Giới hạn trình mô tả tệp tin65535
Quy trình người dùng tối đa65535
+
+
+
+
+ +
+ Cấu hình blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Phiên bản Polygon EdgeThực hiện 8377162281d1a2e4342ae27cd4e5367c4364aee2 trên nhánh phát triển
Các nút là trình xác thực30
Các nút không phải trình xác thực0
Đồng thuậnIBFT PoA
Thời gian khối2000ms
Giới hạn gas khối5242880
+
+
+
+
+ +
+ Cấu hình Loadbot +
+
+ + + + + + + + + + + + + +
Tổng số lượng giao dịch10000
Số lượng giao dịch được gửi mỗi giây400
Loại giao dịchChuyển từ EOA sang EOA
+
+
+
+
diff --git a/archive/edge/vi-edge/performance-reports/test-history/test-2022-03-02.md b/archive/edge/vi-edge/performance-reports/test-history/test-2022-03-02.md new file mode 100644 index 0000000000..1e43522c09 --- /dev/null +++ b/archive/edge/vi-edge/performance-reports/test-history/test-2022-03-02.md @@ -0,0 +1,389 @@ +--- +id: test-2022-03-02 +title: Ngày 02/03/2022 +description: "Kiểm tra hiệu suất từ ngày 02/03." +keywords: + - docs + - polygon + - edge + - performance + - test + - load +--- + +### Tóm tắt {#summary} + +:::caution +Vui lòng lưu ý rằng `loadbot`chúng tôi đã sử dụng để thực hiện các thử nghiệm này, hiện đang bị giảm giá. +::: + +Thử nghiệm này được thực hiện để đo lường việc chuyển token SC ERC20 và chức năng mint token SC ERC721 với tải nặng và tốc độ của các giao dịch. + +Mục đích là để kiểm tra xem mọi thứ có hoạt động như mong đợi khi tải nặng hay không. Đó cũng là lý do chúng tôi đã giới thiệu các chỉ số gas trong đầu ra của loadbot, cho chúng ta biết liệu các khối có được lấp đầy các giao dịch đúng cách hay không. + +Tất cả giao dịch đã được gửi đến một nút thông qua API GRPC và biên nhận được nhận qua API JSON-RPC. Sau khi tất cả giao dịch được thực hiện, thông tin gas được đọc từ mỗi khối, sử dụng phương thức eth_getBlockByNumber JSON-RPC. + +Mục đích của chúng ta không phải là cố gắng đạt được mức TPS tối đa có thể, vì giới hạn gas khối & thời gian khối được đặt thành các giá trị lành mạnh không tốn nhiều tài nguyên hệ thống và sẽ cho phép mục này chạy trên phần cứng hàng hóa. + +### Kết quả ERC20 {#results-erc20} + +| Phương diện | Giá trị | +| ------ | ----- | +| Loại giao dịch | ERC20 | +| Số lượng giao dịch mỗi giây | 65 | +| Số lượng giao dịch thất bại | 0 | +| Số lượng giao dịch thành công | 5000 | +| Thời gian chạy giao dịch ERC20 | 76,681690s | +| Thời gian Triển khai SC | 4,048250s | + +### Kết quả ERC721 {#results-erc721} + +| Phương diện | Giá trị | +| ------ | ----- | +| Loại giao dịch | ERC721 | +| Số lượng giao dịch mỗi giây | 20 | +| Số lượng giao dịch thất bại | 0 | +| Số lượng giao dịch thành công | 2000 | +| Thời gian chạy giao dịch ERC721 | 97,239920s | +| Thời gian Triển khai SC | 3,048970s | + +### Môi trường ERC20 {#environment-erc20} + +
+ Cấu hình máy chủ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Nhà cung cấp đám mâyAWS
Kích thước phiên bảnt2.micro
Kết nối mạngmạng con riêng
Hệ điều hànhLinux Ubuntu 20.04 LTS - Focal Fossa
Giới hạn trình mô tả tệp tin65535
Quy trình người dùng tối đa65535
+
+
+
+
+ +
+ Cấu hình blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Phiên bản Polygon EdgeCam kết 8a033aa1afb191abdac04636d318f83f32511f3c trên nhánh phát triển
Các nút là trình xác thực6
Các nút không phải trình xác thực0
Đồng thuậnIBFT PoA
Thời gian khối2s
Giới hạn gas khối5242880
Sử dụng khối trung bình95%
+
+
+
+
+ +
+ Cấu hình Loadbot +
+
+ + + + + + + + + + + + + +
Tổng Giao dịch5000
Giao dịch được gửi mỗi giây200
Loại giao dịchGiao dịch chuyển ERC20 sang ERC20
+
+
+
+
+ +
+ Nhật ký loadbot + + [COUNT DATA] + Transactions submitted = 5000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 65 + + [TURN AROUND DATA] + Average transaction turn around = 25.034950s + Fastest transaction turn around = 3.056460s + Slowest transaction turn around = 47.366220s + Total loadbot execution time = 76.681690s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x7224Dad537291bb6bA277d3e1cCD48cf87B208E7 + Total execution time = 4.048250s + Blocks required = 1 + + Block #557781 = 1 txns (1055769 gasUsed / 5242880 gasLimit) utilization = 20% + + Average utilization across all blocks: 20% + + [BLOCK DATA] + Blocks required = 29 + + Block #557783 = 178 txns (5212100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557785 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557786 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557787 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557788 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557789 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557791 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557792 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557793 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557794 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557795 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557797 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557798 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557799 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557800 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557801 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557803 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557804 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557805 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557806 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557807 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557809 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557810 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557811 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557812 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557813 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557815 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557816 = 178 txns (5197100 gasUsed / 5242880 gasLimit) utilization = 99% + Block #557817 = 16 txns (474800 gasUsed / 5242880 gasLimit) utilization = 9% + + Average utilization across all blocks: 95% + +
+ +### Môi trường ERC721 {#environment-erc721} + +
+ Cấu hình máy chủ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Nhà cung cấp đám mâyAWS
Kích thước phiên bảnt2.micro
Kết nối mạngmạng con riêng
Hệ điều hànhLinux Ubuntu 20.04 LTS - Focal Fossa
Giới hạn trình mô tả tệp tin65535
Quy trình người dùng tối đa65535
+
+
+
+
+ +
+ Cấu hình blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Phiên bản Polygon EdgeCam kết 8a033aa1afb191abdac04636d318f83f32511f3c trên nhánh phát triển
Các nút là trình xác thực6
Các nút không phải trình xác thực0
Đồng thuậnIBFT PoA
Thời gian khối2s
Giới hạn gas khối5242880
Sử dụng khối trung bình94%
+
+
+
+
+ +
+ Cấu hình Loadbot +
+
+ + + + + + + + + + + + + +
Tổng Giao dịch2000
Giao dịch được gửi mỗi giây200
Loại giao dịchĐúc token ERC721
+
+
+
+
+ +
+ Nhật ký loadbot + + [COUNT DATA] + Transactions submitted = 2000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 20 + + [TURN AROUND DATA] + Average transaction turn around = 43.034620s + Fastest transaction turn around = 4.007210s + Slowest transaction turn around = 84.184340s + Total loadbot execution time = 97.239920s + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x79D9167FcCC5087D28B2D0cDA27ffAA23A731F51 + Total execution time = 3.048970s + Blocks required = 1 + + Block #558955 = 1 txns (2528760 gasUsed / 5242880 gasLimit) utilization = 48% + + Average utilization across all blocks: 48% + + [BLOCK DATA] + Blocks required = 46 + + Block #558957 = 44 txns (5104824 gasUsed / 5242880 gasLimit) utilization = 97% + Block #558958 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558959 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558960 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558961 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558962 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558963 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558964 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558965 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558966 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558967 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558968 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558969 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558970 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558971 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558972 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558973 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558974 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558975 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558976 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558977 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558978 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558979 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558980 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558981 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558982 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558983 = 13 txns (1505298 gasUsed / 5242880 gasLimit) utilization = 28% + Block #558984 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558985 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558986 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558987 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558988 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558989 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558990 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558991 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558992 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558993 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558994 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558995 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558996 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558997 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558998 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #558999 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559000 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559001 = 45 txns (5189970 gasUsed / 5242880 gasLimit) utilization = 98% + Block #559002 = 8 txns (929568 gasUsed / 5242880 gasLimit) utilization = 17% + + Average utilization across all blocks: 94% + +
+ + diff --git a/archive/edge/vi-edge/performance-reports/test-history/test-2022-03-23.md b/archive/edge/vi-edge/performance-reports/test-history/test-2022-03-23.md new file mode 100644 index 0000000000..57447ff553 --- /dev/null +++ b/archive/edge/vi-edge/performance-reports/test-history/test-2022-03-23.md @@ -0,0 +1,956 @@ +--- +id: test-2022-03-23 +title: Ngày 23/03/2022 +description: "Kiểm tra hiệu suất từ ngày 23 tháng 3." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes +--- + +### Tóm tắt {#summary} + +:::caution +Vui lòng lưu ý rằng `loadbot`chúng tôi đã sử dụng để thực hiện các thử nghiệm này, hiện đang bị giảm giá. +::: + +Thử nghiệm này được thực hiện để đo lường các lần chuyển token SC ERC20, mint token SC ERC721 và chức năng giao dịch EOA sang EOA với tải nặng và tốc độ của giao dịch trên các nút có tài nguyên phần cứng cao hơn. + +Mục đích là để kiểm tra xem mọi thứ có hoạt động như mong đợi khi tải nặng hay không. Đó cũng là lý do chúng tôi đã giới thiệu các chỉ số gas trong đầu ra của loadbot, mục này chúng ta biết liệu các khối có được lấp đầy các giao dịch đúng cách hay không. + +Tất cả giao dịch đã được gửi đến một nút thông qua API GRPC và biên nhận được nhận qua API JSON-RPC. Sau khi tất cả giao dịch được thực hiện, thông tin gas được đọc từ mỗi khối, sử dụng phương thức eth_getBlockByNumber JSON-RPC. + +Mục đích của chúng tôi là cố gắng đạt mức TPS tối đa với tài nguyên phần cứng có sẵn. + Để làm được như vậy, chúng tôi đã sửa đổi giới hạn gas và các thông số thời gian khối nhằm cung cấp kết quả tps tốt nhất và duy trì tính toàn vẹn và ổn định của hệ thống. + + +:::info Giới hạn gas khối + +Giới hạn gas khối có thể được tăng lên một con số tương đối cao nếu các giao dịch sử dụng nhiều gas để thực hiện. Trong ví dụ được nêu dưới đây, việc mint token ERC721 hoạt động nhanh hơn nhiều với giới hạn gas khối được đặt thành 80 000 000 (thay vì 20 triệu), nhưng với việc chuyển token ERC20 với giới hạn 80 triệu. gas khối, máy chủ bị sập nguồn. +::: + +:::info Môi trường sản xuất +Khi định cấu hình môi trường sản xuất, bạn cần phải cẩn thận nếu bạn đang cố đạt được hiệu suất cao của chuỗi. Nếu thông số giới hạn gas được đặt thành giá trị cao, thời gian khối được đặt về 1 giây và có nhiều giao dịch trên một nút, nút đó sẽ tiêu thụ rất nhiều (thậm chí là toàn bộ) RAM và có thể gây ra sự cố máy chủ. + Sử dụng loadbot để kiểm tra mọi thứ kỹ lưỡng, giám sát việc sử dụng tài nguyên hệ thống và thiết lập các thông số cấu hình của bạn cho phù hợp. +::: + +:::info Lỗi hết bộ nhớ + +Một số bản phân phối linux sẽ tự động giết quá trình sử dụng RAM rất cao (lỗi OOM), để duy trì sự ổn định của hệ thống. Đầu ra nhật ký của lỗi OOM này trông giống như dưới đây. +``` +Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB +``` +::: + +### Kết quả chuyển từ EOA sang EOA {#results-of-eoa-to-eoa-transfers} +| Phương diện | Giá trị | +| ------ | ----- | +| Loại giao dịch | EOA sang EOA | +| Số lượng giao dịch mỗi giây | 689 | +| Số lượng giao dịch thất bại | 0 | +| Số lượng giao dịch thành công | 20000 | +| Tổng khối được sử dụng | 25 | +| Tổng thời gian chạy | 29,921110s | + +### Kết quả giao dịch token ERC20 {#results-of-erc20-token-transfers} + +| Phương diện | Giá trị | +| ------ | ----- | +| Loại giao dịch | ERC20 | +| Số lượng giao dịch mỗi giây | 500 | +| Số lượng giao dịch thất bại | 0 | +| Số lượng giao dịch thành công | 20000 | +| Tổng khối được sử dụng | 33 | +| Thời gian chạy giao dịch ERC20 | 40,402900s | +| Thời gian Triển khai SC | 2,004140s | + +### Kết quả mint token ERC721 + {#results-of-erc721-token-minting} + +| Phương diện | Giá trị | +| ------ | ----- | +| Loại giao dịch | ERC721 | +| Số lượng giao dịch mỗi giây | 157 | +| Số lượng giao dịch thất bại | 0 | +| Số lượng giao dịch thành công | 20000 | +| Tổng khối được sử dụng | 124 | +| Thời gian chạy giao dịch ERC721 | 127,537340s | +| Thời gian Triển khai SC | 2,004420s | + + +### Kết quả mint token ERC721 với giới hạn gas khối rất cao (80 triệu) {#results-of-erc721-token-minting-with-a-very-high-block-gas-limit-80-mil} +| Phương diện | Giá trị | +| ------ | ----- | +| Loại giao dịch | ERC721 | +| Số lượng giao dịch mỗi giây | 487 | +| Số lượng giao dịch thất bại | 0 | +| Số lượng giao dịch thành công | 20000 | +| Tổng khối được sử dụng | 34 | +| Thời gian chạy giao dịch ERC721 | 41,098410s | +| Thời gian Triển khai SC | 2,004300s | + + +### Môi trường EOA sang EOA {#environment-eoa-to-eoa} +
+ Cấu hình máy chủ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Nhà cung cấp đám mâyAWS
Kích thước phiên bảnc5.2xlarge
Kết nối mạngmạng con riêng
Hệ điều hànhAmazon Linux 2 AMI (HVM) - Kernel 5.10
Giới hạn trình mô tả tệp tin65535
Quy trình người dùng tối đa65535
+
+
+
+
+ +
+ Cấu hình blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Phiên bản Polygon EdgeThực hiện 06e11eac8da98c79c938fc53dda2da3318cfbe04 trên nhánh phát triển
Các nút là trình xác thực4
Các nút không phải trình xác thực0
Đồng thuậnIBFT PoA
Thời gian khối1s
Giới hạn gas khối20000000
Số lượng tối đa1000000
Sử dụng khối trung bình84,00%
+
+
+
+
+ +
+ Cấu hình Loadbot +
+
+ + + + + + + + + + + + + +
Tổng số lượng giao dịch20000
Số lượng giao dịch được gửi mỗi giây689
Loại giao dịchChuyển từ EOA sang EOA
+
+
+
+
+ +
+ Nhật ký loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 689 + + [TURN AROUND DATA] + Average transaction turn around = 5.685740s + Fastest transaction turn around = 2.004480s + Slowest transaction turn around = 9.013790s + Total loadbot execution time = 29.921110s + + [BLOCK DATA] + Blocks required = 25 + + Block #435 = 865 txns (18165000 gasUsed / 20000000 gasLimit) utilization = 90.83% + Block #436 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #437 = 360 txns (7560000 gasUsed / 20000000 gasLimit) utilization = 37.80% + Block #438 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #439 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #440 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #442 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #443 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #444 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #445 = 157 txns (3297000 gasUsed / 20000000 gasLimit) utilization = 16.48% + Block #446 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #447 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #448 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #450 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #451 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #452 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #453 = 363 txns (7623000 gasUsed / 20000000 gasLimit) utilization = 38.12% + Block #454 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #455 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #456 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #458 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #459 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #460 = 952 txns (19992000 gasUsed / 20000000 gasLimit) utilization = 99.96% + Block #461 = 16 txns (336000 gasUsed / 20000000 gasLimit) utilization = 1.68% + Block #462 = 151 txns (3171000 gasUsed / 20000000 gasLimit) utilization = 15.86% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.00% +
+ +### Môi trường ERC20 {#environment-erc20} +
+ Cấu hình máy chủ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Nhà cung cấp đám mâyAWS
Kích thước phiên bảnc5.2xlarge
Kết nối mạngmạng con riêng
Hệ điều hànhAmazon Linux 2 AMI (HVM) - Kernel 5.10
Giới hạn trình mô tả tệp tin65535
Quy trình người dùng tối đa65535
+
+
+
+
+ +
+ Cấu hình blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Phiên bản Polygon EdgeThực hiện 06e11eac8da98c79c938fc53dda2da3318cfbe04 trên nhánh phát triển
Các nút là trình xác thực4
Các nút không phải trình xác thực0
Đồng thuậnIBFT PoA
Thời gian khối1s
Giới hạn gas khối20000000
Số lượng tối đa1000000
Sử dụng khối trung bình88.38%
+
+
+
+
+ +
+ Cấu hình Loadbot +
+
+ + + + + + + + + + + + + +
Tổng số lượng giao dịch20000
Số lượng giao dịch được gửi mỗi giây500
Loại giao dịchGiao dịch chuyển ERC20 sang ERC20
+
+
+
+
+ +
+ Nhật ký loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 500 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0xfCCb5bC1E2EdCcE6336f3C3112af488E9f7fFd45 + Total execution time = 2.004140s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #643 = 1 txns (1055769 gasUsed / 20000000 gasLimit) utilization = 5.28% + + [TURN AROUND DATA] + Average transaction turn around = 10.011350s + Fastest transaction turn around = 2.005370s + Slowest transaction turn around = 18.039780s + Total loadbot execution time = 40.402900s + + [BLOCK DATA] + Blocks required = 33 + + Block #645 = 684 txns (19962000 gasUsed / 20000000 gasLimit) utilization = 99.81% + Block #646 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #647 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #648 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #650 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #651 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #652 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #653 = 1 txns (37550 gasUsed / 20000000 gasLimit) utilization = 0.19% + Block #654 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #655 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #656 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #657 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #658 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #659 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #660 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #661 = 200 txns (5838400 gasUsed / 20000000 gasLimit) utilization = 29.19% + Block #662 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #663 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #664 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #666 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #667 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #668 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #669 = 414 txns (12076500 gasUsed / 20000000 gasLimit) utilization = 60.38% + Block #670 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #671 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #672 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #673 = 46 txns (1349300 gasUsed / 20000000 gasLimit) utilization = 6.75% + Block #674 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #675 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #676 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #678 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #679 = 685 txns (19976150 gasUsed / 20000000 gasLimit) utilization = 99.88% + Block #680 = 645 txns (18810150 gasUsed / 20000000 gasLimit) utilization = 94.05% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 88.38% + +
+ +### Môi trường ERC721 {#environment-erc721} +
+ Cấu hình máy chủ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Nhà cung cấp đám mâyAWS
Kích thước phiên bảnc5.2xlarge
Kết nối mạngmạng con riêng
Hệ điều hànhAmazon Linux 2 AMI (HVM) - Kernel 5.10
Giới hạn trình mô tả tệp tin65535
Quy trình người dùng tối đa65535
+
+
+
+
+ +
+ Cấu hình blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Phiên bản Polygon EdgeThực hiện 06e11eac8da98c79c938fc53dda2da3318cfbe04 trên nhánh phát triển
Các nút là trình xác thực4
Các nút không phải trình xác thực0
Đồng thuậnIBFT PoA
Thời gian khối1s
Giới hạn gas khối20000000
Số lượng tối đa1000000
Sử dụng khối trung bình92,90%
+
+
+
+
+ +
+ Cấu hình Loadbot +
+
+ + + + + + + + + + + + + +
Tổng số lượng giao dịch20000
Số lượng giao dịch được gửi mỗi giây157
Loại giao dịchĐúc token ERC721
+
+
+
+
+ +
+ Nhật ký loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 157 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x04D4F76817D951fc15E08392cBB056B50fea64aa + Total execution time = 2.004420s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #1173 = 1 txns (2528760 gasUsed / 20000000 gasLimit) utilization = 12.64% + + [TURN AROUND DATA] + Average transaction turn around = 53.282990s + Fastest transaction turn around = 2.003130s + Slowest transaction turn around = 105.151960s + Total loadbot execution time = 127.537340s + + [BLOCK DATA] + Blocks required = 124 + + Block #1175 = 173 txns (19958658 gasUsed / 20000000 gasLimit) utilization = 99.79% + Block #1176 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1177 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1178 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1179 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1180 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1181 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1182 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1183 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1184 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1185 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1186 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1187 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1188 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1189 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1190 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1191 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1192 = 47 txns (5420262 gasUsed / 20000000 gasLimit) utilization = 27.10% + Block #1193 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1194 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1195 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1196 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1197 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1198 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1199 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1200 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1201 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1202 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1203 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1204 = 45 txns (5189970 gasUsed / 20000000 gasLimit) utilization = 25.95% + Block #1205 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1206 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1207 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1208 = 59 txns (6802014 gasUsed / 20000000 gasLimit) utilization = 34.01% + Block #1209 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1210 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1211 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1212 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1213 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1214 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1215 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1216 = 42 txns (4844532 gasUsed / 20000000 gasLimit) utilization = 24.22% + Block #1217 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1218 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1219 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1220 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1221 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1222 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1223 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1224 = 26 txns (3002196 gasUsed / 20000000 gasLimit) utilization = 15.01% + Block #1225 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1226 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1227 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1228 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1229 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1230 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1231 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1232 = 76 txns (8759496 gasUsed / 20000000 gasLimit) utilization = 43.80% + Block #1233 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1234 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1235 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1236 = 90 txns (10371540 gasUsed / 20000000 gasLimit) utilization = 51.86% + Block #1237 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1238 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1239 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1240 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1241 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1242 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1243 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1244 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1245 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1246 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1247 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1248 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1249 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1250 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1251 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1252 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1253 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1254 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1255 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1256 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1257 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1258 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1259 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1260 = 99 txns (11407854 gasUsed / 20000000 gasLimit) utilization = 57.04% + Block #1261 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1262 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1263 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1264 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1265 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1266 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1267 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1268 = 18 txns (2081028 gasUsed / 20000000 gasLimit) utilization = 10.41% + Block #1269 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1270 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1271 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1272 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1273 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1274 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1275 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1276 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1277 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1278 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1279 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1280 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1281 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1282 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1283 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1284 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1285 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1286 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1287 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1288 = 78 txns (8989788 gasUsed / 20000000 gasLimit) utilization = 44.95% + Block #1289 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1290 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1291 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1292 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1293 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1294 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1295 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1296 = 30 txns (3462780 gasUsed / 20000000 gasLimit) utilization = 17.31% + Block #1297 = 173 txns (19928658 gasUsed / 20000000 gasLimit) utilization = 99.64% + Block #1298 = 14 txns (1620444 gasUsed / 20000000 gasLimit) utilization = 8.10% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 92.90% + +
+ +### Môi trường ERC20 - giới hạn gas khối rất cao {#environment-erc20-very-high-block-gas-limit} +
+ Cấu hình máy chủ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Nhà cung cấp đám mâyAWS
Kích thước phiên bảnc5.2xlarge
Kết nối mạngmạng con riêng
Hệ điều hànhAmazon Linux 2 AMI (HVM) - Kernel 5.10
Giới hạn trình mô tả tệp tin65535
Quy trình người dùng tối đa65535
+
+
+
+
+ +
+ Cấu hình blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Phiên bản Polygon EdgeThực hiện 06e11eac8da98c79c938fc53dda2da3318cfbe04 trên nhánh phát triển
Các nút là trình xác thực4
Các nút không phải trình xác thực0
Đồng thuậnIBFT PoA
Thời gian khối1s
Giới hạn gas khối80000000
Số lượng tối đa1000000
Sử dụng khối trung bình---
+
+
+
+
+ +
+ Cấu hình Loadbot +
+
+ + + + + + + + + + + + + +
Tổng số lượng giao dịch20000
Số lượng giao dịch được gửi mỗi giây---
Loại giao dịchGiao dịch chuyển ERC20 sang ERC20
+
+
+
+
+ +
+ Nhật ký lỗi OOM + + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=/,mems_allowed=0,global_oom,task_memcg=/,task=polygon-edge,pid=4560,uid=1000 + Mar 23 00:19:06 ip-10-151-2-196 kernel: Out of memory: Killed process 4560 (polygon-edge) total-vm:16687652kB, anon-rss:14964372kB, file-rss:0kB, shmem-rss:0kB, UID:1000 pgtables:29668kB oom_score_adj:0 + Mar 23 00:19:06 ip-10-151-2-196 kernel: oom_reaper: reaped process 4560 (polygon-edge), now anon-rss:0kB, file-rss:0kB, shmem-rss:0kB + +
+ +### Môi trường ERC721 - giới hạn gas khối rất cao {#environment-erc721-very-high-block-gas-limit} +
+ Cấu hình máy chủ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Nhà cung cấp đám mâyAWS
Kích thước phiên bảnc5.2xlarge
Kết nối mạngmạng con riêng
Hệ điều hànhAmazon Linux 2 AMI (HVM) - Kernel 5.10
Giới hạn trình mô tả tệp tin65535
Quy trình người dùng tối đa65535
+
+
+
+
+ +
+ Cấu hình blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Phiên bản Polygon EdgeThực hiện 06e11eac8da98c79c938fc53dda2da3318cfbe04 trên nhánh phát triển
Các nút là trình xác thực4
Các nút không phải trình xác thực0
Đồng thuậnIBFT PoA
Thời gian khối1s
Giới hạn gas khối80000000
Số lượng tối đa1000000
Sử dụng khối trung bình84,68%
+
+
+
+
+ +
+ Cấu hình Loadbot +
+
+ + + + + + + + + + + + + +
Tổng số lượng giao dịch20000
Số lượng giao dịch được gửi mỗi giây487
Loại giao dịchĐúc token ERC721
+
+
+
+
+ +
+ Nhật ký loadbot + + [COUNT DATA] + Transactions submitted = 20000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 487 + + [CONTRACT DEPLOYMENT DATA] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.004300s + + [CONTRACT BLOCK DATA] + Blocks required = 1 + + Block #17 = 1 txns (2528760 gasUsed / 80000000 gasLimit) utilization = 3.16% + + [TURN AROUND DATA] + Average transaction turn around = 9.621830s + Fastest transaction turn around = 2.006890s + Slowest transaction turn around = 18.106630s + Total loadbot execution time = 41.098410s + + [BLOCK DATA] + Blocks required = 34 + + Block #19 = 694 txns (79949724 gasUsed / 80000000 gasLimit) utilization = 99.94% + Block #20 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #21 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #22 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #23 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #24 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #25 = 150 txns (17280300 gasUsed / 80000000 gasLimit) utilization = 21.60% + Block #26 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #27 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #28 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #29 = 25 txns (2887050 gasUsed / 80000000 gasLimit) utilization = 3.61% + Block #30 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #31 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #32 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #34 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #35 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #36 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #38 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #39 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #40 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #41 = 132 txns (15207672 gasUsed / 80000000 gasLimit) utilization = 19.01% + Block #42 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #43 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #44 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #45 = 74 txns (8529204 gasUsed / 80000000 gasLimit) utilization = 10.66% + Block #46 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #47 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #48 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #50 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #51 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #52 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #53 = 5 txns (584130 gasUsed / 80000000 gasLimit) utilization = 0.73% + Block #54 = 694 txns (79919724 gasUsed / 80000000 gasLimit) utilization = 99.90% + Block #55 = 182 txns (20964972 gasUsed / 80000000 gasLimit) utilization = 26.21% + + [AVERAGE BLOCK UTILIZATION] + Average utilization acorss all blocks = 84.68% + +
diff --git a/archive/edge/vi-edge/performance-reports/test-history/test-2022-07-04.md b/archive/edge/vi-edge/performance-reports/test-history/test-2022-07-04.md new file mode 100644 index 0000000000..02ad0360ec --- /dev/null +++ b/archive/edge/vi-edge/performance-reports/test-history/test-2022-07-04.md @@ -0,0 +1,568 @@ +--- +id: test-2022-07-04 +title: Ngày 04/04/2022 +description: "Thử nghiệm hiệu suất vào ngày 04/07." +keywords: + - docs + - polygon + - edge + - performance + - test + - EOA + - nodes + - ERC20 + - ERC721 +--- + +### Tóm tắt {#summary} + +:::caution +Vui lòng lưu ý rằng `loadbot`chúng tôi đã sử dụng để thực hiện các thử nghiệm này, hiện đang bị giảm giá. +::: + +Thử nghiệm này được thực hiện để đo lường các lần chuyển token SC ERC20, mint token SC ERC721 và chức năng giao dịch EOA sang EOA với tải nặng và tốc độ của giao dịch trên các nút có tài nguyên phần cứng cao hơn. + +Mục đích là để kiểm tra xem mọi thứ có hoạt động như mong đợi khi tải nặng hay không. Đó cũng là lý do chúng tôi đã giới thiệu các chỉ số gas trong đầu ra của loadbot, mục này chúng ta biết liệu các khối có được lấp đầy các giao dịch đúng cách hay không. + +Tất cả giao dịch đã được gửi đến một nút thông qua API GRPC và biên nhận được nhận qua API JSON-RPC. Sau khi tất cả giao dịch được thực hiện, thông tin gas được đọc từ mỗi khối, sử dụng phương thức eth_getBlockByNumber JSON-RPC. + +Mục đích của chúng tôi là cố gắng đạt mức TPS tối đa với tài nguyên phần cứng có sẵn. + Để làm được như vậy, chúng tôi đã sửa đổi giới hạn gas và các thông số thời gian của khối nhằm cung cấp kết quả tps tốt nhất và duy trì tính toàn vẹn và ổn định của hệ thống. + + + +:::info Môi trường sản xuất +Khi định cấu hình môi trường sản xuất, bạn cần phải cẩn thận nếu bạn đang cố đạt được hiệu suất cao của chuỗi. Nếu thông số giới hạn gas được đặt thành giá trị cao, thời gian khối được đặt về 1 giây và có nhiều giao dịch trên một nút, nút đó sẽ tiêu thụ rất nhiều (thậm chí là toàn bộ) RAM và có thể gây ra sự cố máy chủ. + Sử dụng loadbot để kiểm tra mọi thứ kỹ lưỡng, giám sát việc sử dụng tài nguyên hệ thống và thiết lập các thông số cấu hình của bạn cho phù hợp. +::: + + + +### Kết quả chuyển từ EOA sang EOA {#results-of-eoa-to-eoa-transfers} +| Phương diện | Giá trị | +| ------ | ----- | +| Loại giao dịch | EOA sang EOA | +| Số lượng giao dịch mỗi giây | 1428 | +| Số lượng giao dịch thất bại | 0 | +| Số lượng giao dịch thành công | 30000 | +| Tổng khối được sử dụng | 15 | +| Tổng thời gian chạy | 21,374620s | + +### Kết quả giao dịch token ERC20 + {#results-of-erc20-token-transfers} + +| Phương diện | Giá trị | +| ------ | ----- | +| Loại giao dịch | ERC20 | +| Số lượng giao dịch mỗi giây | 1111 | +| Số lượng giao dịch thất bại | 0 | +| Số lượng giao dịch thành công | 50000 | +| Tổng khối được sử dụng | 38 | +| Thời gian chạy giao dịch ERC20 | 45,906450s | +| Thời gian Triển khai SC | 2,006580s | + +### Kết quả mint token ERC721 + {#results-of-erc721-token-minting} + +| Phương diện | Giá trị | +| ------ | ----- | +| Loại giao dịch | ERC721 | +| Số lượng giao dịch mỗi giây | 714 | +| Số lượng giao dịch thất bại | 0 | +| Số lượng giao dịch thành công | 30000 | +| Tổng khối được sử dụng | 39 | +| Thời gian chạy giao dịch ERC721 | 42,864140s | +| Thời gian Triển khai SC | 2,005500s | + + + + +### Môi trường EOA sang EOA {#environment-eoa-to-eoa} +
+ Cấu hình máy chủ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Nhà cung cấp đám mâyAWS EC2
Kích thước phiên bảnc6a.48xlarge
Kết nối mạngmạng con riêng
Hệ điều hànhLinux Ubuntu 20.04 LTS - Focal Fossa
Giới hạn trình mô tả tệp tin65535
Quy trình người dùng tối đa65535
+
+
+
+
+ +
+ Cấu hình blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Phiên bản Polygon EdgePhát hành v0.4.1
Các nút là trình xác thực4
Các nút không phải trình xác thực0
Đồng thuậnIBFT PoA
Thời gian khối1s
Giới hạn gas khối70778880
Số lượng tối đa276480
Sử dụng khối trung bình59,34%
+
+
+
+
+ +
+ Cấu hình Loadbot +
+
+ + + + + + + + + + + + + +
Tổng số lượng giao dịch30000
Số lượng giao dịch được gửi mỗi giây1428
Loại giao dịchChuyển từ EOA sang EOA
+
+
+
+
+ +
+ Nhật ký loadbot + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1428 + + [TURN AROUND DATA] + Average transaction turn around = 4.394900s + Fastest transaction turn around = 1.133980s + Slowest transaction turn around = 7.258690s + Total loadbot execution time = 21.374620s + + [BLOCK DATA] + Blocks required = 15 + + Block #110 = 1268 txns (26628000 gasUsed / 70778880 gasLimit) utilization = 37.62% + Block #111 = 2744 txns (57624000 gasUsed / 70778880 gasLimit) utilization = 81.41% + Block #112 = 2333 txns (48993000 gasUsed / 70778880 gasLimit) utilization = 69.22% + Block #113 = 1326 txns (27846000 gasUsed / 70778880 gasLimit) utilization = 39.34% + Block #114 = 1852 txns (38892000 gasUsed / 70778880 gasLimit) utilization = 54.95% + Block #115 = 2270 txns (47670000 gasUsed / 70778880 gasLimit) utilization = 67.35% + Block #116 = 559 txns (11739000 gasUsed / 70778880 gasLimit) utilization = 16.59% + Block #117 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #118 = 910 txns (19110000 gasUsed / 70778880 gasLimit) utilization = 27.00% + Block #119 = 3132 txns (65772000 gasUsed / 70778880 gasLimit) utilization = 92.93% + Block #120 = 1207 txns (25347000 gasUsed / 70778880 gasLimit) utilization = 35.81% + Block #121 = 3370 txns (70770000 gasUsed / 70778880 gasLimit) utilization = 99.99% + Block #122 = 2734 txns (57414000 gasUsed / 70778880 gasLimit) utilization = 81.12% + Block #123 = 2737 txns (57477000 gasUsed / 70778880 gasLimit) utilization = 81.21% + Block #124 = 188 txns (3948000 gasUsed / 70778880 gasLimit) utilization = 5.58% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 59.34% +
+ +### Môi trường ERC20 {#environment-erc20} +
+ Cấu hình máy chủ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Nhà cung cấp đám mâyAWS EC2
Kích thước phiên bảnc6a.48xlarge
Kết nối mạngmạng con riêng
Hệ điều hànhLinux Ubuntu 20.04 LTS - Focal Fossa
Giới hạn trình mô tả tệp tin65535
Quy trình người dùng tối đa65535
+
+
+
+
+ +
+ Cấu hình blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Phiên bản Polygon EdgePhát hành v0.4.1
Các nút là trình xác thực4
Các nút không phải trình xác thực0
Đồng thuậnIBFT PoA
Thời gian khối1s
Giới hạn gas khối47185920
Số lượng tối đa184320
Sử dụng khối trung bình81,29%
+
+
+
+
+ +
+ Cấu hình Loadbot +
+
+ + + + + + + + + + + + + +
Tổng Giao dịch50000
Giao dịch được gửi mỗi giây1111
Loại giao dịchGiao dịch chuyển ERC20 sang ERC20
+
+
+
+
+ +
+ Nhật ký loadbot + + [COUNT DATA] + Transactions submitted = 50000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 1111 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x33123b7a4420798b1D208ABBac657B7b103edbD9 + Total execution time = 2.006580s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #174 = 1 txns (1055757 gasUsed / 47185920 gasLimit) utilization = 2.24% + + [TURN AROUND DATA] + Average transaction turn around = 8.856780s + Fastest transaction turn around = 2.006200s + Slowest transaction turn around = 15.977210s + Total loadbot execution time = 45.906450s + + [BLOCK DATA] + Blocks required = 38 + + Block #176 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #177 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #178 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #179 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #180 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #181 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #182 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #183 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #184 = 688 txns (20055200 gasUsed / 47185920 gasLimit) utilization = 42.50% + Block #185 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #186 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #187 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #188 = 317 txns (9240550 gasUsed / 47185920 gasLimit) utilization = 19.58% + Block #189 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #190 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #191 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #192 = 89 txns (2594350 gasUsed / 47185920 gasLimit) utilization = 5.50% + Block #193 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #194 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #195 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #196 = 795 txns (23174250 gasUsed / 47185920 gasLimit) utilization = 49.11% + Block #197 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #198 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #199 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #200 = 594 txns (17315100 gasUsed / 47185920 gasLimit) utilization = 36.70% + Block #201 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #202 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #203 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #204 = 208 txns (6063200 gasUsed / 47185920 gasLimit) utilization = 12.85% + Block #205 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #206 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #207 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #208 = 30 txns (874500 gasUsed / 47185920 gasLimit) utilization = 1.85% + Block #209 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #210 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #211 = 1618 txns (47164700 gasUsed / 47185920 gasLimit) utilization = 99.96% + Block #212 = 177 txns (5159550 gasUsed / 47185920 gasLimit) utilization = 10.93% + Block #213 = 180 txns (5247000 gasUsed / 47185920 gasLimit) utilization = 11.12% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 81.29% + +
+ +### Môi trường ERC721 {#environment-erc721} +
+ Cấu hình máy chủ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Nhà cung cấp đám mâyAWS EC2
Kích thước phiên bảnc6a.48xlarge
Kết nối mạngmạng con riêng
Hệ điều hànhLinux Ubuntu 20.04 LTS - Focal Fossa
Giới hạn trình mô tả tệp tin65535
Quy trình người dùng tối đa65535
+
+
+
+
+ +
+ Cấu hình blockchain +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Phiên bản Polygon EdgePhát hành v0.4.1
Các nút là trình xác thực4
Các nút không phải trình xác thực0
Đồng thuậnIBFT PoA
Thời gian khối1s
Giới hạn gas khối94371840
Số lượng tối đa1000000
Sử dụng khối trung bình93,88%
+
+
+
+
+ +
+ Cấu hình Loadbot +
+
+ + + + + + + + + + + + + +
Tổng số lượng giao dịch30000
Giao dịch được gửi mỗi giây714
Loại giao dịchĐúc token ERC721
+
+
+
+
+ +
+ Nhật ký loadbot + + [COUNT DATA] + Transactions submitted = 30000 + Transactions failed = 0 + + [APPROXIMATE TPS] + Approximate number of transactions per second = 714 + + [CONTRACT DEPLOYMENT INFO] + Contract address = 0x4Ceff7F2f9fC9f150a42AfcabceEDABeB723E56f + Total execution time = 2.005500s + + [CONTRACT DEPLOYMENT BLOCK DATA] + Blocks required = 1 + Block #59 = 1 txns (2528772 gasUsed / 94371840 gasLimit) utilization = 2.68% + + [TURN AROUND DATA] + Average transaction turn around = 13.191620s + Fastest transaction turn around = 2.034710s + Slowest transaction turn around = 23.686180s + Total loadbot execution time = 42.864140s + + [BLOCK DATA] + Blocks required = 39 + + Block #61 = 818 txns (94237644 gasUsed / 94371840 gasLimit) utilization = 99.86% + Block #62 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #63 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #64 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #65 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #66 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #67 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #68 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #69 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #70 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #71 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #72 = 510 txns (58738980 gasUsed / 94371840 gasLimit) utilization = 62.24% + Block #73 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #74 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #75 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #76 = 674 txns (77624892 gasUsed / 94371840 gasLimit) utilization = 82.25% + Block #77 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #78 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #79 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #80 = 179 txns (20621682 gasUsed / 94371840 gasLimit) utilization = 21.85% + Block #81 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #82 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #83 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #84 = 231 txns (26609898 gasUsed / 94371840 gasLimit) utilization = 28.20% + Block #85 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #86 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #87 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #88 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #89 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #90 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #91 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #92 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #93 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #94 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #95 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #96 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #97 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #98 = 819 txns (94322802 gasUsed / 94371840 gasLimit) utilization = 99.95% + Block #99 = 561 txns (64612038 gasUsed / 94371840 gasLimit) utilization = 68.47% + + [AVERAGE BLOCK UTILIZATION] + Average utilization across all blocks = 93.88% + +
+ + diff --git a/archive/edge/vi-edge/troubleshooting.md b/archive/edge/vi-edge/troubleshooting.md new file mode 100644 index 0000000000..2bf0d287b9 --- /dev/null +++ b/archive/edge/vi-edge/troubleshooting.md @@ -0,0 +1,66 @@ +--- +id: troubleshooting +title: Khắc phục sự cố +description: "Phần khắc phục sự cố dành cho Polygon Edge" +keywords: + - docs + - polygon + - edge + - troubleshooting + +--- + +# Khắc phục sự cố {#troubleshooting} + +## Lỗi `method=eth_call err="invalid signature"` {#error} + +Khi bạn đang sử dụng ví để thực hiện giao dịch với Polygon Edge, hãy đảm bảo rằng trong thiết lập mạng cục bộ ví của bạn: + +1. `chainID`là đúng. `chainID`mặc định cho Edge là `100`, nhưng có thể được tùy chỉnh bằng cờ genesis `--chain-id`. + +````bash +genesis [--chain-id CHAIN_ID] +```` +2. Đảm bảo rằng, trên trường “URL RPC”, bạn sử dụng cổng JSON RPC của nút bạn đang kết nối. + + +## Cách lấy URL WebSocket {#how-to-get-a-websocket-url} + +Theo mặc định, khi bạn chạy Polygon Edge, nó sẽ hiển thị một điểm cuối WebSocket dựa trên vị trí chuỗi. Lược đồ URL `wss://` được sử dụng cho các liên kết HTTPS và `ws://` cho HTTP. + +URL Localhost Websocket: +````bash +ws://:/ws +```` +Vui lòng lưu ý rằng số cổng phụ thuộc vào cổng JSON-RPC đã chọn cho nút. + +URL Websocket Edgenet: +````bash +wss://rpc-edgenet.polygon.technology/ws +```` + +## Lỗi `insufficient funds` khi cố gắng triển khai hợp đồng {#error-when-trying-to-deploy-a-contract} + +Nếu bạn gặp lỗi này, hãy đảm bảo rằng bạn có đủ tiền tại địa chỉ mong muốn và địa chỉ được sử dụng là địa chỉ chính xác.
Để thiết lập số dư định trước, bạn có thể sử dụng cờ genesis `genesis [--premine ADDRESS:VALUE]`khi đang tạo tệp genesis. Ví dụ sử dụng cờ này: +````bash +genesis --premine 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862:1000000000000000000000 +```` +Lệnh này định trước 1000000000000000000000 WEI cho 0x3956E90e632AEbBF34DEB49b71c28A83Bc029862. + + +## Token ERC20 không được phát hành khi sử dụng Chainbridge {#erc20-tokens-not-released-while-using-chainbridge} + +Nếu bạn cố gắng chuyển token ERC20 giữa Polygon POS và mạng Edge cục bộ, và token ERC20 của bạn được nạp, đề xuất cũng được thực thi tại trình chuyển tiếp, nhưng token không được phát hành trong mạng Edge của bạn, hãy đảm bảo ERC20 Handler trong chuỗi Polygon Edge có đủ token để phát hành.
Hợp đồng Handler trong chuỗi đích phải có đủ token để phát hành cho chế độ giải phóng khóa. Nếu bạn không có bất kỳ token ERC20 nào trong ERC20 Handler thuộc mạng Edge cục bộ của bạn, vui lòng mint token mới và chuyển chúng sang ERC20 Handler. + +## Lỗi `Incorrect fee supplied` khi sử dụng Chainbridge {#error-when-using-chainbridge} + +Bạn có thể gặp lỗi này khi cố gắng chuyển token ERC20 giữa chuỗi Mumbai Polygon POS và thiết lập Polygon Edge cục bộ. Lỗi này xuất hiện khi bạn đặt phí triển khai sử dụng cờ `--fee`, nhưng bạn không đặt cùng một giá trị trong giao dịch nộp tiền. Bạn có thể sử dụng lệnh bên dưới để thay đổi phí: +````bash + $ cb-sol-cli admin set-fee --bridge --fee 0 --url --privateKey + ```` +Bạn có thể tìm thêm thông tin về lá cờ [này.](https://github.com/ChainSafe/chainbridge-deploy/blob/main/cb-sol-cli/docs/deploy.md) + + + + + diff --git a/archive/edge/vi-edge/validator-hosting.md b/archive/edge/vi-edge/validator-hosting.md new file mode 100644 index 0000000000..d994f368f3 --- /dev/null +++ b/archive/edge/vi-edge/validator-hosting.md @@ -0,0 +1,314 @@ +--- +id: validator-hosting +title: Lưu trữ trình xác thực + +description: "Điều kiện để thực hiện lưu trữ đối với Polygon Edge\n" +keywords: +- docs +- polygon +- edge +- hosting +- cloud +- setup +- validator +--- + +Dưới đây là các đề xuất để lưu trữ đúng cách một nút trình xác thực trong mạng Polygon Edge. + Vui lòng chú ý đến tất cả các mục được liệt kê dưới đây để đảm bảo + rằng thiết lập trình xác thực của bạn được định cấu hình đúng cách, mang lại sự an toàn, ổn định và hoạt động hiệu quả. + + +## Kiến thức cơ bản + {#knowledge-base} + +Trước khi vận hành nút trình xác thực, vui lòng đọc kỹ tài liệu này. + Các tài liệu bổ sung có thể hữu ích là: + + +- [Cài đặt](get-started/installation) +- [Thiết lập đám mây](get-started/set-up-ibft-on-the-cloud) +- [Lệnh CLI](get-started/cli-commands) +- [Tệp cấu hình máy chủ](configuration/sample-config) +- [Khóa riêng tư](configuration/manage-private-keys) +- [Số liệu Prometheus +](configuration/prometheus-metrics) +- [Trình quản lý bí mật](/docs/category/secret-managers) +- [Sao lưu/Phục hồi ](working-with-node/backup-restore) + +## Yêu cầu hệ thống tối thiểu {#minimum-system-requirements} + +| Loại | Giá trị | Ảnh hưởng bởi | +|------|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------| +| CPU | 2 lõi + |
  • Số lượng truy vấn JSON-RPC
  • Kích thước của trạng thái blockchain
  • Giới hạn gas khối
  • Thời gian khối
| +| RAM | 2 GB |
  • Số lượng truy vấn JSON-RPC
  • Kích thước của trạng thái blockchain
  • Giới hạn gas khối
| +| Ổ đĩa |
  • 10 GB phân vùng gốc
  • 30 GB phân vùng gốc với LVM cho phép mở rộng
|
  • Kích thước của trạng thái blockchain
| + + +## Cấu hình dịch vụ {#service-configuration} + +Nhị phân `polygon-edge` cần hoạt động như một dịch vụ hệ thống tự động khi kết nối mạng được thiết lập và có + các chức năng khởi động / dừng / khởi động lại. + Chúng tôi khuyến nghị sử dụng trình quản lý dịch vụ như `systemd.` + +Ví dụ `systemd` tệp cấu hình hệ thống: + +``` +[Unit] +Description=Polygon Edge Server +After=network.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +Restart=always +RestartSec=10 +User=ubuntu +ExecStart=/usr/local/bin/polygon-edge server --config /home/ubuntu/polygon/config.yaml + +[Install] +WantedBy=multi-user.target +``` + +### Nhị phân {#binary} + +Trong khối lượng vận hành `polygon-edge` chỉ nên triển khai nhị phân từ các tệp nhị phân phát hành GitHub được tạo sẵn - thay vì biên dịch thủ công. +:::info +Bằng cách biên dịch thủ công nhánh GitHub `develop`, bạn có thể thực hiện những thay đổi đột phá trong môi trường của mình. + Vì vậy, bạn chỉ nên triển khai nhị phân Polygon Edge từ các bản phát hành, vì các bản này sẽ chứa + thông tin về những thay đổi lớn và cách khắc phục chúng. + +::: + +Vui lòng tham khảo mục [Cài đặt](/docs/edge/get-started/installation) để có thông tin tổng quan về phương pháp cài đặt. + + +### Lưu trữ dữ liệu + {#data-storage} + +Thư mục `data/` chứa toàn bộ trạng thái blockchain nên được đặt trên một ổ đĩa chuyên dụng, có thể + tự động sao lưu, mở rộng bộ nhớ và cho phép gắn vào một phiên bản khác trong trường hợp bị lỗi. + + + +### Tệp bản ghi {#log-files} + +Các tệp bản ghi cần được luân chuyển hàng ngày (bằng công cụ như `logrotate`). +:::warning +Nếu được định cấu hình mà không luân chuyển bản ghi, các tệp bản ghi có thể sử dụng hết dung lượng ổ cứng có sẵn, làm gián đoạn thời gian hoạt động của trình xác thực. + +::: + +Ví dụ `logrotate`cấu hình: +``` +/home/ubuntu/polygon/logs/node.log +{ + rotate 7 + daily + missingok + notifempty + compress + prerotate + /usr/bin/systemctl stop polygon-edge.service + endscript + postrotate + /usr/bin/systemctl start polygon-edge.service + endscript +} +``` + + +Tham khảo phần [Bản ghi](#logging) bên dưới để xem các khuyến nghị về lưu trữ bản ghi. + + +### Các mục phụ thuộc bổ sung + {#additional-dependencies} + +`polygon-edge` được biên dịch tĩnh, không yêu cầu thêm các mục phụ thuộc vào hệ điều hành máy chủ. + + +## Bảo trì {#maintenance} + +Dưới đây là các phương pháp tốt nhất để duy trì hoạt động của nút trình xác thực trên mạng Polygon Edge. + + +### Sao lưu {#backup} + +Có hai loại quy trình sao lưu được khuyến nghị dành cho nút Polygon Edge. + + +Bạn nên sử dụng cả hai nếu có thể, với bản sao lưu Polygon Edge luôn sẵn sàng. + + +* ***Sao lưu dữ liệu*** : Sao lưu hàng ngày dữ liệu `data/` của nút Polygon Edge hoặc của VM hoàn chỉnh nếu có thể. + + + +* ***Sao lưu Polygon Edge*** : Chúng tôi khuyến nghị sử dụng Hoạt động CRON hàng ngày để thực hiện sao lưu thường xuyên Polygon Edge và di chuyển các tệp `.dat` đến vị trí ngoại vi hoặc bộ lưu trữ đối tượng đám mây an toàn. + + +Bản sao lưu Polygon Edge lý tưởng sẽ không chồng chéo với bản sao lưu dữ liệu ở trên. + + +Tham khảo mục [Sao lưu/khôi phục phiên bản của nút](working-with-node/backup-restore) để xem hướng dẫn về cách thực hiện sao lưu Polygon Edge. + +### Bản ghi {#logging} + +Các bản ghi được xuất bởi nút Polygon Edge cần: + +- được gửi đến kho dữ liệu bên ngoài có khả năng lập chỉ mục và tìm kiếm + +- có thời gian lưu trữ là 30 ngày + + +Nếu đây là lần đầu bạn thiết lập trình xác thực Polygon Edge, chúng tôi khuyên bạn nên khởi động nút + với tùy chọn `--log-level=DEBUG` để có thể nhanh chóng gỡ lỗi nếu gặp phải bất kỳ sự cố nào. + + +:::info + `--log-level=DEBUG` sẽ đảm bảo đầu ra bản ghi của nút cụ thể nhất có thể. + Bản ghi gỡ lỗi sẽ làm tăng đáng kể kích thước của tệp bản ghi, hãy cân nhắc vấn đề này khi thiết lập + giải pháp luân chuyên bản ghi. +::: +### Bản vá bảo mật hệ điều hành + {#os-security-patches} + +Ít nhất một lần mỗi tháng, quản trị viên cần đảm bảo rằng hệ điều hành của phiên bản trình xác thực được cập nhật với các bản vá mới nhất. + + +## Chỉ số {#metrics} + +### Chỉ số hệ thống + {#system-metrics} + +Quản trị viên cần thiết lập một trình giám sát chỉ số hệ thống, (ví dụ: Telegraf + InfluxDB + Grafana hoặc SaaS của bên thứ ba). + + +Thiết lập các chỉ số cần được theo dõi và cảnh báo: + + +| Tên chỉ số + | Ngưỡng báo động + | +|-----------------------|-------------------------------| +| Mức sử dụng CPU (%) + | > 90% trong hơn 5 phút + | +| Mức sử dụng RAM (%) | > 90% trong hơn 5 phút + | +| Sử dụng ổ đĩa gốc + | > 90% | +| Sử dụng ổ đĩa dữ liệu | > 90% | + +### Chỉ số trình xác thực + {#validator-metrics} + +Quản trị viên cần thiết lập bộ chỉ số từ API Prometheus của Polygon Edge để có thể + giám sát hiệu suất của blockchain. + + +Tham khảo [Chỉ số Prometheus](configuration/prometheus-metrics) để hiểu rõ về các chỉ số được hiển thị và cách thiết lập bộ chỉ số Prometheus. + + + +Cần đặc biệt chú ý đến các chỉ số sau: + +- ***Thời gian sản xuất khối*** - nếu thời gian sản xuất cao hơn bình thường, có thể có vấn đề tiềm ẩn với mạng lưới +- ***Số lượng lượt đồng thuận*** - nếu có nhiều hơn 1 lượt, có thể có vấn đề tiềm ẩn với tập hợp trình xác thực của mạng lưới +- ***Số lượng máy ngang hàng*** - nếu số lượng máy ngang hàng giảm, báo hiện có sự cố kết nối trong mạng + lưới + +## Bảo mật {#security} + +Dưới đây là các phương pháp tốt nhất để đảm bảo hoạt động của nút trình xác thực trên mạng Polygon Edge. + + +### Dịch vụ API {#api-services} + +- ***JSON-RPC*** - Chỉ dịch vụ API cần được công khai (trực tiếp hoặc thông qua bộ cân bằng tải). + API có thể hoạt động trên tất cả các giao diện hoặc trên địa chỉ IP cụ thể (ví dụ: `--json-rpc 0.0.0.0:8545`hoặc `--json-prc 192.168.1.1:8545`):::info +Vì đây là API công khai, bạn nên sử dụng bộ cân bằng tải/proxy ngược để đảm bảo về bảo mật và giới hạn tốc độ. + +::: + + +- ***LibP2P*** - Đây là API kết nối mạng được các nút sử dụng để giao tiếp ngang hàng. + API này cần hoạt động được trên tất cả các giao diện hoặc trên một địa chỉ IP cụ thể + ( `--libp2p 0.0.0.0:1478`hoặc `--libp2p 192.168.1.1:1478`). API này không được hiển thị công khai, + nhưng có thể được truy cập từ tất cả các nút. +:::info +Nếu được chạy trên localhost ( `--libp2p 127.0.0.1:1478`) các nút khác sẽ không thể kết nối. + +::: + + +- ***GRPC***- API này chỉ được sử dụng để chạy các lệnh của trình điều hành. + Vì vậy, nó sẽ hoạt động riêng trên localhost ( `--grpc-address 127.0.0.1:9632`). + + +### Bí mật Polygon Edge {#polygon-edge-secrets} + +Bí mật Polygon Edge ( `ibft` và khóa `libp2p`) không được lưu trên hệ thống tệp cục bộ. Thay vào đó, nên sử dụng một [Trình quản lý bí mật](configuration/secret-managers/set-up-aws-ssm) được hỗ trợ . Việc lưu trữ bí mật vào hệ thống tệp cục bộ chỉ nên được áp dụng trong môi trường phi vận hành. + + +## Cập nhật {#update} + +Sau đây là quy trình cập nhật cho các nút trình xác thực, được mô tả theo từng bước. + + +### Quy trình cập nhật {#update-procedure} + +- Tải xuống nhị phân Polygon Edge mới nhất từ ​​[bản phát hành](https://github.com/0xPolygon/polygon-edge/releases) GitHub chính thứ +c +- Dừng dịch vụ Polygon Edge (ví dụ: `sudo systemctl stop polygon-edge.service`) + +- Thay thế tệp nhị phân `polygon-edge` hiện có bằng tệp đã tải xuống (ví dụ: `sudo mv polygon-edge /usr/local/bin/`) + +- Kiểm tra xem phiên bản `polygon-edge` đang dùng có chính xác hay không bằng cách chạy `polygon-edge version`- phải tương ứng với phiên bản phát hành + +- Kiểm tra tài liệu phát hành và có cần thực hiện các bước tương thích ngược cần thiết hay không trước khi bắt đầu dịch vụ `polygon-edge` + +- Bắt đầu dịch vụ `polygon-edge` (ví dụ: `sudo systemctl start polygon-edge.service`) +- Cuối cùng, kiểm tra kết quả bản ghi `polygon-edge` và đảm bảo mọi thứ hoạt động mà không phát sinh bản ghi `[ERROR]` + +:::warning +Khi có một bản phát hành ngắt, quy trình cập nhật này phải được thực hiện trên tất cả các nút vì + tệp nhị phân đang chạy không tương thích với bản phát hành mới. + + +Điều này có nghĩa là chuỗi phải được tạm dừng trong một khoảng thời gian ngắn (cho đến khi mã nhị phân `polygon-edge` được thay thế và dịch vụ được khởi động lại) + vì vậy hãy lên kế hoạch hợp lý. + + +Bạn có thể sử dụng các công cụ như **[Ansible](https://www.ansible.com/)** hoặc một số tập lệnh tùy chỉnh để cập nhật hiệu quả + và giảm thiểu thời gian chuỗi ngừng hoạt động. + +::: + +## Quy trình khởi động {#startup-procedure} + +Sau đây là luồng tối ưu cho quy trình khởi động của trình xác thực Polygon Edge + + +- Tham khảo thêm các tài liệu được liệt kê trong phần [Kiến thức cơ bản](#knowledge-base) + +- Áp dụng các bản vá hệ điều hành mới nhất trên nút trình xác thực + +- Tải xuống bản nhị phân `polygon-edge` mới nhất từ​​ bản [phát hành](https://github.com/0xPolygon/polygon-edge/releases) GitHub chính thức và đặt trong phiên bản cục bộ +`PATH` +- Khởi động một trong những [trình quản lý bí mật](/docs/category/secret-managers) được hỗ trợ bằng lệnh CLI `polygon-edge secrets generate` +- Tạo và lưu trữ bí mật bằng [lệnh CLI](/docs/edge/get-started/cli-commands#secrets-init-flags)`polygon-edge secrets init` +- Ghi lại các giá trị `NodeID` và `Public key (address)` + +- Tạo tập tin `genesis.json` theo mô tả trong mục [thiết lập đám mây](get-started/set-up-ibft-on-the-cloud#step-3-generate-the-genesis-file-with-the-4-nodes-as-validators) bằng [lệnh CLI](/docs/edge/get-started/cli-commands#genesis-flags) `polygon-edge genesis`. + +- Tạo tệp cấu hình mặc định bằng [lệnh CLI](/docs/edge/configuration/sample-config)`polygon-edge server export` +- Sửa tệp `default-config.yaml` để phù hợp với môi trường nút trình xác thực cục bộ (các đường dẫn tệp, v.v.) +- Tạo một dịch vụ Polygon Edge ( `systemd`hoặc tương tự) trong đó nhị phân `polygon-edge` sẽ vận hành máy chủ từ tệp `default-config.yaml` + +- Khởi động máy chủ Polygon Edge bằng cách khởi động dịch vụ (ví dụ: `systemctl start polygon-edge`) + +- Kiểm tra đầu ra bản ghi `polygon-edge`, đảm bảo rằng các khối đang được tạo ra và không có bản ghi `[ERROR]` + +- Kiểm tra chức năng chuỗi bằng cách triển khai phương thức JSON-RPC như +[`eth_chainId`](/docs/edge/api/json-rpc-eth#eth_chainid) diff --git a/archive/edge/vi-edge/working-with-node/backup-restore.md b/archive/edge/vi-edge/working-with-node/backup-restore.md new file mode 100644 index 0000000000..bf8417ca32 --- /dev/null +++ b/archive/edge/vi-edge/working-with-node/backup-restore.md @@ -0,0 +1,118 @@ +--- +id: backup-restore +title: Sao lưu/khôi phục phiên bản nút + +description: "Cách sao lưu và khôi phục một phiên bản nút Polygon Edge.\n" +keywords: + - docs + - polygon + - edge + - instance + - restore + - directory + - node +--- + +## Tổng quan {#overview} + +Hướng dẫn này đi vào chi tiết cách thức sao lưu và khôi phục một phiên bản nút Polygon Edge. + Phần này gồm các thư mục cơ sở và nội dung bên trong, cũng như thông tin về các tệp quan trọng để thực hiện sao lưu và khôi phục thành công. + + +## Thư mục cơ bản {#base-folders} + +Polygon Edge tận dụng LevelDB làm công cụ lưu trữ. + Khi khởi động nút Polygon Edge, các thư mục con sau đây sẽ được tạo trong thư mục chỉ định: + +* **blockchain** - Lưu trữ dữ liệu blockchain +* **trie** - Lưu trữ các Merkle trie (dữ liệu trạng thái thế giới) +* **keystore** - Lưu trữ khóa riêng dành cho máy khách. Mục này gồm khóa riêng tư libp2p và khóa niêm phong/trình xác thực +* **consensus** - Lưu trữ bất kỳ thông tin đồng thuận nào mà máy khách có thể cần đến khi hoạt động. Hiện tại, mục này lưu trữ *khóa trình xác thực riêng tư* của nút + +Điều quan trọng là các thư mục này phải được bảo quản để phiên bản Polygon Edge có thể hoạt động trơn tru. + + +## Tạo bản sao lưu từ một nút đang hoạt động và khôi phục cho nút mới + {#create-backup-from-a-running-node-and-restore-for-new-node} + +Phần này hướng dẫn bạn cách tạo dữ liệu lưu trữ của blockchain trên một nút đang hoạt động và khôi phục nó trong một phiên bản khác. + + +### Sao lưu {#backup} + +Lệnh `backup` nạp các khối từ một nút đang hoạt động bằng gRPC và tạo một tệp lưu trữ. + Nếu `--from` và `--to` không được cho sẵn trong lệnh, lệnh này sẽ nạp các khối từ genesis đến mới nhất. + +```bash +$ polygon-edge backup --grpc-address 127.0.0.1:9632 --out backup.dat [--from 0x0] [--to 0x100] +``` + +### Khôi phục + {#restore} + +Máy chủ nhập các khối từ kho lưu trữ khi bắt đầu khi được kích hoạt bằng cờ `--restore`. + Hãy đảm bảo rằng có khóa cho mỗi nút mới. + Để tìm hiểu thêm về việc nhập hoặc tạo khóa, hãy truy cập [phần Quản lý bí mật](/docs/edge/configuration/secret-managers/set-up-aws-ssm). + +```bash +$ polygon-edge server --restore archive.dat +``` + +## Sao lưu/Khôi phục toàn bộ dữ liệu + {#back-up-restore-whole-data} + +Phần này sẽ hướng dẫn cách sao lưu dữ liệu bao gồm dữ liệu trạng thái và khóa, cũng như cách khôi phục vào phiên bản mới. + + +### Bước 1: Dừng máy khách đang chạy + {#step-1-stop-the-running-client} + +Vì Polygon Edge sử dụng **LevelDB** để lưu trữ dữ liệu, nút cần dừng hoạt động trong suốt thời gian sao lưu, + vì **LevelDB** không cho phép truy cập đồng thời vào các tệp cơ sở dữ liệu. + + +Ngoài ra, Polygon Edge cũng thực hiện đẩy dữ liệu khi đóng. + + +Bước đầu tiên là cần dừng máy khách đang hoạt động (thông qua trình quản lý dịch vụ hoặc một số cơ chế có thể gửi tín hiệu SIGINT đến quy trình), + qua đó, cho phép kích hoạt 2 sự kiện trong khi tắt: + +* Thực hiển đẩy dữ liệu sang đĩa + +* Phát hành khóa các tệp DB bằng LevelDB + + +### Bước 2: Sao lưu thư mục + {#step-2-backup-the-directory} + +Tới bước này, khi máy khách không hoạt động, thư mục dữ liệu có thể được sao lưu sang một phương tiện khác. + Lưu ý rằng các tệp có phần mở rộng `.key` sẽ chứa dữ liệu khóa riêng tư có thể được sử dụng để mạo danh nút hiện tại, + nên không được chia sẻ chúng với một bên thứ ba/không xác định. + + +:::info +Vui lòng sao lưu và khôi phục tệp `genesis` đã tạo theo cách thủ công, để nút được khôi phục hoạt động hoàn toàn. + +::: + +## Khôi phục + {#restore-1} + +### Bước 1: Dừng máy khách đang chạy + {#step-1-stop-the-running-client-1} + +Nếu bất kỳ phiên bản nào của Polygon Edge đang hoạt động, nó cần phải dừng lại để bước 2 có thể thành công. + + +### Bước 2: Sao chép thư mục dữ liệu đã sao lưu vào thư mục mong muốn + {#step-2-copy-the-backed-up-data-directory-to-the-desired-folder} + +Khi máy khách ngưng hoạt động, thư mục dữ liệu đã được sao lưu trước đó có thể được sao chép sang thư mục mong muốn. + Ngoài ra, khôi phục tệp `genesis`đã sao chép trước đó. + + +### Bước 3: Chạy máy khách Polygon Edge khi đang chỉ định thư mục dữ liệu chính xác + {#step-3-run-the-polygon-edge-client-while-specifying-the-correct-data-directory} + +Để Polygon Edge có thể sử dụng thư mục dữ liệu đã khôi phục, khi khởi chạy, người dùng cần chỉ định đường dẫn đến + thư mục dữ liệu. Vui lòng tham khảo phần [Lệnh CLI](/docs/edge/get-started/cli-commands) để biết thông tin về thông tin về cờ `data-dir`. diff --git a/archive/edge/vi-edge/working-with-node/query-json-rpc.md b/archive/edge/vi-edge/working-with-node/query-json-rpc.md new file mode 100644 index 0000000000..0e4c70af97 --- /dev/null +++ b/archive/edge/vi-edge/working-with-node/query-json-rpc.md @@ -0,0 +1,87 @@ +--- +id: query-json-rpc +title: Truy vấn điểm cuối JSON RPC +description: "Truy vấn dữ liệu và bắt đầu chuỗi với tài khoản định trước." +keywords: + - docs + - polygon + - edge + - query + - premine + - node +--- + +## Tổng quan {#overview} + +Lớp JSON-RPC của Polygon Edge cung cấp cho các nhà phát triển chức năng tương tác dễ dàng với blockchain, thông qua yêu cầu HTTP. + +Ví dụ này bao gồm việc sử dụng các công cụ như **curl** để truy vấn thông tin, cũng như bắt đầu chuỗi với tài khoản định trước, và gửi giao dịch. + +## Bước 1: Tạo tệp tin genesis bằng tài khoản định trước {#step-1-create-a-genesis-file-with-a-premined-account} + +Để tạo tệp tin genesis, hãy chạy lệnh sau: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010 +```` + +Cờ **premine** đặt địa chỉ cần được đưa vào với số dư ban đầu trong tệp tin **genesis**.
Trong trường hợp này, địa chỉ `0x1010101010101010101010101010101010101010` sẽ có **số dư mặc định** ban đầu là +`0xD3C21BCECCEDA1000000`(1 triệu đồng tiền bản địa). + +Nếu chúng ta muốn chỉ định số dư, chúng ta có thể tách số dư và địa chỉ bằng một `:`, như sau: +````bash +polygon-edge genesis --premine 0x1010101010101010101010101010101010101010:0x123123 +```` + +Số dư có thể là một `hex` hoặc giá trị `uint256`. + +:::warning Chỉ với những tài khoản định trước mà bạn có khoá riêng tư! + +Nếu bạn xác định trước các tài khoản và không có khóa riêng tư để truy cập, số dư định trước của bạn sẽ không thể sử dụng được +::: + +## Bước 2: Khởi động Polygon Edge ở chế độ nhà phát triển {#step-2-start-the-polygon-edge-in-dev-mode} + +Để bắt đầu Polygon Edge ở chế độ phát triển, được giải thích trong phần [Lệnh CLI](/docs/edge/get-started/cli-commands), hãy chạy lệnh sau: +````bash +polygon-edge server --chain genesis.json --dev --log-level debug +```` + +## Bước 3: Truy vấn số dư tài khoản {#step-3-query-the-account-balance} + +Bây giờ máy khách đã thiết lập và chạy ở chế độ nhà phát triển, bằng cách sử dụng tệp tin genesis được tạo ở **bước 1**, chúng ta có thể sử dụng một công cụ như **curl** để truy vấn số dư tài khoản: +````bash +curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0x1010101010101010101010101010101010101010", "latest"],"id":1}' localhost:8545 +```` + +Lệnh sẽ trả về kết quả đầu ra sau đây: +````bash +{ + "id":1, + "result":"0x100000000000000000000000000" +} +```` + +## Bước 4: Gửi giao dịch chuyển khoản {#step-4-send-a-transfer-transaction} + +Bây giờ đã xác nhận tài khoản mà chúng ta thiết lập như tài khoản định trước có số dư chính xác, chúng ta có thể chuyển một số ether: + +````js +var Web3 = require("web3"); + +const web3 = new Web3(""); //example: ws://localhost:10002/ws +web3.eth.accounts + .signTransaction( + { + to: "", + value: web3.utils.toWei(""), + gas: 21000, + }, + "" + ) + .then((signedTxData) => { + web3.eth + .sendSignedTransaction(signedTxData.rawTransaction) + .on("receipt", console.log); + }); + +```` diff --git a/archive/edge/vi-edge/working-with-node/query-operator-info.md b/archive/edge/vi-edge/working-with-node/query-operator-info.md new file mode 100644 index 0000000000..4341f34e7a --- /dev/null +++ b/archive/edge/vi-edge/working-with-node/query-operator-info.md @@ -0,0 +1,103 @@ +--- +id: query-operator-info +title: Truy vấn thông tin trình vận hành + +description: "Cách truy vấn thông tin trình vận hành." +keywords: + - docs + - polygon + - edge + - node + - query + - operator +--- + +## Điều kiện tiên quyết {#prerequisites} + +Hướng dẫn này giả định rằng bạn đã làm theo hướng dẫn [Cài đặt cục bộ](/docs/edge/get-started/set-up-ibft-locally) hoặc [cách thiết lập cụm IBFT trên đám mây](/docs/edge/get-started/set-up-ibft-on-the-cloud). + + +Cần có một nút hoạt động để truy vấn bất kỳ loại thông tin của trình vận hành nào. + + +Với Polygon Edge, các trình vận hành nút có quyền kiểm soát và nắm thông tin về những gì nút đang thực hiện.
Bất cứ lúc nào, chúng cũng có thể sử dụng lớp thông tin nút được phát triển trên gRPC và nhận thông tin có nghĩa - mà không cần sàng lọc bản ghi. + + +:::note + +Nếu nút của bạn không chạy trên `127.0.0.1:8545`, bạn nên thêm cờ `--grpc-address ` vào các lệnh được liệt kê trong tài liệu này. + + +::: + +## Thông tin máy ngang hàng + {#peer-information} + +### Danh sách máy ngang hàng {#peers-list} + +Để nhận danh sách đầy đủ các máy ngang hàng đang được kết nối (bao gồm cả nút đang chạy), hãy chạy lệnh sau: + +````bash +polygon-edge peers list +```` + +Thao tác này sẽ trả về danh sách các địa chỉ libp2p hiện là máy ngang hàng của máy khách đang chạy. + + +### Trạng thái máy ngang hàng {#peer-status} + +Để xem trạng thái của một máy ngang hàng cụ thể, hãy chạy: + +````bash +polygon-edge peers status --peer-id
+```` +Với tham số *địa chỉ* là địa chỉ libp2p của máy ngang hàng. + + +## Thông tin IBFT {#ibft-info} + +Trong nhiều trường hợp, một trình vận hành sẽ muốn biết về trạng thái của nút hoạt động theo đồng thuận IBFT. + + +Thật may, Polygon Edge cung cấp cách thức dễ dàng để tìm thông tin này. + + +### Snapshot {#snapshots} + +Chạy lệnh sau sẽ trả về snapshot mới nhất. + +````bash +polygon-edge ibft snapshot +```` +Để truy vấn snapshot tại một số lượng khối cụ thể (số khối), trình vận hành có thể chạy: + +````bash +polygon-edge ibft snapshot --num +```` + +### Ứng cử viên + {#candidates} + +Để nhận thông tin mới nhất về các ứng cử viên, trình vận hành có thể chạy: + +````bash +polygon-edge ibft candidates +```` +Lệnh này truy vấn nhóm ứng cử viên được đề xuất hiện tại, cũng như các ứng cử viên chưa được đưa vào + +### Trạng thái {#status} + +Lệnh sau trả về các khóa của trình xác thực hiện tại của máy khách IBFT đang hoạt động: + +````bash +polygon-edge ibft status +```` + +## Nhóm giao dịch + {#transaction-pool} + +Để tìm số lượng giao dịch hiện tại trong nhóm giao dịch, trình vận hành có thể chạy: + +````bash +polygon-edge txpool status +```` diff --git a/docs/avail/architecture/avail-consensus.md b/docs/avail/architecture/avail-consensus.md deleted file mode 100644 index 24945c4806..0000000000 --- a/docs/avail/architecture/avail-consensus.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -id: avail-consensus -title: Avail's Consensus -sidebar_label: Consensus -description: Learn about Avail's consensus mechanism -keywords: - - docs - - polygon - - avail - - consensus - - proof of stake - - nominated proof of stake - - pos - - npos -image: https://matic.network/banners/matic-network-16x9.png -slug: avail-consensus ---- - -## Data availability committees - -Until now, the approach to maintaining DA solutions has generally been through -a DAC (data availability committee). A DAC is responsible for posting -signatures back to the main chain and attesting to the availability of off-chain -data. The DAC must ensure that data is readily available. - -Through a DAC, scaling solutions rely on a DAC to reach a Validium. The issue -with DACs is that data availability becomes a trusted service upon a small group -of committee members who are responsible for storing and truthfully reporting data. - -Avail is not a DAC, but an actual blockchain network with its consensus -mechanism, and has its own set of validator nodes and block producers. - -## Proof of Stake - -:::caution Current validators - -With the initial launch of the Avail testnet, validators will be -internally operated and maintained by Polygon. - -::: - -Traditional proof of stake systems require block production authors to have -token holdings (stake) on-chain to produce blocks, as opposed to computational -resources (work). - -Polygon's products use PoS (proof of stake) or a modification of PoS. - -Usually, validators in traditional PoS systems that have the most stake -have the most influence and control of the network. Systems with many network maintainers -tend to form off-chain pools to maximize capital gains by reducing reward variance. This -centralization challenge alleviates when pools are included on-chain that allows token -holders to back network maintainers who they feel best represent them and the interests -of the network. This also distributes the validator power concentration, assuming the -right voting and election mechanisms are in place, as the overall stake on the network -is allocated as a one-to-many or many-to-many relationship instead of only relying on a -one-to-one relationship, where trust is put in the "highest staked" validators. This -modification of proof of stake can be administered through delegation or nomination, -commonly referred to as DPoS (delegated proof of stake) or NPoS (nominated proof of stake). -Polygon's scaling solutions have adapted these enhanced mechanisms, including Polygon -Avail. - -Avail uses NPoS with a modification in block verification. The actors involved are -still validators and nominators. - -Light clients can also contribute to data availability on Avail. Avail's consensus -requires that two-thirds plus 1 of the validators reach consensus for validity. - -## Nominators - -Nominators can choose to back a set of candidate Avail validators with their -stake. Nominators will nominate those validators who they feel will -effectively provide data availability. - -:::info What is the difference between DPos and NPoS? - -At face value, delegation and nomination seem like the same action, especially -from an avid staker's point of view. However, the differences lay in the underlying -consensus mechanisms and how validator selection occurs. - -In DPoS, a voting-centric election system determines a fixed number of -validators to secure the network. Delegators can delegate their -stake against candidate network validators by using it as voting power to back -delegates. Delegators often support validators on the highest staked, as higher-staked -validators have a higher chance of election. The delegates with the most votes -become the network's validators and can verify transactions. While using their -stake as voting power, on Avail, they are not subject to consequences via slashing if -their elected validator behaves maliciously. In other DPoS systems, delegators may -be subject to slashing. - -In NPoS, delegators turn into nominators and use their stake in a similar -manner to nominate potential candidate validators to secure the network. -Stake is locked on-chain, and contrary to DPoS, nominators are subject to slashing -based on the potential malicious behavior of their nominations. In this regard, -NPoS is a more proactive staking mechanism as opposed to staking that is "set and -forget", as nominators look out for well-behaving and sustainable validators. This -also encourages validators to create robust validator operations to attract and -maintain nominations. - -::: diff --git a/docs/avail/architecture/avail-system-overview.md b/docs/avail/architecture/avail-system-overview.md deleted file mode 100644 index 6dea3aa59f..0000000000 --- a/docs/avail/architecture/avail-system-overview.md +++ /dev/null @@ -1,242 +0,0 @@ ---- -id: avail-system-overview -title: System Overview -sidebar_label: System Overview -description: Learn about the architecture of the Avail chain. -keywords: - - docs - - polygon - - avail - - data - - availability - - architecture -image: https://matic.network/banners/matic-network-16x9.png -slug: avail-system-overview ---- - -## Modularity - -Currently, monolithic blockchain architectures like that of Ethereum -cannot efficiently handle the execution, settlement, and data availability. - -Modularizing execution to scale blockchains is what rollup-centric -chain models attempt to do. This can work well when the settlement and -data availability layers are on the same layer, which is the approach -Ethereum rollups take. Still, there are necessary trade-offs when working -with rollups, as the rollup construction can be more secure depending on -the security of the data availability layer but would be inherently more -challenging to scale. - -However, a granular design creates different layers to be lightweight -protocols, like microservices. Then, the overall network becomes a collection -of loosely-coupled lightweight protocols. An example is a data availability -layer that only specializes in data availability. Polygon Avail is a -Substrate-based layer two blockchain for DA (data availability). - -:::note Substrate runtime - -Although Avail is based on the Substrate codebase, it includes modifications -to the block structure that prevent it from interoperating with other Substrate -networks. Avail implements an independent network unrelated to Polkadot or Kusama. - -::: - -Avail provides a high guarantee of data availability to any light client, -but does not make higher guarantees to light clients about DA than any other -network. Avail focuses on making it possible to prove that block data is -available without downloading the whole block by leveraging Kate polynomial -commitments, erasure coding, and other technologies to allow light clients (which -download only the _headers_ of the chain) to efficiently and randomly -sample small amounts of the block data to verify its full -availability. However, there are fundamentally different primitives than -fraud-proof-based DA systems, which are explained [here](https://blog.polygon.technology/the-data-availability-problem-6b74b619ffcc/). - -:::info Providing data availability - -The DA guarantee is something a client determines for itself; it does not have to -trust nodes. As the number of light clients grows, they collectively sample the entire -block (even though each client only samples a small percentage). Light clients eventually -form a p2p network amongst themselves; thus, after a block has been sampled, it becomes -highly available — that is, even if the nodes were to go down (or attempt to censor a block), -the light clients would be able to re-construct the block by sharing the pieces amongst -themselves. - -::: - -### Enabling the next set of solutions - -Avail will take rollups to the next level as chains can allocate -their data availability component to Avail. Avail also provides an alternative -way to bootstrap any standalone chain, as chains can offload their data -availability. There are, of course, trade-offs that are made with different modularity -approaches, but the overall goal is to maintain high security while being able -to scale. - -Transaction costs are also reduced. Avail can grow block size with a smaller -impact on the validator workload than a monolithic chain. When a monolithic chain -increases block size, validators have to do a lot more work because blocks have to -execute, and state has to be calculated. Since Avail has no execution environment, -it is much cheaper to increase the block size. The cost is not zero because of the need to -calculate KZG commitments and generate proofs, but still inexpensive. - -Avail also makes sovereign rollups a possibility. Users can create sovereign chains that -rely on Avail's validators to reach consensus on transaction data and order. -Sovereign rollups on Avail allow for seamless upgrades, as users can push updates to -application-specific nodes to upgrade the chain and, in turn, upgrade to new settlement -logic. Whereas in a traditional environment, the network requires a fork. - -:::info Avail does not have an execution environment - -Avail does not run smart contracts but allows other chains to make their transaction -data available through Avail. These chains may implement their execution environments of -any kind, EVM, Wasm, or anything else. - -::: - -:::info Avail doesn't care what the data is for - -Avail guarantees that block data is available but does not care about -what that data is. The data can be transactions but can take -on other forms too. - -::: - -Data availability on Avail is available for a window of time that it is -required. For instance, beyond needing data or reconstruction, security is not -compromised. - -Storage systems, on the other hand, are designed to store data for long -periods, and include incentivization mechanisms to encourage users -to store data. - -## Validation - -### Peer validation - -Three types of peers typically compose an ecosystem: - -* **Validator nodes:** - A validator collects transactions from the mempool, executes them, and generates a - candidate block that is appended to the network. The block contains a small block - header with the digest and metadata of the transactions in the block. -* **Full nodes:** - The candidate block propagates to full nodes across the network for verification. - The nodes will re-execute the transactions contained in the candidate block. -* **Light clients** - Light clients only fetch the block header to use for verification and will fetch - transaction details from neighboring full nodes as needed. - -While a secure approach, Avail addresses the limitations of this architecture to create -robustness and increased guarantees. Light clients can be tricked into accepting blocks -whose underlying data is unavailable. A block producer can include a malicious transaction -in a block and not reveal its entire content to the network. As mentioned in the Avail -documentation, this is known as the data availability problem. - -Avail's network peers include: - -* **Validator nodes:** - Protocol incentivized full nodes that participate in the consensus. Validator nodes - on Avail do not execute transactions. They package up arbitrary transactions and - construct candidate blocks, generating KZG commitments for the data. - > Other validators check that generated blocks are correct. - -* **Avail (DA) full nodes:** - Nodes that download and make available all block data for all applications - using Avail. Similarly, Avail full nodes do not execute transactions. - -* **Avail (DA) light clients:** - Clients that only download block headers randomly sample small parts of - the block to verify availability. They expose a local API to interact with the - Avail network. - -:::info The goal of Avail is not to be reliant on full nodes to keep data available - - The aim is to give similar DA guarantees to a light client as a full node. - Users are encouraged to use Avail light clients. However, they can still run Avail - full nodes, which are well supported. - -::: - -:::caution The local API is a WIP and is not yet stable -::: - -This allows applications that wish to use Avail to embed the DA light -client. They can then build: - -* **App full nodes:** - - Embed an Avail (DA) light client - - Download all data for a specific appID - - Implement an execution environment to run transactions - - Maintain application state - -* **App light clients:** - - Embed an Avail (DA) light client - - Implement end-user-facing functionality - -The Avail ecosystem will also feature bridges to enable specific -use-cases. One such bridge being designed at this time is an -_attestation bridge_ that will post attestations of data available on -Avail to Ethereum, thus allowing the creation of validiums. - -## State verification - -### Block verification -> DA verification - -#### Validators - -Instead of Avail validators verifying the application state, they concentrate -on ensuring the availability of posted transaction data and providing transaction -ordering. A block is considered valid only if the data behind that block is available. - -Avail validators take on incoming transactions, order them, construct a candidate block, -and propose to the network. The block contains special features, especially for DA—erasure -coding and KZG commitments. This is in a particular format, so clients can do -random sampling and download only a single application's transactions. -Other validators verify the block by ensuring the block is well formed, the KZG commitments -check out, the data is there, etc. - -#### Clients - -Requiring data to be available prevents block producers from releasing block headers -without releasing the data behind them, as this prevents clients from reading the -transactions necessary to compute the state of their applications. As with other chains, -Avail uses data availability verification to address this through DA checks which utilize -erasure codes; these checks are heavily used in data redundancy design. - -Erasure codes effectively duplicate data so that if part of a block is -suppressed, clients can re-construct that part by using another part of the block. -This means that a node trying to hide that part would need to hide a lot more. - -> The technique is used in devices like CD-ROMs and multi-disk (RAID) arrays (for instance, -> if a hard drive dies, it can be replaced and re-constructed from the data on other disks). - -What is unique about Avail is that the chain design allows *anyone* to check DA without -needing to download the data. DA checks require each light client to sample a minimal -number of random chunks from each block in the chain. A set of light clients can collectively -sample the entire blockchain in this manner. Consequently, the more non-consensus nodes there -are, the greater the block size (and throughput) can securely exist. Meaning, non-consensus -nodes can contribute to the throughput and security of the network. - -### Transaction settlement - -Avail will use a settlement layer built with Polygon Edge. The settlement layer -provides an EVM-compatible blockchain for rollups to store their data and perform -dispute resolution. The settlement layer utilizes Polygon Avail for its DA. -When rollups are using a settlement layer, they also inherit all the -DA properties of Avail. - -:::note Different ways to settle - -There are different ways to use Avail, and the validiums will not use the -settlement layer, but rather settle on Ethereum. - -::: - -Avail offers data hosting and ordering. The execution layer will likely come from -multiple off-chain scaling solutions or legacy execution layers. The settlement -layer takes on the verification and dispute resolution component. - -## Resources - -- [Introduction to Avail by Polygon blog post](https://medium.com/the-polygon-blog/introducing-avail-by-polygon-a-robust-general-purpose-scalable-data-availability-layer-98bc9814c048). -- [Polygon Talks: Polygon Avail](https://www.youtube.com/watch?v=okqMT1v3xi0) diff --git a/docs/avail/faq.md b/docs/avail/faq.md deleted file mode 100644 index 448e6a45a3..0000000000 --- a/docs/avail/faq.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -id: faq -title: FAQ -sidebar_label: FAQ -description: Frequently asked questions about Polygon Avail -keywords: - - docs - - polygon - - avail - - availability - - client - - consensus - - faq -image: https://matic.network/banners/matic-network-16x9.png -slug: faq ---- - -:::tip - -If you do not find your question on this page, please submit your question on the -**[Polygon Avail Discord server](https://discord.gg/jXbK2DDeNt)**. - -::: - -## What is a light client? - -Light clients allow users to interact with a blockchain network -without having to sync the full blockchain while maintaining -decentralization and security. Generally, they download the blockchain -headers, but not the contents of each block. Avail (DA) light clients -additionally verify that block contents are available by performing -Data Availability Sampling, a technique where small random sections of -a block are downloaded. - -## What is a popular use case of a light client? - -There are many use-cases which today rely on an intermediary to -maintain a full node, such that end users of a blockchain do not -communicate directly with the blockchain but instead through the -intermediary. Light clients have until now not been a suitable -replacement for this architecture because they lacked data -availability guarantees. Avail solves this issue, thus enabling more -applications to directly participate on the blockchain network without -intermediaries. Although Avail does support full nodes, we expect most -applications will not need to run one, or will need to run fewer. - -## What is data availability sampling? - -Avail light clients, like other light clients, only download the -headers of the blockchain. However, they additional perform data -availability sampling: a technique that randomly samples small -sections of the block data and verifies they are correct. When -combined with erasure coding and Kate polynomial commitments, Avail -clients are able to provide strong (nearly 100%) guarantees of -availability without relying on fraud proofs, and with only a small -constant number of queries. - -## How is erasure coding used to increase data availability guarantees? - -Erasure coding is a technique that encodes data in a way that spreads -out the information over multiple "shards", such that the loss of some -number of those shards can be tolerated. That is, the information can -be reconstructed from the other shards. Applied to the blockchain, -this means that we effectively increase the size of each block, but we -prevent a malicious actor from being able to hide any part of a block -up to the redundant shard size. - -Since a malicious actor needs to hide a large part of the block in -order to attempt to hide even a single transaction, it makes it much -more likely that random sampling would catch the large gaps in the -data. Effectively, erasure coding makes the data availibility sampling -technique much more powerful. - -## What are Kate commitments? - -Kate commitments, introduced by Aniket Kate, Gregory M. Zaverucha, and Ian Goldberg in 2010, provide a -way to commit to polynomials in a succinct manner. Recently, polynomial commitments came to the forefront, -being primarily used as commitments in PLONK-like zero knowledge constructions. - -In our construction, we use Kate commitments for the following reasons: - -- It allows us to commit to values in a succinct manner to be kept inside the block header. -- Short openings are possible which helps a light client verify availability. -- The cryptographic binding property helps us avoid fraud proofs by making it computationally infeasible - to produce wrong commitments. - - - -In the future, we might use other polynomial commitment schemes, if that gives us better bounds or guarantees. - -## Since Avail is used by multiple applications, does that mean chains have to download transactions from other chains? - -No. Avail headers contain an index that allows a given application to -determine and download only the sections of a block that have data for -that application. Thus, they are largely unaffected by other chains -using Avail at the same time or by block sizes. - -The only exception is data availability sampling. In order to verify -that data is available (and due to the nature of erasure coding), -clients sample small parts of the block at random, including possibly -sections that contain data for other applications. diff --git a/docs/avail/how-tos/avail-quick-start.md b/docs/avail/how-tos/avail-quick-start.md deleted file mode 100644 index f63d221ec2..0000000000 --- a/docs/avail/how-tos/avail-quick-start.md +++ /dev/null @@ -1,652 +0,0 @@ ---- -id: avail-quick-start -title: How to use Polygon Avail -sidebar_label: How to use Avail -description: Learn how to use Polygon Avail -keywords: - - docs - - polygon - - avail - - data - - availability - - how-to - - extrinsic - - explorer -image: https://matic.network/banners/matic-network-16x9.png -slug: avail-quick-start ---- -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import useBaseUrl from '@docusaurus/useBaseUrl'; - -:::note We are working on improving many of the current features - -We appreciate you using our testnet and encourage your valuable feedback -through one of our **[community channels](https://polygon.technology/community/)**. - -::: - -## Generate an Avail Account - -You can generate an account using one of two methods: -- [Avail Explorer](https://testnet.polygonavail.net/) -- Console/Typescript - - - - -Head over to [Avail Explorer](https://testnet.polygonavail.net/). - - - -:::note - -**[Avail Explorer](https://testnet.polygonavail.net/)** is a fork -of **[Polkadot-JS Apps](https://polkadot.js.org/)**. The interface and navigation are the same -if you are familiar with Polkadot-JS Apps. - -::: - -Navigate to the **Accounts** tab and click on the **Accounts** sub-tab. - - - -:::info Address Format - -As Avail is implemented using [Substrate](https://substrate.io/), generic Substrate addresses -always start with a 5 and follow the **[SS58 address format](https://docs.substrate.io/v3/advanced/ss58/)**. - -::: - -On the Accounts page, click on the **Add account** button and follow the steps in the pop-up window. - - - -:::caution Key Management - -The seed phrase is your account key, which controls your account. -You should not store your seed phrase on a device that has or may have access to -an internet connection. The seed phrase should be written down and stored on a non-digital -medium. - -Storing your account's JSON file does not have to be as rigourous as storing the seed phrase, -as long as you use a strong password to encrypt the file. You can import the JSON file to -access your account. - -::: - -## Receive AVL Testnet Tokens - -On the Avail Explorer, click on the icon next to your account name to -copy your address. Alternatively, you can copy the address manually. - - - -Head over to the [Polygon faucet](https://faucet.polygon.technology). - -On the faucet page, select `DA Network` and `DA (Test Token)` as the network and token. -Paste your account address and click on **Submit**. The transfer will up to one -minute to complete. - - - -Upon successful transfer, your account should now have a non-zero balance. If you face any issues -obtaining tokens from the faucet, please reach out to the -[support team](https://support.polygon.technology/support/home). - -## Submit a New Transaction - -On the Avail Explorer, navigate to the **Developer** tab and click on -the **Extrinsics** sub-tab. - - - -Select your newly created account. - - - -There are many extrinsics to choose from; go ahead and select -the `dataAvailability` extrinsic from the **extrinsic dropdown menu**. - -:::info What are extrinsics? - -Extrinsics are a form of external information and can either be inherents, signed transactions, -or unsigned Transactions. More details about extrinsics are available in the -[Substrate documentation](https://docs.substrate.io/v3/concepts/extrinsics/). - -::: - -You can then use the dropdown menu on the right-hand side to create an application key or -submit data. - - - - -In this example, `createApplicationKey` is used to create an application key. - - - -Enter the value you wish to submit as part of this transaction using the `App_ID`, or -without a default key value as `0`. - - - -:::note - -Before sending a transaction using `App_ID`, it must be created using the `createApplicationKey` field. - -::: - -Submit the transaction. Head over to the [Avail Explorer](https://testnet.polygonavail.net/#/explorer). -The recent event list should list your transaction. You can click on the event and expand it to check out -the transaction details. - - - - - -In this example, `submitBlockLengthProposal` is used to submit data. - - - -Enter the values you wish to submit as part of this transaction for `row` and `col`. - - - -Submit the transaction. Head over to the [Avail Explorer](https://testnet.polygonavail.net/#/explorer). -The recent event list should list your transaction. You can click on the event and expand it to check out -the transaction details. - - - - -:::info How to get guarantees that the data behind the transaction is available? - -We have abstracted out the nitty-gritty of verifying data availability and have hosted a light client -for your use. All you need to do is click on the block number against your desired transaction and -see all of the block details. - -You will also see a *confidence factor*. If it shows `0%`, give it some time and recheck it later. -Otherwise, it should show a non-zero confidence level indicating the probability with which the underlying data -is available. - -::: - - - - -Alternatively, you can use the console/typescript to generate an Avail account -via [`@polkadot/api`](https://polkadot.js.org/docs/). Create a new folder and add the -JS library using `yarn add @polkadot/api` or `npm install @polkadot/api` - -:::info - -Make sure Typescript dependencies are added for running the script. Here, -`@polkadot/api` version `7.9.1` is used. - -You can use `ts-node` to execute Typescript files in the console. Either use -`yarn add ts-node typescript '@types/node'` or `npm i ts-node typescript '@types/node'` -to install the packages. - -For instance, if you create a script called `account.ts`, you can execute the script -in the command line by running: - -```bash - -ts-node account.ts - -``` - -You will also need to **[connect to a node](../node/avail-node-management.md)** before running -the scripts. - -::: - -To generate an account, run the following script: - -```typescript - -const { ApiPromise, WsProvider, Keyring } = require('@polkadot/api'); -const {mnemonicGenerate, cryptoWaitReady } = require('@polkadot/util-crypto'); - -const keyring = new Keyring({ type: 'sr25519' }); - -async function createApi() { - - // Create the API and wait until ready - return ApiPromise.create({ - types: { - AccountInfo: 'AccountInfoWithRefCount', - }, - }); -} - -async function main () { - // Create the API and wait until ready - const api = await createApi(); - - const keyring = new Keyring({ type: 'sr25519'}); - const mnemonic = mnemonicGenerate(); - - const pair = keyring.createFromUri(mnemonic, { name: 'test_pair' },'sr25519'); - console.log(pair.meta.name, 'has address', pair.address, 'and the mnemonic is', mnemonic); - process.exit(0); - -} -main().catch(console.error) - -``` - -Sample Result: - -``` - -test_pair has address 5Gq1hKAiSKFkdmcFjTt3U8KEaxDHp613hbdSmqJCRswMkwCB and the mnemonic is decrease lunar scatter pattern spoil alpha index trend vacant sorry scatter never - -``` - -:::info Address Format - -As Avail is implemented using [Substrate](https://substrate.io/), generic Substrate addresses -always start with a 5 and follow the **[SS58 address format](https://docs.substrate.io/v3/advanced/ss58/)**. - -::: - -:::info Key derivation and signing algorithm - -The reasons for using `sr25519` are outlined **[here](https://wiki.polkadot.network/docs/learn-cryptography#keypairs-and-signing)**. - -::: - -Save the newly generated address and mnemonic phrase for next steps. - -:::caution Key Management - -The seed phrase is your account key, which controls your account. -You should not store your seed phrase on a device that has or may have access to -an internet connection. The seed phrase should be written down and stored on a non-digital -medium. - -::: - -## Receive AVL Testnet Tokens - -Head over to the [Polygon faucet](https://faucet.polygon.technology). - -On the faucet page, select `DA (Test Token)` and `DA Network` as the token and network, -respectively. Paste your account address and click on **Submit**. The transfer will take up to one -minute to complete. - - - -Upon successful transfer, your account should now have a non-zero balance. If you face any issues obtaining tokens from the faucet, please reach out to the [support team](https://support.polygon.technology/support/home). - -### Balance Check with `@polkadot/api` - -Use the following script to check the balance of the account you just created: - -```typescript - -const { ApiPromise, WsProvider, Keyring } = require('@polkadot/api'); -const {mnemonicGenerate, cryptoWaitReady } = require('@polkadot/util-crypto'); - -import type { ISubmittableResult} from '@polkadot/types/types'; - -const keyring = new Keyring({ type: 'sr25519' }); - -async function createApi() { - // Initialise the provider to connect to the local node - const provider = new WsProvider('wss://testnet.polygonavail.net/ws'); - - // Create the API and wait until ready - return ApiPromise.create({ - provider, - types: { - DataLookup: { - size: 'u32', - index: 'Vec<(u32,u32)>' - }, - KateExtrinsicRoot: { - hash: 'Hash', - commitment: 'Vec', - rows: 'u16', - cols: 'u16' - }, - KateHeader: { - parentHash: 'Hash', - number: 'Compact', - stateRoot: 'Hash', - extrinsicsRoot: 'KateExtrinsicRoot', - digest: 'Digest', - app_data_lookup: 'DataLookup' - }, - Header: 'KateHeader', - AppId: 'u32', - CheckAppId: { - extra: { - appId: 'u32', - }, - types: {} - } - }, - signedExtensions: { - CheckAppId: { - extrinsic: { - appId: 'u32' - }, - payload: {} - }, - }, - }); -} - -async function main () { - // Create the API and wait until ready - const api = await createApi(); - - // Retrieve the chain & node information information via rpc calls - const [chain, nodeName, nodeVersion] = await Promise.all([ - api.rpc.system.chain(), - api.rpc.system.name(), - api.rpc.system.version() - ]); - - console.log(`You are connected to chain ${chain} using ${nodeName} v${nodeVersion}`); - - //address which is generated from previous step👇 - let ADDRESS = '_ADDRESS_'; - console.log(ADDRESS); - try{ - let { data: { free:balance}} = await api.query.system.account(ADDRESS) - console.log(`${ADDRESS} has balance of ${balance}`) - }catch (e){ - console.log(e) - }finally{ - process.exit(0) - } -} -main().catch(console.error) - -``` - -Sample Result: - -``` -You are connected to chain Avail-Testnet using Polygon Avail Node v3.0.0-6c8781e-x86_64-linux-gnu -5HBCFfAs5gfqYgSinsr5s1nSZY2uRCh8MhYhXXp6Y9jNRJFB -5HBCFfAs5gfqYgSinsr5s1nSZY2uRCh8MhYhXXp6Y9jNRJFB has balance of 0 -``` - -> You should get balance as `0` if the account is newly created and you have not used the faucet. -> You should also see the confirmation of the transaction. - -:::tip Using The Avail Explorer - -For convenience, you can add the account you generated with -`@polkadot/api` on the Avail Explorer UI to perform account actions. - -::: - -## Submit a New Transaction - -You can use the provided scripts in this section to sign and submit transactions. - -:::note - -Replace `value` and `APP_ID` with those you want to submit. -Also, replace the mnemonic string with your own. - -::: - - - - -The following script creates an application key: - -```typescript - -const { ApiPromise, WsProvider, Keyring } = require('@polkadot/api'); -const {mnemonicGenerate, cryptoWaitReady } = require('@polkadot/util-crypto'); - -import type { ISubmittableResult} from '@polkadot/types/types'; - -const ALICE = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; -const BOB = '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty'; - -const keyring = new Keyring({ type: 'sr25519' }); - -async function createApi() { - // Initialise the provider to connect to the local node - const provider = new WsProvider('ws://127.0.0.1:9944'); - - // Create the API and wait until ready - return ApiPromise.create({ - provider, - types: { - DataLookup: { - size: 'u32', - index: 'Vec<(u32,u32)>' - }, - KateExtrinsicRoot: { - hash: 'Hash', - commitment: 'Vec', - rows: 'u16', - cols: 'u16' - }, - KateHeader: { - parentHash: 'Hash', - number: 'Compact', - stateRoot: 'Hash', - extrinsicsRoot: 'KateExtrinsicRoot', - digest: 'Digest', - app_data_lookup: 'DataLookup' - }, - Header: 'KateHeader', - AppId: 'u32', - CheckAppId: { - extra: { - appId: 'u32', - }, - types: {} - } - }, - signedExtensions: { - CheckAppId: { - extrinsic: { - appId: 'u32' - }, - payload: {} - }, - }, - }); -} - -async function main () { - // Create the API and wait until ready - const api = await createApi(); - - //enter your mnemonic generated from the previous step and replace below. - const pair = keyring.addFromUri( 'put your mnemonic', { name: 'test pair' }, 'sr25519'); - // Retrieve the chain & node information information via rpc calls - const [chain, nodeName, nodeVersion] = await Promise.all([ - api.rpc.system.chain(), - api.rpc.system.name(), - api.rpc.system.version() - ]); - console.log(`You are connected to chain ${chain} using ${nodeName} v${nodeVersion}`); - try{ - let KEY = 1; - let createId = api.tx.dataAvailability.createApplicationKey(KEY); - const unsub = await createId - .signAndSend( - pair, - { app_id: 0}, - ( result: ISubmittableResult ) => { - console.log(`Tx status: ${result.status}`); - - if (result.status.isInBlock) { - console.log(`Tx included at block hash ${result.status.asInBlock}`); - } else if (result.status.isFinalized) { - console.log(`Tx included at blockHash ${result.status.asFinalized}`); - - result.events.forEach(({ phase, event: { data, method, section } }) => { - console.log(`\t' ${phase}: ${section}.${method}:: ${data}`); - }); - unsub - process.exit(0); - } - }); - }catch(e){ - console.error(e); - } -} -main().catch(console.error) - -``` - - - - -The following script submits data: - -```typescript - -const { ApiPromise, WsProvider, Keyring } = require('@polkadot/api'); -const {mnemonicGenerate, cryptoWaitReady } = require('@polkadot/util-crypto'); - -import type { EventRecord, ExtrinsicStatus, H256, SignedBlock } from '@polkadot/types/interfaces'; -import type { ISubmittableResult} from '@polkadot/types/types'; - -const keyring = new Keyring({ type: 'sr25519' }); - -async function createApi() { - // Initialise the provider to connect to the local node - const provider = new WsProvider('wss://testnet.polygonavail.net/ws'); - - // Create the API and wait until ready - return ApiPromise.create({ - provider, - types: { - DataLookup: { - size: 'u32', - index: 'Vec<(u32,u32)>' - }, - KateExtrinsicRoot: { - hash: 'Hash', - commitment: 'Vec', - rows: 'u16', - cols: 'u16' - }, - KateHeader: { - parentHash: 'Hash', - number: 'Compact', - stateRoot: 'Hash', - extrinsicsRoot: 'KateExtrinsicRoot', - digest: 'Digest', - app_data_lookup: 'DataLookup' - }, - Header: 'KateHeader', - AppId: 'u32', - CheckAppId: { - extra: { - appId: 'u32', - }, - types: {} - } - }, - signedExtensions: { - CheckAppId: { - extrinsic: { - appId: 'u32' - }, - payload: {} - }, - }, - }); -} - -async function main () { - // Create the API and wait until ready - const api = await createApi(); - - //enter your mnemonic generated from the previous step and replace below 👇. - const pair = keyring.addFromUri( 'enter mnemonic here', { name: 'test pair' }, 'sr25519'); - // Retrieve the chain & node information information via rpc calls - const [chain, nodeName, nodeVersion] = await Promise.all([ - api.rpc.system.chain(), - api.rpc.system.name(), - api.rpc.system.version() - ]); - - console.log(`You are connected to chain ${chain} using ${nodeName} v${nodeVersion}`); - - try{ - let APP_ID = 1; - let VALUE = `iucakcbak`; - let transfer = api.tx.dataAvailability.submitData(VALUE); - const unsub = await transfer - .signAndSend( - pair, - { app_id: APP_ID}, - ( result: ISubmittableResult ) => { - console.log(`Tx status: ${result.status}`); - - if (result.status.isInBlock) { - console.log(`Tx included at block hash ${result.status.asInBlock}`); - } else if (result.status.isFinalized) { - console.log(`Tx included at blockHash ${result.status.asFinalized}`); - - result.events.forEach(({ phase, event: { data, method, section } }) => { - console.log(`\t' ${phase}: ${section}.${method}:: ${data}`); - }); - - process.exit(0); - } - }); - }catch(e){ - console.error(e); - } -} -main().catch(console.error) - -``` - - - - -You can head over to the [Avail Explorer](https://testnet.polygonavail.net/#/explorer), and the -recent event list should list your transaction. You can click on the event and expand it to check out -the transaction details. - -:::info How to get guarantees that the data behind the transaction is available? - -You can use the following curl request to check out the confidence level. Just replace the block number with the -one you wish to get availability guarantees for. - -```bash - -curl -s -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","method":"get_blockConfidence","params": {"number": block_number_here}, "id": 1}' 'https://polygon-da-light.matic.today/v1/json-rpc' - -``` -::: - - - diff --git a/docs/avail/introduction/what-is-avail.md b/docs/avail/introduction/what-is-avail.md deleted file mode 100644 index ba884613eb..0000000000 --- a/docs/avail/introduction/what-is-avail.md +++ /dev/null @@ -1,146 +0,0 @@ ---- -id: what-is-avail -title: Avail by Polygon -sidebar_label: Introduction to Avail -description: Learn about Polygon's data availability chain -keywords: - - docs - - polygon - - avail - - availability - - scale - - rollup -image: https://matic.network/banners/matic-network-16x9.png -slug: what-is-avail ---- - - - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import useBaseUrl from '@docusaurus/useBaseUrl'; - -Avail is a blockchain that is laser-focused on data availability: -ordering and recording blockchain transactions, and making it possible -to prove that block data is available without downloading the whole -block. This allows it to scale in ways that monolithic blockchains -cannot. - -:::note A Robust General-Purpose Scalable Data Availability Layer - -* Enables Layer-2 solutions to offer increased scalability throughput - by leveraging Avail to build Validiums with off-chain data - availability. - -* Enables standalone chains or sidechains with arbitrary execution - environments to bootstrap validator security without needing to - create and manage their own validator set by guaranteeing - transaction data availability. - -::: - -## Current Availability and Scaling Challenges - - - - -### What is the data availability problem? - -Peers in a blockchain network need a way to ensure that all the data of a newly proposed block is -readily available. If the data is not available, the block might contain malicious transactions -which are being hidden by the block producer. Even if the block contains non-malicious transactions, -hiding them might compromise the security of the system. - -### Avail's approach to data availability - -#### High Guarantee - -Avail provides a provable, high-level of guarantee that data is -available. Light clients can independendly verify availability in a -constant number of queries, without downloading the entire block. - -#### Minimum Trust - -No need to be a validator or host a full node. Even with a light -client, get verifiable availability. - -#### Easy to Use - -Built using modified Substrate, the solution focuses on ease of use, whether you host an application or -operate an off-chain scaling solution. - -#### Perfect for Off-Chain Scaling - -Unlock the full scaling potential of your off-chain scaling solution by keeping the data with us and -still avoiding the DA problem on L1. - -#### Execution Agnostic - -Chains that use Avail can implement any type of execution environment -irrespective of the application logic. Transactions from any -environment are supported: EVM, Wasm, or even new VMs that have not -been built yet. Avail is perfect for experimenting with new execution -layers. - -#### Bootstrapping Security - -Avail enables new chains to be created without needing to spin up a -new validator set, and leverage Avail's instead. Avail takes care of -transaction sequencing, consensus, and availability in exchange for -simple transaction fees (gas). - -#### Fast provable finality using NPoS - -Fast provable finality via Nominated Proof of Stake. Backed by KZG -commitments and erasure coding. - - - - -Start by checking out this [blog post](https://blog.polygon.technology/polygon-research-ethereum-scaling-with-rollups-8a2c221bf644/) on scaling -Ethereum with Rollups. - -## Avail-Powered Validiums - -Due to the architecture of monolithic blockchains -(such as Ethereum in its current state), operating the blockchain is -expensive, resulting in high transaction fees. Rollups attempt to extract -the burden of execution by running transactions off-chain and then posting -the execution results and the [usually compressed] transaction data. - -Validiums are the next step: instead of posting the transaction data, -it is kept available off-chain, where a proof/attestation is only -posted to the base layer. This is by far the most cost-effective solution -because both execution and data availability are kept off-chain while still -allowing for final verification and settlement on the layer 1 chain. - -Avail is a blockchain optimized for data availability. Any rollup that -wishes to become a validium can switch to post transaction data to -Avail instead of the layer 1 and deploy a verification contract that, in -addition to verifying the correct execution, also verifies data -availability. - -:::note Attestation - -The Avail team will make this data availability verification simple on -Ethereum by building an attestation bridge to post data availability -attestations directly to Ethereum. This will make the verification -contract's job a simple one, since the DA attestations will already be -on-chain. This bridge is currently in design; please reach out to the -Avail team for more information or to join our early access program. - -::: - - - - -## See also - -* [Introducing Avail by Polygon — a Robust General-Purpose Scalable Data Availability Layer](https://polygontech.medium.com/introducing-avail-by-polygon-a-robust-general-purpose-scalable-data-availability-layer-98bc9814c048) -* [The Data Availability Problem](https://blog.polygon.technology/the-data-availability-problem-6b74b619ffcc/) diff --git a/docs/avail/node/avail-node-management.md b/docs/avail/node/avail-node-management.md deleted file mode 100644 index a4162563da..0000000000 --- a/docs/avail/node/avail-node-management.md +++ /dev/null @@ -1,526 +0,0 @@ ---- -id: avail-node-management -title: Run an Avail Node -sidebar_label: Run an Avail node -description: "Learn about running an Avail node." -keywords: - - docs - - polygon - - avail - - node -image: https://matic.network/banners/matic-network-16x9.png -slug: avail-node-management ---- -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import useBaseUrl from '@docusaurus/useBaseUrl'; - -:::tip Common practice - -Users often run nodes on a cloud server. You may consider using a VPS provider to run your node. - -::: - -## Prerequisites - -The following list of standard hardware is a recommendation of hardware specs that your environment should -have. - - - - - -The hardware specs should at least have: - -* 4GB RAM -* 2 core CPU -* 20-40 GB SSD - - - - -The hardware recommendations for running a validator on a Substrate-based chain: - -* CPU - Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz -* Storage - A NVMe solid state drive with about 256GB. Should be reasonably sized to deal with - blockchain growth. -* Memory - 64GB ECC - - - - -### Node prerequisites: Install Rust & dependencies - -:::info Installation steps by Substrate - -Avail is a Substrate-based chain and requires the same configuration to run a Substrate chain. - -Additional installation documentation is available in the Substrate -**[getting started documentation](https://docs.substrate.io/v3/getting-started/installation/)**. - -::: - -Once you choose an environment to run your node, ensure Rust is installed. -If you already have Rust installed, run the following command to make sure you are using the latest version. - -```sh -rustup update -``` - -If not, start by running the following command to fetch the latest version of Rust: - -```sh -curl https://sh.rustup.rs -sSf | sh -s -- -y -``` - -To configure your shell, run: - -```sh -source $HOME/.cargo/env -``` - -Verify your installation with: - -```sh -rustc --version -``` - - - - - -## Run Avail Locally - -Clone the [Avail source code](https://github.com/maticnetwork/avail): - -```sh -git clone git@github.com:maticnetwork/avail.git -``` - -Compile the source code: - -```sh -cargo build --release -``` - -:::caution This process usually takes time - -::: - -Run a local dev node with temporary datastore: - -```sh -./target/release/data-avail --dev --tmp -``` - - - - -## Data Availability Deployments - -:::info Onboarding validators - -In Avail's current state, the Avail team will maintain the network and run -internal validators. - -::: - -:::warning System administration - -Although Polygon Avail is in testnet phase, in general, users should have **significant system -administration experience** when running validator nodes. - -Validator nodes are responsbile for maintaining and securing the network by staking tokens with real -value. Validators need to understand how to manage their node, its associated hardware & configuration, -and be wary that they are subject to being slashed due to actions like being offline or equivocation. - -When in doubt, reach out to the Validator Engagement team. - -::: - - - - - -## Docker Setup - -The easiest way to deploy your own Avail validator node is using Docker. - -### Run the latest version of the Docker container - -Use the default parameters and expose the P2P port with `-p 30333` by running: - -```shell -docker run -p 30333 --name my_val 0xpolygon/avail:latest -``` - -Any extra parameter will be added to the `data-avail` binary as an argument. -If you want to use a specific node key and limit the maximum number of incoming connections -to `10`, you can use: - -```shell -docker run -p 30333 --name my_val 0xpolygon/avail:latest --in-peers=10 --node-key 80027666cebec66464611eb0d5c36416213d83a9c689006a80efcf479826de7d -``` - -This image uses two volumes: - - `/da/state` to store the database of the chain - - `/da/keystore` to store the validator's private keys - -Most likelihood you want to bind these volumes to a specific points, like: - -```shell -docker run -p 30333 --name my_val -v /volumes/da/state:/da/state -v /volumes/da/keystore/:/da/keystore 0xpolygon/avail:latest -``` - -### Insert private keys - -These private keys will be used by the validator to sign blocks and finalize the chain when it -acts as an active validator. They are stored into `/da/keystore` in plain text format, so you -should take extra care over that volume. - -In order to insert these keys, we will open a shell inside the running container: - -```shell -docker exec -it my_val bash -root@5f55e51e5a85:/da# /da/bin/data-avail key insert \ - --chain=/da/genesis/testnet.chain.spec.raw.json \ - --base-path=/da/state/ \ - --keystore-path=/da/keystore/ \ - --suri=0x7d98...cae6 \ - --key-type=babe \ - --scheme=Sr25519 -``` - -The **--suri** parameter is the private key as a mnemonic phrase (or secret phrase) where you can generate -one using the `subkey` tool in Substrate. - -:::note Learn about subkey - -To learn about how to use subkey, visit the -[Subkey Substrate documentation](https://docs.substrate.io/v3/tools/subkey/). - -::: - -This command should be **repeated for each pair of key type -and scheme** shown in the following table: - -| Key Type | Scheme | -| -------- | --------- | -| babe | Sr25519 | -| gran | *Ed25519* | -| imon | Sr25519 | -| audi | Sr25519 | - -## Bond AVL tokens - -It is highly recommended that you set up a stash and controller account and have separate key -(two separate accounts) for both. - -:::info Stash and Controller Keys - -- A controller key is used to control staking actions for your account -- A stash key is used to control your funds. **It is recommended that the stash key be a cold wallet or offline - and not be used for account related activities like submitting extrinsics. - -Follow the [Polkadot Wiki](https://wiki.polkadot.network/docs/learn-staking#accounts) and the -[Substrate Hub](https://docs.substrate.io/v3/concepts/account-abstractions/#:~:text=Controller%20Key%3A%20a%20Controller%20account,somewhat%20regularly%20for%20validator%20maintenance) -to learn more about stash and controller accounts and how to manage them. - -::: - -You will start by creating two accounts; ensure each account has enough funds to pay the fees for -making transactions. - -:::tip Storing funds - -Keep most of your funds in the stash account since it is meant to be the custodian of -your staking funds, and have just enough funds in the controller account to pay for fees. - -Make sure not to bond all your AVL balance since you will be unable to pay transaction fees from your bonded -balance. - -::: - -It is now time to set up your validator by doing the following: - - - Bond the AVL of the Stash account. These token will be put at stake for the security of the network and - subject to slashing. - - Select the Controller. This is the account that will decide when to start or stop validating. - -First, go to the **Developer** tab in the [Avail Apps](https://devnet-avail.polygon.technology/) -navbar and click on **Extrinsics**. - -* **Stash** account - Select your Stash account. In this example, we bond 1001 AVL tokens, where the - minimum bonding amount is 1000. Make sure that your Stash account contains at least this much. - You can, of course, stake more than this. -* **Controller** account - Select the Controller account created earlier. This account will need a - small amount of AVL in order to start and stop validating. -* **Value** bonded - The amount of AVL tokens you want to bond from your Stash account. - - :::note - - You do not need to bond all of the AVL in that account. Also note that you can always bond more `AVL` later. - However, withdrawing any bonded amount requires the duration of the unbonding period. - - ::: - -* **Payment** destination - The account where the rewards from validating are sent. More information can be found - [here](https://wiki.polkadot.network/docs/learn-staking#reward-distribution). - - - -Select the **staking** pallet, and the **bond** extrinsic. - - - -Create a transaction where your **stash** account bounds 1001 AVLs at least to your **controller** account, -as shown below. - - - -## Set Session Keys - -Once your node is **fully synced**, you need to rotate and submit your session keys. - -### Rotate you session keys - -Run this command on the same machine (while the node is running with the default HTTP RPC port configured): - -```shell -docker exec -it my_val bash -root@5f55e51e5a85:/da# curl \ - -H "Content-Type: application/json" \ - -d '{"id":1, "jsonrpc":"2.0", "method": "author_rotateKeys", "params":[]}' \ - http://localhost:9933 -``` - -The output will have a hex-encoded "result" field. The result is the concatenation of the four public keys. -Save this result for a later step. - -You can restart your node at this point. - -### Submitting the `setKeys` transaction - -You need to tell the chain your Session keys by signing and submitting an extrinsic. This is what associates -your validator with your Controller account. - -Navigate to the [Network > Staking](https://devnet-avail.polygon.technology/#/staking). -Here, you can perform various staking actions. Navigate to **Account actions** , and select **Set Session Key** -on the bonding account you generated earlier. Enter the output `from author_rotateKeys` in the field and click on -"Set Session Key". - - - -After submitting this extrinsic, you are ready to start validating. - -## Validate - -To verify that your node is live and synchronized, navigate to -[Network > Staking](https://devnet-avail.polygon.technology/#/staking) and select -**Waiting**. Your account should be shown there. A new validator set is selected every **era**, -based on the staking amount. - - - - -## Build from the Source Code - -Clone the repo and checkout to the right branch: - -```shell -git clone git@github.com:maticnetwork/avail.git -``` - -Only build the node binaries - -```shell -cargo build --release -p data-avail -``` - -### Optional: How to generate deterministic WASM - -:::note This step is **not required** and it should only be used to verify that WASM matches with -the source code. - -::: - -The `srtool` allows building **WASM runtimes in a deterministic way**, allowing CIs and users, with -various machines and OS, to produce a *strictly identical* WASM runtime. - -1. Install [srtool-cli](https://github.com/chevdor/srtool-cli) - -2. Move to your `substrate` root folder and build the WASM runtime: - -```shell -srtool build -r runtime/ --package da-runtime -``` - -You should expect an output like the following: - -```shell -Found 1.57.0, we will be using paritytech/srtool:1.57.0 for the build -🧰 Substrate Runtime Toolbox - srtool v0.9.19 🧰 - - by Chevdor - -info: using existing install for '1.57.0-x86_64-unknown-linux-gnu' -info: override toolchain for '/build' set to '1.57.0-x86_64-unknown-linux-gnu' - -1.57.0-x86_64-unknown-linux-gnu unchanged - rustc 1.57.0 (f1edd0429 2021-11-29) - -🏗 Building node-template-runtime as release using rustc 1.57.0 (f1edd0429 2021-11-29) -⏳ That can take a little while, be patient... subsequent builds will be faster. - Since you have to wait a little, you may want to learn more about Substrate runtimes: - https://docs.substrate.io/v3/getting-started/architecture/ - Updating git repository `https://github.com/maticnetwork/plonk.git` - Updating crates.io index -Downloading crates ... - Downloaded addr2line v0.17.0 - Downloaded void v1.0.2 - ... - - Compiling pallet-staking v3.0.0 (/build/frame/staking) - Compiling pallet-babe v3.0.0 (/build/frame/babe) - Finished release [optimized] target(s) in 5m 31s - -✨ Your Substrate WASM Runtime is ready! ✨ -Summary generated with srtool v0.9.19 using the docker image paritytech/srtool:1.57.0: -Package : node-template-runtime v2.0.0 -GIT commit : 0c920993026117aa83c905bfcbe881a71ae3e8a3 -GIT tag : v3.0.0 -GIT branch : da-poc-upgrade-3.0 -Rustc : rustc 1.57.0 (f1edd0429 2021-11-29) -Time : 2022-01-18T15:55:30Z - -== Compact -Version : node-template-1 (node-template-1.tx1.au10) -Metadata : V12 -Size : 1.75 MB (1832581 bytes) -Proposal : 0xb1b534eb700006140cc980c89c1f3a9ad7a5ababa3e2aa8b9a17c5ae71d9b61c -IPFS : QmanwTMjMhWL8uL974VzrA6XVUg17x7czYqEftop6dhkP2 -BLAKE2_256 : 0xa1f8434cba25d4bee440d61b9ce6eeaa0d948ff2173187d940e8c3d87086737c -Wasm : ./bin/node-template/runtime//target/srtool/release/wbuild/node-template-runtime/node_template_runtime.compact.wasm - -== Compressed -No compressed runtime found -``` - -Now you only need to replace the WASM file in your `target/release` folder and rebuild the node -binary. Another option is to replace the WASM code in `genesis > runtime > frameSystem > code` in -your `chain.spec` file. - - - - -## Build & Run `avail-light` & `data-avail` - -First, build the Docker images, `client:asdr` (using branch `feature/app-specific-data-retrieval_2`) and `da:asdr` -(using branch `feature/app-specific-data-retrieval`): - -```shell -export DOCKER_BUILDKIT = 1 -docker build --ssh default -t client:asdr --build-arg BRANCH=feature/app-specific-data-retrieval_2 -f images/client/Dockerfile images/client/ -``` - -Next, run the services using **docker-compose.light-client.yml**: - -```shell -docker-compose -f docker-compose.light-client.yml up -``` - -### Using Monk templates - -#### Testnet using three validators - -On the testnet, validators use the development accounts: `Alice`, `Bob`, and `Charlie`. - -#### Step 1: Build images - -```shell -export DOCKER_BUILDKIT=1 -docker build -t da:ava-33 --build-arg BRANCH=miguel/ava-33-create-monk-template-for-da-testnet -f images/da/Dockerfile images/da/ -``` - -#### Step 2: Load Monk templates - -The testnet only need to load two monk templates: - -- **monk/polygon-da-base.matic.today.yaml**, which contains common definition for DevNet & TestNet. -- **monk/polygon-da-devnet.matic.today.yaml**, where validators are defined. - -```shell -monk s ns-delete /templates/local/polygon -monk load monk/polygon-da-base.matic.today.yaml -monk load monk/polygon-da-devnet.matic.today.yaml -``` - -#### Step 3: Run templates - -Once templates are loaded, we only need to run three nodes: - -```shell -monk run polygon/da-dev-validator-1 polygon/da-dev-validator-2 polygon/da-dev-validator-3 -``` - -Now you can check logs using `monk logs`, i.e.: - -```shell -monk logs -f -l 100 polygon/da-dev-validator-1 -``` - -You should expect: - -``` -2022-03-22 10:52:20 ✨ Imported #9 (0x911b…bdf5) -2022-03-22 10:52:23 💤 Idle (2 peers), best: #9 (0x911b…bdf5), finalized #7 (0x6309…0366), ⬇ 1.5kiB/s ⬆ 1.8kiB/s -2022-03-22 10:52:28 💤 Idle (2 peers), best: #9 (0x911b…bdf5), finalized #7 (0x6309…0366), ⬇ 1.2kiB/s ⬆ 1.2kiB/s -2022-03-22 10:52:33 💤 Idle (2 peers), best: #9 (0x911b…bdf5), finalized #7 (0x6309…0366), ⬇ 1.2kiB/s ⬆ 1.2kiB/s -2022-03-22 10:52:38 💤 Idle (2 peers), best: #9 (0x911b…bdf5), finalized #7 (0x6309…0366), ⬇ 1.1kiB/s ⬆ 1.1kiB/s -2022-03-22 10:52:40 Rows: 1 Cols: 4 Size: 128 -2022-03-22 10:52:40 Time to extend block 150.509µs -2022-03-22 10:52:40 Time to prepare 181.938µs -2022-03-22 10:52:40 Number of CPU cores: 16 -2022-03-22 10:52:40 Time to build a commitment 1.766672ms -2022-03-22 10:52:40 ✨ Imported #10 (0x64f4…84b5) -2022-03-22 10:52:43 💤 Idle (2 peers), best: #10 (0x64f4…84b5), finalized #8 (0x3c88…cfe1), ⬇ 1.6kiB/s ⬆ 1.6kiB/s -2022-03-22 10:52:48 💤 Idle (2 peers), best: #10 (0x64f4…84b5), finalized #8 (0x3c88…cfe1), ⬇ 1.1kiB/s ⬆ 1.1kiB/s -2022-03-22 10:52:53 💤 Idle (2 peers), best: #10 (0x64f4…84b5), finalized #8 (0x3c88…cfe1), ⬇ 1.2kiB/s ⬆ 1.2kiB/s -2022-03-22 10:52:58 💤 Idle (2 peers), best: #10 (0x64f4…84b5), finalized #8 (0x3c88…cfe1), ⬇ 1.2kiB/s ⬆ 1.2kiB/s -2022-03-22 10:53:00 Rows: 1 Cols: 4 Size: 128 -2022-03-22 10:53:00 Time to extend block 146.593µs -2022-03-22 10:53:00 Time to prepare 175.756µs -2022-03-22 10:53:00 Number of CPU cores: 16 -2022-03-22 10:53:00 Time to build a commitment 1.891133ms -2022-03-22 10:53:00 ✨ Imported #11 (0x0a5e…43d6) -``` - -#### Purge Node State - -In this configuration, the state of the node is stored at `/var/lib/monkd/volumes/dev/validator`, so -you can remove these folders or just use `monk purge`: - -``` -monk purge polygon/da-dev-validator-1 polygon/da-dev-validator-2 polygon/da-dev-validator-3 -``` - - - - - diff --git a/docs/contribute/bug-bounty-program.md b/docs/contribute/bug-bounty-program.md index 4f5c348a64..4e3c2cc212 100644 --- a/docs/contribute/bug-bounty-program.md +++ b/docs/contribute/bug-bounty-program.md @@ -1,14 +1,14 @@ --- id: bug-bounty-program title: Bug Bounty Program -sidebar_label: Bug bounty program -description: Know more about Polygon's Bug Bounty Program. +sidebar_label: Bug Bounty Program +description: "Learn about Polygon's Bug Bounty Program." keywords: - docs - matic - polygon - bug bounty -image: https://matic.network/banners/matic-network-16x9.png +image: https://wiki.polygon.technology/img/polygon-logo.png slug: bug-bountry-program --- @@ -30,12 +30,10 @@ Explore the [code on GitHub](https://github.com/maticnetwork). There are 3 main Set up a test network locally. See [Running a node on the local environment](https://github.com/maticnetwork/matic-cli) -The Polygon CLI repository is an easy way to setup and manage the entire Polygon stack, including **Heimdall**, **Bor**, and the **Staking & Plasma smart contracts** on a local environment. This would help in simulating tests and attacks locally. +The Polygon CLI repository is an easy way to setup and manage the entire Polygon stack, including **Heimdall**, **Bor**, and the **Staking smart contracts** on a local environment. This would help in simulating tests and attacks locally. -If you want to run a full node on the Polygon Mainnet or Mumbai Testnet, you can follow the links below: - -* [Run a Validator Node with Ansible](/docs/maintain/validate/run-validator-ansible) -* [Run a Validator Node from Binaries](/docs/maintain/validate/run-validator-binaries) +If you want to run a full node on the Polygon Mainnet or Mumbai Testnet, you can follow the +[Run a Validator Node](/docs/pos/operate/validator/run-validator) guide. ## Obtaining tokens for testing @@ -48,4 +46,7 @@ Check out the forum and join the discussion on Discord. * [Forum](https://forum.polygon.technology) * [Discord](https://discord.com/invite/0xPolygon) -See also the [Immunefi Bug Bounty Program](https://immunefi.com/bounty/polygon/). +You are encouraged to explore the following opportunities in our Bug Bounty Programs: +* [Immunefi POS](https://immunefi.com/bounty/polygon/): this program focuses on all Smart Contract and Blockchain assets related to Polygon PoS +* [Immunefi zkEVM](https://immunefi.com/bounty/polygonzkevm/): this program focuses on all Smart Contract and Blockchain assets related to Polygon zkEVM +* [HackerOne](https://hackerone.com/polygon-technology): this program focuses on all web applications and other assets under Polygon Labs diff --git a/docs/contribute/community-maintainers.md b/docs/contribute/community-maintainers.md index a021e6b509..bc677b8618 100644 --- a/docs/contribute/community-maintainers.md +++ b/docs/contribute/community-maintainers.md @@ -1,7 +1,7 @@ --- id: wiki-maintainers title: Wiki Maintainers -sidebar_label: Maintainers +sidebar_label: Wiki Maintainers description: A list of Polygon Wiki maintainers keywords: - docs @@ -11,7 +11,7 @@ keywords: - docs - maintainers - contributors -image: https://matic.network/banners/matic-network-16x9.png +image: https://wiki.polygon.technology/img/polygon-logo.png slug: community-maintainers --- diff --git a/docs/contribute/contributor-guidelines.md b/docs/contribute/contributor-guidelines.md index b9b369d2ef..2c76e43832 100644 --- a/docs/contribute/contributor-guidelines.md +++ b/docs/contribute/contributor-guidelines.md @@ -1,7 +1,7 @@ --- id: contributor-guidelines title: How to Contribute -sidebar_label: Contributor guidelines +sidebar_label: How to Contribute description: Prepare for your upcoming contribution keywords: - docs @@ -10,12 +10,14 @@ keywords: - contribute - contributor - contributing -image: https://matic.network/banners/matic-network-16x9.png +image: https://wiki.polygon.technology/img/polygon-logo.png slug: orientation --- -:::tip -Feel free to [raise an issue on our Polygon Wiki repository](https://github.com/maticnetwork/matic-docs/issues) +:::tip Open a pull request + +Feel free to [raise an issue on the Polygon Wiki repository](https://github.com/maticnetwork/matic-docs/issues). + ::: ## Identify an area to Contribute to @@ -26,7 +28,7 @@ There are several ways to identify an area where you can contribute to the Wiki: saying “I want to help contribute to the Polygon Wiki”. They’ll work with you to find an area for you to contribute. - If you have a specific contribution in mind but are unsure about it, confirm whether - the contribution is appropriate by contacting one of the [Wiki maintainers](/docs/contribute/community-maintainers)directly. + the contribution is appropriate by contacting one of the [Wiki maintainers](/docs/contribute/community-maintainers) directly. - If you do not have a specific contribution in mind, you can also browse the issues labelled as `help wanted` on the [Polygon GitHub repos](https://github.com/maticnetwork). - Issues that additionally have the `good first issue` label are considered ideal for @@ -38,7 +40,6 @@ There are several ways to identify an area where you can contribute to the Wiki: against the `master` branch (kindly check the sample PR). - The documentation team will review the PR or reach out accordingly. - Repository: https://github.com/maticnetwork/matic-docs - - Sample PR: https://github.com/maticnetwork/matic-docs/pull/360 :::tip If you want to run our Wiki locally on your machine, check the section [running the Wiki locally](https://github.com/maticnetwork/matic-docs#run-the-wiki-locally). If you are adding a new document, it is recommended to just have a basic summary/introduction and a link to your Github or documentation for more details. @@ -72,7 +73,7 @@ Try writing your commit message by targeting user functionality as often as you :::note Example -This is a standard git log `--oneline` to show how these information could be stored: +This is a standard git log `--oneline` to show how this information could be stored: ``` * 5a39f73 fix: encoding issues with non-ascii chars. diff --git a/docs/contribute/how-to-translate.md b/docs/contribute/how-to-translate.md index 6f52f96934..832283c13c 100644 --- a/docs/contribute/how-to-translate.md +++ b/docs/contribute/how-to-translate.md @@ -1,7 +1,7 @@ --- -id: how-to-translate -title: How to Translate -sidebar_label: Help with translations +id: translate +title: Help With Translations +sidebar_label: Help With Translations description: Learn how to help translate the Polygon Wiki. keywords: - docs @@ -11,13 +11,20 @@ keywords: - translation - contribute - language -image: https://matic.network/banners/matic-network-16x9.png -slug: how-to-translate +image: https://wiki.polygon.technology/img/polygon-logo.png +slug: translate --- -:::info Page is being updated +:::caution State of translations and localization efforts -Please see the **[Docusaurus guide](https://docusaurus.io/docs/i18n/crowdin#translate-the-sources)** -in the meantime. +We are committed to making the Polygon documentation accessible to a global audience and have added support for around fifteen languages, with more to come. However, the translations are still a work in progress, and we are working on automating the process to keep them up-to-date. We are also looking for native speakers in the community to help retranslate some sections and translate new content for the first time. Additionally, we are planning to support more languages in the future. + +::: + +:::info Help with translations + +We are also currently exploring options for translation management and may reactivate our use of [Crowdin](https://crowdin.com/) shortly for community contributions. Thank you for your patience and support as we continue to improve the localization of our documentation. + +Please see the **[Docusaurus guide](https://docusaurus.io/docs/i18n/crowdin#translate-the-sources)** in the meantime. ::: diff --git a/docs/contribute/non-native-speakers.md b/docs/contribute/non-native-speakers.md deleted file mode 100644 index ba7be0d279..0000000000 --- a/docs/contribute/non-native-speakers.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -id: non-native-speakers -title: Non-native Speakers -sidebar_label: Non-native speakers -description: Learn how to contribute to the Polygon Wiki as a non-native speaker. -keywords: - - docs - - matic - - polygon - - non-native - - speakers - - contribute - - language -image: https://matic.network/banners/matic-network-16x9.png -slug: non-native-speakers ---- - -:::info Page is being updated - -Please see the -**[OpenStack guide](https://docs.openstack.org/doc-contrib-guide/non-native-english-speakers.html)** -in the meantime. - -::: diff --git a/docs/contribute/tutorial-template.md b/docs/contribute/tutorial-template.md index edadb12a59..ee8d50eee9 100644 --- a/docs/contribute/tutorial-template.md +++ b/docs/contribute/tutorial-template.md @@ -1,7 +1,7 @@ --- id: tutorial-template title: General Tutorial Template -sidebar_label: Tutorial template +sidebar_label: Tutorial Template description: Follow the tutorial template when writing a technical tutorial. keywords: - docs @@ -11,26 +11,26 @@ keywords: - tutorial - contribute - template -image: https://matic.network/banners/matic-network-16x9.png -slug: tutorial-template +image: https://wiki.polygon.technology/img/polygon-logo.png +slug: tutorial-template --- -This template should be used when contributing a tutorial to the Polygon +This template should be used when contributing a tutorial to the Polygon Wiki. You may choose to contribute a tutorial on a topic of your choosing. ## General guidelines -* The tutorial's scope should be clear from the title. -* The tutorial should be able to accurately describe the features +* The tutorial's scope should be clear from the title. +* The tutorial should be able to accurately describe the features and functionalities of product(s) or service(s). * Try to keep the tutorial swift and concise, but expand on key concepts where appropriate. Give background information and further context when possible. -* For configuration and implementation steps, be specific. -* Please try your best to add supporting imagery, icons, or screenshots that - complement the written content. +* For configuration and implementation steps, be specific. +* Please try your best to add supporting imagery, icons, or screenshots that + complement the written content. > The documentation team would also be happy to work with you on creating diagrams. -* Remember the audience you are writing for. If the material has a certain difficulty - level it should be mentioned in the tutorial. +* Remember the audience you are writing for. If the material has a certain difficulty + level it should be mentioned in the tutorial. > If there are steps a user should take before running through a tutorial, please mention them. * The documentation would be happy to jointly work on creating a tutorial. * Remember to consider the **[Style guide](writing-style.md)**. @@ -41,7 +41,7 @@ If you notice that the current tutorials on the Polygon Wiki do not follow this template, it is because the documentation team decided to implement a standard, so the tutorial flow is consistent across all tutorials. The team is working on updating these tutorials -to resemble this template. If you are interested, you can also update an +to resemble this template. If you are interested, you can also update an existing tutorial to restructure it. ::: @@ -51,8 +51,8 @@ existing tutorial to restructure it. ### Overview Explain the product(s) or service(s) being discussed in the tutorial. -Give background information for the purpose of the tutorial and what the -tutorial aims to present. The tutorial should always be based on using a +Give background information for the purpose of the tutorial and what the +tutorial aims to present. The tutorial should always be based on using a Polygon product. ### What you'll learn @@ -61,24 +61,24 @@ Summarize what the user will learn throughout the tutorial. :::note Example -You'll explore how to use the Truffle Suite to build dApps +You'll explore how to use the Truffle Suite to build dApps Polygon. ::: #### Learning outcomes -Outline the learning outcomes. +Outline the learning outcomes. :::note Example 1. You will learn about Fauna. 2. You will learn how you can use ReactJS for the UI of your dApp. -3. You will learn how to safeguard dApp data. +3. You will learn how to safeguard dApp data. ::: -Mention prerequisites and what the user should +Mention prerequisites and what the user should already be familiar with. Link the necessary documentation for areas that the user should already be knowledgeable about. @@ -109,7 +109,7 @@ You will use Solidity to create a smart contract in a ChainIDE environment. ### The tutorial itself -In general, the tutorial can be presented in the best categorization that +In general, the tutorial can be presented in the best categorization that the writer sees fit; this should be reflected in the [What you'll do](#what-youll-do) section. However, the tutorial sections should touch on these three main categories: @@ -137,7 +137,7 @@ Outline next steps that the user can take. :::note Example -Congratulations on deploying your smart contract. You now know how to use ChainIDE +Congratulations on deploying your smart contract. You now know how to use ChainIDE to create and deploy smart contracts. Consider trying out "this tutorial". ::: diff --git a/docs/contribute/writing-style.md b/docs/contribute/writing-style.md index e74c40dcc8..b00d0e95fa 100644 --- a/docs/contribute/writing-style.md +++ b/docs/contribute/writing-style.md @@ -1,7 +1,7 @@ --- id: writing-style title: General Writing Guidelines -sidebar_label: General writing guidelines +sidebar_label: Writing Guidelines description: Follow the following guidelines when writing. keywords: - docs @@ -11,36 +11,36 @@ keywords: - writing - contribute - style -image: https://matic.network/banners/matic-network-16x9.png -slug: writing-style +image: https://wiki.polygon.technology/img/polygon-logo.png +slug: writing-style --- -This guideline focuses on best practices for writing technical documentation and -on the style conventions to use when developing documentation for the Polygon Wiki. -The goal of this guide is to help contributors write content that is clear, concise, +This guideline focuses on best practices for writing technical documentation and +on the style conventions to use when developing documentation for the Polygon Wiki. +The goal of this guide is to help contributors write content that is clear, concise, and consistent. The Polygon team treats the Polygon Wiki as an official Docs product. ## Primary guidelines -We believe one of the things that makes Polygon special is its coherent design and we -seek to retain this defining characteristic. The Polygon team treats the Polygon Wiki -as an official Docs product. From the outset we defined some guidelines to ensure new +We believe one of the things that makes Polygon special is its coherent design and we +seek to retain this defining characteristic. The Polygon team treats the Polygon Wiki +as an official Docs product. From the outset we defined some guidelines to ensure new contributions only ever enhance the overall project: -- **Quality**: Code in the Polygon project should meet the style guidelines, with - sufficient test-cases, descriptive commit messages, evidence that the contribution - does not break any compatibility commitments or cause adverse feature interactions, +- **Quality**: Code in the Polygon project should meet the style guidelines, with + sufficient test-cases, descriptive commit messages, evidence that the contribution + does not break any compatibility commitments or cause adverse feature interactions, and evidence of high-quality peer-review. -- **Size**: The Polygon project’s culture is one of small pull-requests, regularly - submitted. The larger a pull-request, the more likely it is that you will be asked +- **Size**: The Polygon project’s culture is one of small pull-requests, regularly + submitted. The larger a pull-request, the more likely it is that you will be asked to resubmit as a series of self-contained and individually reviewable smaller PRs. -- **Maintainability**: If the feature will require ongoing maintenance (e.g. support - for a particular brand of database), we may ask you to accept responsibility for +- **Maintainability**: If the feature will require ongoing maintenance (e.g. support + for a particular brand of database), we may ask you to accept responsibility for maintaining this feature. The Style guide takes motivation from the following style manuals: -> If you are unable to find the answer to a style, voice, or terminology question +> If you are unable to find the answer to a style, voice, or terminology question > in this guide, please consult these resources. - [Google's Style Guide](https://github.com/google/styleguide/blob/gh-pages/docguide/style.md) @@ -51,7 +51,7 @@ The Style guide takes motivation from the following style manuals: The Wiki is built using [Docusaurus](https://docusaurus.io/), a static-site generator for building documentation sites in markdown. The Wiki follows the following metadata -template for its markdown files and should be adpated for each new document: +template for its markdown files and should be adapted for each new document: ``` --- @@ -73,9 +73,9 @@ slug: community-maintainers ``` There are some important aspects to consider when writing the metadata for a markdown file: -- We ask contributors to use a **unique id**; avoid **only** using generic words or sentences like "Introduction" or "Overview". +- We ask contributors to use a **unique id**; avoid **only** using generic words or sentences like "Introduction" or "Overview". - The **title** is the sentence used at the beginning of the article, "General Writing Guidelines" for this article. So, it is not necessary to add an H1/H2 header to introduce each article. Instead, use this **title** from the metadata. -- The **description** can not be too lengthy, since it is used on the index tiles which has a limitation for the number of characters. For example, the description "Blockchain is an immutable ledger for recording transactions" for the *basics-blockchain.md* appears on an index tile as such: +- The **description** can not be too lengthy, since it is used on the index tiles which has a limitation for the number of characters. For example, the description "Blockchain is an immutable ledger for recording transactions" for the *basics-blockchain.md* appears on an index tile as such: ![img](/img/contribute/index-tile.png) The **description** then should have **up to 60 characters**, considering spaces between characters. @@ -83,30 +83,30 @@ There are some important aspects to consider when writing the metadata for a mar :::note -Please see the +Please see the [official metadata documentation](https://docusaurus.io/docs/next/api/plugins/@docusaurus/plugin-content-docs#markdown-front-matter) for more details. ::: ### Share the experience with the reader -- First Person: Do not use "I" or "me". Use the first person point of view sparingly and - with intention. When overused, the first person narrative can overwhelm the sense of a +- First Person: Do not use "I" or "me". Use the first person point of view sparingly and + with intention. When overused, the first person narrative can overwhelm the sense of a shared experience and obscure the reader’s journey. -- Second Person: In most cases, address the reader directly. For tutorials, use either first - person plural—we, us, our, ours—or second person point of view. Because tutorials provide - a more guided approach to a topic, using the first person plural is a more natural and +- Second Person: In most cases, address the reader directly. For tutorials, use either first + person plural—we, us, our, ours—or second person point of view. Because tutorials provide + a more guided approach to a topic, using the first person plural is a more natural and commonly-accepted practice than in other types of documentation. - Third Person: Do not use “we” to refer to Polygon or Polygon Technology. -- Active Voice: Use present tense whenever possible. There are situations where a passive +- Active Voice: Use present tense whenever possible. There are situations where a passive voice is appropriate; revert to passive voice when the agent needs to be the focus. -- Keep the human presence in mind: having a dynamic tone when describing technical concepts - really helps a reader connect with the material as opposed to describing software (or code) +- Keep the human presence in mind: having a dynamic tone when describing technical concepts + really helps a reader connect with the material as opposed to describing software (or code) only for what it does. -- Pronouns: use gender-neutral pronouns, like “they” whenever possible. Generally, you can - change any noun from singular to plural to have subject-verb-pronoun agreement and avoid the +- Pronouns: use gender-neutral pronouns, like “they” whenever possible. Generally, you can + change any noun from singular to plural to have subject-verb-pronoun agreement and avoid the use of gender-specific pronouns like “he”, “him”, “his” or “she”, “her”, “hers”. - - Be wary of impersonal and potentially ambiguous pronouns. If you use any of the following + - Be wary of impersonal and potentially ambiguous pronouns. If you use any of the following impersonal pronouns, be sure you answer “of what?”, “of which?”, or “as what?” in the sentence. - all, another, any - each, either @@ -115,19 +115,19 @@ Please see the - same, several, some, such - that, them, these, those -### Being swift and concise +### Being swift and concise - Documentation is strong and meaningful when the necessary words and right phrases are used. - Use common, well-known words whenever possible. - Avoid flowery language and excessive literary phrases. - Avoid jargon, colloquialisms, and idiomatic phrases. - - Avoid adverbs and subjective statements. For example, don’t use words and phrases that include - easily, rapidly, simply, quickly. If need be, it is also better to underexaggerate than to + - Avoid adverbs and subjective statements. For example, don’t use words and phrases that include + easily, rapidly, simply, quickly. If need be, it is also better to underexaggerate than to overexaggerate. - - Don’t use phrases that introduce ambiguity. For example, instead of “When this release is live...” + - Don’t use phrases that introduce ambiguity. For example, instead of “When this release is live...” use “After this release is live...”. - - Pay extra attention to with word choice. Choosing to use “since” (implying a period of time) instead - of “because” (implying cause and result) or using “once” (single occurrence) instead of “after” + - Pay extra attention to with word choice. Choosing to use “since” (implying a period of time) instead + of “because” (implying cause and result) or using “once” (single occurrence) instead of “after” (each time). - Avoid exclamation marks. - Avoid adding unnecessary words or phrases. Some examples: @@ -138,12 +138,12 @@ Please see the - Use a conversational tone that is not too formal, but should still be professional. - Clarity: give life to the word or phrase where possible. For example: - Rather than saying “e.g.”, use “for example”. - - Rather than saying “i.e.”, use “that is” or rewrite the sentence to make the meaning clear without + - Rather than saying “i.e.”, use “that is” or rewrite the sentence to make the meaning clear without needing extra qualification. - - Rather than saying “etc.”, use “and so on” or revise the content to make the term unnecessary. Instead + - Rather than saying “etc.”, use “and so on” or revise the content to make the term unnecessary. Instead of “etc.” to end a list of examples, focus on an example or two and use "such as" or "like". - Instead of “caveat”, use an appropriate English substitute such as “notice”, “caution”, or “warning”. - - Contractions give documentation a more natural conversational tone—at least for English speakers. + - Contractions give documentation a more natural conversational tone—at least for English speakers. Be conscious of when and why you use contractions. ## Structure @@ -156,29 +156,29 @@ The reader should understand what a paragraph is about from its first sentence. ## Product documentation -If you are writing about a specific product, ensure the document resembles that -product. Previously, the Polygon documentation was generalized, based around Polygon PoS. -Now that there are multiple Polygon-based products, contributors need be wary about their +If you are writing about a specific product, ensure the document resembles that +product. Previously, the Polygon documentation was generalized, based around Polygon PoS. +Now that there are multiple Polygon-based products, contributors need be wary about their additions. For instance, "Deploying a smart contract on Polygon using ####" is ambiguous. If this tutorial -was referring to Polygon PoS, it should be clear, as in, -"Deploying a smart contract on Polygon PoS using ####". Using the same example with a +was referring to Polygon PoS, it should be clear, as in, +"Deploying a smart contract on Polygon PoS using ####". Using the same example with a Polygon Rollup, like Polygon Hermez, "Deploying a smart contract on Polygon Hermez using ####". Ensure that the product documentation, whether a general guide or tutorial, is added -to the right product documentation Hub. For most documents, their reference should exist under -one of the general Hubs (e.g. "Develop" or "Validate"), but the actual document -will live under its product documentation. You will need reference the document in the Hub by +to the right product documentation Hub. For most documents, their reference should exist under +one of the general Hubs (e.g. "Develop" or "Validate"), but the actual document +will live under its product documentation. You will need reference the document in the Hub by adding it to `sidebars.js`. However, the actual document itself will exist in its respective product documentation Hub, -and it will redirect the user once they click on it. The same guideline applies to most -documents. Their reference should exist under one of the general Hubs, but the actual document +and it will redirect the user once they click on it. The same guideline applies to most +documents. Their reference should exist under one of the general Hubs, but the actual document will live under its product documentation. -Most of the API-based documentation on the Polygon Wiki are in the form of -reference documentation, with the exception of the APIs mentioned in tutorials. -For instance, the API documentation on Matic.js provides information about the +Most of the API-based documentation on the Polygon Wiki are in the form of +reference documentation, with the exception of the APIs mentioned in tutorials. +For instance, the API documentation on Matic.js provides information about the structure, parameters, and return values for each function or method in the API. ## API documentation @@ -190,7 +190,7 @@ Consider the following when documenting an API: * A full parameter list: * Parameter types * Syntax expressions with placeholders showing available parameters - * Special formatting + * Special formatting * Code examples for multiple languages. * A sample call with the expected output. * Error Codes. Edge cases. diff --git a/docs/delegate/delegate.md b/docs/delegate/delegate.md new file mode 100644 index 0000000000..10be36c7fc --- /dev/null +++ b/docs/delegate/delegate.md @@ -0,0 +1,171 @@ +--- +id: delegate +title: How to Delegate +description: Learn how to become a delegator on the Polygon Network. +keywords: + - docs + - matic + - polygon + - how to delegate + - validator + - stake +image: https://wiki.polygon.technology/img/polygon-logo.png +slug: delegate +--- +import useBaseUrl from '@docusaurus/useBaseUrl'; + +# How to Delegate + +This is a step-by-step guide to help you become a [delegator](/docs/maintain/glossary.md#delegator) on the Polygon Network. + +The only prerequisite is to have your MATIC tokens and ETH on the Ethereum mainnet address. + +## Access the dashboard + +1. In your wallet (e.g. MetaMask), choose the Ethereum mainnet. + +
+ +
+
+ +2. Log in to [Polygon Staking](https://staking.polygon.technology/). +3. Once you log in, you will see some overall statistics along with the list of validators. + +![img](/img/staking/home.png) + +:::note + +If you are a validator, use a different non-validating address to log in as delegator. + +::: + +## Delegate to a Validator + +1. Click **Become a Delegator** or scroll down to a specific validator and click **Delegate**. + +![img](/img/staking/home.png) + +2. Provide the amount of MATIC to delegate. + +
+ +
+
+ +3. Approve the delegation transaction and click **Delegate**. + +
+ +
+
+ +After the delegation transaction completes, you will see the **Delegation Completed** message. + +
+ +
+
+ +## View your delegations + +To view your delegations, click [My Account](https://staking.polygon.technology/account). + +![img](/img/staking/myAccount.png) + +## Withdraw rewards + +1. Click [My Account](https://staking.polygon.technology/account). + +
+ +
+
+ +2. Under your delegated validator, click **Withdraw Reward**. + +
+ +
+
+ +This will withdraw the MATIC token rewards to your Ethereum address. + +## Restake rewards + +1. Click [My Account](https://staking.polygon.technology/account). + +
+ +
+
+ +2. Under your delegated validator, click **Restake Reward**. + +
+ +
+
+ +This will restake the MATIC token rewards to the validator and increase your delegation stake. + +## Unbond from a Validator + +1. Click [My Account](https://staking.polygon.technology/account). + +
+ +
+
+ +2. Under your delegated validator, click **Unbond**. + +
+ +
+
+ +This will withdraw your rewards from the validator and your entire stake from the validator. + +Your withdrawn rewards will show up immediately on your Ethereum account. + +Your withdrawn stake funds will be locked for 80 [checkpoints](/docs/maintain/glossary.md#checkpoint-transaction). + +
+ +
+
+ +:::note + +The fund locking for the unbonding period is in place to ensure there is no malicious behaviour on the network. + +::: + +## Move stake from one node to another node + +Moving stake from one node to another node is a single transaction. There are no delays or unbonding periods during this event. + +1. Log in to the [My Account](https://wallet.polygon.technology/staking/my-account) on the Staking dashboard. +1. Click **Move Stake** under your delegated validator. +1. Select an external validator and click **Stake here**. + +
+ +
+
+ +4. Provide the stake amount and click **Move Stake**. + +
+ +
+
+ +This will move the stake. The dashboard will update after 12 block confirmations. + +:::info + +Moving stake is allowed between any nodes. The only exception is moving stake from one Foundation node to another Foundation node which is not allowed. + +::: diff --git a/docs/delegate/delegator-faq.md b/docs/delegate/delegator-faq.md new file mode 100644 index 0000000000..25a9583c73 --- /dev/null +++ b/docs/delegate/delegator-faq.md @@ -0,0 +1,241 @@ +--- +id: delegator-faq +title: Delegator FAQ +sidebar_label: Delegator FAQ +description: FAQs related to Delegation on Polygon network +keywords: + - docs + - polygon + - how to delegate + - validator + - stake + - faq + - delegator +image: https://wiki.polygon.technology/img/polygon-logo.png +--- +import useBaseUrl from '@docusaurus/useBaseUrl'; + +### What is the Staking Dashboard URL? + +The staking dashboard URL is https://staking.polygon.technology/. + +### What is the minimum stake amount? + +There is no minimum stake amount to delegate. However, you can always start with 1 MATIC token. + +### How many rewards will I get if I delegate? + +Please use the [Staking Rewards Calculator](https://staking.polygon.technology/rewards-calculator) to determine your estimates. + +### Why does my transaction take so long? + +All staking transactions of Polygon happen on Ethereum for security reasons. + +The time taken to complete a transaction depends on the gas fees that you have allowed and also the network congestion of Ethereum mainnet at that point in time. You can always use the “Speed Up” option to increase the gas fees so that your transaction can be completed soon. + +### Which wallets are currently supported? + +Currently, only the MetaMask extension on the desktop browser and Coinbase Wallet are supported. Additionally you can use WalletConnect and Walletlink from supported mobile wallets to interact with the Staking UI dashboard on desktop / laptop. We will be gradually adding support for other wallets soon. + +### Are hardware wallets supported? + +Yes, hardware wallets are supported. You can use the "Connect Hardware Wallet" option on MetaMask and connect your Hardware wallet and then continue the delegation process. + +### Why can’t I stake directly from Binance? + +Staking through Binance is not yet supported. There will be an announcement if and when Binance starts supporting it. + +### I have completed my delegation, where can I check details? + +Once you have completed your delegation, wait for 12 block confirmations on Ethereum (approx. 3-5 minutes), then on the Dashboard, you can click on **My Account**. + +
+ +
+ +### Where can I check my rewards? + +On the Dashboard, you can click on the **My Account** option on the left-hand side. + +
+ +
+ +### Do I need ETH to pay for Gas fees? + +Yes. You should provision for ~0.05-0.1 ETH to be safe. + +### Do I need to deposit MATIC tokens to the Polygon Mainnet network for staking? + +No. All your funds need to be on the Main Ethereum Network. + +### When I try to do the transaction my Confirm button is disabled, why so? + +Please check if you have enough ETH for the gas fees. + +### When does reward get distributed? + +The rewards are distributed whenever a checkpoint is submitted. + +Currently, 20188 MATIC tokens are distributed proportionately on each successful checkpoint submission to each delegator based on their stake relative to the overall staking pool of all validators and delegators. Also, the percentage for the reward distributed to each delegator will vary with each checkpoint depending on the relative stake of the delegator, validator and the overall stake. + +(Note that there is a 10% proposer bonus that accrues to the validator who submits the checkpoint, but over time, the effect of the extra bonus is nullified over multiple checkpoints by different validators.) + +The checkpoint submission is done by one of the validators approximately every 34 minutes. This time is approximate and may vary based on validator consensus on the Polygon Heimdall layer. This may also vary based on Ethereum Network. Higher congestion in the network may result in delayed checkpoints. + +You can track checkpoints on the staking contract [here](https://etherscan.io/address/0x86e4dc95c7fbdbf52e33d563bbdb00823894c287) + +### Why does reward keep getting decreased every checkpoint? + +Actual rewards earned will depend on the actual total locked supply in the network at each checkpoint. This is expected to vary significantly as more MATIC tokens get locked in the staking contracts. + +Rewards will be higher, to begin with, and will keep decreasing as the locked supply % goes up. This change in locked supply is captured at every checkpoint, and rewards are calculated based on this. + +### How can I claim my rewards? + +You can claim your rewards instantly by clicking on the **Withdraw Reward** button. This will transfer the rewards accumulated to your delegated account on Metamask. + +
+ +
+ +### What is the Unbonding period? + +The unbonding period on Polygon is approximately 9 days now. It was 19 days previously. This period applies to the originally delegated amount and re-delegated amounts - it does not apply to any rewards that were not re-delegated. + +### Will I keep receiving rewards after I unbond? + +No. Once you unbond, you will stop receiving rewards. + +### How many transactions does the delegation require? + +Delegation requires 2 transactions, one after the other. One to **Approve** the request and another to **Deposit**. + +
+ +
+ +### What does Redelegate Rewards mean? + +Redelegating your rewards simply means that you want to increase your stake by restaking the rewards you have accumulated. + +### Can I stake to any validator? + +Yes. All validators are Polygon Foundation nodes currently. + +We are doing a phased rollout of the Polygon Mainnet. Later on, external validators will be onboarded gradually. Please see https://blog.matic.network/mainnet-is-going-live-announcing-the-launch-sequence/ for more details. + +### Which browser is compatible with Staking Dashboard? + +Chrome, Firefox, and Brave + +### My MetaMask is stuck at confirming after login, what do I do? Or nothing happens when I try to login? + +Check for the following: + +- If you’re using Brave, please turn off the option for **Use Crypto Wallets** in the settings panel. +- Check if you are logged into Metamask +- Check if you are logged into MetaMask with Trezor/Ledger. You need to additionally turn on permission to call contracts on your Ledger device, if not enabled already. +- Check your system timestamp. If the system time is not correct, you will need to correct it. + +### How do I send funds from Binance or other exchanges to Polygon wallet? + +Technically, the Polygon Wallet Suite/Staking interface is just a web application. Currently it supports the following wallets - Metamask, WalletConnect, and WalletLink. + +First, you must withdraw your funds from Binance or any other exchange to your Ethereum address on Metamask. If you don't know how to use Metamask, google it a bit. There are plenty of videos and blogs to get started with it. + +### When can I become a validator and how many tokens do I for that? + +A user can earn a validator spot only by if the below conditions come into play: +1. When a validator decides to unstake from the network, or +2. Wait for the auction mechanism and replace the inactive validator. + +The minimum stake depends on the auction process where one user outbids another. + +### If I have earned rewards while delegating, and if I add additional funds to the same validator node, what happens? + +If you have not re-delegated your rewards before delegating additional funds to the same validator node, your rewards will be withdrawn automatically. + +In case you dont want that to happen, re-delegate your rewards before delegating additional funds. + +### I have delegated my tokens via MetaMask on the Staking dashboard. Do I need to keep my system or device on? + +No. Once your Delegation transactions are confirmed, and you can see your tokens reflected in the **Total Stake** and **New Reward** sections, then you are done. There is no need to keep your system or device on. + +### I have unbonded, how long will it take to Unbond? + +The unbonding period is currently set to 82 checkpoints. This is approximately 9 days. Every checkpoint takes approximately 34 minutes. However, some checkpoints could be delayed upto ~1 hour due to congestion on Ethereum. + +### I have unbonded, and I now see the Claim Stake button, but it is disabled, why is that? + +The Claim Stake button will only be enabled when your unbonding period is complete. The unbonding period is currently set at 82 checkpoints. + +### Do I know when will the Claim Stake button be enabled? + +Yes, under the Claim Stake button you would see a note on how many checkpoints are pending before the Claim Stake button would be enabled. Every checkpoint takes approximately 30 minutes. However, some checkpoints could be delayed upto ~1 hour due to congestion on Ethereum. + +
+ +
+ +### How do I switch my delegation from Foundation Nodes to External nodes? + +You can switch your Delegation using the **Move Stake** option on the Staking UI. This will switch your Delegation from the Foundation node to any other external node of your choice. + +
+ +
+ +You will see a list of other validators: + +
+ +
+ +### Will there be any ubonding period when I switch Delegation from Foundation nodes to external nodes? + +There will be no Unbonding period when you switch Delegation from foundation nodes to external nodes. It will be a direct switch without any delays. However, if you are unbonding from a Foundation Node or an External node there will be an Unbonding period for that. + +### Are they any specifics to choose an external node during switch delegation? + +No. You can choose any node of your choice. + +### What happens to my rewards that are accumalated if I switch delegation from Foundation to External node? + +If you haven't already claimed your rewards before switching delegation, then upon successful switch of your delegation from Foundation to External the Rewards that were accumalated till then will be transferred back to your account. + +### Will delegation on the External Nodes work the same as Foundation Nodes? + +Yes, it will work the same as Foundation nodes. + +### Will I still get rewards after delegating to an External Node? + +Yes, rewards will be distributed the same as earlier with the Foundation nodes. Every successful submission of a checkpoint will yield in rewards. Rewards will be distributed and calculated at every checkpoint relative to the stake ratio, as currently implemented. + +### Will there be any unbonding period if I unbond from an External Node? + +Yes, the unbonding period will stay the same as currently implemented. 82 Checkpoints. + +### Will there be any locking period after I switch my Delegation from Foundation to External node? + +No. There won't be any locking period after you switch your delegation. + +### Can I partially switch my delegation from Foundation to External nodes? + +Yes, you will have the option to partially move your stake from Foundation node to an external node. The remaining partial stake will remain on the Foundation node. You can then move that to another node of your choice or the same node. + +### Can I switch delegation from an external node to another external node? + +No, the **Move Stake** option is only available on the Foundation Nodes. If you want to switch your delegation from an external node to another external node, you will have to unbond first and then delegate to another external node. + +### When will the Foundations node be turned off? + +The foundation nodes will be turned off by the end of January, 2021. + +### Will there be any Foundation nodes in the future? + +No, there won't be any Foundation nodes in the future. + +### How many transactions do I need to pay for Gas when I do a Move Stake? + +The Move Stake is a single transaction only. All transactions would be on the Ethereum Blockchain so you would need to spend some ETH while doing the Move Stake transaction. diff --git a/docs/faq/staking-faq.md b/docs/delegate/staking-faq.md similarity index 76% rename from docs/faq/staking-faq.md rename to docs/delegate/staking-faq.md index bd1fb69fad..10a19cc4db 100644 --- a/docs/faq/staking-faq.md +++ b/docs/delegate/staking-faq.md @@ -6,19 +6,19 @@ description: Build your next blockchain app on Polygon. keywords: - docs - matic -image: https://matic.network/banners/matic-network-16x9.png +image: https://wiki.polygon.technology/img/polygon-logo.png --- import useBaseUrl from '@docusaurus/useBaseUrl'; ### How to stake tokens on Polygon? -For Staking you would need to have funds on the Ethereum Mainnet (more information [here](https://etherscan.io/gastracker)). Log into Metamask on the Ethereum network using the Staking Dashboard. https://staking.polygon.technology/ +For Staking you would need to have funds on the Ethereum Mainnet (more information [here](https://etherscan.io/gastracker)). Log into MetaMask on the Ethereum network using the Staking Dashboard. https://staking.polygon.technology/ Please watch this video for a graphical illustration of how this works: @@ -27,8 +27,8 @@ You can navigate to "Your Delegations", choose one of the stakes and click on "S Please watch this video for a graphical illustration of how this works: -