Compare commits

...

9 Commits

Author SHA1 Message Date
Alex Ant de3e27493c Russification 2026-03-22 12:33:35 +05:00
Alex Ant 4d324084e8 bump version 2025-10-15 21:50:04 +05:00
Alex Ant eae8cd24f4 fix types 2025-10-15 10:50:05 +05:00
Alex Ant 0529c28563 Реализация вызова метода assert_recover_key_account 2025-10-15 01:45:39 +05:00
Dark Sun 3e7f4e7254 update Dockerfile 2024-04-10 17:47:14 +03:00
Dark Sun 3be71635ac Dockerfile 2024-04-10 17:13:09 +03:00
Dark Sun e6c412e2c3 Dockerfile 2024-04-10 17:12:03 +03:00
Dark Sun 960076f4ce update version 2024-04-10 10:38:12 +03:00
Dark Sun 7d12b93e7e add get_account_ram_usage method 2024-04-09 18:45:15 +03:00
60 changed files with 7057 additions and 2065 deletions
+1
View File
@@ -1,3 +1,4 @@
tmp/
# Prerequisites
*.d
+3 -3
View File
@@ -14,9 +14,9 @@ endif()
project(cdt)
set(VERSION_MAJOR 4)
set(VERSION_MINOR 0)
set(VERSION_PATCH 1)
set(VERSION_SUFFIX "rc1")
set(VERSION_MINOR 2)
set(VERSION_PATCH 0)
# set(VERSION_SUFFIX "rc1")
if (VERSION_SUFFIX)
set(VERSION_FULL "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}-${VERSION_SUFFIX}")
+9
View File
@@ -0,0 +1,9 @@
FROM ubuntu:latest
WORKDIR /workdir
COPY build/cdt_*.deb /workdir
RUN apt-get update && apt-get install -y wget cmake build-essential g++ libboost-all-dev libz3-dev && \
apt install ./cdt_*.deb -y && \
rm cdt_*.deb
+40 -14
View File
@@ -1,4 +1,5 @@
# Doxyfile 1.8.9.1
# HTML: doxygen-awesome + кастомные header/footer — используйте Doxygen 1.9.x или новее.
# This file describes the settings to be used by the documentation system
# doxygen (www.doxygen.org) for a project.
@@ -32,19 +33,19 @@ DOXYFILE_ENCODING = UTF-8
# title of most generated pages and in a few other places.
# The default value is: My Project.
PROJECT_NAME = "Eos"
PROJECT_NAME = CDT
# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
# could be handy for archiving the generated documentation or if some version
# control system is used.
PROJECT_NUMBER =
PROJECT_NUMBER = v4.2.0
# Using the PROJECT_BRIEF tag one can provide an optional one line description
# for a project that appears at the top of each page and should give viewer a
# quick idea about the purpose of the project. Keep the description short.
PROJECT_BRIEF =
PROJECT_BRIEF = инструменты разработчика
# With the PROJECT_LOGO tag one can specify a logo or an icon that is included
# in the documentation. The maximum height of the logo should not exceed 55
@@ -91,7 +92,7 @@ ALLOW_UNICODE_NAMES = NO
# Ukrainian and Vietnamese.
# The default value is: English.
OUTPUT_LANGUAGE = English
OUTPUT_LANGUAGE = Russian
# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member
# descriptions after the members that are listed in the file and class
@@ -677,7 +678,7 @@ FILE_VERSION_FILTER =
# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
# tag is left empty.
LAYOUT_FILE =
LAYOUT_FILE = docs/DoxygenLayout.xml
# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
# the reference definitions. This must be a list of .bib files. The .bib
@@ -758,7 +759,9 @@ WARN_LOGFILE =
# spaces.
# Note: If this tag is empty the current directory is searched.
INPUT = libraries/eosiolib/core libraries/eosiolib/contracts
INPUT = README.md \
libraries/eosiolib/core \
libraries/eosiolib/contracts
# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
@@ -894,7 +897,7 @@ FILTER_SOURCE_PATTERNS =
# (index.html). This can be useful if you have a project on for instance GitHub
# and want to reuse the introduction page also for the doxygen output.
USE_MDFILE_AS_MAINPAGE =
USE_MDFILE_AS_MAINPAGE = README.md
#---------------------------------------------------------------------------
# Configuration options related to source browsing
@@ -1050,7 +1053,7 @@ HTML_FILE_EXTENSION = .html
# of the possible markers and block names see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_HEADER =
HTML_HEADER = docs/css/docs/doxygen-custom/header.html
# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
# generated HTML page. If the tag is left blank doxygen will generate a standard
@@ -1060,7 +1063,7 @@ HTML_HEADER =
# that doxygen normally uses.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FOOTER =
HTML_FOOTER = docs/css/docs/doxygen-custom/footer.html
# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
# sheet that is used by each HTML page. It can be used to fine-tune the look of
@@ -1085,7 +1088,7 @@ HTML_STYLESHEET =
# list). For an example see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_STYLESHEET =
HTML_EXTRA_STYLESHEET = docs/css/doxygen-awesome.css docs/css/docs/doxygen-custom/custom.css docs/css/doxygen-awesome-sidebar-only.css docs/css/doxygen-awesome-sidebar-only-darkmode-toggle.css
# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the HTML output directory. Note
@@ -1095,7 +1098,7 @@ HTML_EXTRA_STYLESHEET =
# files will be copied as-is; there are no commands or markers available.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_FILES =
HTML_EXTRA_FILES = docs/css/doxygen-awesome-darkmode-toggle.js docs/css/mermaid.min.js docs/css/docs/doxygen-custom/custom.js
# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
# will adjust the colors in the style sheet and background images according to
@@ -1133,7 +1136,18 @@ HTML_COLORSTYLE_GAMMA = 80
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_TIMESTAMP = YES
HTML_TIMESTAMP = NO
# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML
# documentation will contain a main index with vertical navigation menus that
# are dynamically created via JavaScript. If disabled, the navigation index will
# consists of multiple levels of tabs that are statically embedded in every HTML
# page. Disable this option to support browsers that do not have JavaScript,
# like the Qt help browser.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_DYNAMIC_MENUS = YES
# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
# documentation will contain sections that can be hidden and shown after the
@@ -1370,7 +1384,19 @@ DISABLE_INDEX = NO
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_TREEVIEW = NO
GENERATE_TREEVIEW = YES
# When both GENERATE_TREEVIEW and DISABLE_INDEX are set to YES, then the
# FULL_SIDEBAR option determines if the side bar is limited to only the treeview
# area (value NO) or if it should extend to the full height of the window (value
# YES). Setting this to YES gives a layout similar to
# https://docs.readthedocs.io with more room for contents, but less room for the
# project logo, title, and description. If either GENERATE_TREEVIEW or
# DISABLE_INDEX is set to NO, this option has no effect.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
FULL_SIDEBAR = NO
# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
# doxygen will group on one line in the generated HTML documentation.
@@ -1387,7 +1413,7 @@ ENUM_VALUES_PER_LINE = 4
# Minimum value: 0, maximum value: 1500, default value: 250.
# This tag requires that the tag GENERATE_HTML is set to YES.
TREEVIEW_WIDTH = 250
TREEVIEW_WIDTH = 200
# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to
# external symbols imported via tag files in a separate window.
+58 -65
View File
@@ -1,38 +1,39 @@
# CDT (Contract Development Toolkit)
Contract Development Toolkit (CDT) is a C/C++ toolchain targeting WebAssembly (WASM) and a set of tools to facilitate development of smart contracts written in C/C++ that are meant to be deployed to an [Antelope](https://github.com/AntelopeIO/) blockchain.
**Contract Development Toolkit (CDT)** — это цепочка инструментов C/C++ для сборки WebAssembly (WASM) и набор утилит для разработки смарт-контрактов на C/C++, предназначенных для развёртывания в блокчейне **COOPOS** (совместим с протоколом [Antelope](https://github.com/AntelopeIO/)).
In addition to being a general purpose WebAssembly toolchain, specific features and optimizations are available to support building Antelope-based smart contracts. This new toolchain is built around [Clang 9](https://github.com/AntelopeIO/cdt-llvm), which means that CDT inherits the optimizations and analyses from that version of LLVM, but as the WASM target is still considered experimental, some optimizations are incomplete or not available.
Помимо универсальной сборки WebAssembly, CDT добавляет возможности и оптимизации именно под смарт-контракты. Инструментарий опирается на [Clang 9](https://github.com/coopenomics/cdt-llvm) и LLVM этого поколения; целевой WASM по-прежнему считается экспериментальным, поэтому часть оптимизаций может быть неполной или недоступной.
## Repo organization
## Структура репозитория
The `main` branch is the development branch: do not use this for production. Refer to the [release page](https://github.com/AntelopeIO/cdt/releases) for current information on releases, pre-releases, and obsolete releases as well as the corresponding tags for those releases.
## Binary packages
Ветка `main` — ветка разработки: **не используйте её в продакшене**. Актуальные релизы, пре-релизы и устаревшие версии смотрите на [странице релизов](https://github.com/coopenomics/cdt/releases) и по соответствующим тегам.
CDT currently supports Linux x86_64 Debian packages. Visit the [release page](https://github.com/AntelopeIO/cdt/releases) to download the package for the appropriate version of CDT. This is the fastest way to get started with the software.
### Debian package install
## Бинарные пакеты
Download the appropriate version of the Debian package and then install it. To download and install the latest version, run the following:
Поддерживаются пакеты Debian для Linux x86_64. Скачать сборку под нужную версию CDT можно на [странице релизов](https://github.com/coopenomics/cdt/releases) — это самый быстрый способ начать работу.
### Установка пакета Debian
Скачайте подходящий `.deb` и установите. Пример для актуального релиза **v4.2.0** (другие версии — на странице релизов):
```sh
wget https://github.com/AntelopeIO/cdt/releases/download/v4.0.0/cdt_4.0.0_amd64.deb
sudo apt install ./cdt_4.0.0_amd64.deb
wget https://github.com/coopenomics/cdt/releases/download/v4.2.0/cdt_4.2.0-1_amd64.deb
sudo apt install ./cdt_4.2.0-1_amd64.deb
```
### Debian package uninstall
To remove CDT that was installed using a Debian package, simply execute the following command:
### Удаление пакета Debian
```sh
sudo apt remove cdt
```
## Building from source
## Сборка из исходников
Recent Ubuntu LTS releases are the only Linux distributions that we fully support. Other Linux distros and other POSIX operating systems (such as macOS) are tended to on a best-effort basis and may not be full featured.
Полностью поддерживаются недавние LTS-релизы Ubuntu. Другие дистрибутивы Linux и POSIX-системы (включая macOS) — по возможности, без гарантии полного набора функций.
The instructions below assume that you are building on Ubuntu 20.04.
Ниже предполагается **Ubuntu 20.04**.
### Install dependencies
### Зависимости
```sh
apt-get update && apt-get install \
@@ -51,36 +52,32 @@ apt-get update && apt-get install \
python3 -m pip install pygments
```
### Allowing integration tests to build
### Интеграционные тесты
Integration tests require access to a build of [Leap](https://github.com/AntelopeIO/leap), a C++ implementation of the Antelope protocol. Simply installing Leap from a binary package will not be sufficient.
Для них нужна сборка [Leap](https://github.com/AntelopeIO/leap) (реализация протокола Antelope) из исходников; одного бинарного пакета Leap обычно недостаточно.
If you do not wish to build Leap, you can continue with building CDT but without building the integration tests. Otherwise, follow the instructions below before running `cmake`.
First, ensure that Leap has been built from source (see Leap's [README](https://github.com/AntelopeIO/leap#building-from-source) for details) and identify the build path, e.g. `/path/to/leap/build/`.
Then, execute the following command in the same terminal session that you will use to build CDT:
Если Leap собирать не планируете, CDT можно собрать без интеграционных тестов. Иначе перед `cmake` в той же сессии терминала задайте путь к сборке Leap, например:
```sh
export leap_DIR=/path/to/leap/build/lib/cmake/leap
```
Now you can continue with the steps to build CDT as described. When you run `cmake` make sure that it does not report `leap package not found`. If it does, this means CDT was not able to find a build of Leap at the specified path in `leap_DIR` and will therefore continue without building the integration tests.
Далее при `cmake` не должно появляться сообщения вроде `leap package not found`; иначе интеграционные тесты не соберутся.
### ccache
If issues persist with ccache when building CDT, you can disable ccache:
При проблемах со сборкой через ccache можно отключить его:
```sh
export CCACHE_DISABLE=1
```
### Build CDT
### Сборка CDT
**A Warning On Parallel Compilation Jobs (`-j` flag)**: When building C/C++ software often the build is performed in parallel via a command such as `make -j $(nproc)` which uses the number of CPU cores as the number of compilation jobs to perform simultaneously. However, be aware that some compilation units (.cpp files) in CDT are extremely complex and can consume a large amount of memory to compile. If you are running into issues due to amount of memory available on your build host, you may need to reduce the level of parallelization used for the build. For example, instead of `make -j $(nproc)` you can try `make -j2`. Failures due to memory exhaustion will typically but not always manifest as compiler crashes.
**Параллельная сборка (`-j`)**: часть единиц трансляции в CDT очень тяжёлые по памяти. Если компилятор падает или нехватает RAM, уменьшите параллелизм, например `make -j2` вместо `make -j $(nproc)`.
```sh
git clone --recursive https://github.com/AntelopeIO/cdt
git clone --recursive https://github.com/coopenomics/cdt
cd cdt
mkdir build
cd build
@@ -88,69 +85,65 @@ cmake ..
make -j $(nproc)
```
The binaries will be located at in the `build/bin` directory. You can export the path to the directory to your `PATH` environment variable which allows you to conveniently use them to compile contracts without installing CDT globally. Alternatively, you can use CMake toolchain file located in `build/lib/cmake/CDTWasmToolchain.cmake` to compile the contracts in your CMake project, which also allows you to avoid installing CDT globally.
Исполняемые файлы — в `build/bin`. Можно добавить каталог в `PATH`, либо использовать CMake toolchain `build/lib/cmake/CDTWasmToolchain.cmake` в своём проекте без глобальной установки CDT.
If you would prefer to install CDT globally, see the section [Install CDT](#install-cdt) below.
Глобальная установка описана в разделе [Установка CDT](#установка-cdt).
#### Build CDT in debug mode
#### Отладочная сборка
To build CDT in debug mode (with debug symbols) you need to add the following flags to cmake command:
```sh
cmake -DCMAKE_BUILD_TYPE="Debug" -DTOOLS_BUILD_TYPE="Debug" -DLIBS_BUILD_TYPE="Debug" ..
```
### Run tests
### Тесты
#### Run unit tests
#### Модульные
```sh
cd build
ctest
```
#### Run integration tests (if built)
#### Интеграционные (если собирались)
```sh
cd build/tests/integration
ctest
```
### Install CDT
### Установка CDT
Installing CDT globally on your system will install the following tools in a location accessible to your `PATH`:
Глобальная установка добавляет в `PATH`, среди прочего:
* cdt-abidiff
* cdt-ar
* cdt-cc
* cdt-cpp
* cdt-init
* cdt-ld
* cdt-nm
* cdt-objcopy
* cdt-objdump
* cdt-ranlib
* cdt-readelf
* cdt-strip
* eosio-pp
* eosio-wasm2wast
* eosio-wast2wasm
* cdt-abidiff
* cdt-ar
* cdt-cc
* cdt-cpp
* cdt-init
* cdt-ld
* cdt-nm
* cdt-objcopy
* cdt-objdump
* cdt-ranlib
* cdt-readelf
* cdt-strip
* eosio-pp
* eosio-wasm2wast
* eosio-wast2wasm
It will also install CMake files for CDT accessible within a `cmake/cdt` directory located within your system's `lib` directory.
#### Manual installation
Также ставятся CMake-файлы CDT (каталог `cmake/cdt` в системном `lib`).
One option for installing CDT globally is via `make install`. From within the `build` directory, run the following command:
#### Ручная установка
Из каталога `build`:
```
sudo make install
```
#### Package installation
#### Установка из собранного пакета
A better option for installing CDT globally is to generate a package and then install the package. This makes uninstalling CDT much easier.
From within the `build` directory, run the following commands to generate a Debian package:
Удобнее сгенерировать пакет и поставить его — так проще удалить CDT позже.
```sh
cd packages
@@ -158,9 +151,9 @@ bash ./generate_package.sh deb ubuntu-20.04 amd64
sudo apt install ./cdt_*_amd64.deb
```
### Uninstall CDT
### Удаление CDT
#### Uninstall CDT after manual installation with make
#### После `make install`
```sh
sudo rm -fr /usr/local/cdt
@@ -169,12 +162,12 @@ sudo rm /usr/local/bin/eosio-*
sudo rm /usr/local/bin/cdt-*
```
#### Uninstall CDT that was installed using a Debian package
#### После пакета Debian
```sh
sudo apt remove cdt
```
## License
## Лицензия
[MIT](./LICENSE)
+233
View File
@@ -0,0 +1,233 @@
<doxygenlayout version="1.0">
<!-- Шаблон навигации как в monocoop/contracts; Doxygen ≥ 1.9 рекомендуется для doxygen-awesome -->
<navindex>
<tab type="mainpage" visible="yes" title="Главная" intro=""/>
<tab type="modules" visible="yes" title="Группы" intro=""/>
<tab type="classes" visible="yes" title="">
<tab type="classlist" visible="yes" title="" intro=""/>
<tab type="classindex" visible="$ALPHABETICAL_INDEX" title=""/>
<tab type="hierarchy" visible="yes" title="" intro=""/>
<tab type="classmembers" visible="yes" title="" intro=""/>
</tab>
<tab type="namespaces" visible="yes" title="">
<tab type="namespacelist" visible="yes" title="" intro=""/>
<tab type="namespacemembers" visible="yes" title="" intro=""/>
</tab>
<tab type="concepts" visible="yes" title="">
</tab>
<tab type="interfaces" visible="yes" title="">
<tab type="interfacelist" visible="yes" title="" intro=""/>
<tab type="interfaceindex" visible="$ALPHABETICAL_INDEX" title=""/>
<tab type="interfacehierarchy" visible="yes" title="" intro=""/>
</tab>
<tab type="structs" visible="yes" title="">
<tab type="structlist" visible="yes" title="" intro=""/>
<tab type="structindex" visible="$ALPHABETICAL_INDEX" title=""/>
</tab>
<tab type="exceptions" visible="yes" title="">
<tab type="exceptionlist" visible="yes" title="" intro=""/>
<tab type="exceptionindex" visible="$ALPHABETICAL_INDEX" title=""/>
<tab type="exceptionhierarchy" visible="yes" title="" intro=""/>
</tab>
<tab type="files" visible="yes" title="Файлы" intro="Исходники библиотек eosiolib (CDT)">
<tab type="filelist" visible="yes" title="Обозреватель" intro=""/>
<tab type="globals" visible="yes" title="" intro="Список членов"/>
</tab>
</navindex>
<class>
<briefdescription visible="yes"/>
<includes visible="$SHOW_HEADERFILE"/>
<inheritancegraph visible="$CLASS_GRAPH"/>
<collaborationgraph visible="$COLLABORATION_GRAPH"/>
<memberdecl>
<nestedclasses visible="yes" title=""/>
<publictypes title=""/>
<services title=""/>
<interfaces title=""/>
<publicslots title=""/>
<signals title=""/>
<publicmethods title=""/>
<publicstaticmethods title=""/>
<publicattributes title=""/>
<publicstaticattributes title=""/>
<protectedtypes title=""/>
<protectedslots title=""/>
<protectedmethods title=""/>
<protectedstaticmethods title=""/>
<protectedattributes title=""/>
<protectedstaticattributes title=""/>
<packagetypes title=""/>
<packagemethods title=""/>
<packagestaticmethods title=""/>
<packageattributes title=""/>
<packagestaticattributes title=""/>
<properties title=""/>
<events title=""/>
<privatetypes title=""/>
<privateslots title=""/>
<privatemethods title=""/>
<privatestaticmethods title=""/>
<privateattributes title=""/>
<privatestaticattributes title=""/>
<friends title=""/>
<related title="" subtitle=""/>
<membergroups visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
<memberdef>
<inlineclasses title=""/>
<typedefs title=""/>
<enums title=""/>
<services title=""/>
<interfaces title=""/>
<constructors title=""/>
<functions title=""/>
<related title=""/>
<variables title=""/>
<properties title=""/>
<events title=""/>
</memberdef>
<allmemberslink visible="yes"/>
<usedfiles visible="$SHOW_USED_FILES"/>
<authorsection visible="yes"/>
</class>
<namespace>
<briefdescription visible="yes"/>
<memberdecl>
<nestednamespaces visible="yes" title=""/>
<constantgroups visible="yes" title=""/>
<interfaces visible="yes" title=""/>
<classes visible="yes" title=""/>
<concepts visible="yes" title=""/>
<structs visible="yes" title=""/>
<exceptions visible="yes" title=""/>
<typedefs title=""/>
<sequences title=""/>
<dictionaries title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
<membergroups visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
<memberdef>
<inlineclasses title=""/>
<typedefs title=""/>
<sequences title=""/>
<dictionaries title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
</memberdef>
<authorsection visible="yes"/>
</namespace>
<concept>
<briefdescription visible="yes"/>
<includes visible="$SHOW_HEADERFILE"/>
<definition visible="yes" title=""/>
<detaileddescription title=""/>
<authorsection visible="yes"/>
</concept>
<file>
<briefdescription visible="yes"/>
<includes visible="$SHOW_INCLUDE_FILES"/>
<includegraph visible="$INCLUDE_GRAPH"/>
<includedbygraph visible="$INCLUDED_BY_GRAPH"/>
<sourcelink visible="yes"/>
<memberdecl>
<interfaces visible="yes" title=""/>
<classes visible="yes" title=""/>
<structs visible="yes" title=""/>
<exceptions visible="yes" title=""/>
<namespaces visible="yes" title=""/>
<concepts visible="yes" title=""/>
<constantgroups visible="yes" title=""/>
<defines title=""/>
<typedefs title=""/>
<sequences title=""/>
<dictionaries title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
<membergroups visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
<memberdef>
<inlineclasses title=""/>
<defines title=""/>
<typedefs title=""/>
<sequences title=""/>
<dictionaries title=""/>
<enums title=""/>
<functions title=""/>
<variables title=""/>
</memberdef>
<authorsection/>
</file>
<group>
<briefdescription visible="yes"/>
<groupgraph visible="$GROUP_GRAPHS"/>
<memberdecl>
<nestedgroups visible="yes" title=""/>
<dirs visible="yes" title=""/>
<files visible="yes" title=""/>
<namespaces visible="yes" title=""/>
<concepts visible="yes" title=""/>
<classes visible="yes" title=""/>
<defines title=""/>
<typedefs title=""/>
<sequences title=""/>
<dictionaries title=""/>
<enums title=""/>
<enumvalues title=""/>
<functions title=""/>
<variables title=""/>
<signals title=""/>
<publicslots title=""/>
<protectedslots title=""/>
<privateslots title=""/>
<events title=""/>
<properties title=""/>
<friends title=""/>
<membergroups visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
<memberdef>
<pagedocs/>
<inlineclasses title=""/>
<defines title=""/>
<typedefs title=""/>
<sequences title=""/>
<dictionaries title=""/>
<enums title=""/>
<enumvalues title=""/>
<functions title=""/>
<variables title=""/>
<signals title=""/>
<publicslots title=""/>
<protectedslots title=""/>
<privateslots title=""/>
<events title=""/>
<properties title=""/>
<friends title=""/>
</memberdef>
<authorsection visible="yes"/>
</group>
<directory>
<briefdescription visible="yes"/>
<directorygraph visible="yes"/>
<memberdecl>
<dirs visible="yes"/>
<files visible="yes"/>
</memberdecl>
<detaileddescription title=""/>
</directory>
</doxygenlayout>
+70
View File
@@ -0,0 +1,70 @@
dl.post {
margin-left: 25px !important;
padding: 10px !important;
}
.anchor {
position: relative;
top: -200px;
}
.github-corner svg {
fill: var(--primary-light-color);
color: var(--page-background-color);
width: 72px;
height: 72px;
}
@media screen and (max-width: 767px) {
.github-corner svg {
width: 55px;
height: 55px;
}
#projectnumber {
margin-right: 22px;
}
}
/* Делаем весь пункт меню кликабельным */
#nav-tree .item {
cursor: pointer;
border-radius: 3px;
transition: background-color 0.2s ease;
}
/* Выделение активного пункта */
#nav-tree .item.selected {
background-color: #d8e8f8;
font-weight: bold;
}
h6 {
font-size: 1.1em;
padding-top: 10px;
}
h5 {
font-size: 1.15em;
padding-top: 10px;
}
h4 {
font-size: 1.2em;
padding-top: 10px;
}
h3 {
font-size: 1.25em;
padding-top: 10px;
}
h2 {
font-size: 1.3em;
padding-top: 10px;
}
h1 {
font-size: 1.4em;
padding-top: 10px;
}
+30
View File
@@ -0,0 +1,30 @@
<!-- HTML footer for doxygen 1.9.1-->
<!-- start footer part -->
<!--BEGIN GENERATE_TREEVIEW-->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
$navpath
<li class="footer">$generatedby <a href="https://www.doxygen.org/index.html"><img class="footer" src="$relpath^doxygen.svg" width="104" height="31" alt="doxygen"/></a> $doxygenversion </li>
</ul>
</div>
<!--END GENERATE_TREEVIEW-->
<!--BEGIN !GENERATE_TREEVIEW-->
<hr class="footer"/><address class="footer"><small>
$generatedby&#160;<a href="https://www.doxygen.org/index.html"><img class="footer" src="$relpath^doxygen.svg" width="104" height="31" alt="doxygen"/></a> $doxygenversion
</small></address>
<!--END !GENERATE_TREEVIEW-->
<script type="text/javascript">
$(function() {
toggleButton = document.createElement('doxygen-awesome-dark-mode-toggle')
toggleButton.title = "Toggle Light/Dark Mode"
$(document).ready(function(){
document.getElementById("MSearchBox").parentNode.appendChild(toggleButton)
})
$(window).resize(function(){
document.getElementById("MSearchBox").parentNode.appendChild(toggleButton)
})
})
</script>
</body>
</html>
+98
View File
@@ -0,0 +1,98 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen $doxygenversion"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<!-- BEGIN opengraph metadata -->
<meta property="og:title" content="CDT / eosiolib" />
<meta property="og:image" content="https://repository-images.githubusercontent.com/348492097/4f16df80-88fb-11eb-9d31-4015ff22c452" />
<meta property="og:description" content="Документация библиотек Contract Development Toolkit (eosiolib)" />
<meta property="og:url" content="https://jothepro.github.io/doxygen-awesome-css/" />
<!-- END opengraph metadata -->
<!-- BEGIN twitter metadata -->
<meta name="twitter:image:src" content="https://repository-images.githubusercontent.com/348492097/4f16df80-88fb-11eb-9d31-4015ff22c452" />
<meta name="twitter:title" content="CDT / eosiolib" />
<meta name="twitter:description" content="Документация библиотек Contract Development Toolkit (eosiolib)" />
<!-- END twitter metadata -->
<!--BEGIN PROJECT_NAME--><title>$projectname: $title</title><!--END PROJECT_NAME-->
<!--BEGIN !PROJECT_NAME--><title>$title</title><!--END !PROJECT_NAME-->
<link href="$relpath^tabs.css" rel="stylesheet" type="text/css"/>
<link rel="icon" type="image/svg+xml" href="logo.drawio.svg"/>
<script type="text/javascript" src="$relpath^jquery.js"></script>
<script type="text/javascript" src="$relpath^dynsections.js"></script>
<script type="text/javascript" src="$relpath^doxygen-awesome-darkmode-toggle.js"></script>
<script type="text/javascript" src="$relpath^mermaid.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
if (window.mermaid) {
try {
const isDarkMode = document.documentElement.classList.contains('dark-mode');
const theme = isDarkMode ? 'dark' : 'neutral';
mermaid.initialize({
startOnLoad: true,
theme: theme,
securityLevel: 'loose',
fontFamily: 'arial',
fontSize: 14
});
} catch (error) {
console.warn('Mermaid initialization error:', error);
}
}
});
</script>
$treeview
$search
$mathjax
<link href="$relpath^$stylesheet" rel="stylesheet" type="text/css" />
$extrastylesheet
</head>
<body>
<a href="https://github.com/AntelopeIO/cdt" class="github-corner" title="Исходники CDT на GitHub">
<svg viewBox="0 0 250 250" style="position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true">
<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<!--BEGIN TITLEAREA-->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<!--BEGIN PROJECT_LOGO-->
<td id="projectlogo"><img alt="Logo" src="$relpath^$projectlogo"/></td>
<!--END PROJECT_LOGO-->
<!--BEGIN PROJECT_NAME-->
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">$projectname
<!--BEGIN PROJECT_NUMBER-->&#160;<span id="projectnumber">$projectnumber</span><!--END PROJECT_NUMBER-->
</div>
<!--BEGIN PROJECT_BRIEF--><div id="projectbrief">$projectbrief</div><!--END PROJECT_BRIEF-->
</td>
<!--END PROJECT_NAME-->
<!--BEGIN !PROJECT_NAME-->
<!--BEGIN PROJECT_BRIEF-->
<td style="padding-left: 0.5em;">
<div id="projectbrief">$projectbrief</div>
</td>
<!--END PROJECT_BRIEF-->
<!--END !PROJECT_NAME-->
<!--BEGIN DISABLE_INDEX-->
<!--BEGIN SEARCHENGINE-->
<td>$searchbox</td>
<!--END SEARCHENGINE-->
<!--END DISABLE_INDEX-->
</tr>
</tbody>
</table>
</div>
<!--END TITLEAREA-->
<!-- end header part -->
+122
View File
@@ -0,0 +1,122 @@
/**
Doxygen Awesome
https://github.com/jothepro/doxygen-awesome-css
MIT License
Copyright (c) 2021 jothepro
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.
*/
class DoxygenAwesomeDarkModeToggle extends HTMLElement {
static prefersLightModeInDarkModeKey = "prefers-light-mode-in-dark-mode"
static prefersDarkModeInLightModeKey = "prefers-dark-mode-in-light-mode"
static _staticConstructor = function() {
DoxygenAwesomeDarkModeToggle.darkModeEnabled = DoxygenAwesomeDarkModeToggle.userPreference
DoxygenAwesomeDarkModeToggle.enableDarkMode(DoxygenAwesomeDarkModeToggle.darkModeEnabled)
// Update the color scheme when the browsers preference changes
// without user interaction on the website.
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
DoxygenAwesomeDarkModeToggle.onSystemPreferenceChanged()
})
// Update the color scheme when the tab is made visible again.
// It is possible that the appearance was changed in another tab
// while this tab was in the background.
document.addEventListener("visibilitychange", visibilityState => {
if (document.visibilityState === 'visible') {
DoxygenAwesomeDarkModeToggle.onSystemPreferenceChanged()
}
});
}()
constructor() {
super();
this.onclick=this.toggleDarkMode
}
/**
* @returns `true` for dark-mode, `false` for light-mode system preference
*/
static get systemPreference() {
return window.matchMedia('(prefers-color-scheme: dark)').matches
}
/**
* @returns `true` for dark-mode, `false` for light-mode user preference
*/
static get userPreference() {
return (!DoxygenAwesomeDarkModeToggle.systemPreference && localStorage.getItem(DoxygenAwesomeDarkModeToggle.prefersDarkModeInLightModeKey)) ||
(DoxygenAwesomeDarkModeToggle.systemPreference && !localStorage.getItem(DoxygenAwesomeDarkModeToggle.prefersLightModeInDarkModeKey))
}
static set userPreference(userPreference) {
DoxygenAwesomeDarkModeToggle.darkModeEnabled = userPreference
if(!userPreference) {
if(DoxygenAwesomeDarkModeToggle.systemPreference) {
localStorage.setItem(DoxygenAwesomeDarkModeToggle.prefersLightModeInDarkModeKey, true)
} else {
localStorage.removeItem(DoxygenAwesomeDarkModeToggle.prefersDarkModeInLightModeKey)
}
} else {
if(!DoxygenAwesomeDarkModeToggle.systemPreference) {
localStorage.setItem(DoxygenAwesomeDarkModeToggle.prefersDarkModeInLightModeKey, true)
} else {
localStorage.removeItem(DoxygenAwesomeDarkModeToggle.prefersLightModeInDarkModeKey)
}
}
DoxygenAwesomeDarkModeToggle.onUserPreferenceChanged()
}
static enableDarkMode(enable) {
let head = document.getElementsByTagName('head')[0]
if(enable) {
document.documentElement.classList.add("dark-mode")
document.documentElement.classList.remove("light-mode")
} else {
document.documentElement.classList.remove("dark-mode")
document.documentElement.classList.add("light-mode")
}
DoxygenAwesomeDarkModeToggle.updateMermaidTheme(enable)
}
static updateMermaidTheme(isDarkMode) {
if (window.mermaid) {
window.location.reload();
}
}
static onSystemPreferenceChanged() {
DoxygenAwesomeDarkModeToggle.darkModeEnabled = DoxygenAwesomeDarkModeToggle.userPreference
DoxygenAwesomeDarkModeToggle.enableDarkMode(DoxygenAwesomeDarkModeToggle.darkModeEnabled)
}
static onUserPreferenceChanged() {
DoxygenAwesomeDarkModeToggle.enableDarkMode(DoxygenAwesomeDarkModeToggle.darkModeEnabled)
}
toggleDarkMode() {
DoxygenAwesomeDarkModeToggle.userPreference = !DoxygenAwesomeDarkModeToggle.userPreference
}
}
customElements.define("doxygen-awesome-dark-mode-toggle", DoxygenAwesomeDarkModeToggle);
@@ -0,0 +1,40 @@
/**
Doxygen Awesome
https://github.com/jothepro/doxygen-awesome-css
MIT License
Copyright (c) 2021 jothepro
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.
*/
@media screen and (min-width: 768px) {
#MSearchBox {
width: calc(var(--side-nav-fixed-width) - calc(2 * var(--spacing-medium)) - var(--searchbar-height) - 1px);
}
#MSearchField {
width: calc(var(--side-nav-fixed-width) - calc(2 * var(--spacing-medium)) - 66px - var(--searchbar-height));
}
}
+112
View File
@@ -0,0 +1,112 @@
/**
Doxygen Awesome
https://github.com/jothepro/doxygen-awesome-css
MIT License
Copyright (c) 2021 jothepro
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.
*/
html {
/* side nav width. MUST be = `TREEVIEW_WIDTH`.
* Make sure it is wide enought to contain the page title (logo + title + version)
*/
--side-nav-fixed-width: 340px;
--menu-display: none;
--top-height: 120px;
}
@media screen and (min-width: 768px) {
html {
--searchbar-background: var(--page-background-color);
}
#side-nav {
min-width: var(--side-nav-fixed-width);
max-width: var(--side-nav-fixed-width);
top: var(--top-height);
overflow: visible;
}
#nav-tree, #side-nav {
height: calc(100vh - var(--top-height)) !important;
}
#nav-tree {
padding: 0;
}
#top {
display: block;
border-bottom: none;
height: var(--top-height);
margin-bottom: calc(0px - var(--top-height));
max-width: var(--side-nav-fixed-width);
background: var(--side-nav-background);
}
#main-nav {
float: left;
padding-right: 0;
}
.ui-resizable-handle {
cursor: default;
width: 1px !important;
box-shadow: 0 calc(-2 * var(--top-height)) 0 0 var(--separator-color);
}
#nav-path {
position: fixed;
right: 0;
left: var(--side-nav-fixed-width);
bottom: 0;
width: auto;
}
#doc-content {
height: calc(100vh - 31px) !important;
padding-bottom: calc(3 * var(--spacing-large));
padding-top: calc(var(--top-height) - 80px);
box-sizing: border-box;
margin-left: var(--side-nav-fixed-width) !important;
}
nav ul.navList > li ul {
display: block;
}
#MSearchBox {
width: calc(var(--side-nav-fixed-width) - calc(2 * var(--spacing-medium)));
}
#MSearchField {
width: calc(var(--side-nav-fixed-width) - calc(2 * var(--spacing-medium)) - 65px);
}
#MSearchResultsWindow {
left: var(--spacing-medium) !important;
right: auto;
}
}
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="61px" height="74px" viewBox="-0.5 -0.5 61 74" content="&lt;mxfile host=&quot;drawio-plugin&quot; modified=&quot;2021-03-16T23:58:23.462Z&quot; agent=&quot;5.0 (Macintosh; Intel Mac OS X 10_16_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36&quot; version=&quot;13.7.9&quot; etag=&quot;JoeaGLJ54FcERO7YrWLQ&quot; type=&quot;embed&quot;&gt;&lt;diagram id=&quot;JMB9aH8b_oZ7EWDuqJgx&quot; name=&quot;Page-1&quot;&gt;7VdNc5swEP01HDsjkGPDsSVJe+lMZnzoWYENaAwsI8ux6a+vCCtA4KSu62kmSS+M9LT7tB9P0uDxuDx8VaLOv2MKhRew9ODxay8Igigy3xZoCOC8AzIl0w7yB2AtfwKBjNCdTGHrGGrEQsvaBROsKki0gwmlcO+aPWDh7lqLDGbAOhHFHP0hU513aHjFBvwbyCy3O/uMVkphjQnY5iLF/QjiNx6PFaLuRuUhhqKtna1L53f7zGofmIJKn+RAcTyKYkfJUWC6sdlmCnc1mYHScDhWY3Fvzdk8Br/PzCgCsAStGmNCRJy2JDH4pIV8VMG+edS4rCcZcjMDSu+ZVP3fpwpV+rnVh5ndF5hsPP4l16VhvPbN8AErTWI0re7mMRaonpw5Y8tlHBvcsNzKwnpttVDaslZYgcXIhj3NFW56LS1bbrM44l6m4Wq5MLhxzEDfgZKmAKDWtUhklRFNgqVM7LYb0Enu8I9j9dkVC80KtgS6Lb3fGnYVgXSm/1Ez2fFu7oeTYA/CuIUWU1AILR9d/mN9pR3uUJqde7F88leOWhYLl2GLO5UAOY2FP+GxMm3c6CwNlXlKY9oompFZ3Rps59EOkuw8BoH2BTtNs8EfaZbUdYZkXQGuXhDgR9DYRBycXURj00D+UmMT2ktJLnr9B8HG0IzFcPkHYfUe3oPZqfOjMEiDs1+KEw5n9P/+/1f3f/gq1394lt7erqQ+0HVvpsPPRWc+/KHxm18=&lt;/diagram&gt;&lt;/mxfile&gt;"><defs/><g><path d="M 13 57 L 13.01 57.01 L 15.87 50.14 L 18.37 43.14 L 20.91 36.15 L 23.67 29.25 L 26.4 22.33 Q 30 13 33.71 22.28 L 33.55 22.22 L 35.48 26.91 L 37.49 31.64 L 39.48 36.36 L 41.2 40.97 L 43.05 45.63" fill="none" stroke="#010508" stroke-opacity="0.1" stroke-width="6" stroke-linejoin="round" stroke-linecap="round" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 47.51 56.77 L 47.65 56.93 L 45.43 54.91 L 43.41 53.11 L 41.43 51.35 L 39.63 49.8 L 37.48 47.86 L 37.39 47.64 L 39.79 47.17 L 41.9 45.98 L 44.24 45.37 L 46.48 44.52 L 48.62 43.4 L 48.54 43.39 L 48.58 46.09 L 48.04 48.74 L 48.04 51.43 L 47.8 54.1 L 47.51 56.77 Z Z" fill-opacity="0.1" fill="#010508" stroke="#010508" stroke-opacity="0.1" stroke-width="6" stroke-linejoin="round" stroke-linecap="round" stroke-miterlimit="10" pointer-events="all"/><path d="M 10 43 L 9.94 42.88 L 12.16 41.98 L 14.31 40.96 L 16.51 40.01 L 18.62 38.89 L 20.88 38.1 Q 30 34 40 34 L 40 33.75 L 42 33.83 L 44 33.8 L 46 33.79 L 48 34.05 L 50 34" fill="none" stroke="#010508" stroke-opacity="0.1" stroke-width="7" stroke-linejoin="round" stroke-linecap="round" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 10 54 L 9.97 53.99 L 12.69 47.07 L 15.43 40.16 L 18.07 33.21 L 20.65 26.24 L 23.4 19.33 Q 27 10 30.71 19.28 L 30.66 19.26 L 32.46 23.91 L 34.55 28.66 L 36.26 33.27 L 38.35 38.03 L 40.05 42.63" fill="none" stroke="#1982d2" stroke-width="6" stroke-linejoin="round" stroke-linecap="round" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 44.51 53.77 L 44.56 53.83 L 42.48 51.97 L 40.5 50.21 L 38.48 48.41 L 36.41 46.56 L 34.48 44.86 L 34.55 45.02 L 36.72 44 L 39 43.24 L 41.21 42.28 L 43.48 41.51 L 45.62 40.4 L 45.78 40.42 L 45.51 43.09 L 45.01 45.74 L 44.87 48.42 L 44.94 51.12 L 44.51 53.77 Z Z" fill="#1982d2" stroke="#1982d2" stroke-width="6" stroke-linejoin="round" stroke-linecap="round" stroke-miterlimit="10" pointer-events="all"/><path d="M 7 40 L 7.02 40.05 L 9.28 39.25 L 11.33 38 L 13.48 36.96 L 15.73 36.14 L 17.88 35.1 Q 27 31 37 31 L 37 30.79 L 39 31.11 L 41 30.85 L 43 30.78 L 45 30.89 L 47 31" fill="none" stroke="#1982d2" stroke-width="8" stroke-linejoin="round" stroke-linecap="round" stroke-miterlimit="10" pointer-events="stroke"/></g></svg>

After

Width:  |  Height:  |  Size: 3.5 KiB

+2659
View File
File diff suppressed because one or more lines are too long
+14 -14
View File
@@ -12,10 +12,10 @@ extern "C" {
/**
* @addtogroup action_c Action C API
* @ingroup c_api
* @brief Defines API for querying action and sending action
* @brief Определяет API для запроса полей действия и отправки действия
*
*
* A EOS.IO action has the following abstract structure:
* Абстрактная структура действия COOPOS:
*
* ```
* struct action {
@@ -26,7 +26,7 @@ extern "C" {
* };
* ```
*
* This API enables your contract to inspect the fields on the current action and act accordingly.
* Этот API позволяет контракту читать поля текущего действия и реагировать соответствующим образом.
*
* Example:
* @code
@@ -66,7 +66,7 @@ extern "C" {
/**
* Copy up to length bytes of current action data to the specified location
*
* @brief Copy current action data to the specified location
* @brief Скопировать данные текущего действия в указанный буфер
* @param msg - a pointer where up to length bytes of the current action data will be copied
* @param len - len of the current action data to be copied, 0 to report required size
* @return the number of bytes copied to msg, or number of bytes that can be copied if len==0 passed
@@ -79,16 +79,16 @@ uint32_t read_action_data( void* msg, uint32_t len );
/**
* Get the length of the current action's data field. This method is useful for dynamically sized actions
*
* @brief Get the length of current action's data field
* @brief Получить длину поля data текущего действия
* @return the length of the current action's data field
*/
__attribute__((eosio_wasm_import))
uint32_t action_data_size( void );
/**
* Add the specified account to set of accounts to be notified
* Добавить указанную учётную запись в множество адресатов уведомления
*
* @brief Add the specified account to set of accounts to be notified
* @brief Добавить указанную учётную запись в множество адресатов уведомления
* @param name - name of the account to be verified
*/
__attribute__((eosio_wasm_import))
@@ -97,7 +97,7 @@ void require_recipient( capi_name name );
/**
* Verifies that name exists in the set of provided auths on a action. Throws if not found.
*
* @brief Verify specified account exists in the set of provided auths
* @brief Проверить, что указанная учётная запись есть среди предоставленных авторизаций
* @param name - name of the account to be verified
*/
__attribute__((eosio_wasm_import))
@@ -106,7 +106,7 @@ void require_auth( capi_name name );
/**
* Verifies that name has auth.
*
* @brief Verifies that name has auth.
* @brief Проверить наличие авторизации у учётной записи name
* @param name - name of the account to be verified
*/
__attribute__((eosio_wasm_import))
@@ -115,7 +115,7 @@ bool has_auth( capi_name name );
/**
* Verifies that name exists in the set of provided auths on a action. Throws if not found.
*
* @brief Verify specified account exists in the set of provided auths
* @brief Проверить, что указанная учётная запись есть среди предоставленных авторизаций
* @param name - name of the account to be verified
* @param permission - permission level to be verified
*/
@@ -125,7 +125,7 @@ void require_auth2( capi_name name, capi_name permission );
/**
* Verifies that @ref name is an existing account.
*
* @brief Verifies that @ref name is an existing account.
* @brief Проверить, что @ref name — существующая учётная запись
* @param name - name of the account to check
*/
__attribute__((eosio_wasm_import))
@@ -154,7 +154,7 @@ void send_context_free_inline(char *serialized_action, size_t size);
/**
* Returns the time in microseconds from 1970 of the publication_time
* @brief Get the publication time
* @brief Получить время публикации
* @return the time in microseconds from 1970 of the publication_time
*/
__attribute__((eosio_wasm_import))
@@ -162,7 +162,7 @@ uint64_t publication_time( void );
/**
* Get the current receiver of the action
* @brief Get the current receiver of the action
* @brief Получить текущего получателя действия
* @return the account which specifies the current receiver of the action
*/
__attribute__((eosio_wasm_import))
@@ -180,7 +180,7 @@ capi_name current_receiver( void );
/**
* Set the action return value which will be included in the action_receipt
* @brief Set the action return value
* @brief Задать возвращаемое значение действия
* @param return_value - serialized return value
* @param size - size of serialized return value in bytes
* @pre `return_value` is a valid pointer to an array at least `size` bytes long
+1 -1
View File
@@ -12,7 +12,7 @@ extern "C" {
/**
* @addtogroup chain
* @ingroup c_api
* @brief Defines %C API for querying internal chain state
* @brief Определяет C API для запроса внутреннего состояния цепи
* @{
*/
+36 -1
View File
@@ -10,7 +10,7 @@ extern "C" {
/**
* @addtogroup crypto Crypto
* @brief Defines %C API for calculating and checking hash
* @brief Определяет C API для вычисления и проверки хешей
* @{
*/
@@ -232,6 +232,41 @@ int recover_key( const struct capi_checksum256* digest, const char* sig, size_t
__attribute__((eosio_wasm_import))
void assert_recover_key( const struct capi_checksum256* digest, const char* sig, size_t siglen, const char* pub, size_t publen );
/**
* Tests a signature against a hash, verifies the recovered public key matches the expected one,
* and checks that this public key belongs to the specified account permission.
*
* @ingroup crypto
* @param digest - Pointer to the digest/hash of the message that was signed
* @param sig - Pointer to the signature
* @param siglen - Length of the signature
* @param pub - Pointer to the expected public key
* @param publen - Length of the expected public key
* @param account - The account name to verify key ownership
* @param permission - The permission name to check (e.g., active, owner)
*
* @pre `digest` is a valid pointer to a `capi_checksum256` struct
* @pre `sig` is a valid pointer to a buffer containing the signature
* @pre `pub` is a valid pointer to a buffer containing the expected public key
*
* @post Throws if signature is invalid, key doesn't match, or key doesn't belong to account permission
*
* Example:
* @code
* capi_checksum256 digest;
* char sig[65];
* size_t siglen = 65;
* char pub[34];
* size_t publen = 34;
* capi_name account = N(myaccount);
* capi_name permission = N(active);
* assert_recover_key_account( &digest, sig, siglen, pub, publen, account, permission );
* // If all checks pass, code continues here
* @endcode
*/
__attribute__((eosio_wasm_import))
void assert_recover_key_account( const struct capi_checksum256* digest, const char* sig, size_t siglen, const char* pub, size_t publen, uint64_t account, uint64_t permission );
#ifdef __cplusplus
}
#endif
+2 -2
View File
@@ -10,8 +10,8 @@ extern "C" {
/**
* @addtogroup crypto Crypto
* @brief Defines extension of %C API for calculating and checking hash which
* require activating crypto protocol feature
* @brief Расширение C API для вычисления и проверки хешей; требует активации
* протокольной возможности crypto
* @{
*/
+63 -63
View File
@@ -1,7 +1,7 @@
/**
* @file db.h
* @copyright defined in eos/LICENSE
* @brief Defines C API for interfacing with blockchain database
* @brief Определяет C API для работы с базой данных блокчейна COOPOS
*/
#pragma once
@@ -13,8 +13,8 @@ extern "C" {
/**
* @addtogroup database_c_api Database C API
* @ingroup c_api
* @brief Defines %C APIs for interfacing with the database.
* @details Database C API provides low level interface to EOSIO database.
* @brief Определяет %C API для работы с базой данных.
* @details Database C API provides low level interface to COOPOS database.
*
* @section tabletypes Supported Table Types
* Following are the table types supported by the C API:
@@ -30,7 +30,7 @@ extern "C" {
*/
/**
* @brief Store a record in a primary 64-bit integer index table
* @brief Сохранить запись в первичной таблице с 64-битным целочисленным индексом
* @param scope - The scope where the table resides (implied to be within the code of the current receiver)
* @param table - The table name
* @param payer - The account that pays for the storage costs
@@ -46,7 +46,7 @@ __attribute__((eosio_wasm_import))
int32_t db_store_i64(uint64_t scope, capi_name table, capi_name payer, uint64_t id, const void* data, uint32_t len);
/**
* @brief Update a record in a primary 64-bit integer index table
* @brief Обновить запись в первичной таблице с 64-битным целочисленным индексом
* @param iterator - Iterator to the table row containing the record to update
* @param payer - The account that pays for the storage costs (use 0 to continue using current payer)
* @param data - New updated record
@@ -65,7 +65,7 @@ __attribute__((eosio_wasm_import))
void db_update_i64(int32_t iterator, capi_name payer, const void* data, uint32_t len);
/**
* @brief Remove a record from a primary 64-bit integer index table
* @brief Удалить запись из первичной таблицы с 64-битным целочисленным индексом
* @param iterator - Iterator to the table row to remove
* @pre `iterator` points to an existing table row in the table
* @post the table row pointed to by `iterator` is removed and the associated storage costs are refunded to the payer
@@ -82,7 +82,7 @@ __attribute__((eosio_wasm_import))
void db_remove_i64(int32_t iterator);
/**
* @brief Get a record in a primary 64-bit integer index table
* @brief Получить запись из первичной таблицы с 64-битным целочисленным индексом
* @param iterator - The iterator to the table row containing the record to retrieve
* @param data - Pointer to the buffer which will be filled with the retrieved record
* @param len - Size of the buffer
@@ -104,7 +104,7 @@ __attribute__((eosio_wasm_import))
int32_t db_get_i64(int32_t iterator, const void* data, uint32_t len);
/**
* @brief Find the table row following the referenced table row in a primary 64-bit integer index table
* @brief Найти строку таблицы, следующую за указанной, в первичной таблице с 64-битным целочисленным индексом
* @param iterator - The iterator to the referenced table row
* @param primary - Pointer to a `uint64_t` variable which will have its value set to the primary key of the next table row
* @return iterator to the table row following the referenced table row (or the end iterator of the table if the referenced table row is the last one in the table)
@@ -125,7 +125,7 @@ __attribute__((eosio_wasm_import))
int32_t db_next_i64(int32_t iterator, uint64_t* primary);
/**
* @brief Find the table row preceding the referenced table row in a primary 64-bit integer index table
* @brief Найти строку таблицы, предшествующую указанной, в первичной таблице с 64-битным целочисленным индексом
* @param iterator - The iterator to the referenced table row
* @param primary - Pointer to a `uint64_t` variable which will have its value set to the primary key of the previous table row
* @return iterator to the table row preceding the referenced table row assuming one exists (it will return -1 if the referenced table row is the first one in the table)
@@ -143,7 +143,7 @@ __attribute__((eosio_wasm_import))
int32_t db_previous_i64(int32_t iterator, uint64_t* primary);
/**
* @brief Find a table row in a primary 64-bit integer index table by primary key
* @brief Найти строку таблицы в первичной таблице с 64-битным целочисленным индексом по первичному ключу
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -160,7 +160,7 @@ __attribute__((eosio_wasm_import))
int32_t db_find_i64(capi_name code, uint64_t scope, capi_name table, uint64_t id);
/**
* @brief Find the table row in a primary 64-bit integer index table that matches the lowerbound condition for a given primary key
* @brief Найти строку в первичной таблице с 64-битным целочисленным индексом, удовлетворяющую условию нижней границы для заданного первичного ключа
* @details The table row that matches the lowerbound condition is the first table row in the table with the lowest primary key that is >= the given key
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
@@ -172,7 +172,7 @@ __attribute__((eosio_wasm_import))
int32_t db_lowerbound_i64(capi_name code, uint64_t scope, capi_name table, uint64_t id);
/**
* @brief Find the table row in a primary 64-bit integer index table that matches the upperbound condition for a given primary key
* @brief Найти строку в первичной таблице с 64-битным целочисленным индексом, удовлетворяющую условию верхней границы для заданного первичного ключа
* @details The table row that matches the upperbound condition is the first table row in the table with the lowest primary key that is > the given key
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
@@ -184,7 +184,7 @@ __attribute__((eosio_wasm_import))
int32_t db_upperbound_i64(capi_name code, uint64_t scope, capi_name table, uint64_t id);
/**
* @brief Get an iterator representing just-past-the-end of the last table row of a primary 64-bit integer index table
* @brief Получить итератор «сразу после» последней строки первичной таблицы с 64-битным целочисленным индексом
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -194,7 +194,7 @@ __attribute__((eosio_wasm_import))
int32_t db_end_i64(capi_name code, uint64_t scope, capi_name table);
/**
* @brief Store an association of a 64-bit integer secondary key to a primary key in a secondary 64-bit integer index table
* @brief Сохранить связь 64-битного целочисленного вторичного ключа с первичным ключом во вторичной таблице с 64-битным целочисленным индексом
* @param scope - The scope where the table resides (implied to be within the code of the current receiver)
* @param table - The table name
* @param payer - The account that pays for the storage costs
@@ -207,7 +207,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx64_store(uint64_t scope, capi_name table, capi_name payer, uint64_t id, const uint64_t* secondary);
/**
* @brief Update an association for a 64-bit integer secondary key to a primary key in a secondary 64-bit integer index table
* @brief Обновить связь 64-битного целочисленного вторичного ключа с первичным ключом во вторичной таблице с 64-битным целочисленным индексом
* @param iterator - The iterator to the table row containing the secondary key association to update
* @param payer - The account that pays for the storage costs (use 0 to continue using current payer)
* @param secondary - Pointer to the **new** secondary key that will replace the existing one of the association
@@ -218,7 +218,7 @@ __attribute__((eosio_wasm_import))
void db_idx64_update(int32_t iterator, capi_name payer, const uint64_t* secondary);
/**
* @brief Remove a table row from a secondary 64-bit integer index table
* @brief Удалить строку из вторичной таблицы с 64-битным целочисленным индексом
* @param iterator - Iterator to the table row to remove
* @pre `iterator` points to an existing table row in the table
* @post the table row pointed to by `iterator` is removed and the associated storage costs are refunded to the payer
@@ -227,7 +227,7 @@ __attribute__((eosio_wasm_import))
void db_idx64_remove(int32_t iterator);
/**
* @brief Find the table row following the referenced table row in a secondary 64-bit integer index table
* @brief Найти строку таблицы, следующую за указанной, во вторичной таблице с 64-битным целочисленным индексом
* @param iterator - The iterator to the referenced table row
* @param primary - Pointer to a `uint64_t` variable which will have its value set to the primary key of the next table row
* @return iterator to the table row following the referenced table row (or the end iterator of the table if the referenced table row is the last one in the table)
@@ -238,7 +238,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx64_next(int32_t iterator, uint64_t* primary);
/**
* @brief Find the table row preceding the referenced table row in a secondary 64-bit integer index table
* @brief Найти строку таблицы, предшествующую указанной, во вторичной таблице с 64-битным целочисленным индексом
* @param iterator - The iterator to the referenced table row
* @param primary - Pointer to a `uint64_t` variable which will have its value set to the primary key of the previous table row
* @return iterator to the table row preceding the referenced table row assuming one exists (it will return -1 if the referenced table row is the first one in the table)
@@ -249,7 +249,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx64_previous(int32_t iterator, uint64_t* primary);
/**
* @brief Find a table row in a secondary 64-bit integer index table by primary key
* @brief Найти строку таблицы во вторичной таблице с 64-битным целочисленным индексом по первичному ключу
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -262,7 +262,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx64_find_primary(capi_name code, uint64_t scope, capi_name table, uint64_t* secondary, uint64_t primary);
/**
* @brief Find a table row in a secondary 64-bit integer index table by secondary key
* @brief Найти строку таблицы во вторичной таблице с 64-битным целочисленным индексом по вторичному ключу
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -275,7 +275,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx64_find_secondary(capi_name code, uint64_t scope, capi_name table, const uint64_t* secondary, uint64_t* primary);
/**
* @brief Find the table row in a secondary 64-bit integer index table that matches the lowerbound condition for a given secondary key
* @brief Найти строку во вторичной таблице с 64-битным целочисленным индексом, удовлетворяющую условию нижней границы для заданного вторичного ключа
* @details The table row that matches the lowerbound condition is the first table row in the table with the lowest secondary key that is >= the given key
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
@@ -290,7 +290,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx64_lowerbound(capi_name code, uint64_t scope, capi_name table, uint64_t* secondary, uint64_t* primary);
/**
* @brief Find the table row in a secondary 64-bit integer index table that matches the upperbound condition for a given secondary key
* @brief Найти строку во вторичной таблице с 64-битным целочисленным индексом, удовлетворяющую условию верхней границы для заданного вторичного ключа
* @details The table row that matches the upperbound condition is the first table row in the table with the lowest secondary key that is > the given key
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
@@ -305,7 +305,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx64_upperbound(capi_name code, uint64_t scope, capi_name table, uint64_t* secondary, uint64_t* primary);
/**
* @brief Get an end iterator representing just-past-the-end of the last table row of a secondary 64-bit integer index table
* @brief Получить конечный итератор «сразу после» последней строки вторичной таблицы с 64-битным целочисленным индексом
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -317,7 +317,7 @@ int32_t db_idx64_end(capi_name code, uint64_t scope, capi_name table);
/**
* @brief Store an association of a 128-bit integer secondary key to a primary key in a secondary 128-bit integer index table
* @brief Сохранить связь 128-битного целочисленного вторичного ключа с первичным ключом во вторичной таблице с 128-битным целочисленным индексом
* @param scope - The scope where the table resides (implied to be within the code of the current receiver)
* @param table - The table name
* @param payer - The account that pays for the storage costs
@@ -330,7 +330,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx128_store(uint64_t scope, capi_name table, capi_name payer, uint64_t id, const uint128_t* secondary);
/**
* @brief Update an association for a 128-bit integer secondary key to a primary key in a secondary 128-bit integer index table
* @brief Обновить связь 128-битного целочисленного вторичного ключа с первичным ключом во вторичной таблице с 128-битным целочисленным индексом
* @param iterator - The iterator to the table row containing the secondary key association to update
* @param payer - The account that pays for the storage costs (use 0 to continue using current payer)
* @param secondary - Pointer to the **new** secondary key that will replace the existing one of the association
@@ -341,7 +341,7 @@ __attribute__((eosio_wasm_import))
void db_idx128_update(int32_t iterator, capi_name payer, const uint128_t* secondary);
/**
* @brief Remove a table row from a secondary 128-bit integer index table
* @brief Удалить строку из вторичной таблицы с 128-битным целочисленным индексом
* @param iterator - Iterator to the table row to remove
* @pre `iterator` points to an existing table row in the table
* @post the table row pointed to by `iterator` is removed and the associated storage costs are refunded to the payer
@@ -350,7 +350,7 @@ __attribute__((eosio_wasm_import))
void db_idx128_remove(int32_t iterator);
/**
* @brief Find the table row following the referenced table row in a secondary 128-bit integer index table
* @brief Найти строку таблицы, следующую за указанной, во вторичной таблице с 128-битным целочисленным индексом
* @param iterator - The iterator to the referenced table row
* @param primary - Pointer to a `uint64_t` variable which will have its value set to the primary key of the next table row
* @return iterator to the table row following the referenced table row (or the end iterator of the table if the referenced table row is the last one in the table)
@@ -361,7 +361,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx128_next(int32_t iterator, uint64_t* primary);
/**
* @brief Find the table row preceding the referenced table row in a secondary 128-bit integer index table
* @brief Найти строку таблицы, предшествующую указанной, во вторичной таблице с 128-битным целочисленным индексом
* @param iterator - The iterator to the referenced table row
* @param primary - Pointer to a `uint64_t` variable which will have its value set to the primary key of the previous table row
* @return iterator to the table row preceding the referenced table row assuming one exists (it will return -1 if the referenced table row is the first one in the table)
@@ -372,7 +372,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx128_previous(int32_t iterator, uint64_t* primary);
/**
* @brief Find a table row in a secondary 128-bit integer index table by primary key
* @brief Найти строку таблицы во вторичной таблице с 128-битным целочисленным индексом по первичному ключу
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -385,7 +385,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx128_find_primary(capi_name code, uint64_t scope, capi_name table, uint128_t* secondary, uint64_t primary);
/**
* @brief Find a table row in a secondary 128-bit integer index table by secondary key
* @brief Найти строку таблицы во вторичной таблице с 128-битным целочисленным индексом по вторичному ключу
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -398,7 +398,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx128_find_secondary(capi_name code, uint64_t scope, capi_name table, const uint128_t* secondary, uint64_t* primary);
/**
* @brief Find the table row in a secondary 128-bit integer index table that matches the lowerbound condition for a given secondary key
* @brief Найти строку во вторичной таблице с 128-битным целочисленным индексом, удовлетворяющую условию нижней границы для заданного вторичного ключа
* @details The table row that matches the lowerbound condition is the first table row in the table with the lowest secondary key that is >= the given key
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
@@ -413,7 +413,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx128_lowerbound(capi_name code, uint64_t scope, capi_name table, uint128_t* secondary, uint64_t* primary);
/**
* @brief Find the table row in a secondary 128-bit integer index table that matches the upperbound condition for a given secondary key
* @brief Найти строку во вторичной таблице с 128-битным целочисленным индексом, удовлетворяющую условию верхней границы для заданного вторичного ключа
* @details The table row that matches the upperbound condition is the first table row in the table with the lowest secondary key that is > the given key
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
@@ -428,7 +428,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx128_upperbound(capi_name code, uint64_t scope, capi_name table, uint128_t* secondary, uint64_t* primary);
/**
* @brief Get an end iterator representing just-past-the-end of the last table row of a secondary 128-bit integer index table
* @brief Получить конечный итератор «сразу после» последней строки вторичной таблицы с 128-битным целочисленным индексом
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -438,7 +438,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx128_end(capi_name code, uint64_t scope, capi_name table);
/**
* @brief Store an association of a 256-bit secondary key to a primary key in a secondary 256-bit index table
* @brief Сохранить связь 256-битного вторичного ключа с первичным ключом во вторичной таблице с 256-битным индексом
* @param scope - The scope where the table resides (implied to be within the code of the current receiver)
* @param table - The table name
* @param payer - The account that pays for the storage costs
@@ -452,7 +452,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx256_store(uint64_t scope, capi_name table, capi_name payer, uint64_t id, const uint128_t* data, uint32_t data_len );
/**
* @brief Update an association for a 256-bit secondary key to a primary key in a secondary 256-bit index table
* @brief Обновить связь 256-битного вторичного ключа с первичным ключом во вторичной таблице с 256-битным индексом
* @param iterator - The iterator to the table row containing the secondary key association to update
* @param payer - The account that pays for the storage costs (use 0 to continue using current payer)
* @param data - Pointer to the **new** secondary key data (which is stored as an array of 2 `uint128_t` integers) that will replace the existing one of the association
@@ -464,7 +464,7 @@ __attribute__((eosio_wasm_import))
void db_idx256_update(int32_t iterator, capi_name payer, const uint128_t* data, uint32_t data_len);
/**
* @brief Remove a table row from a secondary 256-bit index table
* @brief Удалить строку из вторичной таблицы с 256-битным индексом
* @param iterator - Iterator to the table row to remove
* @pre `iterator` points to an existing table row in the table
* @post the table row pointed to by `iterator` is removed and the associated storage costs are refunded to the payer
@@ -473,7 +473,7 @@ __attribute__((eosio_wasm_import))
void db_idx256_remove(int32_t iterator);
/**
* @brief Find the table row following the referenced table row in a secondary 256-bit index table
* @brief Найти строку таблицы, следующую за указанной, во вторичной таблице с 256-битным индексом
* @param iterator - The iterator to the referenced table row
* @param primary - Pointer to a `uint64_t` variable which will have its value set to the primary key of the next table row
* @return iterator to the table row following the referenced table row (or the end iterator of the table if the referenced table row is the last one in the table)
@@ -484,7 +484,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx256_next(int32_t iterator, uint64_t* primary);
/**
* @brief Find the table row preceding the referenced table row in a secondary 256-bit index table
* @brief Найти строку таблицы, предшествующую указанной, во вторичной таблице с 256-битным индексом
* @param iterator - The iterator to the referenced table row
* @param primary - Pointer to a `uint64_t` variable which will have its value set to the primary key of the previous table row
* @return iterator to the table row preceding the referenced table row assuming one exists (it will return -1 if the referenced table row is the first one in the table)
@@ -495,7 +495,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx256_previous(int32_t iterator, uint64_t* primary);
/**
* @brief Find a table row in a secondary 128-bit integer index table by primary key
* @brief Найти строку таблицы во вторичной таблице с 256-битным индексом по первичному ключу
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -509,7 +509,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx256_find_primary(capi_name code, uint64_t scope, capi_name table, uint128_t* data, uint32_t data_len, uint64_t primary);
/**
* @brief Find a table row in a secondary 256-bit index table by secondary key
* @brief Найти строку таблицы во вторичной таблице с 256-битным индексом по вторичному ключу
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -523,7 +523,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx256_find_secondary(capi_name code, uint64_t scope, capi_name table, const uint128_t* data, uint32_t data_len, uint64_t* primary);
/**
* @brief Find the table row in a secondary 256-bit index table that matches the lowerbound condition for a given secondary key
* @brief Найти строку во вторичной таблице с 256-битным индексом, удовлетворяющую условию нижней границы для заданного вторичного ключа
* @details The table row that matches the lowerbound condition is the first table row in the table with the lowest secondary key that is >= the given key (uses lexicographical ordering on the 256-bit keys)
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
@@ -539,7 +539,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx256_lowerbound(capi_name code, uint64_t scope, capi_name table, uint128_t* data, uint32_t data_len, uint64_t* primary);
/**
* @brief Find the table row in a secondary 256-bit index table that matches the upperbound condition for a given secondary key
* @brief Найти строку во вторичной таблице с 256-битным индексом, удовлетворяющую условию верхней границы для заданного вторичного ключа
* @details The table row that matches the upperbound condition is the first table row in the table with the lowest secondary key that is > the given key (uses lexicographical ordering on the 256-bit keys)
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
@@ -555,7 +555,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx256_upperbound(capi_name code, uint64_t scope, capi_name table, uint128_t* data, uint32_t data_len, uint64_t* primary);
/**
* @brief Get an end iterator representing just-past-the-end of the last table row of a secondary 256-bit index table
* @brief Получить конечный итератор «сразу после» последней строки вторичной таблицы с 256-битным индексом
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -565,7 +565,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx256_end(capi_name code, uint64_t scope, capi_name table);
/**
* @brief Store an association of a double-precision floating-point secondary key to a primary key in a secondary double-precision floating-point index table
* @brief Сохранить связь вторичного ключа с плавающей запятой двойной точности (double) с первичным ключом во вторичной таблице с индексом по double
* @param scope - The scope where the table resides (implied to be within the code of the current receiver)
* @param table - The table name
* @param payer - The account that pays for the storage costs
@@ -578,7 +578,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_double_store(uint64_t scope, capi_name table, capi_name payer, uint64_t id, const double* secondary);
/**
* @brief Update an association for a double-precision floating-point secondary key to a primary key in a secondary double-precision floating-point index table
* @brief Обновить связь вторичного ключа с плавающей запятой двойной точности (double) с первичным ключом во вторичной таблице с индексом по double
* @param iterator - The iterator to the table row containing the secondary key association to update
* @param payer - The account that pays for the storage costs (use 0 to continue using current payer)
* @param secondary - Pointer to the **new** secondary key that will replace the existing one of the association
@@ -589,7 +589,7 @@ __attribute__((eosio_wasm_import))
void db_idx_double_update(int32_t iterator, capi_name payer, const double* secondary);
/**
* @brief Remove a table row from a secondary double-precision floating-point index table
* @brief Удалить строку из вторичной таблицы с индексом по double
* @param iterator - Iterator to the table row to remove
* @pre `iterator` points to an existing table row in the table
* @post the table row pointed to by `iterator` is removed and the associated storage costs are refunded to the payer
@@ -598,7 +598,7 @@ __attribute__((eosio_wasm_import))
void db_idx_double_remove(int32_t iterator);
/**
* @brief Find the table row following the referenced table row in a secondary double-precision floating-point index table
* @brief Найти строку таблицы, следующую за указанной, во вторичной таблице с индексом по double
* @param iterator - The iterator to the referenced table row
* @param primary - Pointer to a `uint64_t` variable which will have its value set to the primary key of the next table row
* @return iterator to the table row following the referenced table row (or the end iterator of the table if the referenced table row is the last one in the table)
@@ -609,7 +609,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_double_next(int32_t iterator, uint64_t* primary);
/**
* @brief Find the table row preceding the referenced table row in a secondary double-precision floating-point index table
* @brief Найти строку таблицы, предшествующую указанной, во вторичной таблице с индексом по double
* @param iterator - The iterator to the referenced table row
* @param primary - Pointer to a `uint64_t` variable which will have its value set to the primary key of the previous table row
* @return iterator to the table row preceding the referenced table row assuming one exists (it will return -1 if the referenced table row is the first one in the table)
@@ -620,7 +620,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_double_previous(int32_t iterator, uint64_t* primary);
/**
* @brief Find a table row in a secondary double-precision floating-point index table by primary key
* @brief Найти строку таблицы во вторичной таблице с индексом по double по первичному ключу
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -633,7 +633,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_double_find_primary(capi_name code, uint64_t scope, capi_name table, double* secondary, uint64_t primary);
/**
* @brief Find a table row in a secondary double-precision floating-point index table by secondary key
* @brief Найти строку таблицы во вторичной таблице с индексом по double по вторичному ключу
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -646,7 +646,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_double_find_secondary(capi_name code, uint64_t scope, capi_name table, const double* secondary, uint64_t* primary);
/**
* @brief Find the table row in a secondary double-precision floating-point index table that matches the lowerbound condition for a given secondary key
* @brief Найти строку во вторичной таблице с индексом по double, удовлетворяющую условию нижней границы для заданного вторичного ключа
* @details The table row that matches the lowerbound condition is the first table row in the table with the lowest secondary key that is >= the given key
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
@@ -661,7 +661,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_double_lowerbound(capi_name code, uint64_t scope, capi_name table, double* secondary, uint64_t* primary);
/**
* @brief Find the table row in a secondary double-precision floating-point index table that matches the upperbound condition for a given secondary key
* @brief Найти строку во вторичной таблице с индексом по double, удовлетворяющую условию верхней границы для заданного вторичного ключа
* @details The table row that matches the upperbound condition is the first table row in the table with the lowest secondary key that is > the given key
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
@@ -676,7 +676,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_double_upperbound(capi_name code, uint64_t scope, capi_name table, double* secondary, uint64_t* primary);
/**
* @brief Get an end iterator representing just-past-the-end of the last table row of a secondary double-precision floating-point index table
* @brief Получить конечный итератор «сразу после» последней строки вторичной таблицы с индексом по double
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -686,7 +686,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_double_end(capi_name code, uint64_t scope, capi_name table);
/**
* @brief Store an association of a quadruple-precision floating-point secondary key to a primary key in a secondary quadruple-precision floating-point index table
* @brief Сохранить связь вторичного ключа с плавающей запятой повышенной точности (long double) с первичным ключом во вторичной таблице с индексом по long double
* @param scope - The scope where the table resides (implied to be within the code of the current receiver)
* @param table - The table name
* @param payer - The account that pays for the storage costs
@@ -699,7 +699,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_long_double_store(uint64_t scope, capi_name table, capi_name payer, uint64_t id, const long double* secondary);
/**
* @brief Update an association for a quadruple-precision floating-point secondary key to a primary key in a secondary quadruple-precision floating-point index table
* @brief Обновить связь вторичного ключа с плавающей запятой повышенной точности (long double) с первичным ключом во вторичной таблице с индексом по long double
* @param iterator - The iterator to the table row containing the secondary key association to update
* @param payer - The account that pays for the storage costs (use 0 to continue using current payer)
* @param secondary - Pointer to the **new** secondary key that will replace the existing one of the association
@@ -710,7 +710,7 @@ __attribute__((eosio_wasm_import))
void db_idx_long_double_update(int32_t iterator, capi_name payer, const long double* secondary);
/**
* @brief Remove a table row from a secondary quadruple-precision floating-point index table
* @brief Удалить строку из вторичной таблицы с индексом по long double
* @param iterator - Iterator to the table row to remove
* @pre `iterator` points to an existing table row in the table
* @post the table row pointed to by `iterator` is removed and the associated storage costs are refunded to the payer
@@ -719,7 +719,7 @@ __attribute__((eosio_wasm_import))
void db_idx_long_double_remove(int32_t iterator);
/**
* @brief Find the table row following the referenced table row in a secondary quadruple-precision floating-point index table
* @brief Найти строку таблицы, следующую за указанной, во вторичной таблице с индексом по long double
* @param iterator - The iterator to the referenced table row
* @param primary - Pointer to a `uint64_t` variable which will have its value set to the primary key of the next table row
* @return iterator to the table row following the referenced table row (or the end iterator of the table if the referenced table row is the last one in the table)
@@ -730,7 +730,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_long_double_next(int32_t iterator, uint64_t* primary);
/**
* @brief Find the table row preceding the referenced table row in a secondary quadruple-precision floating-point index table
* @brief Найти строку таблицы, предшествующую указанной, во вторичной таблице с индексом по long double
* @param iterator - The iterator to the referenced table row
* @param primary - Pointer to a `uint64_t` variable which will have its value set to the primary key of the previous table row
* @return iterator to the table row preceding the referenced table row assuming one exists (it will return -1 if the referenced table row is the first one in the table)
@@ -741,7 +741,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_long_double_previous(int32_t iterator, uint64_t* primary);
/**
* @brief Find a table row in a secondary quadruple-precision floating-point index table by primary key
* @brief Найти строку таблицы во вторичной таблице с индексом по long double по первичному ключу
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -754,7 +754,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_long_double_find_primary(capi_name code, uint64_t scope, capi_name table, long double* secondary, uint64_t primary);
/**
* @brief Find a table row in a secondary quadruple-precision floating-point index table by secondary key
* @brief Найти строку таблицы во вторичной таблице с индексом по long double по вторичному ключу
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
@@ -767,7 +767,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_long_double_find_secondary(capi_name code, uint64_t scope, capi_name table, const long double* secondary, uint64_t* primary);
/**
* @brief Find the table row in a secondary quadruple-precision floating-point index table that matches the lowerbound condition for a given secondary key
* @brief Найти строку во вторичной таблице с индексом по long double, удовлетворяющую условию нижней границы для заданного вторичного ключа
* @details The table row that matches the lowerbound condition is the first table row in the table with the lowest secondary key that is >= the given key
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
@@ -782,7 +782,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_long_double_lowerbound(capi_name code, uint64_t scope, capi_name table, long double* secondary, uint64_t* primary);
/**
* @brief Find the table row in a secondary quadruple-precision floating-point index table that matches the upperbound condition for a given secondary key
* @brief Найти строку во вторичной таблице с индексом по long double, удовлетворяющую условию верхней границы для заданного вторичного ключа
* @details The table row that matches the upperbound condition is the first table row in the table with the lowest secondary key that is > the given key
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
@@ -797,7 +797,7 @@ __attribute__((eosio_wasm_import))
int32_t db_idx_long_double_upperbound(capi_name code, uint64_t scope, capi_name table, long double* secondary, uint64_t* primary);
/**
* @brief Get an end iterator representing just-past-the-end of the last table row of a secondary quadruple-precision floating-point index table
* @brief Получить конечный итератор «сразу после» последней строки вторичной таблицы с индексом по long double
* @param code - The name of the owner of the table
* @param scope - The scope where the table resides
* @param table - The table name
+1 -1
View File
@@ -12,7 +12,7 @@ extern "C" {
* @defgroup permission_c Permissions C API
* @ingroup c_api
*
* @brief Methods for testing against transactions, delays, keys and permissions
* @brief Методы проверки относительно транзакций, задержек, ключей и разрешений
* @{
*/
+3 -3
View File
@@ -12,7 +12,7 @@ extern "C" {
/**
* @defgroup console_c Console C API
* @ingroup c_api
* @brief Defnes %C API to log/print text messages
* @brief Определяет C API для журналирования и вывода текстовых сообщений
* @{
*/
@@ -48,7 +48,7 @@ void prints_l( const char* cstr, uint32_t len);
/**
* Prints value as a 64 bit signed integer
*
* @brief Prints value as a 64 bit signed integer
* @brief Вывести значение как 64-битное целое со знаком
* @param value of 64 bit signed integer to be printed
*
* Example:
@@ -165,7 +165,7 @@ void printn( uint64_t name );
/**
* Prints hexidecimal data of length datalen
*
* @brief Prints hexidecimal data of length datalen
* @brief Вывести шестнадцатеричные данные длиной datalen
* @param data to be printed
* @param datalen length of the data to be printed
*
+11 -1
View File
@@ -7,9 +7,19 @@ extern "C" {
/**
* @defgroup privileged_c Privileged C API
* @ingroup c_api
* @brief Defines %C Privileged API
* @brief Определяет привилегированный C API
*/
/**
* Get the RAM usage an account
*
* @param account - name of the account whose resource limit to get
* @param used_ram_bytes - pointer to `int64_t` to hold retrieved ram usage in absolute bytes
*/
__attribute__((eosio_wasm_import))
void get_account_ram_usage( capi_name account, int64_t* used_ram_bytes );
/**
* Get the resource limits of an account
*
+2 -2
View File
@@ -11,7 +11,7 @@ extern "C" {
/**
* @addtogroup system
* @ingroup c_api
* @brief Defines API for interacting with system level intrinsics
* @brief Определяет API для вызова системных интринсиков
* @{
*/
@@ -45,7 +45,7 @@ void eosio_assert_message( uint32_t test, const char* msg, uint32_t msg_len );
/**
* Aborts processing of this action and unwinds all pending changes if the test condition is true
*
* @brief Aborts processing of this action and unwinds all pending changes
* @brief Прервать обработку действия и откатить все ожидающие изменения
* @param test - 0 to abort, 1 to ignore
* @param code - the error code
*/
+24 -28
View File
@@ -11,29 +11,25 @@ extern "C" {
/**
* @addtogroup transaction_c Transaction API
* @ingroup c_api
* @brief Defines C API for sending transactions and inline actions
* @brief Определяет C API для отправки транзакций и inline-действий
*
* @details Deferred transactions will not be processed until a future block. They
* can therefore have no effect on the success of failure of their parent
* transaction so long as they appear well formed. If any other condition
* causes the parent transaction to be marked as failing, then the deferred
* transaction will never be processed.
* @details Отложенные транзакции не выполняются до одного из будущих блоков. Поэтому
* при корректном виде они не влияют на успех или неудачу родительской транзакции.
* Если по иным причинам родительская транзакция помечается как неуспешная,
* отложенная транзакция никогда не будет обработана.
*
* Deferred transactions must adhere to the permissions available to the
* parent transaction or, in the future, delegated to the contract account
* for future use.
* Отложенные транзакции должны укладываться в разрешения, доступные родительской
* транзакции, либо (в будущем) делегированные учётной записи контракта.
*
* An inline message allows one contract to send another contract a message
* which is processed immediately after the current message's processing
* ends such that the success or failure of the parent transaction is
* dependent on the success of the message. If an inline message fails in
* processing then the whole tree of transactions and actions rooted in the
* block will me marked as failing and none of effects on the database will
* persist.
* Inline-сообщение позволяет одному контракту отправить другому сообщение,
* обрабатываемое сразу после завершения текущего сообщения; успех или неудача
* родительской транзакции зависит от успеха этого сообщения. При сбое обработки
* inline-сообщения всё дерево транзакций и действий, укоренённое в блоке,
* помечается как неуспешное, и эффекты в базе состояния не сохраняются.
*
* Inline actions and Deferred transactions must adhere to the permissions
* available to the parent transaction or, in the future, delegated to the
* contract account for future use.
* Inline-действия и отложенные транзакции должны укладываться в разрешения,
* доступные родительской транзакции, либо (в будущем) делегированные учётной
* записи контракта.
* @{
*/
@@ -52,7 +48,7 @@ void send_deferred(const uint128_t* sender_id, capi_name payer, const char *seri
/**
* Cancels a deferred transaction.
*
* @brief Cancels a deferred transaction.
* @brief Отменить отложенную транзакцию
* @param sender_id - The id of the sender
*
* @pre The deferred transaction ID exists.
@@ -74,7 +70,7 @@ int cancel_deferred(const uint128_t* sender_id);
/**
* Access a copy of the currently executing transaction.
*
* @brief Access a copy of the currently executing transaction.
* @brief Получить копию текущей выполняемой транзакции
* @param buffer - a buffer to write the current transaction to
* @param size - the size of the buffer, 0 to return required size
* @return the size of the transaction written to the buffer, or number of bytes that can be copied if size==0 passed
@@ -85,7 +81,7 @@ size_t read_transaction(char *buffer, size_t size);
/**
* Gets the size of the currently executing transaction.
*
* @brief Gets the size of the currently executing transaction.
* @brief Получить размер текущей выполняемой транзакции
* @return size of the currently executing transaction
*/
__attribute__((eosio_wasm_import))
@@ -94,7 +90,7 @@ size_t transaction_size( void );
/**
* Gets the block number used for TAPOS on the currently executing transaction.
*
* @brief Gets the block number used for TAPOS on the currently executing transaction.
* @brief Получить номер блока TAPOS для текущей выполняемой транзакции
* @return block number used for TAPOS on the currently executing transaction
* Example:
* @code
@@ -107,7 +103,7 @@ int tapos_block_num( void );
/**
* Gets the block prefix used for TAPOS on the currently executing transaction.
*
* @brief Gets the block prefix used for TAPOS on the currently executing transaction.
* @brief Получить префикс блока TAPOS для текущей выполняемой транзакции
* @return block prefix used for TAPOS on the currently executing transaction
* Example:
* @code
@@ -120,7 +116,7 @@ int tapos_block_prefix( void );
/**
* Gets the expiration of the currently executing transaction.
*
* @brief Gets the expiration of the currently executing transaction.
* @brief Получить срок действия (expiration) текущей выполняемой транзакции
* @return expiration of the currently executing transaction in seconds since Unix epoch
* Example:
* @code
@@ -132,9 +128,9 @@ __attribute__((eosio_wasm_import))
uint32_t expiration( void );
/**
* Retrieves the indicated action from the active transaction.
* Извлечь указанное действие из активной транзакции
*
* @brief Retrieves the indicated action from the active transaction.
* @brief Извлечь указанное действие из активной транзакции
* @param type - 0 for context free action, 1 for action
* @param index - the index of the requested action
* @param buff - output packed buff of the action
@@ -147,7 +143,7 @@ int get_action( uint32_t type, uint32_t index, char* buff, size_t size );
/**
* Retrieve the signed_transaction.context_free_data[index].
*
* @brief Retrieve the signed_transaction.context_free_data[index].
* @brief Извлечь signed_transaction.context_free_data[index]
* @param index - the index of the context_free_data entry to retrieve
* @param buff - output buff of the context_free_data entry
* @param size - amount of context_free_data[index] to retrieve into buff, 0 to report required size
+4 -4
View File
@@ -11,12 +11,12 @@
/**
* @defgroup c_types
* @ingroup c_api
* @brief Specifies builtin types, typedefs and aliases
* @brief Задаёт встроенные типы, typedef и псевдонимы
*/
/**
* @addtogroup c_types
* @brief Specifies builtin types, typedefs and aliases
* @brief Задаёт встроенные типы, typedef и псевдонимы
* @{
*/
@@ -30,7 +30,7 @@
typedef uint64_t capi_name;
/**
* EOSIO Public Key. K1 and R1 keys are 34 bytes. Newer keys can be variable-sized
* Публичный ключ COOPOS. Ключи K1 и R1 — 34 байта. Более новые типы ключей могут быть переменной длины
*/
struct __attribute__((deprecated("newer public key types cannot be represented as a fixed size structure", "char[]")))
capi_public_key {
@@ -38,7 +38,7 @@ capi_public_key {
};
/**
* EOSIO Signature. K1 and R1 signatures are 66 bytes. Newer signatures can be variable-sized
* Подпись COOPOS. Подписи K1 и R1 — 66 байт. Более новые типы подписей могут быть переменной длины
*/
struct __attribute__((deprecated("newer signature types cannot be represented as a fixed size structure", "char[]")))
capi_signature {
+101 -101
View File
@@ -1,6 +1,6 @@
/**
* @file
* @copyright defined in eos/LICENSE
* @copyright определён в eos/LICENSE
*/
#pragma once
#include <cstdlib>
@@ -67,17 +67,17 @@ namespace eosio {
};
/**
* @defgroup action Action
* @defgroup action Действие
* @ingroup contracts
* @brief Defines type-safe C++ wrappers for querying action and sending action
* @note There are some methods from the @ref action that can be used directly from C++
* @brief Типобезопасные C++-обёртки для чтения данных действия и отправки действия
* @note Некоторые методы из @ref action можно вызывать напрямую из C++
*/
/**
* @ingroup action
* @return Unpacked action data casted as T.
* @return Распакованные данные действия, приведённые к типу T.
*
* Example:
* Пример:
*
* @code
* struct dummy_action {
@@ -100,28 +100,28 @@ namespace eosio {
}
/**
* Add the specified account to set of accounts to be notified
* Добавляет указанный аккаунт в множество аккаунтов для уведомления
*
* @ingroup action
* @brief Add the specified account to set of accounts to be notified
* @param notify_account - name of the account to be verified
* @brief Добавляет указанный аккаунт в множество аккаунтов для уведомления
* @param notify_account — имя аккаунта для проверки
*/
inline void require_recipient( name notify_account ){
internal_use_do_not_use::require_recipient( notify_account.value );
}
/**
* All of the listed accounts will be added to the set of accounts to be notified
* Все перечисленные аккаунты будут добавлены в множество аккаунтов для уведомления
*
* This helper method enables you to add multiple accounts to accounts to be notified list with a single
* call rather than having to call the similar C API multiple times.
* Вспомогательный метод позволяет добавить несколько аккаунтов в список уведомляемых одним
* вызовом вместо многократного вызова аналогичного C API.
*
* @ingroup action
* @param notify_account account to be notified
* @param remaining_accounts accounts to be notified
* @note action.code is also considered as part of the set of notified accounts
* @param notify_account аккаунт для уведомления
* @param remaining_accounts аккаунты для уведомления
* @note action.code также считается частью множества уведомляемых аккаунтов
*
* Example:
* Пример:
*
* @code
* require_recipient("Account1"_n, "Account2"_n, "Account3"_n); // throws exception if any of them not in set.
@@ -134,38 +134,38 @@ namespace eosio {
}
/**
* Verifies that @ref name exists in the set of provided auths on a action. Fails if not found.
* Проверяет, что @ref name входит в множество предоставленных полномочий (auths) для действия. Завершается с ошибкой, если не найдено.
*
* @ingroup action
* @param name - name of the account to be verified
* @param name — имя проверяемого аккаунта
*/
inline void require_auth( name n ) {
internal_use_do_not_use::require_auth( n.value );
}
/**
* Returns the time in microseconds from 1970 of the publication_time
* Возвращает время в микросекундах с 1970 года для publication_time
*
* @ingroup action
* @return the time in microseconds from 1970 of the publication_time
* @return время в микросекундах с 1970 года для publication_time
*/
inline time_point publication_time() {
return time_point( microseconds ( internal_use_do_not_use::publication_time() ) );
}
/**
* Get the current receiver of the action
* @return the account which specifies the current receiver of the action
* Возвращает текущего получателя действия
* @return аккаунт — текущий получатель действия
*/
inline name current_receiver() {
return name{internal_use_do_not_use::current_receiver()};
}
/**
* Get the hash of the code currently published on the given account
* @param account Name of the account to hash the code of
* @param full_result Optional: If a full result struct is desired, a pointer to the struct to populate
* @return The SHA256 hash of the specified account's code
* Возвращает хэш кода, опубликованного на указанном аккаунте
* @param account имя аккаунта, код которого хэшируется
* @param full_result необязательно: при необходимости полной структуры результата — указатель на заполняемую структуру
* @return SHA256-хэш кода указанного аккаунта
*/
inline checksum256 get_code_hash( name account, code_hash_result* full_result = nullptr ) {
if (full_result == nullptr)
@@ -206,75 +206,75 @@ namespace eosio {
}
/**
* Copy up to length bytes of current action data to the specified location
* Копирует до len байт данных текущего действия в указанное место
*
* @ingroup action
* @param msg - a pointer where up to length bytes of the current action data will be copied
* @param len - len of the current action data to be copied, 0 to report required size
* @return the number of bytes copied to msg, or number of bytes that can be copied if len==0 passed
* @pre `msg` is a valid pointer to a range of memory at least `len` bytes long
* @post `msg` is filled with packed action data
* @param msg — указатель, куда будут скопированы до len байт данных текущего действия
* @param len — число байт данных текущего действия для копирования; 0 — вернуть требуемый размер
* @return число скопированных в msg байт либо число байт, которые можно скопировать, если передан len==0
* @pre `msg` — корректный указатель на область памяти длиной не менее `len` байт
* @post `msg` заполнен упакованными данными действия
*/
inline uint32_t read_action_data( void* msg, uint32_t len ) {
return internal_use_do_not_use::read_action_data(msg, len);
}
/**
* Get the length of the current action's data field. This method is useful for dynamically sized actions
* Возвращает длину поля данных текущего действия. Полезно для действий с динамическим размером
*
* @return the length of the current action's data field
* @return длина поля данных текущего действия
*/
inline uint32_t action_data_size() {
return internal_use_do_not_use::action_data_size();
}
/**
* Packed representation of a permission level (Authorization)
* Упакованное представление уровня разрешения (авторизация)
*
* @ingroup action
*/
struct permission_level {
/**
* Construct a new permission level object with actor name and permission name
* Создаёт объект уровня разрешения с именем актора и именем разрешения
*
* @param a - Name of the account who owns this authorization
* @param p - Name of the permission
* @param a — имя аккаунта, которому принадлежит эта авторизация
* @param p — имя разрешения
*/
permission_level( name a, name p ):actor(a),permission(p){}
/**
* Default Constructor
* Конструктор по умолчанию
*
*/
permission_level(){}
/**
* Name of the account who owns this permission
* Имя аккаунта, которому принадлежит это разрешение
*/
name actor;
/**
* Name of the permission
* Имя разрешения
*/
name permission;
/**
* Check equality of two permissions
* Проверка равенства двух разрешений
*
* @param a - first permission to compare
* @param b - second permission to compare
* @return true if equal
* @return false if unequal
* @param a — первое сравниваемое разрешение
* @param b — второе сравниваемое разрешение
* @return true, если равны
* @return false, если не равны
*/
friend constexpr bool operator == ( const permission_level& a, const permission_level& b ) {
return std::tie( a.actor, a.permission ) == std::tie( b.actor, b.permission );
}
/**
* Lexicographically compares two permissions
* Лексикографическое сравнение двух разрешений
*
* @param a - first permission to compare
* @param b - second permission to compare
* @return true if a < b
* @return false if a >= b
* @param a — первое сравниваемое разрешение
* @param b — второе сравниваемое разрешение
* @return true, если a < b
* @return false, если a >= b
*/
friend constexpr bool operator < ( const permission_level& a, const permission_level& b ) {
return std::tie( a.actor, a.permission ) < std::tie( b.actor, b.permission );
@@ -284,88 +284,88 @@ namespace eosio {
};
/**
* Require the specified authorization for this action. If this action doesn't contain the specified auth, it will fail.
* Требует указанную авторизацию для этого действия. Если действие не содержит указанной авторизации, выполнение завершится с ошибкой.
*
* @ingroup action
* @param level - Authorization to be required
* @param level — требуемая авторизация
*/
inline void require_auth( const permission_level& level ) {
internal_use_do_not_use::require_auth2( level.actor.value, level.permission.value );
}
/**
* Verifies that @ref n has auth.
* Проверяет, что у @ref n есть авторизация в текущем действии.
*
* @ingroup action
* @param n - name of the account to be verified
* @param n — имя проверяемого аккаунта
*/
inline bool has_auth( name n ) {
return internal_use_do_not_use::has_auth( n.value );
}
/**
* Verifies that @ref n is an existing account.
* Проверяет, что @ref n — существующий аккаунт.
*
* @ingroup action
* @param n - name of the account to check
* @param n — имя проверяемого аккаунта
*/
inline bool is_account( name n ) {
return internal_use_do_not_use::is_account( n.value );
}
/**
* This is the packed representation of an action along with
* meta-data about the authorization levels.
* Упакованное представление действия вместе с
* метаданными об уровнях авторизации.
*
* @ingroup action
*/
struct action {
/**
* Name of the account the action is intended for
* Имя аккаунта, для которого предназначено действие
*/
name account;
/**
* Name of the action
* Имя действия
*/
name name;
/**
* List of permissions that authorize this action
* Список разрешений, авторизующих это действие
*/
std::vector<permission_level> authorization;
/**
* Payload data
* Полезная нагрузка (данные)
*/
std::vector<char> data;
/**
* Default Constructor
* Конструктор по умолчанию
*/
action() = default;
/**
* Construct a new action object with the given permission, action receiver, action name, action struct
* Создаёт объект действия с заданным разрешением, получателем действия, именем действия и структурой действия
*
* @tparam T - Type of action struct, must be serializable by `pack(...)`
* @param auth - The permissions that authorizes this action
* @param a - The name of the account this action is intended for (action receiver)
* @param n - The name of the action
* @param value - The action struct that will be serialized via pack into data
* @tparam T — тип структуры действия, должен сериализоваться через `pack(...)`
* @param auth — разрешение, авторизующее это действие
* @param a — имя аккаунта-получателя действия
* @param n — имя действия
* @param value — структура действия, сериализуемая через pack в data
*/
template<typename T>
action( const permission_level& auth, struct name a, struct name n, T&& value )
:account(a), name(n), authorization(1,auth), data(pack(std::forward<T>(value))) {}
/**
* Construct a new action object with the given list of permissions, action receiver, action name, action struct
* Создаёт объект действия с заданным списком разрешений, получателем, именем действия и структурой действия
*
* @tparam T - Type of action struct, must be serializable by `pack(...)`
* @param auths - The list of permissions that authorize this action
* @param a - The name of the account this action is intended for (action receiver)
* @param n - The name of the action
* @param value - The action struct that will be serialized via pack into data
* @tparam T — тип структуры действия, должен сериализоваться через `pack(...)`
* @param auths — список разрешений, авторизующих это действие
* @param a — имя аккаунта-получателя действия
* @param n — имя действия
* @param value — структура действия, сериализуемая через pack в data
*/
template<typename T>
action( std::vector<permission_level> auths, struct name a, struct name n, T&& value )
@@ -378,7 +378,7 @@ namespace eosio {
/// @endcond
/**
* Send the action as inline action
* Отправляет действие как встроенное (inline)
*/
void send() const {
auto serialize = pack(*this);
@@ -386,9 +386,9 @@ namespace eosio {
}
/**
* Send the action as inline context free action
* Отправляет действие как встроенное контекстно-свободное (context free)
*
* @pre This action should not contain any authorizations
* @pre это действие не должно содержать авторизаций
*/
void send_context_free() const {
eosio::check( authorization.size() == 0, "context free actions cannot have authorizations");
@@ -397,10 +397,10 @@ namespace eosio {
}
/**
* Retrieve the unpacked data as T
* Возвращает распакованные данные как T
*
* @tparam T expected type of data
* @return the action data
* @tparam T ожидаемый тип данных
* @return данные действия
*/
template<typename T>
T data_as() {
@@ -488,10 +488,10 @@ namespace eosio {
}
/**
* Wrapper for an action object.
* Обёртка над объектом действия.
*
* @brief Used to wrap an a particular action to simplify the process of other contracts sending inline actions to "wrapped" action.
* Example:
* @brief Обёртка для конкретного действия, упрощающая отправку встроенных (inline) действий к этому действию из других контрактов.
* Пример:
* @code
* // defined by contract writer of the actions
* using transfer_act = action_wrapper<"transfer"_n, &token::transfer>;
@@ -628,29 +628,29 @@ INLINE_ACTION_SENDER3( CONTRACT_CLASS, NAME, ::eosio::name(#NAME) )
#define INLINE_ACTION_SENDER(...) BLUEGRASS_META_OVERLOAD(INLINE_ACTION_SENDER,__VA_ARGS__)(__VA_ARGS__)
/**
* Send an inline-action from inside a contract.
* Отправка встроенного (inline) действия из контракта.
*
* @brief A macro to simplify calling inline actions
* @details The send inline action macro is intended to simplify the process of calling inline actions. When calling new actions from existing actions
* EOSIO supports two communication models, inline and deferred. Inline actions are executed as part of the current transaction. This macro
* creates an @ref action using the supplied parameters and automatically calls action.send() on this newly created action.
* @brief Макрос для упрощения вызова встроенных (inline) действий
* @details Макрос отправки встроенного действия упрощает вызов встроенных действий. При вызове новых действий из уже выполняемых
* COOPOS поддерживает две модели обмена: встроенные (inline) и отложенные (deferred). Встроенные действия выполняются как часть текущей транзакции. Этот макрос
* создаёт @ref action с переданными параметрами и автоматически вызывает action.send() для этого действия.
*
* Example:
* Пример:
* @code
* SEND_INLINE_ACTION( *this, transfer, {st.issuer,N(active)}, {st.issuer, to, quantity, memo} );
* @endcode
*
* The example above is taken from eosio.token.
* This example:
* uses the passed in, dereferenced `this` pointer, to call this.get_self() i.e. the eosio.token contract;
* calls the eosio.token::transfer() action;
* uses the active permission of the "issuer" account;
* uses parameters st.issuer, to, quantity and memo.
* This macro creates an action struct used to 'send()' (call) transfer(account_name from, account_name to, asset quantity, string memo)
* Приведённый выше пример взят из контракта токена COOPOS (аналог стандартного токена).
* В примере:
* используется переданный разыменованный указатель `this` для вызова this.get_self(), т.е. контракта токена COOPOS;
* вызывается действие transfer контракта токена COOPOS;
* используется разрешение active аккаунта «issuer»;
* передаются параметры st.issuer, to, quantity и memo.
* Макрос создаёт структуру действия для вызова send() — вызова transfer(account_name from, account_name to, asset quantity, string memo)
*
* @param CONTRACT - The contract to call, which contains the action being sent, maps to the @ref account
* @param NAME - The name of the action to be called, maps to a @ref name
* @param ... - The authorising permission, maps to an @ref authorization , followed by the parameters of the action, maps to a @ref data.
* @param CONTRACT — вызываемый контракт, содержащий отправляемое действие; соответствует @ref account
* @param NAME — имя вызываемого действия; соответствует @ref name
* @param ... — авторизующее разрешение; соответствует @ref authorization, затем параметры действия; соответствуют @ref data.
*/
#define SEND_INLINE_ACTION( CONTRACT, NAME, ... )\
+22 -22
View File
@@ -5,14 +5,14 @@
/**
* @defgroup contract Contract
* @defgroup contract Контракт (Contract)
* @ingroup contracts
* @ingroup types
* @brief Defines contract type which is %base class for every EOSIO contract
* @brief Определяет тип контракта — %базовый класс для каждого контракта COOPOS
*/
/**
* Helper macros to reduce the verbosity for common contracts
* Вспомогательные макросы для сокращения шаблонного кода в типовых контрактах
* @ingroup contract
*/
#define CONTRACT class [[eosio::contract]]
@@ -22,72 +22,72 @@
namespace eosio {
/**
* %Base class for EOSIO contract.
* %Базовый класс контракта COOPOS.
*
* @ingroup contract
* @details %A new contract should derive from this class, so it can make use of EOSIO_ABI macro.
* @details Новый контракт должен наследовать этот класс, чтобы можно было использовать макрос EOSIO_ABI.
*/
class contract {
public:
/**
* Construct a new contract given the contract name
* Создаёт контракт с заданными параметрами
*
* @param self - The name of the account this contract is deployed on
* @param first_receiver - The account the incoming action was first received at.
* @param ds - The datastream used
* @param self — имя аккаунта, на котором развёрнут контракт
* @param first_receiver — аккаунт, на который действие впервые поступило
* @param ds — используемый поток данных (datastream)
*/
contract( name self, name first_receiver, datastream<const char*> ds ):_self(self),_first_receiver(first_receiver),_ds(ds) {}
/**
*
* Get this contract name
* Имя этого контракта
*
* @return name - The name of this contract
* @return name — имя контракта
*/
inline name get_self()const { return _self; }
/**
* The first_receiver name of the action this contract is processing.
* Имя first_receiver для обрабатываемого действия (устаревший метод).
*
* @return name - The first_receiver name of the action this contract is processing.
* @return name — первый получатель текущего действия (параметр конструктора `first_receiver`)
*/
[[deprecated]]
inline name get_code()const { return _first_receiver; }
/**
* The account the incoming action was first received at.
* Аккаунт, на который входящее действие впервые поступило.
*
* @return name - The first_receiver name of the action this contract is processing.
* @return name — первый получатель текущего действия (параметр конструктора `first_receiver`)
*/
inline name get_first_receiver()const { return _first_receiver; }
/**
* Get the datastream for this contract
* Поток данных (datastream) этого контракта
*
* @return datastream<const char*> - The datastream for this contract
* @return datastream<const char*> — поток данных контракта
*/
inline datastream<const char*>& get_datastream() { return _ds; }
/**
* Get the datastream for this contract
* Поток данных (datastream) этого контракта (константная версия)
*
* @return datastream<const char*> - The datastream for this contract
* @return datastream<const char*> — поток данных контракта
*/
inline const datastream<const char*>& get_datastream()const { return _ds; }
protected:
/**
* The name of the account this contract is deployed on.
* Имя аккаунта, на котором развёрнут контракт.
*/
name _self;
/**
* The account the incoming action was first received at.
* Аккаунт, на который входящее действие впервые поступило.
*/
name _first_receiver;
/**
* The datastream for this contract
* Поток данных (datastream) контракта
*/
datastream<const char*> _ds = datastream<const char*>(nullptr, 0);
};
@@ -7,9 +7,9 @@
namespace eosio {
/**
* @defgroup dispatcher Dispatcher
* @defgroup dispatcher Диспетчер (Dispatcher)
* @ingroup contracts
* @brief Defines C++ functions to dispatch action to proper action handler inside a contract
* @brief Определяет функции C++ для маршрутизации действия к соответствующему обработчику внутри контракта
*/
@@ -27,13 +27,13 @@ namespace eosio {
/// @endcond
/**
* This method will dynamically dispatch an incoming set of actions to
* Динамически направляет входящие действия к обработчикам вида
*
* ```
* static Contract::on( ActionType )
* ```
*
* For this to work the Actions must be derived from eosio::contract
* Контракт, принимающий действия, должен наследовать eosio::contract
*
* @ingroup dispatcher
*
@@ -51,15 +51,15 @@ namespace eosio {
/**
* Unpack the received action and execute the correponding action handler
* Распаковывает полученное действие и вызывает соответствующий обработчик
*
* @ingroup dispatcher
* @tparam T - The contract class that has the correponding action handler, this contract should be derived from eosio::contract
* @tparam Q - The namespace of the action handler function
* @tparam Args - The arguments that the action handler accepts, i.e. members of the action
* @param obj - The contract object that has the correponding action handler
* @param func - The action handler
* @return true
* @tparam T — класс контракта с обработчиком действия; должен наследовать eosio::contract
* @tparam Args — типы аргументов обработчика (поля действия)
* @param self — имя, передаваемое в конструктор экземпляра контракта
* @param code — код, передаваемый в конструктор экземпляра контракта
* @param func — указатель на метод-обработчик действия
* @return true — если действие распаковано и обработчик вызван
*/
template<typename T, typename... Args>
bool execute_action( name self, name code, void (T::*func)(Args...) ) {
@@ -105,14 +105,14 @@ namespace eosio {
/// @endcond
/**
* Convenient macro to create contract apply handler
* Удобный макрос для создания обработчика apply контракта
*
* @ingroup dispatcher
* @note To be able to use this macro, the contract needs to be derived from eosio::contract
* @param TYPE - The class name of the contract
* @param MEMBERS - The sequence of available actions supported by this contract
* @note Чтобы использовать макрос, класс контракта должен наследовать eosio::contract
* @param TYPE — имя класса контракта
* @param MEMBERS — последовательность поддерживаемых действий контракта
*
* Example:
* Пример:
* @code
* EOSIO_DISPATCH( eosio::bios, (setpriv)(setalimits)(setglimits)(setprods)(reqauth) )
* @endcode
+7 -7
View File
@@ -1,6 +1,6 @@
/**
* @file
* @copyright defined in eos/LICENSE
* @copyright как определено в eos/LICENSE
*/
#pragma once
#include "action.hpp"
@@ -14,16 +14,16 @@ static_assert( sizeof(long) == sizeof(int), "unexpected size difference" );
#endif
/**
* @defgroup core Core API
* @brief C++ Core API for chain-agnostic smart-contract functionality
* @defgroup core API ядра
* @brief C++ API ядра для функциональности смарт-контрактов, не зависящей от конкретной сети
*/
/**
* @defgroup contracts Contracts API
* @brief C++ Contracts API for chain-dependent smart-contract functionality
* @defgroup contracts API контрактов
* @brief C++ API контрактов для функциональности смарт-контрактов, зависящей от сети COOPOS
*/
/**
* @defgroup types Types
* @brief C++ Types API for data layout of data-structures available for the EOSIO platform
* @defgroup types Типы
* @brief C++ API типов для компоновки данных структур, доступных на платформе COOPOS
*/
+182 -182
View File
@@ -1,6 +1,6 @@
/**
* @file
* @copyright defined in eos/LICENSE
* @copyright как определено в eos/LICENSE
*/
#pragma once
@@ -22,7 +22,7 @@
#include <memory>
/**
* @defgroup multiindex Multi Index Table
* @defgroup multiindex Многоиндексная таблица (Multi Index)
* @ingroup contracts
*/
@@ -341,13 +341,13 @@ namespace _multi_index_detail {
}
/**
* The indexed_by struct is used to instantiate the indices for the Multi-Index table. In EOSIO, up to 16 secondary indices can be specified.
* Структура indexed_by используется для задания индексов многоиндексной таблицы. В COOPOS можно задать до 16 вторичных индексов.
*
* @ingroup multiindex
* @tparam IndexName - is the name of the index. The name must be provided as an EOSIO base32 encoded 64-bit integer and must conform to the EOSIO naming requirements of a maximum of 13 characters, the first twelve from the lowercase characters a-z, digits 1-5, and ".", and if there is a 13th character, it is restricted to lowercase characters a-p and ".".
* @tparam Extractor - is a function call operator that takes a const reference to the table object type and returns either a secondary key type or a reference to a secondary key type. It is recommended to use the `eosio::const_mem_fun` template.
* @tparam IndexName — имя индекса. Имя задаётся как 64-битное целое в кодировке base32 COOPOS и должно соответствовать правилам имён COOPOS: не более 13 символов; первые двенадцать — строчные буквы az, цифры 1–5 и «.»; если есть 13-й символ, допускаются только строчные ap и «.».
* @tparam Extractor — функтор (оператор вызова функции), принимающий const-ссылку на тип объекта строки таблицы и возвращающий тип вторичного ключа или ссылку на него. Рекомендуется использовать шаблон `eosio::const_mem_fun`.
*
* Example:
* Пример:
*
*
* @code
@@ -381,22 +381,22 @@ struct indexed_by {
/**
* @ingroup multiindex
*
* @brief Defines EOSIO Multi Index Table
* @details EOSIO Multi-Index API provides a C++ interface to the EOSIO database. It is patterned after Boost Multi Index Container.
* EOSIO Multi-Index table requires exactly a uint64_t primary key. For the table to be able to retrieve the primary key,
* the object stored inside the table is required to have a const member function called primary_key() that returns uint64_t.
* EOSIO Multi-Index table also supports up to 16 secondary indices. The type of the secondary indices could be any of:
* @brief Определяет многоиндексную таблицу COOPOS (Multi Index Table)
* @details API многоиндексных таблиц COOPOS даёт C++-интерфейс к базе данных COOPOS и устроен по образцу Boost Multi Index Container.
* Многоиндексная таблица COOPOS требует ровно один первичный ключ типа uint64_t. Чтобы таблица могла получать первичный ключ,
* у хранимого в ней объекта должна быть const-функция-член primary_key(), возвращающая uint64_t.
* Многоиндексная таблица COOPOS также поддерживает до 16 вторичных индексов. Тип вторичного индекса может быть одним из:
* - uint64_t
* - uint128_t
* - double
* - long double
* - eosio::checksum256
*
* @tparam TableName - name of the table
* @tparam T - type of the data stored inside the table
* @tparam Indices - secondary indices for the table, up to 16 indices is supported here
* @tparam TableName — имя таблицы
* @tparam T — тип данных, хранимых в таблице
* @tparam Indices — вторичные индексы таблицы; поддерживается до 16 индексов
*
* Example:
* Пример:
*
* @code
* #include <eosiolib/eosio.hpp>
@@ -644,24 +644,24 @@ class multi_index
}
/**
* Gets the object with the smallest primary key in the case where the secondary key is not unique.
* Возвращает объект с наименьшим первичным ключом, если вторичный ключ не уникален.
*
* Avoid the common pitfall of copy-assigning the T& reference returned
* to a stack-allocated local variable and then passing that into modify of the multi-index.
* The most common mistake is when the local variable is defined as auto
* typename, instead it should be of type auto& or decltype(auto).
* Избегайте типичной ошибки: присвоить возвращённую ссылку T& локальной переменной на стеке
* и передать её в modify многоиндексной таблицы.
* Часто ошибка в том, что локальная переменная объявлена как auto без ссылки;
* нужно использовать auto& или decltype(auto).
*/
const T& get( secondary_key_type&& secondary, const char* error_msg = "unable to find secondary key" )const {
return get( secondary, error_msg );
}
/**
* Gets the object with the smallest primary key in the case where the secondary key is not unique.
* Возвращает объект с наименьшим первичным ключом, если вторичный ключ не уникален.
*
* Avoid the common pitfall of copy-assigning the T& reference returned
* to a stack-allocated local variable and then passing that into modify of the multi-index.
* The most common mistake is when the local variable is defined as auto
* typename, instead it should be of type auto& or decltype(auto).
* Избегайте типичной ошибки: присвоить возвращённую ссылку T& локальной переменной на стеке
* и передать её в modify многоиндексной таблицы.
* Часто ошибка в том, что локальная переменная объявлена как auto без ссылки;
* нужно использовать auto& или decltype(auto).
*/
const T& get( const secondary_key_type& secondary, const char* error_msg = "unable to find secondary key" )const {
auto result = find( secondary );
@@ -705,9 +705,9 @@ class multi_index
return {this, &mi};
}
/**
* Warning: the interator_to can have undefined behavior if the caller
* passes in a reference to a stack-allocated object rather than the
* reference returned by get or by dereferencing a const_iterator.
* Предупреждение: iterator_to может вести себя неопределённо, если вызывающий код
* передаёт ссылку на объект на стеке вместо ссылки, возвращённой get
* или полученной разыменованием const_iterator.
*/
const_iterator iterator_to( const T& obj ) {
using namespace _multi_index_detail;
@@ -843,27 +843,27 @@ class multi_index
public:
/**
* Constructs an instance of a Multi-Index table.
* Создаёт экземпляр многоиндексной таблицы.
* @ingroup multiindex
*
* @param code - Account that owns table
* @param scope - Scope identifier within the code hierarchy
* @param code — аккаунт-владелец таблицы
* @param scope — идентификатор области (scope) в иерархии кода
*
* @pre code and scope member properties are initialized
* @post each secondary index table initialized
* @post Secondary indices are updated to refer to the newly added object. If the secondary index tables do not exist, they are created.
* @post The payer is charged for the storage usage of the new object and, if the table (and secondary index tables) must be created, for the overhead of the table creation.
* @pre свойства code и scope заданы
* @post каждая таблица вторичного индекса инициализирована
* @post Вторичные индексы обновлены для ссылки на новый объект; при отсутствии таблиц вторичных индексов они создаются.
* @post С плательщика взимается хранение нового объекта и, при необходимости создания таблицы (и таблиц вторичных индексов), накладные расходы на создание.
*
* Notes
* The `eosio::multi_index` template has template parameters `<name::raw TableName, typename T, typename... Indices>`, where:
* - `TableName` is the name of the table, maximum 12 characters long, characters in the name from the set of lowercase letters, digits 1 to 5, and the "." (period) character and is converted to a eosio::raw - which wraps uint64_t;
* - `T` is the object type (i.e., row definition);
* - `Indices` is a list of up to 16 secondary indices.
* - Each must be a default constructable class or struct
* - Each must have a function call operator that takes a const reference to the table object type and returns either a secondary key type or a reference to a secondary key type
* - It is recommended to use the eosio::const_mem_fun template
* Замечания
* Шаблон `eosio::multi_index` имеет параметры `<name::raw TableName, typename T, typename... Indices>`, где:
* - `TableName` — имя таблицы, не более 12 символов из набора строчных букв, цифр 1–5 и «.»; преобразуется в eosio::raw (обёртка над uint64_t);
* - `T` — тип объекта (определение строки);
* - `Indices` — список до 16 вторичных индексов.
* - Каждый элемент должен быть классом или структурой с конструктором по умолчанию
* - У каждого должен быть оператор вызова, принимающий const-ссылку на тип объекта строки и возвращающий вторичный ключ или ссылку на него
* - Рекомендуется шаблон eosio::const_mem_fun
*
* Example:
* Пример:
*
* @code
* #include <eosiolib/eosio.hpp>
@@ -894,12 +894,12 @@ class multi_index
{}
/**
* Returns the `code` member property.
* Возвращает свойство-член `code`.
* @ingroup multiindex
*
* @return Account name of the Code that owns the Primary Table.
* @return Имя аккаунта кода, которому принадлежит первичная таблица.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -915,12 +915,12 @@ class multi_index
name get_code()const { return _code; }
/**
* Returns the `scope` member property.
* Возвращает свойство-член `scope`.
* @ingroup multiindex
*
* @return Scope id of the Scope within the Code of the Current Receiver under which the desired Primary Table instance can be found.
* @return Идентификатор области (scope) в коде текущего получателя, под которым находится нужный экземпляр первичной таблицы.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -999,12 +999,12 @@ class multi_index
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
/**
* Returns an iterator pointing to the object_type with the lowest primary key value in the Multi-Index table.
* Возвращает итератор на объект с наименьшим значением первичного ключа в многоиндексной таблице.
* @ingroup multiindex
*
* @return An iterator pointing to the object_type with the lowest primary key value in the Multi-Index table.
* @return Итератор на объект с наименьшим первичным ключом в многоиндексной таблице.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1025,12 +1025,12 @@ class multi_index
}
/**
* Returns an iterator pointing to the object_type with the lowest primary key value in the Multi-Index table.
* Возвращает итератор на объект с наименьшим значением первичного ключа в многоиндексной таблице.
* @ingroup multiindex
*
* @return An iterator pointing to the object_type with the lowest primary key value in the Multi-Index table.
* @return Итератор на объект с наименьшим первичным ключом в многоиндексной таблице.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1049,12 +1049,12 @@ class multi_index
const_iterator begin()const { return cbegin(); }
/**
* Returns an iterator referring to the `past-the-end` element in the multi index container. The `past-the-end` element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced.
* Возвращает итератор на элемент «после последнего» в контейнере multi_index. Такой элемент — теоретический следующий за последним; на реальный объект не указывает и разыменовывать его нельзя.
* @ingroup multiindex
*
* @return An iterator referring to the `past-the-end` element in the multi index container.
* @return Итератор на позицию «после последнего» в контейнере multi_index.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1073,12 +1073,12 @@ class multi_index
const_iterator cend()const { return const_iterator( this ); }
/**
* Returns an iterator referring to the `past-the-end` element in the multi index container. The `past-the-end` element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced.
* Возвращает итератор на элемент «после последнего» в контейнере multi_index. Такой элемент — теоретический следующий за последним; на реальный объект не указывает и разыменовывать его нельзя.
* @ingroup multiindex
*
* @return An iterator referring to the `past-the-end` element in the multi index container.
* @return Итератор на позицию «после последнего» в контейнере multi_index.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1097,12 +1097,12 @@ class multi_index
const_iterator end()const { return cend(); }
/**
* Returns a reverse iterator pointing to the `object_type` with the highest primary key value in the Multi-Index table.
* Возвращает обратный итератор на объект с наибольшим первичным ключом в многоиндексной таблице.
* @ingroup multiindex
*
* @return A reverse iterator pointing to the `object_type` with the highest primary key value in the Multi-Index table.
* @return Обратный итератор на объект с наибольшим первичным ключом в многоиндексной таблице.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1132,12 +1132,12 @@ class multi_index
const_reverse_iterator crbegin()const { return std::make_reverse_iterator(cend()); }
/**
* Returns a reverse iterator pointing to the `object_type` with the highest primary key value in the Multi-Index table.
* Возвращает обратный итератор на объект с наибольшим первичным ключом в многоиндексной таблице.
* @ingroup multiindex
*
* @return A reverse iterator pointing to the `object_type` with the highest primary key value in the Multi-Index table.
* @return Обратный итератор на объект с наибольшим первичным ключом в многоиндексной таблице.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1167,12 +1167,12 @@ class multi_index
const_reverse_iterator rbegin()const { return crbegin(); }
/**
* Returns an iterator pointing to the `object_type` with the lowest primary key value in the Multi-Index table.
* Возвращает итератор на объект с наименьшим первичным ключом в многоиндексной таблице.
* @ingroup multiindex
*
* @return An iterator pointing to the `object_type` with the lowest primary key value in the Multi-Index table.
* @return Итератор на объект с наименьшим первичным ключом в многоиндексной таблице.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1203,12 +1203,12 @@ class multi_index
const_reverse_iterator crend()const { return std::make_reverse_iterator(cbegin()); }
/**
* Returns an iterator pointing to the `object_type` with the lowest primary key value in the Multi-Index table.
* Возвращает итератор на объект с наименьшим первичным ключом в многоиндексной таблице.
* @ingroup multiindex
*
* @return An iterator pointing to the `object_type` with the lowest primary key value in the Multi-Index table.
* @return Итератор на объект с наименьшим первичным ключом в многоиндексной таблице.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1239,13 +1239,13 @@ class multi_index
const_reverse_iterator rend()const { return crend(); }
/**
* Searches for the `object_type` with the lowest primary key that is greater than or equal to a given primary key.
* Ищет объект с наименьшим первичным ключом, который больше или равен заданному первичному ключу.
* @ingroup multiindex
*
* @param primary - Primary key that establishes the target value for the lower bound search.
* @return An iterator pointing to the `object_type` that has the lowest primary key that is greater than or equal to `primary`. If an object could not be found, or if the table does not exist**, it will return the `end` iterator.
* @param primary — первичный ключ, задающий целевое значение для поиска нижней границы
* @return Итератор на объект с наименьшим первичным ключом ≥ `primary`. Если объект не найден или таблицы нет**, возвращается итератор `end`.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the get_index() example below. Replace myaction() {...}
@@ -1287,13 +1287,13 @@ class multi_index
}
/**
* Searches for the `object_type` with the lowest primary key that is greater than a given primary key.
* Ищет объект с наименьшим первичным ключом, строго большим заданного первичного ключа.
* @ingroup multiindex
*
* @param primary - Primary key that establishes the target value for the upper bound search
* @return An iterator pointing to the `object_type` that has the lowest primary key that is greater than a given `primary` key. If an object could not be found, or if the table does not exist**, it will return the `end` iterator.
* @param primary — первичный ключ, задающий целевое значение для поиска верхней границы
* @return Итератор на объект с наименьшим первичным ключом, большим `primary`. Если объект не найден или таблицы нет**, возвращается итератор `end`.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the get_index() example below. Replace myaction() {...}
@@ -1333,16 +1333,16 @@ class multi_index
}
/**
* Returns an available primary key.
* Возвращает свободный первичный ключ.
* @ingroup multiindex
*
* @return An available (unused) primary key value.
* @return Доступное (неиспользованное) значение первичного ключа.
*
* Notes:
* Intended to be used in tables in which the primary keys of the table are strictly intended to be auto-incrementing, and thus will never be set to custom values by the contract. Violating this expectation could result in the table appearing to be full due to inability to allocate an available primary key.
* Ideally this method would only be used to determine the appropriate primary key to use within new objects added to a table in which the primary keys of the table are strictly intended from the beginning to be autoincrementing and thus will not ever be set to custom arbitrary values by the contract. Violating this agreement could result in the table appearing full when in reality there is plenty of space left.
* Замечания:
* Предназначено для таблиц, где первичные ключи строго автоинкрементируются и контракт никогда не задаёт произвольные значения. Нарушение этого ожидания может привести к тому, что таблица будет казаться заполненной из‑за невозможности выделить свободный первичный ключ.
* В идеале метод используют только для выбора первичного ключа новых строк в таблицах, изначально рассчитанных на автоинкремент без произвольных значений со стороны контракта. Нарушение этого соглашения может дать ложное ощущение переполнения при наличии свободного места.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1383,14 +1383,14 @@ class multi_index
}
/**
* Returns an appropriately typed Secondary Index.
* Возвращает вторичный индекс нужного типа.
* @ingroup multiindex
*
* @tparam IndexName - the ID of the desired secondary index
* @tparam IndexName — идентификатор нужного вторичного индекса
*
* @return An index of the appropriate type: Primitive 64-bit unsigned integer key (idx64), Primitive 128-bit unsigned integer key (idx128), 128-bit fixed-size lexicographical key (idx128), 256-bit fixed-size lexicographical key (idx256), Floating point key, Double precision floating point key, Long Double (quadruple) precision floating point key
* @return Индекс соответствующего типа: 64-битный беззнаковый целочисленный ключ (idx64), 128-битный беззнаковый целочисленный ключ (idx128), 128-битный ключ фиксированной длины в лексикографическом порядке (idx128), 256-битный ключ фиксированной длины (idx256), ключ с плавающей точкой, ключ double, ключ long double (четверная точность)
*
* Example:
* Пример:
*
* @code
* #include <eosiolib/eosio.hpp>
@@ -1437,14 +1437,14 @@ class multi_index
}
/**
* Returns an appropriately typed Secondary Index.
* Возвращает вторичный индекс нужного типа.
* @ingroup multiindex
*
* @tparam IndexName - the ID of the desired secondary index
* @tparam IndexName — идентификатор нужного вторичного индекса
*
* @return An index of the appropriate type: Primitive 64-bit unsigned integer key (idx64), Primitive 128-bit unsigned integer key (idx128), 128-bit fixed-size lexicographical key (idx128), 256-bit fixed-size lexicographical key (idx256), Floating point key, Double precision floating point key, Long Double (quadruple) precision floating point key
* @return Индекс соответствующего типа: 64-битный беззнаковый целочисленный ключ (idx64), 128-битный беззнаковый целочисленный ключ (idx128), 128-битный ключ фиксированной длины в лексикографическом порядке (idx128), 256-битный ключ фиксированной длины (idx256), ключ с плавающей точкой, ключ double, ключ long double (четверная точность)
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the get_index() example. Replace myaction() {...}
@@ -1488,14 +1488,14 @@ class multi_index
}
/**
* Returns an iterator to the given object in a Multi-Index table.
* Возвращает итератор на заданный объект в многоиндексной таблице.
* @ingroup multiindex
*
* @param obj - A reference to the desired object
* @param obj — ссылка на нужный объект
*
* @return An iterator to the given object
* @return Итератор на этот объект
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the get_index() example. Replace myaction() {...}
@@ -1522,9 +1522,9 @@ class multi_index
* EOSIO_DISPATCH( addressbook, (myaction) )
* @endcode
*
* Warning: the interator_to can have undefined behavior if the caller
* passes in a reference to a stack-allocated object rather than the
* reference returned by get or by dereferencing a const_iterator.
* Предупреждение: iterator_to может вести себя неопределённо, если вызывающий код
* передаёт ссылку на объект на стеке вместо ссылки, возвращённой get
* или полученной разыменованием const_iterator.
*/
const_iterator iterator_to( const T& obj )const {
const auto& objitem = static_cast<const item&>(obj);
@@ -1532,22 +1532,22 @@ class multi_index
return {this, &objitem};
}
/**
* Adds a new object (i.e., row) to the table.
* Добавляет в таблицу новый объект (строку).
* @ingroup multiindex
*
* @param payer - Account name of the payer for the Storage usage of the new object
* @param constructor - Lambda function that does an in-place initialization of the object to be created in the table
* @param payer — имя аккаунта-плательщика за хранение нового объекта
* @param constructor — лямбда для инициализации создаваемого объекта на месте
*
* @pre A multi index table has been instantiated
* @post A new object is created in the Multi-Index table, with a unique primary key (as specified in the object). The object is serialized and written to the table. If the table does not exist, it is created.
* @post Secondary indices are updated to refer to the newly added object. If the secondary index tables do not exist, they are created.
* @post The payer is charged for the storage usage of the new object and, if the table (and secondary index tables) must be created, for the overhead of the table creation.
* @pre создан экземпляр многоиндексной таблицы
* @post В многоиндексной таблице создан новый объект с уникальным первичным ключом (как в объекте). Объект сериализуется и записывается; при отсутствии таблицы она создаётся.
* @post Вторичные индексы обновлены для нового объекта; при отсутствии таблиц вторичных индексов они создаются.
* @post С плательщика взимается хранение нового объекта и при необходимости создания таблицы (и вторичных индексов) — накладные расходы.
*
* @return A primary key iterator to the newly created object
* @return Итератор по первичному ключу на созданный объект
*
* Exception - The account is not authorized to write to the table.
* Исключение — аккаунт не уполномочен записывать в таблицу.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1614,26 +1614,26 @@ class multi_index
}
/**
* Modifies an existing object in a table.
* Изменяет существующий объект в таблице.
* @ingroup multiindex
*
* @param itr - an iterator pointing to the object to be updated
* @param payer - account name of the payer for the storage usage of the updated row
* @param updater - lambda function that updates the target object
* @param itr — итератор на обновляемый объект
* @param payer — имя аккаунта-плательщика за хранение обновлённой строки
* @param updater — лямбда, обновляющая целевой объект
*
* @pre itr points to an existing element
* @pre payer is a valid account that is authorized to execute the action and be billed for storage usage.
* @pre itr указывает на существующий элемент
* @pre payer — действительный аккаунт, уполномоченный выполнять действие и оплачивать хранение
*
* @post The modified object is serialized, then replaces the existing object in the table.
* @post Secondary indices are updated; the primary key of the updated object is not changed.
* @post The payer is charged for the storage usage of the updated object.
* @post If payer is the same as the existing payer, payer only pays for the usage difference between existing and updated object (and is refunded if this difference is negative).
* @post If payer is different from the existing payer, the existing payer is refunded for the storage usage of the existing object.
* @post Изменённый объект сериализуется и заменяет прежний в таблице.
* @post Вторичные индексы обновлены; первичный ключ объекта не меняется.
* @post С плательщика взимается хранение обновлённого объекта.
* @post Если payer совпадает с прежним плательщиком, списывается только разница объёма хранения (при отрицательной разнице — возврат).
* @post Если payer другой, прежнему плательщику возвращается стоимость хранения старого объекта.
*
* Exceptions:
* If called with an invalid precondition, execution is aborted.
* Исключения:
* При нарушении предусловий выполнение прерывается.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1661,26 +1661,26 @@ class multi_index
}
/**
* Modifies an existing object in a table.
* Изменяет существующий объект в таблице.
* @ingroup multiindex
*
* @param obj - a reference to the object to be updated
* @param payer - account name of the payer for the storage usage of the updated row
* @param updater - lambda function that updates the target object
* @param obj — ссылка на обновляемый объект
* @param payer — имя аккаунта-плательщика за хранение обновлённой строки
* @param updater — лямбда, обновляющая целевой объект
*
* @pre obj is an existing object in the table
* @pre payer is a valid account that is authorized to execute the action and be billed for storage usage.
* @pre obj — существующий объект в таблице
* @pre payer — действительный аккаунт, уполномоченный выполнять действие и оплачивать хранение
*
* @post The modified object is serialized, then replaces the existing object in the table.
* @post Secondary indices are updated; the primary key of the updated object is not changed.
* @post The payer is charged for the storage usage of the updated object.
* @post If payer is the same as the existing payer, payer only pays for the usage difference between existing and updated object (and is refunded if this difference is negative).
* @post If payer is different from the existing payer, the existing payer is refunded for the storage usage of the existing object.
* @post Изменённый объект сериализуется и заменяет прежний в таблице.
* @post Вторичные индексы обновлены; первичный ключ объекта не меняется.
* @post С плательщика взимается хранение обновлённого объекта.
* @post Если payer совпадает с прежним плательщиком, списывается только разница объёма хранения (при отрицательной разнице — возврат).
* @post Если payer другой, прежнему плательщику возвращается стоимость хранения старого объекта.
*
* Exceptions:
* If called with an invalid precondition, execution is aborted.
* Исключения:
* При нарушении предусловий выполнение прерывается.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1753,15 +1753,15 @@ class multi_index
}
/**
* Retrieves an existing object from a table using its primary key.
* Извлекает существующий объект из таблицы по первичному ключу.
* @ingroup multiindex
*
* @param primary - Primary key value of the object.
* @return A constant reference to the object containing the specified primary key.
* @param primary — значение первичного ключа объекта
* @return Константная ссылка на объект с указанным первичным ключом
*
* Exception - No object matches the given key.
* Исключение — нет объекта с данным ключом
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1777,12 +1777,12 @@ class multi_index
* EOSIO_DISPATCH( addressbook, (myaction) )
* @endcode
*
* Warning:
* Предупреждение:
*
* Avoid the common pitfall of copy-assigning the T& reference returned
* to a stack-allocated local variable and then passing that into modify of the multi-index.
* The most common mistake is when the local variable is defined as auto
* typename, instead it should be of type auto& or decltype(auto).
* Избегайте присвоения возвращённой ссылки T& локальной переменной на стеке
* и передачи её в modify многоиндексной таблицы.
* Частая ошибка — объявить локальную переменную как auto без ссылки;
* нужно auto& или decltype(auto).
*/
template<typename PK>
const T& get( PK primary, const char* error_msg = "unable to find key" )const {
@@ -1792,13 +1792,13 @@ class multi_index
}
/**
* Search for an existing object in a table using its primary key.
* Ищет существующий объект в таблице по первичному ключу.
* @ingroup multiindex
*
* @param primary - Primary key value of the object
* @return An iterator to the found object which has a primary key equal to `primary` OR the `end` iterator of the referenced table if an object with primary key `primary` is not found.
* @param primary — значение первичного ключа объекта
* @return Итератор на найденный объект с первичным ключом `primary` либо итератор `end`, если объекта с ключом `primary` нет.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1831,12 +1831,12 @@ class multi_index
}
/**
* Search for an existing object in a table using its primary key.
* Ищет существующий объект в таблице по первичному ключу.
* @ingroup multiindex
*
* @param primary - Primary key value of the object
* @param error_msg - error message if an object with primary key `primary` is not found.
* @return An iterator to the found object which has a primary key equal to `primary` OR throws an exception if an object with primary key `primary` is not found.
* @param primary — значение первичного ключа объекта
* @param error_msg — сообщение об ошибке, если объекта с ключом `primary` нет
* @return Итератор на объект с первичным ключом `primary` либо выброс исключения, если объекта нет
*/
template<typename PK>
@@ -1856,24 +1856,24 @@ class multi_index
}
/**
* Remove an existing object from a table using its primary key.
* Удаляет существующий объект из таблицы (по итератору).
* @ingroup multiindex
*
* @param itr - An iterator pointing to the object to be removed
* @param itr — итератор на удаляемый объект
*
* @pre itr points to an existing element
* @post The object is removed from the table and all associated storage is reclaimed.
* @post Secondary indices associated with the table are updated.
* @post The existing payer for storage usage of the object is refunded for the table and secondary indices usage of the removed object, and if the table and indices are removed, for the associated overhead.
* @pre itr указывает на существующий элемент
* @post Объект удалён из таблицы, связанное хранение освобождено.
* @post Обновлены вторичные индексы таблицы.
* @post Прежнему плательщику за хранение возвращается стоимость таблицы и вторичных индексов для удалённого объекта; при удалении таблицы и индексов — также накладные расходы.
*
* @return For the signature with `const_iterator`, returns a pointer to the object following the removed object.
* @return Для сигнатуры с `const_iterator` — итератор на объект, следующий за удалённым.
*
* Exceptions:
* The object to be removed is not in the table.
* The action is not authorized to modify the table.
* The given iterator is invalid.
* Исключения:
* Удаляемого объекта нет в таблице.
* Действие не уполномочено изменять таблицу.
* Недопустимый итератор.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1903,22 +1903,22 @@ class multi_index
}
/**
* Remove an existing object from a table using its primary key.
* Удаляет существующий объект из таблицы.
* @ingroup multiindex
*
* @param obj - Object to be removed
* @param obj — удаляемый объект
*
* @pre obj is an existing object in the table
* @post The object is removed from the table and all associated storage is reclaimed.
* @post Secondary indices associated with the table are updated.
* @post The existing payer for storage usage of the object is refunded for the table and secondary indices usage of the removed object, and if the table and indices are removed, for the associated overhead.
* @pre obj — существующий объект в таблице
* @post Объект удалён из таблицы, связанное хранение освобождено.
* @post Обновлены вторичные индексы таблицы.
* @post Прежнему плательщику за хранение возвращается стоимость таблицы и вторичных индексов для удалённого объекта; при удалении таблицы и индексов — также накладные расходы.
*
* Exceptions:
* The object to be removed is not in the table.
* The action is not authorized to modify the table.
* The given iterator is invalid.
* Исключения:
* Удаляемого объекта нет в таблице.
* Действие не уполномочено изменять таблицу.
* Недопустимый итератор.
*
* Example:
* Пример:
*
* @code
* // This assumes the code from the constructor example. Replace myaction() {...}
@@ -1,6 +1,6 @@
/**
* @file
* @copyright defined in eos/LICENSE
* @copyright см. eos/LICENSE
*/
#pragma once
@@ -33,17 +33,17 @@ namespace eosio {
}
/**
* Checks if a transaction is authorized by a provided set of keys and permissions
* Проверяет, авторизована ли транзакция заданным набором ключей и разрешений (permissions)
* @ingroup permission
*
* @param trx_data - pointer to the start of the serialized transaction
* @param trx_size - size (in bytes) of the serialized transaction
* @param pubkeys_data - pointer to the start of the serialized vector of provided public keys
* @param pubkeys_size - size (in bytes) of serialized vector of provided public keys (can be 0 if no public keys are to be provided)
* @param perms_data - pointer to the start of the serialized vector of provided permissions (empty permission name acts as wildcard)
* @param perms_size - size (in bytes) of the serialized vector of provided permissions
* @param trx_data — указатель на начало сериализованной транзакции
* @param trx_size — размер (в байтах) сериализованной транзакции
* @param pubkeys_data — указатель на начало сериализованного вектора открытых ключей
* @param pubkeys_size — размер (в байтах) сериализованного вектора ключей (0, если ключи не передаются)
* @param perms_data — указатель на начало сериализованного вектора разрешений (пустое имя разрешения — подстановка (совпадает с любым))
* @param perms_size — размер (в байтах) сериализованного вектора разрешений
*
* @return 1 if the transaction is authorized, 0 otherwise
* @return 1, если транзакция авторизована; иначе 0
*/
bool
check_transaction_authorization( const char* trx_data, uint32_t trx_size,
@@ -53,18 +53,18 @@ namespace eosio {
}
/**
* Checks if a permission is authorized by a provided delay and a provided set of keys and permissions
* Проверяет, авторизовано ли разрешение заданной задержкой и набором ключей и разрешений
* @ingroup permission
*
* @param account - the account owner of the permission
* @param permission - the name of the permission to check for authorization
* @param pubkeys_data - pointer to the start of the serialized vector of provided public keys
* @param pubkeys_size - size (in bytes) of serialized vector of provided public keys (can be 0 if no public keys are to be provided)
* @param perms_data - pointer to the start of the serialized vector of provided permissions (empty permission name acts as wildcard)
* @param perms_size - size (in bytes) of the serialized vector of provided permissions
* @param delay - the provided delay in microseconds (cannot exceed INT64_MAX)
* @param account — аккаунт-владелец разрешения
* @param permission — имя проверяемого разрешения
* @param pubkeys_data — указатель на начало сериализованного вектора открытых ключей
* @param pubkeys_size — размер (в байтах) сериализованного вектора ключей (0, если ключи не передаются)
* @param perms_data — указатель на начало сериализованного вектора разрешений (пустое имя — подстановка (совпадает с любым))
* @param perms_size — размер (в байтах) сериализованного вектора разрешений
* @param delay — задержка в микросекундах (не больше INT64_MAX)
*
* @return 1 if the permission is authorized, 0 otherwise
* @return 1, если разрешение авторизовано; иначе 0
*/
bool
check_permission_authorization( name account,
@@ -79,21 +79,21 @@ namespace eosio {
/**
* @defgroup permission Permission
* @defgroup permission Разрешение (permission)
* @ingroup contracts
* @ingroup types
* @brief Defines C++ API functions for validating authorization of keys and permissions
* @brief Определяет функции C++ API COOPOS для проверки авторизации ключей и разрешений (permissions)
*/
/**
* Checks if a transaction is authorized by a provided set of keys and permissions
* Проверяет, авторизована ли транзакция заданным набором ключей и разрешений
* @ingroup permission
*
* @param trx - the transaction for which to check authorizations
* @param provided_permissions - the set of permissions which have authorized the transaction (empty permission name acts as wildcard)
* @param provided_keys - the set of public keys which have authorized the transaction
* @param trx — транзакция, для которой проверяется авторизация
* @param provided_permissions — набор разрешений, которыми подписана транзакция (пустое имя — подстановка (совпадает с любым))
* @param provided_keys — набор открытых ключей, которыми подписана транзакция
*
* @return whether the transaction was authorized by provided keys and permissions
* @return true, если транзакция авторизована указанными ключами и разрешениями
*/
bool
check_transaction_authorization( const transaction& trx,
@@ -127,17 +127,17 @@ namespace eosio {
}
/**
* Checks if a permission is authorized by a provided delay and a provided set of keys and permissions
* Проверяет, авторизовано ли разрешение заданной задержкой и набором ключей и разрешений
*
* @ingroup permission
*
* @param account - the account owner of the permission
* @param permission - the permission name to check for authorization
* @param provided_keys - the set of public keys which have authorized the transaction
* @param provided_permissions - the set of permissions which have authorized the transaction (empty permission name acts as wildcard)
* @param provided_delay_us - the provided delay in microseconds (cannot exceed INT64_MAX)
* @param account — аккаунт-владелец разрешения
* @param permission — имя проверяемого разрешения
* @param provided_keys — набор открытых ключей, подписавших операцию
* @param provided_permissions — набор разрешений (пустое имя — подстановка (совпадает с любым))
* @param provided_delay_us — задержка в микросекундах (не больше INT64_MAX)
*
* @return whether the permission was authorized by provided delay, keys, and permissions
* @return true, если разрешение удовлетворено указанной задержкой, ключами и разрешениями
*/
bool
check_permission_authorization( name account,
@@ -174,14 +174,14 @@ namespace eosio {
}
/**
* Returns the last used time of a permission
* Возвращает время последнего использования разрешения
*
* @ingroup permission
*
* @param account - the account owner of the permission
* @param permission - the name of the permission
* @param account — аккаунт-владелец разрешения
* @param permission — имя разрешения
*
* @return the last used time (in microseconds since Unix epoch) of the permission
* @return момент последнего использования (микросекунды с начала эпохи Unix)
*/
time_point get_permission_last_used( name account, name permission ) {
return time_point(
@@ -191,13 +191,13 @@ namespace eosio {
}
/**
* Returns the creation time of an account
* Возвращает время создания аккаунта
*
* @ingroup permission
*
* @param account - the account
* @param account — аккаунт
*
* @return the creation time (in microseconds since Unix epoch) of the account
* @return момент создания (микросекунды с начала эпохи Unix)
*/
time_point get_account_creation_time( name account ) {
return time_point(
@@ -12,6 +12,9 @@ namespace eosio {
__attribute__((eosio_wasm_import))
bool is_privileged( uint64_t account );
__attribute__((eosio_wasm_import))
void get_account_ram_usage( uint64_t account, int64_t* used_ram_bytes );
__attribute__((eosio_wasm_import))
void get_resource_limits( uint64_t account, int64_t* ram_bytes, int64_t* net_weight, int64_t* cpu_weight );
@@ -39,116 +42,116 @@ namespace eosio {
}
/**
* @defgroup privileged Privileged
* @defgroup privileged Привилегированный API
* @ingroup contracts
* @brief Defines C++ Privileged API
* @brief Определяет привилегированный C++ API COOPOS
*/
/**
* Tunable blockchain configuration that can be changed via consensus
* Настраиваемые параметры цепочки COOPOS, изменяемые по консенсусу
* @ingroup privileged
*/
struct blockchain_parameters {
/**
* The maximum net usage in instructions for a block
* @brief the maximum net usage in instructions for a block
* Максимальное использование сети в инструкциях для блока
* @brief максимальное использование сети в инструкциях для блока
*/
uint64_t max_block_net_usage;
/**
* The target percent (1% == 100, 100%= 10,000) of maximum net usage; exceeding this triggers congestion handling
* @brief The target percent (1% == 100, 100%= 10,000) of maximum net usage; exceeding this triggers congestion handling
* Целевой процент (1% == 100, 100% == 10000) от максимального использования сети; при превышении включается обработка перегрузки
* @brief целевой процент (1% == 100, 100% == 10000) от максимального использования сети; превышение включает обработку перегрузки
*/
uint32_t target_block_net_usage_pct;
/**
* The maximum objectively measured net usage that the chain will allow regardless of account limits
* @brief The maximum objectively measured net usage that the chain will allow regardless of account limits
* Максимальное объективно измеряемое использование сети, которое цепочка COOPOS допускает независимо от лимитов аккаунтов
* @brief максимальное объективно измеряемое использование сети, которое цепочка допускает независимо от лимитов аккаунтов
*/
uint32_t max_transaction_net_usage;
/**
* The base amount of net usage billed for a transaction to cover incidentals
* Базовый объём использования сети, тарифицируемый для транзакции (накладные расходы)
*/
uint32_t base_per_transaction_net_usage;
/**
* The amount of net usage leeway available whilst executing a transaction (still checks against new limits without leeway at the end of the transaction)
* @brief The amount of net usage leeway available whilst executing a transaction (still checks against new limits without leeway at the end of the transaction)
* Запас по использованию сети при выполнении транзакции (в конце транзакции проверка выполняется по новым лимитам без запаса)
* @brief запас по использованию сети при выполнении транзакции (в конце транзакции проверка всё равно выполняется по новым лимитам без запаса)
*/
uint32_t net_usage_leeway;
/**
* The numerator for the discount on net usage of context-free data
* @brief The numerator for the discount on net usage of context-free data
* Числитель скидки на использование сети для данных без контекста (context-free)
* @brief числитель скидки на использование сети для данных без контекста (context-free)
*/
uint32_t context_free_discount_net_usage_num;
/**
* The denominator for the discount on net usage of context-free data
* @brief The denominator for the discount on net usage of context-free data
* Знаменатель скидки на использование сети для данных без контекста (context-free)
* @brief знаменатель скидки на использование сети для данных без контекста (context-free)
*/
uint32_t context_free_discount_net_usage_den;
/**
* The maximum billable cpu usage (in microseconds) for a block
* @brief The maximum billable cpu usage (in microseconds) for a block
* Максимальная тарифицируемая нагрузка CPU (в микросекундах) для блока
* @brief максимальная тарифицируемая нагрузка CPU (в микросекундах) для блока
*/
uint32_t max_block_cpu_usage;
/**
* The target percent (1% == 100, 100%= 10,000) of maximum cpu usage; exceeding this triggers congestion handling
* @brief The target percent (1% == 100, 100%= 10,000) of maximum cpu usage; exceeding this triggers congestion handling
* Целевой процент (1% == 100, 100% == 10000) от максимального использования CPU; при превышении включается обработка перегрузки
* @brief целевой процент (1% == 100, 100% == 10000) от максимального использования CPU; превышение включает обработку перегрузки
*/
uint32_t target_block_cpu_usage_pct;
/**
* The maximum billable cpu usage (in microseconds) that the chain will allow regardless of account limits
* @brief The maximum billable cpu usage (in microseconds) that the chain will allow regardless of account limits
* Максимальная тарифицируемая нагрузка CPU (в микросекундах), которую цепочка COOPOS допускает независимо от лимитов аккаунтов
* @brief максимальная тарифицируемая нагрузка CPU (в микросекундах), которую цепочка допускает независимо от лимитов аккаунтов
*/
uint32_t max_transaction_cpu_usage;
/**
* The minimum billable cpu usage (in microseconds) that the chain requires
* @brief The minimum billable cpu usage (in microseconds) that the chain requires
* Минимальная тарифицируемая нагрузка CPU (в микросекундах), которую требует цепочка COOPOS
* @brief минимальная тарифицируемая нагрузка CPU (в микросекундах), которую требует цепочка
*/
uint32_t min_transaction_cpu_usage;
/**
* Maximum lifetime of a transacton
* @brief Maximum lifetime of a transacton
* Максимальное время жизни транзакции
* @brief максимальное время жизни транзакции
*/
uint32_t max_transaction_lifetime;
/**
* The number of seconds after the time a deferred transaction can first execute until it expires
* @brief the number of seconds after the time a deferred transaction can first execute until it expires
* Число секунд от момента, когда отложенная транзакция может впервые выполниться, до её истечения
* @brief число секунд от момента, когда отложенная транзакция может впервые выполниться, до её истечения
*/
uint32_t deferred_trx_expiration_window;
/**
* The maximum number of seconds that can be imposed as a delay requirement by authorization checks
* @brief The maximum number of seconds that can be imposed as a delay requirement by authorization checks
* Максимальное число секунд задержки, которое могут потребовать проверки авторизации
* @brief максимальное число секунд задержки, которое могут потребовать проверки авторизации
*/
uint32_t max_transaction_delay;
/**
* Maximum size of inline action
* @brief Maximum size of inline action
* Максимальный размер встроенного (inline) действия
* @brief максимальный размер встроенного (inline) действия
*/
uint32_t max_inline_action_size;
/**
* Maximum depth of inline action
* @brief Maximum depth of inline action
* Максимальная глубина вложенности встроенных (inline) действий
* @brief максимальная глубина вложенности встроенных (inline) действий
*/
uint16_t max_inline_action_depth;
/**
* Maximum authority depth
* @brief Maximum authority depth
* Максимальная глубина полномочий (authority)
* @brief максимальная глубина полномочий (authority)
*/
uint16_t max_authority_depth;
@@ -167,66 +170,79 @@ namespace eosio {
};
/**
* Set the blockchain parameters
* Устанавливает параметры цепочки COOPOS
*
* @ingroup privileged
* @param params - New blockchain parameters to set
* @param params — новые параметры цепочки
*/
void set_blockchain_parameters(const eosio::blockchain_parameters& params);
/**
* Retrieve the blolckchain parameters
* Возвращает параметры цепочки COOPOS
*
* @ingroup privileged
* @param params - It will be replaced with the retrieved blockchain params
* @param params — заполняется полученными параметрами цепочки
*/
void get_blockchain_parameters(eosio::blockchain_parameters& params);
/**
* Get the resource limits of an account
* Возвращает использование RAM аккаунтом
*
* @ingroup privileged
* @param account - name of the account whose resource limit to get
* @param ram_bytes - output to hold retrieved ram limit in absolute bytes
* @param net_weight - output to hold net limit
* @param cpu_weight - output to hold cpu limit
* @param account — имя аккаунта
* @param used_ram_bytes — выход: использовано RAM в байтах
*/
inline void get_account_ram_usage( name account, int64_t& used_ram_bytes ) {
internal_use_do_not_use::get_account_ram_usage( account.value, &used_ram_bytes);
}
/**
* Возвращает лимиты ресурсов аккаунта
*
* @ingroup privileged
* @param account — имя аккаунта
* @param ram_bytes — выход: лимит RAM в байтах
* @param net_weight — выход: вес сети (net)
* @param cpu_weight — выход: вес CPU
*/
inline void get_resource_limits( name account, int64_t& ram_bytes, int64_t& net_weight, int64_t& cpu_weight ) {
internal_use_do_not_use::get_resource_limits( account.value, &ram_bytes, &net_weight, &cpu_weight );
}
/**
* Set the resource limits of an account
* Задаёт лимиты ресурсов аккаунта
*
* @ingroup privileged
* @param account - name of the account whose resource limit to be set
* @param ram_bytes - ram limit in absolute bytes
* @param net_weight - fractionally proportionate net limit of available resources based on (weight / total_weight_of_all_accounts)
* @param cpu_weight - fractionally proportionate cpu limit of available resources based on (weight / total_weight_of_all_accounts)
* @param account — имя аккаунта
* @param ram_bytes — лимит RAM в байтах
* @param net_weight — доля лимита сети пропорционально (вес / сумма весов всех аккаунтов)
* @param cpu_weight — доля лимита CPU пропорционально (вес / сумма весов всех аккаунтов)
*/
inline void set_resource_limits( name account, int64_t ram_bytes, int64_t net_weight, int64_t cpu_weight ) {
internal_use_do_not_use::set_resource_limits( account.value, ram_bytes, net_weight, cpu_weight );
}
/**
* Proposes a schedule change using the legacy producer key format
* Предлагает смену расписания в устаревшем формате ключей производителей
*
* @ingroup privileged
* @note Once the block that contains the proposal becomes irreversible, the schedule is promoted to "pending" automatically. Once the block that promotes the schedule is irreversible, the schedule will become "active"
* @param producers - vector of producer keys
* @note Когда блок с предложением становится необратимым, расписание автоматически переходит в состояние «ожидающее» (pending). Когда блок, продвигающий расписание, становится необратимым, расписание становится «активным» (active)
* @param producers — вектор ключей производителей
*
* @return an optional value of the version of the new proposed schedule if successful
* @return при успехе — номер версии нового предложенного расписания; иначе пусто
*/
std::optional<uint64_t> set_proposed_producers( const std::vector<producer_key>& prods );
/**
* Proposes a schedule change using the more flexible key format
* Предлагает смену расписания в более гибком формате полномочий
*
* @ingroup privileged
* @note Once the block that contains the proposal becomes irreversible, the schedule is promoted to "pending" automatically. Once the block that promotes the schedule is irreversible, the schedule will become "active"
* @param producers - vector of producer authorities
* @note Когда блок с предложением становится необратимым, расписание автоматически переходит в «pending». Когда блок, продвигающий расписание, становится необратимым, расписание становится «active»
* @param producers — вектор полномочий производителей
*
* @return an optional value of the version of the new proposed schedule if successful
* @return при успехе — версия нового предложенного расписания; иначе пусто
*/
inline std::optional<uint64_t> set_proposed_producers( const std::vector<producer_authority>& prods ) {
auto packed_prods = eosio::pack( prods );
@@ -237,33 +253,33 @@ namespace eosio {
}
/**
* Check if an account is privileged
* Проверяет, является ли аккаунт привилегированным
*
* @ingroup privileged
* @param account - name of the account to be checked
* @return true if the account is privileged
* @return false if the account is not privileged
* @param account — имя проверяемого аккаунта
* @return true, если аккаунт привилегированный
* @return false, если аккаунт не привилегированный
*/
inline bool is_privileged( name account ) {
return internal_use_do_not_use::is_privileged( account.value );
}
/**
* Set the privileged status of an account
* Задаёт привилегированный статус аккаунта
*
* @ingroup privileged
* @param account - name of the account whose privileged account to be set
* @param is_priv - privileged status
* @param account — имя аккаунта
* @param is_priv — признак привилегированного статуса
*/
inline void set_privileged( name account, bool is_priv ) {
internal_use_do_not_use::set_privileged( account.value, is_priv );
}
/**
* Pre-activate protocol feature
* Предварительно активирует возможность протокола COOPOS
*
* @ingroup privileged
* @param feature_digest - digest of the protocol feature to pre-activate
* @param feature_digest — дайджест возможности протокола для предактивации
*/
inline void preactivate_feature( const checksum256& feature_digest ) {
auto feature_digest_data = feature_digest.extract_as_byte_array();
@@ -6,28 +6,28 @@
namespace eosio {
/**
* @defgroup producer_key Producer Key
* @defgroup producer_key Ключ производителя
* @ingroup contracts
* @ingroup types
* @brief Maps producer with its signing key, used for producer schedule
* @brief Сопоставляет производителя с его ключом подписи блока; используется в расписании производителей
*/
/**
* Maps producer with its signing key, used for producer schedule
* Сопоставляет производителя с ключом подписи блока; используется в расписании производителей
*
* @ingroup producer_key
*/
struct producer_key {
/**
* Name of the producer
* Имя производителя
*
* @ingroup producer_key
*/
name producer_name;
/**
* Block signing key used by this producer
* Ключ подписи блока, используемый этим производителем
*
* @ingroup producer_key
*/
@@ -45,25 +45,25 @@ namespace eosio {
};
/**
* @defgroup producer_schedule Producer Schedule
* @defgroup producer_schedule Расписание производителей
* @ingroup contracts
* @ingroup types
* @brief Defines both the order, account name, and signing keys of the active set of producers.
* @brief Задаёт порядок, имена аккаунтов и ключи подписи активного набора производителей.
*/
/**
* Defines both the order, account name, and signing keys of the active set of producers.
* Задаёт порядок, имена аккаунтов и ключи подписи активного набора производителей
*
* @ingroup producer_schedule
*/
struct producer_schedule {
/**
* Version number of the schedule. It is sequentially incrementing version number
* Номер версии расписания (монотонно возрастающий)
*/
uint32_t version;
/**
* List of producers for this schedule, including its signing key
* Список производителей расписания с ключами подписи
*/
std::vector<producer_key> producers;
@@ -71,29 +71,29 @@ namespace eosio {
};
/**
* @defgroup producer_authority Producer Authority
* @defgroup producer_authority Полномочие производителя
* @ingroup contracts
* @ingroup types
* @brief Maps producer with its a flexible authority structure, used for producer schedule
* @brief Сопоставляет производителя с гибкой структурой полномочий; используется в расписании производителей
*/
/**
* pairs a public key with an integer weight
* Сопоставляет открытый ключ с целочисленным весом
*
* @ingroup producer_authority
*/
struct key_weight {
/**
* public key used in a weighted threshold multi-sig authority
* Открытый ключ во взвешенном пороговом полномочии с несколькими подписями (multi-sig)
*
* @brief public key used in a weighted threshold multi-sig authority
* @brief открытый ключ во взвешенном пороговом полномочии с несколькими подписями (multi-sig)
*/
public_key key;
/**
* weight associated with a signature from the private key associated with the accompanying public key
* Вес подписи закрытым ключом, соответствующим этому открытому ключу
*
* @brief weight of the public key
* @brief вес открытого ключа
*/
uint16_t weight;
@@ -101,25 +101,24 @@ namespace eosio {
};
/**
* block signing authority version 0
* this authority allows for a weighted threshold multi-sig per-producer
* Полномочие подписи блока, версия 0: взвешенный пороговый multi-sig на производителя
*
* @ingroup producer_authority
*
* @brief weighted threshold multi-sig authority
* @brief взвешенное пороговое полномочие с несколькими подписями (multi-sig)
*/
struct block_signing_authority_v0 {
/**
* minimum threshold of accumulated weights from component keys that satisfies this authority
* Минимальный порог суммы весов компонентных ключей, при котором полномочие считается удовлетворённым
*
* @brief minimum threshold of accumulated weights from component keys that satisfies this authority
* @brief минимальный порог суммы весов компонентных ключей, при котором полномочие считается удовлетворённым
*/
uint32_t threshold;
/**
* component keys and their associated weights
* Компонентные ключи и связанные с ними веса
*
* @brief component keys and their associated weights
* @brief компонентные ключи и связанные с ними веса
*/
std::vector<key_weight> keys;
@@ -129,30 +128,30 @@ namespace eosio {
};
/**
* variant of all possible block signing authorities
* Вариант (std::variant) всех допустимых полномочий подписи блока
*
* @ingroup producer_authority
*/
using block_signing_authority = std::variant<block_signing_authority_v0>;
/**
* Maps producer with its signing key, used for producer schedule
* Сопоставляет производителя с полномочием подписи блока; используется в расписании производителей
*
* @ingroup producer_authority
*
* @brief Maps producer with its signing key
* @brief Сопоставляет производителя с его ключом подписи
*/
struct producer_authority {
/**
* Name of the producer
* Имя производителя
*
* @brief Name of the producer
* @brief имя производителя
*/
name producer_name;
/**
* The block signing authority used by this producer
* Полномочие подписи блока для этого производителя
*/
block_signing_authority authority;
@@ -164,10 +163,10 @@ namespace eosio {
};
/**
* Returns back the list of active producer names.
* Возвращает список имён активных производителей
*
* @ingroup producer_schedule
*/
std::vector<name> get_active_producers();
} /// namespace eosio
} /// пространство имён eosio
@@ -18,9 +18,9 @@ __attribute__((eosio_wasm_import)) uint32_t get_active_security_group(char* data
} // namespace internal_use_do_not_use
/**
* @defgroup security_group Security Group
* @defgroup security_group Группа безопасности
* @ingroup contracts
* @brief Defines C++ security group API
* @brief Определяет C++ API группы безопасности
*/
struct security_group {
@@ -30,12 +30,12 @@ struct security_group {
};
/**
* Propose new participants to the security group.
* Предложить новых участников группы безопасности.
*
* @ingroup security_group
* @param participants - the participants.
* @param participants — участники.
*
* @return -1 if proposing a new security group was unsuccessful, otherwise returns 0.
* @return -1, если предложение новой группы безопасности не удалось, иначе 0.
*/
inline int64_t add_security_group_participants(const std::set<name>& participants) {
auto packed_participants = eosio::pack( participants );
@@ -43,12 +43,12 @@ inline int64_t add_security_group_participants(const std::set<name>& participant
}
/**
* Propose to remove participants from the security group.
*å
* Предложить исключить участников из группы безопасности.
*
* @ingroup security_group
* @param participants - the participants.
*å
* @return -1 if proposing a new security group was unsuccessful, otherwise returns 0.
* @param participants — участники.
*
* @return -1, если предложение новой группы безопасности не удалось, иначе 0.
*/
inline int64_t remove_security_group_participants(const std::set<name>& participants){
auto packed_participants = eosio::pack( participants );
@@ -56,12 +56,12 @@ inline int64_t remove_security_group_participants(const std::set<name>& particip
}
/**
* Check if the specified accounts are all in the active security group.
* Проверить, что все указанные аккаунты входят в активную группу безопасности.
*
* @ingroup security_group
* @param participants - the participants.
* @param participants — участники.
*
* @return Returns true if the specified accounts are all in the active security group.
* @return true, если все указанные аккаунты входят в активную группу безопасности.
*/
inline bool in_active_security_group(const std::set<name>& participants){
auto packed_participants = eosio::pack( participants );
@@ -69,13 +69,10 @@ inline bool in_active_security_group(const std::set<name>& participants){
}
/**
* Gets the active security group
* Возвращает активную группу безопасности (распакованную структуру).
*
* @ingroup security_group
* @param[out] packed_security_group - the buffer containing the packed security_group.
*
* @return Returns the size required in the buffer (if the buffer is too small, nothing is written).
*
* @return объект security_group с данными активной группы
*/
inline security_group get_active_security_group() {
size_t buffer_size = internal_use_do_not_use::get_active_security_group(0, 0);
@@ -5,39 +5,39 @@
namespace eosio {
/**
* @defgroup singleton Singleton Table
* @defgroup singleton Singleton-таблица
* @ingroup contracts
* @brief Defines EOSIO Singleton Table used with %multiindex
* @brief Определяет singleton-таблицу COOPOS для использования с %multiindex
*/
/**
* This wrapper uses a single table to store named objects various types.
* Обёртка использует одну таблицу для хранения именованных объектов различных типов.
*
* @ingroup singleton
* @tparam SingletonName - the name of this singleton variable
* @tparam T - the type of the singleton
* @tparam SingletonName — имя этой singleton-переменной
* @tparam T — тип singleton
*/
template<name::raw SingletonName, typename T>
class singleton
{
/**
* Primary key of the data inside singleton table
* Первичный ключ данных в singleton-таблице
*/
constexpr static uint64_t pk_value = static_cast<uint64_t>(SingletonName);
/**
* Structure of data inside the singleton table
* Структура данных в singleton-таблице
*/
struct row {
/**
* Value to be stored inside the singleton table
* Значение, хранимое в singleton-таблице
*/
T value;
/**
* Get primary key of the data
* Возвращает первичный ключ данных
*
* @return uint64_t - Primary Key
* @return uint64_t — первичный ключ
*/
uint64_t primary_key() const { return pk_value; }
@@ -49,28 +49,28 @@ namespace eosio {
public:
/**
* Construct a new singleton object given the table's owner and the scope
* Создаёт объект singleton по владельцу таблицы и области видимости (scope)
*
* @param code - The table's owner
* @param scope - The scope of the table
* @param code — владелец таблицы
* @param scope scope таблицы
*/
singleton( name code, uint64_t scope ) : _t( code, scope ) {}
/**
* Check if the singleton table exists
* Проверяет существование singleton-таблицы
*
* @return true - if exists
* @return false - otherwise
* @return true — если существует
* @return false — иначе
*/
bool exists() {
return _t.find( pk_value ) != _t.end();
}
/**
* Get the value stored inside the singleton table. Will throw an exception if it doesn't exist
* Возвращает значение из singleton-таблицы. Выбрасывает исключение, если записи нет
*
* @brief Get the value stored inside the singleton table
* @return T - The value stored
* @brief Возвращает значение, хранящееся в singleton-таблице
* @return T — сохранённое значение
*/
T get() {
auto itr = _t.find( pk_value );
@@ -79,10 +79,10 @@ namespace eosio {
}
/**
* Get the value stored inside the singleton table. If it doesn't exist, it will return the specified default value
* Возвращает значение из singleton-таблицы. Если записи нет — указанное значение по умолчанию
*
* @param def - The default value to be returned in case the data doesn't exist
* @return T - The value stored
* @param def — значение по умолчанию, если данных нет
* @return T — сохранённое значение
*/
T get_or_default( const T& def = T() ) {
auto itr = _t.find( pk_value );
@@ -90,11 +90,11 @@ namespace eosio {
}
/**
* Get the value stored inside the singleton table. If it doesn't exist, it will create a new one with the specified default value
* Возвращает значение из singleton-таблицы. Если записи нет — создаёт её с указанным значением по умолчанию
*
* @param bill_to_account - The account to bill for the newly created data if the data doesn't exist
* @param def - The default value to be created in case the data doesn't exist
* @return T - The value stored
* @param bill_to_account — аккаунт, с которого списывается оплата за новые данные, если записи не было
* @param def — значение по умолчанию при создании записи
* @return T — сохранённое значение
*/
T get_or_create( name bill_to_account, const T& def = T() ) {
auto itr = _t.find( pk_value );
@@ -103,10 +103,10 @@ namespace eosio {
}
/**
* Set new value to the singleton table
* Записывает новое значение в singleton-таблицу
*
* @param value - New value to be set
* @param bill_to_account - Account to pay for the new value
* @param value — новое значение
* @param bill_to_account — аккаунт, с которого списывается оплата за запись
*/
void set( const T& value, name bill_to_account ) {
auto itr = _t.find( pk_value );
@@ -118,7 +118,7 @@ namespace eosio {
}
/**
* Remove the only data inside singleton table
* Удаляет единственную запись в singleton-таблице
*/
void remove( ) {
auto itr = _t.find( pk_value );
+22 -23
View File
@@ -1,6 +1,6 @@
/**
* @file
* @copyright defined in eos/LICENSE
* @copyright как определено в eos/LICENSE
*/
#pragma once
#include "../../core/eosio/time.hpp"
@@ -31,26 +31,25 @@ namespace eosio {
}
/**
* @addtogroup system System
* @addtogroup system Системные функции (System)
* @ingroup contracts
* @brief Defines time related functions and eosio_exit
* @brief Определяет функции, связанные со временем, и eosio_exit
*/
/**
* This method will abort execution of wasm without failing the contract.
* This is used to bypass all cleanup / destructors that would normally be
* called.
* Прерывает выполнение WASM без признания контракта провалившимся.
* Используется, чтобы обойти обычную очистку и деструкторы при нормальном выходе.
*
<html><p><b>
WARNING: this method will immediately abort execution of wasm code that is on
the stack and would be executed as the method normally returned.
Problems can occur with write-caches, RAII, reference counting
when this method aborts execution of wasm code immediately.
ВНИМАНИЕ: метод немедленно обрывает выполнение WASM-кода на стеке, который
выполнился бы при обычном возврате из функции.
Возможны проблемы с кэшами записи, RAII, подсчётом ссылок,
если выполнение WASM прерывается сразу.
</b></p></html>
* @ingroup system
*
* @param code - the exit code
* Example:
* @param code — код выхода
* Пример:
*
* @code
* eosio_exit(0);
@@ -64,39 +63,39 @@ namespace eosio {
}
/**
* Returns the time in microseconds from 1970 of the current block as a time_point
* Время текущего блока в микросекундах от 1970 года как time_point
*
* @ingroup system
* @return time in microseconds from 1970 of the current block as a time_point
* @return время текущего блока в микросекундах от 1970 года (time_point)
*/
time_point current_time_point();
/**
* Returns the time in microseconds from 1970 of the current block as a block_timestamp
* Время текущего блока в микросекундах от 1970 года как block_timestamp
*
* @ingroup system
* @return time in microseconds from 1970 of the current block as a block_timestamp
* @return время текущего блока в микросекундах от 1970 года (block_timestamp)
*/
block_timestamp current_block_time();
using block_num_t = uint32_t;
/**
* Returns the current block number
* Номер текущего блока
*
* @ingroup system
* @return the current block number
* @return номер текущего блока
*/
inline block_num_t current_block_number() {
return internal_use_do_not_use::get_block_num();
}
/**
* Check if specified protocol feature has been activated
* Проверяет, активирована ли указанная протокольная возможность в COOPOS
*
* @ingroup system
* @param feature_digest - digest of the protocol feature
* @return true if the specified protocol feature has been activated, false otherwise
* @param feature_digest — дайджест протокольной возможности
* @return true, если возможность активирована, иначе false
*/
inline bool is_feature_activated( const checksum256& feature_digest ) {
auto feature_digest_data = feature_digest.extract_as_byte_array();
@@ -106,10 +105,10 @@ namespace eosio {
}
/**
* Return name of account that sent current inline action
* Имя аккаунта, отправившего текущее inline-действие
*
* @ingroup system
* @return name of account that sent the current inline action (empty name if not called from inline action)
* @return имя отправителя текущего inline-действия (пустое имя, если вызов не из inline-действия)
*/
inline name get_sender() {
return name( internal_use_do_not_use::get_sender() );
@@ -1,6 +1,6 @@
/**
* @file
* @copyright defined in eos/LICENSE
* @copyright см. eos/LICENSE
*/
#pragma once
#include "action.hpp"
@@ -43,23 +43,20 @@ namespace eosio {
}
/**
* @defgroup transaction Transaction
* @defgroup transaction Транзакция
* @ingroup contracts
* @brief Type-safe C++ wrappers for transaction C API
* @brief Типобезопасные C++-обёртки над C API транзакций COOPOS
*
* @details An inline message allows one contract to send another contract a message
* which is processed immediately after the current message's processing
* ends such that the success or failure of the parent transaction is
* dependent on the success of the message. If an inline message fails in
* processing then the whole tree of transactions and actions rooted in the
* block will me marked as failing and none of effects on the database will
* persist.
* @details Встроенное (inline) сообщение позволяет одному контракту отправить другому контракту сообщение,
* которое обрабатывается сразу после завершения обработки текущего сообщения,
* так что успех или неудача родительской транзакции зависят от успеха этого сообщения.
* Если встроенное сообщение завершается с ошибкой при обработке, то всё дерево транзакций и действий,
* укоренённое в блоке, помечается как неуспешное, и ни один эффект в базе данных не сохраняется.
*
* Inline actions and Deferred transactions must adhere to the permissions
* available to the parent transaction or, in the future, delegated to the
* contract account for future use.
* Встроенные действия и отложенные транзакции должны соблюдать разрешения (permissions),
* доступные родительской транзакции или, в будущем, делегированные аккаунту контракта для последующего использования.
*
* @note There are some methods from the @ref transactioncapi that can be used directly from C++
* @note Некоторые методы из @ref transactioncapi можно вызывать напрямую из C++
*/
/**
@@ -73,19 +70,19 @@ namespace eosio {
typedef std::vector<extension> extensions_type;
/**
* Class transaction_header contains details about the transaction
* Класс transaction_header содержит сведения о транзакции
*
* @ingroup transaction
* @brief Contains details about the transaction
* @brief Содержит сведения о транзакции
*/
class transaction_header {
public:
/**
* Construct a new transaction_header with an expiration of now + 60 seconds.
* Создаёт новый transaction_header со сроком действия «сейчас + 60 с».
*
* @brief Construct a new transaction_header object initialising the transaction header expiration to now + 60 seconds
* @brief Создаёт объект transaction_header со сроком действия заголовка транзакции «сейчас + 60 с»
*/
transaction_header( time_point_sec exp = time_point_sec(current_time_point()) + 60)
:expiration(exp)
@@ -94,15 +91,15 @@ namespace eosio {
time_point_sec expiration;
uint16_t ref_block_num;
uint32_t ref_block_prefix;
unsigned_int max_net_usage_words = 0UL; /// number of 8 byte words this transaction can serialize into after compressions
uint8_t max_cpu_usage_ms = 0UL; /// number of CPU usage units to bill transaction for
unsigned_int delay_sec = 0UL; /// number of seconds to delay transaction, default: 0
unsigned_int max_net_usage_words = 0UL; /// число 8-байтовых слов, в которые может быть сериализована транзакция после сжатия
uint8_t max_cpu_usage_ms = 0UL; /// число единиц использования CPU для тарификации транзакции
unsigned_int delay_sec = 0UL; /// задержка транзакции в секундах, по умолчанию: 0
EOSLIB_SERIALIZE( transaction_header, (expiration)(ref_block_num)(ref_block_prefix)(max_net_usage_words)(max_cpu_usage_ms)(delay_sec) )
};
/**
* Class transaction contains the actions, context_free_actions and extensions type for a transaction
* Класс transaction содержит действия, context_free_actions и расширения транзакции
*
* @ingroup transaction
*/
@@ -110,17 +107,16 @@ namespace eosio {
public:
/**
* Construct a new transaction with an expiration of now + 60 seconds.
* Создаёт новую транзакцию со сроком действия «сейчас + 60 с».
*/
transaction(time_point_sec exp = time_point_sec(current_time_point()) + 60) : transaction_header( exp ) {}
/**
* Sends this transaction, packs the transaction then sends it as a deferred transaction
* Отправляет эту транзакцию: упаковывает её и отправляет как отложенную (deferred)
*
* @details Writes the symbol_code as a string to the provided char buffer
* @param sender_id - ID of sender
* @param payer - Account paying for RAM
* @param replace_existing - Defaults to false, if this is `0`/false then if the provided sender_id is already in use by an in-flight transaction from this contract, which will be a failing assert. If `1` then transaction will atomically cancel/replace the inflight transaction
* @param sender_id — идентификатор отправителя
* @param payer — аккаунт, оплачивающий RAM
* @param replace_existing — по умолчанию false: при `0`/false, если указанный sender_id уже занят выполняющейся транзакцией этого контракта, сработает неуспешный assert. При `1` транзакция атомарно отменит/заменит текущую «в полёте»
*/
void send(const uint128_t& sender_id, name payer, bool replace_existing = false) const {
auto serialize = pack(*this);
@@ -135,7 +131,7 @@ namespace eosio {
};
/**
* Struct onerror contains and sender id and packed transaction
* Структура onerror содержит идентификатор отправителя и упакованную транзакцию
*
* @ingroup transaction
*/
@@ -144,7 +140,7 @@ namespace eosio {
std::vector<char> sent_trx;
/**
* from_current_action unpacks and returns a onerror struct
* Распаковывает из текущего действия и возвращает структуру onerror
*
* @ingroup transaction
*/
@@ -153,7 +149,7 @@ namespace eosio {
}
/**
* Unpacks and returns a transaction
* Распаковывает и возвращает транзакцию
*/
transaction unpack_sent_trx() const {
return unpack<transaction>(sent_trx);
@@ -163,25 +159,25 @@ namespace eosio {
};
/**
* Send a deferred transaction
* Отправляет отложенную транзакцию
*
* @ingroup transaction
* @param sender_id - Account name of the sender of this deferred transaction
* @param payer - Account name responsible for paying the RAM for this deferred transaction
* @param serialized_transaction - The packed transaction to be deferred
* @param size - The size of the packed transaction, required for persistence.
* @param replace - If true, will replace an existing transaction.
* @param sender_id — имя аккаунта отправителя этой отложенной транзакции
* @param payer — имя аккаунта, отвечающего за оплату RAM для этой отложенной транзакции
* @param serialized_transaction — упакованная транзакция для отложенного выполнения
* @param size — размер упакованной транзакции, необходим для сохранения
* @param replace — если true, заменяет существующую транзакцию
*/
inline void send_deferred(const uint128_t& sender_id, name payer, const char* serialized_transaction, size_t size, bool replace = false) {
internal_use_do_not_use::send_deferred(sender_id, payer.value, serialized_transaction, size, replace);
}
/**
* Retrieve the indicated action from the active transaction.
* Возвращает указанное действие из активной транзакции
*
* @ingroup transaction
* @param type - 0 for context free action, 1 for action
* @param index - the index of the requested action
* @return the indicated action
* @param type 0 для действия без контекста (context free), 1 для обычного действия
* @param index — индекс запрашиваемого действия
* @return запрошенное действие
*/
inline action get_action( uint32_t type, uint32_t index ) {
constexpr size_t max_stack_buffer_size = 512;
@@ -195,29 +191,28 @@ namespace eosio {
}
/**
* Access a copy of the currently executing transaction.
* Читает текущую выполняемую транзакцию в буфер
*
* @ingroup transaction
* @return the currently executing transaction
* @return число байт, записанных в ptr
*/
inline size_t read_transaction(char* ptr, size_t sz) {
return internal_use_do_not_use::read_transaction( ptr, sz );
}
/**
* Cancels a deferred transaction.
*
* @ingroup transaction
* @param sender_id - The id of the sender
*
* @pre The deferred transaction ID exists.
* @pre The deferred transaction ID has not yet been published.
* @post Deferred transaction canceled.
*
* @return 1 if transaction was canceled, 0 if transaction was not found
*
* Example:
*
/**
* Отменяет отложенную транзакцию
*
* @ingroup transaction
* @param sender_id — идентификатор отправителя
*
* @pre Идентификатор отложенной транзакции существует.
* @pre Отложенная транзакция с этим идентификатором ещё не опубликована.
* @post Отложенная транзакция отменена.
*
* @return 1, если транзакция отменена; 0, если транзакция не найдена
*
* Пример:
* @code
* id = 0xffffffffffffffff
* cancel_deferred( id );
@@ -228,21 +223,21 @@ namespace eosio {
}
/**
* Gets the size of the currently executing transaction.
* Возвращает размер текущей выполняемой транзакции
*
* @ingroup transaction
* @return size of the currently executing transaction
* @return размер текущей выполняемой транзакции (байт)
*/
inline size_t transaction_size() {
return internal_use_do_not_use::transaction_size();
}
/**
* Gets the block number used for TAPOS on the currently executing transaction.
* Возвращает номер блока, используемый для TAPOS в текущей выполняемой транзакции.
*
* @ingroup transaction
* @return block number used for TAPOS on the currently executing transaction
* Example:
* @return номер блока TAPOS для текущей транзакции
* Пример:
* @code
* int tbn = tapos_block_num();
* @endcode
@@ -252,11 +247,11 @@ namespace eosio {
}
/**
* Gets the block prefix used for TAPOS on the currently executing transaction.
* Возвращает префикс блока, используемый для TAPOS в текущей выполняемой транзакции
*
* @ingroup transaction
* @return block prefix used for TAPOS on the currently executing transaction
* Example:
* @return префикс блока TAPOS для текущей транзакции
* Пример:
* @code
* int tbp = tapos_block_prefix();
* @endcode
@@ -266,24 +261,24 @@ namespace eosio {
}
/**
* Gets the expiration of the currently executing transaction.
* Возвращает срок действия (expiration) текущей выполняемой транзакции.
*
* @ingroup transaction
* @brief Gets the expiration of the currently executing transaction.
* @return expiration of the currently executing transaction in seconds since Unix epoch
* @brief Возвращает срок действия текущей выполняемой транзакции.
* @return срок действия текущей выполняемой транзакции в секундах с начала эпохи Unix
*/
inline uint32_t expiration() {
return internal_use_do_not_use::expiration();
}
/**
* Retrieve the signed_transaction.context_free_data[index].
* Извлекает signed_transaction.context_free_data[index]
*
* @ingroup transaction
* @param index - the index of the context_free_data entry to retrieve
* @param buff - output buff of the context_free_data entry
* @param size - amount of context_free_data[index] to retrieve into buff, 0 to report required size
* @return size copied, or context_free_data[index].size() if 0 passed for size, or -1 if index not valid
* @param index — индекс записи context_free_data
* @param buff — выходной буфер для данных context_free_data
* @param size — сколько байт context_free_data[index] поместить в buff; 0 — вернуть требуемый размер
* @return число скопированных байт, либо context_free_data[index].size() при size == 0, либо -1 при неверном index
*/
inline int get_context_free_data( uint32_t index, char* buff, size_t size ) {
return internal_use_do_not_use::get_context_free_data(index, buff, size);
+137 -137
View File
@@ -13,39 +13,39 @@ namespace eosio {
char* write_decimal( char* begin, char* end, bool dry_run, uint64_t number, uint8_t num_decimal_places, bool negative );
/**
* @defgroup asset Asset
* @defgroup asset Актив
* @ingroup core
* @brief Defines C++ API for managing assets
* @brief Определяет C++ API для работы с активами
*/
/**
* Stores information for owner of asset
* Хранит данные актива (количество и символ) для владельца.
*
* @ingroup asset
*/
struct asset {
/**
* The amount of the asset
* Количество актива
*/
int64_t amount = 0;
/**
* The symbol name of the asset
* Символ актива
*/
symbol symbol;
/**
* Maximum amount possible for this asset. It's capped to 2^62 - 1
* Максимально допустимое значение количества для этого актива; ограничено 2^62 1
*/
static constexpr int64_t max_amount = (1LL << 62) - 1;
asset() {}
/**
* Construct a new asset given the symbol name and the amount
* Создаёт новый актив по символу и количеству
*
* @param a - The amount of the asset
* @param s - The name of the symbol
* @param a — количество актива
* @param s — символ
*/
asset( int64_t a, class symbol s )
:amount(a),symbol{s}
@@ -55,25 +55,25 @@ namespace eosio {
}
/**
* Check if the amount doesn't exceed the max amount
* Проверяет, что количество не выходит за пределы максимума
*
* @return true - if the amount doesn't exceed the max amount
* @return false - otherwise
* @return true — количество в допустимом диапазоне
* @return false — иначе
*/
bool is_amount_within_range()const { return -max_amount <= amount && amount <= max_amount; }
/**
* Check if the asset is valid. %A valid asset has its amount <= max_amount and its symbol name valid
* Проверяет корректность актива. Корректный актив: количество ≤ max_amount и допустимый символ
*
* @return true - if the asset is valid
* @return false - otherwise
* @return true — актив корректен
* @return false — иначе
*/
bool is_valid()const { return is_amount_within_range() && symbol.is_valid(); }
/**
* Set the amount of the asset
* Задаёт количество актива
*
* @param a - New amount for the asset
* @param a — новое количество
*/
void set_amount( int64_t a ) {
amount = a;
@@ -83,9 +83,9 @@ namespace eosio {
/// @cond OPERATORS
/**
* Unary minus operator
* Унарный минус
*
* @return asset - New asset with its amount is the negative amount of this asset
* @return asset — новый актив с противоположным по знаку количеством
*/
asset operator-()const {
asset r = *this;
@@ -94,11 +94,11 @@ namespace eosio {
}
/**
* Subtraction assignment operator
* Оператор вычитания с присваиванием
*
* @param a - Another asset to subtract this asset with
* @return asset& - Reference to this asset
* @post The amount of this asset is subtracted by the amount of asset a
* @param a — вычитаемый актив
* @return asset& — ссылка на этот актив
* @post из количества этого актива вычитается количество a
*/
asset& operator-=( const asset& a ) {
eosio::check( a.symbol == symbol, "attempt to subtract asset with different symbol" );
@@ -109,11 +109,11 @@ namespace eosio {
}
/**
* Addition Assignment operator
* Оператор сложения с присваиванием
*
* @param a - Another asset to subtract this asset with
* @return asset& - Reference to this asset
* @post The amount of this asset is added with the amount of asset a
* @param a — прибавляемый актив
* @return asset& — ссылка на этот актив
* @post к количеству этого актива прибавляется количество a
*/
asset& operator+=( const asset& a ) {
eosio::check( a.symbol == symbol, "attempt to add asset with different symbol" );
@@ -124,11 +124,11 @@ namespace eosio {
}
/**
* Addition operator
* Оператор сложения
*
* @param a - The first asset to be added
* @param b - The second asset to be added
* @return asset - New asset as the result of addition
* @param a — первый слагаемый актив
* @param b — второй слагаемый актив
* @return asset — сумма
*/
inline friend asset operator+( const asset& a, const asset& b ) {
asset result = a;
@@ -137,11 +137,11 @@ namespace eosio {
}
/**
* Subtraction operator
* Оператор вычитания
*
* @param a - The asset to be subtracted
* @param b - The asset used to subtract
* @return asset - New asset as the result of subtraction of a with b
* @param a — уменьшаемый актив
* @param b — вычитаемый актив
* @return asset — разность a b
*/
inline friend asset operator-( const asset& a, const asset& b ) {
asset result = a;
@@ -150,12 +150,12 @@ namespace eosio {
}
/**
* Multiplication assignment operator, with a number
* Умножение количества на число с присваиванием
*
* @details Multiplication assignment operator. Multiply the amount of this asset with a number and then assign the value to itself.
* @param a - The multiplier for the asset's amount
* @return asset - Reference to this asset
* @post The amount of this asset is multiplied by a
* @details Умножает количество этого актива на число и записывает результат обратно в актив.
* @param a — множитель
* @return asset& — ссылка на этот актив
* @post количество умножено на a
*/
asset& operator*=( int64_t a ) {
int128_t tmp = (int128_t)amount * (int128_t)a;
@@ -166,12 +166,12 @@ namespace eosio {
}
/**
* Multiplication operator, with a number proceeding
* Оператор умножения; множитель справа (asset × int64_t)
*
* @brief Multiplication operator, with a number proceeding
* @param a - The asset to be multiplied
* @param b - The multiplier for the asset's amount
* @return asset - New asset as the result of multiplication
* @brief Оператор умножения; множитель справа (asset × int64_t)
* @param a — умножаемый актив
* @param b — множитель (целое)
* @return asset — произведение
*/
friend asset operator*( const asset& a, int64_t b ) {
asset result = a;
@@ -181,11 +181,11 @@ namespace eosio {
/**
* Multiplication operator, with a number preceeding
* Оператор умножения; множитель слева (int64_t × asset)
*
* @param a - The multiplier for the asset's amount
* @param b - The asset to be multiplied
* @return asset - New asset as the result of multiplication
* @param a — множитель (целое)
* @param b — умножаемый актив
* @return asset — произведение
*/
friend asset operator*( int64_t b, const asset& a ) {
asset result = a;
@@ -194,12 +194,12 @@ namespace eosio {
}
/**
* @brief Division assignment operator, with a number
* @brief Оператор деления количества на число с присваиванием
*
* @details Division assignment operator. Divide the amount of this asset with a number and then assign the value to itself.
* @param a - The divisor for the asset's amount
* @return asset - Reference to this asset
* @post The amount of this asset is divided by a
* @details Делит количество этого актива на число и записывает результат обратно в актив.
* @param a — делитель
* @return asset& — ссылка на этот актив
* @post количество разделено на a
*/
asset& operator/=( int64_t a ) {
eosio::check( a != 0, "divide by zero" );
@@ -209,11 +209,11 @@ namespace eosio {
}
/**
* Division operator, with a number proceeding
* Оператор деления актива на число
*
* @param a - The asset to be divided
* @param b - The divisor for the asset's amount
* @return asset - New asset as the result of division
* @param a — делимый актив
* @param b — делитель (целое)
* @return asset — частное
*/
friend asset operator/( const asset& a, int64_t b ) {
asset result = a;
@@ -222,12 +222,12 @@ namespace eosio {
}
/**
* Division operator, with another asset
* Оператор деления одного актива на другой (по количествам)
*
* @param a - The asset which amount acts as the dividend
* @param b - The asset which amount acts as the divisor
* @return int64_t - the resulted amount after the division
* @pre Both asset must have the same symbol
* @param a — актив, количество которого — делимое
* @param b — актив, количество которого — делитель
* @return int64_t — целочисленное частное двух количеств (a.amount / b.amount)
* @pre у обоих активов один и тот же символ
*/
friend int64_t operator/( const asset& a, const asset& b ) {
eosio::check( b.amount != 0, "divide by zero" );
@@ -236,13 +236,13 @@ namespace eosio {
}
/**
* Equality operator
* Оператор равенства
*
* @param a - The first asset to be compared
* @param b - The second asset to be compared
* @return true - if both asset has the same amount
* @return false - otherwise
* @pre Both asset must have the same symbol
* @param a — первый актив
* @param b — второй актив
* @return true — количества равны
* @return false — иначе
* @pre у обоих активов один и тот же символ
*/
friend bool operator==( const asset& a, const asset& b ) {
eosio::check( a.symbol == b.symbol, "comparison of assets with different symbols is not allowed" );
@@ -250,26 +250,26 @@ namespace eosio {
}
/**
* Inequality operator
* Оператор неравенства
*
* @param a - The first asset to be compared
* @param b - The second asset to be compared
* @return true - if both asset doesn't have the same amount
* @return false - otherwise
* @pre Both asset must have the same symbol
* @param a — первый актив
* @param b — второй актив
* @return true — количества различаются
* @return false — иначе
* @pre у обоих активов один и тот же символ
*/
friend bool operator!=( const asset& a, const asset& b ) {
return !( a == b);
}
/**
* Less than operator
* Оператор «меньше»
*
* @param a - The first asset to be compared
* @param b - The second asset to be compared
* @return true - if the first asset's amount is less than the second asset amount
* @return false - otherwise
* @pre Both asset must have the same symbol
* @param a — первый актив
* @param b — второй актив
* @return true — количество a меньше количества b
* @return false — иначе
* @pre у обоих активов один и тот же символ
*/
friend bool operator<( const asset& a, const asset& b ) {
eosio::check( a.symbol == b.symbol, "comparison of assets with different symbols is not allowed" );
@@ -277,13 +277,13 @@ namespace eosio {
}
/**
* Less or equal to operator
* Оператор «меньше или равно»
*
* @param a - The first asset to be compared
* @param b - The second asset to be compared
* @return true - if the first asset's amount is less or equal to the second asset amount
* @return false - otherwise
* @pre Both asset must have the same symbol
* @param a — первый актив
* @param b — второй актив
* @return true — количество a не больше количества b
* @return false — иначе
* @pre у обоих активов один и тот же символ
*/
friend bool operator<=( const asset& a, const asset& b ) {
eosio::check( a.symbol == b.symbol, "comparison of assets with different symbols is not allowed" );
@@ -291,13 +291,13 @@ namespace eosio {
}
/**
* Greater than operator
* Оператор «больше»
*
* @param a - The first asset to be compared
* @param b - The second asset to be compared
* @return true - if the first asset's amount is greater than the second asset amount
* @return false - otherwise
* @pre Both asset must have the same symbol
* @param a — первый актив
* @param b — второй актив
* @return true — количество a больше количества b
* @return false — иначе
* @pre у обоих активов один и тот же символ
*/
friend bool operator>( const asset& a, const asset& b ) {
eosio::check( a.symbol == b.symbol, "comparison of assets with different symbols is not allowed" );
@@ -305,13 +305,13 @@ namespace eosio {
}
/**
* Greater or equal to operator
* Оператор «больше или равно»
*
* @param a - The first asset to be compared
* @param b - The second asset to be compared
* @return true - if the first asset's amount is greater or equal to the second asset amount
* @return false - otherwise
* @pre Both asset must have the same symbol
* @param a — первый актив
* @param b — второй актив
* @return true — количество a не меньше количества b
* @return false — иначе
* @pre у обоих активов один и тот же символ
*/
friend bool operator>=( const asset& a, const asset& b ) {
eosio::check( a.symbol == b.symbol, "comparison of assets with different symbols is not allowed" );
@@ -321,16 +321,16 @@ namespace eosio {
/// @endcond
/**
* Writes the asset as a string to the provided char buffer
* Записывает представление актива в виде строки в буфер char
*
* @brief Writes the asset as a string to the provided char buffer
* @brief Записывает asset в виде строки в переданный буфер char
* @pre is_valid() == true
* @pre The range [begin, end) must be a valid range of memory to write to.
* @param begin - The start of the char buffer
* @param end - Just past the end of the char buffer
* @param dry_run - If true, do not actually write anything into the range.
* @return char* - Just past the end of the last character that would be written assuming dry_run == false and end was large enough to provide sufficient space. (Meaning only applies if returned pointer >= begin.)
* @post If the output string fits within the range [begin, end) and dry_run == false, the range [begin, returned pointer) contains the string representation of the asset. Nothing is written if dry_run == true or returned pointer > end (insufficient space) or if returned pointer < begin (overflow in calculating desired end).
* @pre диапазон [begin, end) — допустимая область памяти для записи
* @param begin — начало буфера
* @param end — конец буфера (не включая end)
* @param dry_run — если true, ничего не записывать, только вычислить длину
* @return char* — указатель сразу за последним символом, который был бы записан при dry_run == false и достаточном размере буфера (смысл только если возвращаемый указатель ≥ begin)
* @post если строка помещается в [begin, end) и dry_run == false, то [begin, возврат) содержит строковое представление актива; при dry_run == true, недостаточном месте или переполнении при расчёте конца запись не выполняется
*/
char* write_as_string( char* begin, char* end, bool dry_run = false )const {
bool negative = (amount < 0);
@@ -353,9 +353,9 @@ namespace eosio {
}
/**
* %asset to std::string
* Преобразование %asset в std::string
*
* @brief %asset to std::string
* @brief Преобразование %asset в std::string
*/
std::string to_string()const {
int buffer_size = std::max(static_cast<int>(symbol.precision()), 19) + 11;
@@ -367,9 +367,9 @@ namespace eosio {
}
/**
* %Print the asset
* Вывод актива (печать в лог контракта COOPOS)
*
* @brief %Print the asset
* @brief Вывод asset
*/
void print()const {
int buffer_size = std::max(static_cast<int>(symbol.precision()), 19) + 11;
@@ -385,44 +385,44 @@ namespace eosio {
};
/**
* Extended asset which stores the information of the owner of the asset
* Расширенный актив: количество и контракт-эмитент токена в сети COOPOS
*
* @ingroup asset
*/
struct extended_asset {
/**
* The asset
* Сам актив (количество и символ)
*/
asset quantity;
/**
* The owner of the asset
* Имя контракта, выпускающего токен
*/
name contract;
/**
* Get the extended symbol of the asset
* Возвращает расширенный символ (символ + контракт)
*
* @return extended_symbol - The extended symbol of the asset
* @return extended_symbol — расширенный символ
*/
extended_symbol get_extended_symbol()const { return extended_symbol{ quantity.symbol, contract }; }
/**
* Default constructor
* Конструктор по умолчанию
*/
extended_asset() = default;
/**
* Construct a new extended asset given the amount and extended symbol
* Создаёт расширенный актив по количеству и расширенному символу
*/
extended_asset( int64_t v, extended_symbol s ):quantity(v,s.get_symbol()),contract(s.get_contract()){}
/**
* Construct a new extended asset given the asset and owner name
* Создаёт расширенный актив по активу и имени контракта
*/
extended_asset( asset a, name c ):quantity(a),contract(c){}
/**
* %Print the extended asset
* Вывод расширенного актива (печать в лог контракта COOPOS)
*/
void print()const {
quantity.print();
@@ -431,100 +431,100 @@ namespace eosio {
/// @cond OPERATORS
// Unary minus operator
// Унарный минус
extended_asset operator-()const {
return {-quantity, contract};
}
// Subtraction operator
// Оператор вычитания
friend extended_asset operator - ( const extended_asset& a, const extended_asset& b ) {
eosio::check( a.contract == b.contract, "type mismatch" );
return {a.quantity - b.quantity, a.contract};
}
// Addition operator
// Оператор сложения
friend extended_asset operator + ( const extended_asset& a, const extended_asset& b ) {
eosio::check( a.contract == b.contract, "type mismatch" );
return {a.quantity + b.quantity, a.contract};
}
/// Addition operator.
/// Оператор сложения с присваиванием.
friend extended_asset& operator+=( extended_asset& a, const extended_asset& b ) {
eosio::check( a.contract == b.contract, "type mismatch" );
a.quantity += b.quantity;
return a;
}
/// Subtraction operator.
/// Оператор вычитания с присваиванием.
friend extended_asset& operator-=( extended_asset& a, const extended_asset& b ) {
eosio::check( a.contract == b.contract, "type mismatch" );
a.quantity -= b.quantity;
return a;
}
/// Multiplication operator.
/// Умножение на число с присваиванием.
extended_asset& operator*=( int64_t b ) {
quantity *= b;
return *this;
}
/// Multiplication operator.
/// Умножение актива на число.
friend extended_asset operator*( const extended_asset& a, int64_t b ) {
return {a.quantity * b, a.contract};
}
/// Multiplication operator.
/// Умножение числа на актив.
friend extended_asset operator*( int64_t a, const extended_asset& b ) {
return {a * b.quantity, b.contract};
}
/// Division operator. Follows format of 'int64_t operator/( const asset& a, const asset& b )'.
/// Деление расширенных активов по количеству (аналог int64_t operator/( const asset& a, const asset& b )).
friend int64_t operator/( const extended_asset& a, const extended_asset& b ) {
eosio::check( a.contract == b.contract, "type mismatch" );
return a.quantity / b.quantity;
}
/// Division operator.
/// Деление на число с присваиванием.
extended_asset& operator/=( int64_t b ) {
quantity /= b;
return *this;
}
/// Division operator.
/// Деление актива на число.
friend extended_asset operator/( const extended_asset& a, int64_t b ) {
return {a.quantity / b, a.contract};
}
/// Less than operator
/// Оператор «меньше»
friend bool operator<( const extended_asset& a, const extended_asset& b ) {
eosio::check( a.contract == b.contract, "type mismatch" );
return a.quantity < b.quantity;
}
/// Greater than operator
/// Оператор «больше»
friend bool operator>( const extended_asset& a, const extended_asset& b ) {
eosio::check( a.contract == b.contract, "type mismatch" );
return a.quantity > b.quantity;
}
/// Equality operator
/// Оператор равенства
friend bool operator==( const extended_asset& a, const extended_asset& b ) {
return std::tie(a.quantity, a.contract) == std::tie(b.quantity, b.contract);
}
/// Inequality operator
/// Оператор неравенства
friend bool operator!=( const extended_asset& a, const extended_asset& b ) {
return std::tie(a.quantity, a.contract) != std::tie(b.quantity, b.contract);
}
/// Less than or equal operator
/// Оператор «меньше или равно»
friend bool operator<=( const extended_asset& a, const extended_asset& b ) {
eosio::check( a.contract == b.contract, "type mismatch" );
return a.quantity <= b.quantity;
}
/// Greater than or equal operator
/// Оператор «больше или равно»
friend bool operator>=( const extended_asset& a, const extended_asset& b ) {
eosio::check( a.contract == b.contract, "type mismatch" );
return a.quantity >= b.quantity;
@@ -4,17 +4,17 @@
namespace eosio {
/**
* @defgroup binary_extension Binary Extension
* @defgroup binary_extension Двоичное расширение
* @ingroup core
* @ingroup types
* @brief Container to hold a binary payload for an extension
* @brief Контейнер для двоичной полезной нагрузки расширения
*/
/**
* Container to hold a binary payload for an extension
* Опциональное значение типа T для расширений действий/таблиц в COOPOS (аналог optional с размещением в буфере)
*
* @ingroup binary_extension
* @tparam T - Contained typed
* @tparam T — тип хранимого значения
*/
template <typename T>
class binary_extension {
@@ -32,7 +32,7 @@ namespace eosio {
{
::new (&_data) T(std::move(ext));
}
/** construct contained type in place */
/** размещает значение T по месту (in-place) */
template <typename... Args>
constexpr binary_extension( std::in_place_t, Args&&... args )
:_has_value(true)
@@ -82,12 +82,12 @@ namespace eosio {
}
return *this;
}
/** test if container is holding a value */
/** true, если значение присутствует */
constexpr explicit operator bool()const { return _has_value; }
/** test if container is holding a value */
/** true, если значение присутствует */
constexpr bool has_value()const { return _has_value; }
/** get the contained value */
/** ссылка на хранимое значение */
constexpr T& value()& {
if (!_has_value) {
check(false, "cannot get value of empty binary_extension");
@@ -97,7 +97,7 @@ namespace eosio {
/// @cond INTERNAL
/** get the contained value */
/** константная ссылка на хранимое значение */
constexpr const T& value()const & {
if (!_has_value) {
check(false, "cannot get value of empty binary_extension");
@@ -105,8 +105,8 @@ namespace eosio {
return _get();
}
/** get the contained value or a user specified default
* @pre def should be convertible to type T
/** значение или переданный по ссылке запасной объект
* @pre def должен быть приводим к T
* */
template <typename U>
constexpr auto value_or( U&& def ) -> std::enable_if_t<std::is_convertible<U, T>::value, T&>& {
@@ -194,14 +194,14 @@ namespace eosio {
/// @cond IMPLEMENTATIONS
/**
* Serialize a binary_extension into a stream
* Сериализация binary_extension в поток (через value_or())
*
* @ingroup binary_extension
* @brief Serialize a binary_extension
* @param ds - The stream to write
* @param opt - The value to serialize
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @brief Сериализация binary_extension
* @param ds — поток записи
* @param be — значение для сериализации
* @tparam DataStream — тип буфера потока данных
* @return DataStream& — ссылка на поток
*/
template<typename DataStream, typename T>
inline DataStream& operator<<(DataStream& ds, const eosio::binary_extension<T>& be) {
@@ -210,14 +210,14 @@ namespace eosio {
}
/**
* Deserialize a binary_extension from a stream
* Десериализация binary_extension из потока (при наличии остатка в потоке)
*
* @ingroup binary_extension
* @brief Deserialize a binary_extension
* @param ds - The stream to read
* @param opt - The destination for deserialized value
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @brief Десериализация binary_extension
* @param ds — поток чтения
* @param be — приёмник значения
* @tparam DataStream — тип буфера потока данных
* @return DataStream& — ссылка на поток
*/
template<typename DataStream, typename T>
inline DataStream& operator>>(DataStream& ds, eosio::binary_extension<T>& be) {
+17 -17
View File
@@ -1,6 +1,6 @@
/**
* @file
* @copyright defined in eos/LICENSE
* @copyright см. eos/LICENSE
*/
#pragma once
@@ -23,18 +23,18 @@ namespace eosio {
}
/**
* @defgroup system System
* @defgroup system Система
* @ingroup core
* @brief Defines wrappers over eosio_assert
* @brief Обёртки над eosio_assert
*/
/**
* Assert if the predicate fails and use the supplied message.
* Прерывает выполнение контракта, если pred == false; сообщение msg передаётся в среду COOPOS.
*
* @ingroup system
*
* Example:
* Пример:
* @code
* eosio::check(a == b, "a does not equal b");
* @endcode
@@ -45,11 +45,11 @@ namespace eosio {
}
/**
* Assert if the predicate fails and use the supplied message.
* Прерывает выполнение контракта, если pred == false; сообщение — C-строка msg.
*
* @ingroup system
*
* Example:
* Пример:
* @code
* eosio::check(a == b, "a does not equal b");
* @endcode
@@ -61,11 +61,11 @@ namespace eosio {
}
/**
* Assert if the predicate fails and use the supplied message.
* Прерывает выполнение контракта, если pred == false; сообщение — std::string.
*
* @ingroup system
*
* Example:
* Пример:
* @code
* eosio::check(a == b, "a does not equal b");
* @endcode
@@ -77,11 +77,11 @@ namespace eosio {
}
/**
* Assert if the predicate fails and use the supplied message.
* Прерывает выполнение контракта, если pred == false; сообщение — rvalue std::string.
*
* @ingroup system
*
* Example:
* Пример:
* @code
* eosio::check(a == b, "a does not equal b");
* @endcode
@@ -94,11 +94,11 @@ namespace eosio {
/**
* Assert if the predicate fails and use a subset of the supplied message.
* Прерывает выполнение контракта, если pred == false; в среду передаются первые n байт сообщения msg.
*
* @ingroup system
*
* Example:
* Пример:
* @code
* const char* msg = "a does not equal b b does not equal a";
* eosio::check(a == b, "a does not equal b", 18);
@@ -111,11 +111,11 @@ namespace eosio {
}
/**
* Assert if the predicate fails and use a subset of the supplied message.
* Прерывает выполнение контракта, если pred == false; в среду передаются первые n символов строки msg.
*
* @ingroup system
*
* Example:
* Пример:
* @code
* std::string msg = "a does not equal b b does not equal a";
* eosio::check(a == b, msg, 18);
@@ -128,11 +128,11 @@ namespace eosio {
}
/**
* Assert if the predicate fails and use the supplied error code.
* Прерывает выполнение контракта, если pred == false; передаётся числовой код ошибки code (eosio_assert_code).
*
* @ingroup system
*
* Example:
* Пример:
* @code
* eosio::check(a == b, 13);
* @endcode
+114 -93
View File
@@ -1,41 +1,42 @@
/**
* @file
* @copyright defined in eos/LICENSE
* @copyright см. eos/LICENSE
*/
#pragma once
#include "fixed_bytes.hpp"
#include "varint.hpp"
#include "serialize.hpp"
#include "name.hpp"
#include <array>
namespace eosio {
/**
* @defgroup public_key Public Key Type
* @defgroup public_key Тип открытого ключа
* @ingroup core
* @ingroup types
* @brief Specifies public key type
* @brief Задаёт тип открытого ключа
*/
/**
* EOSIO ECC public key data
* Данные открытого ключа ECC в COOPOS
*
* Fixed size representation of either a K1 or R1 compressed public key
* Представление фиксированного размера: сжатый открытый ключ K1 или R1
* @ingroup public_key
*/
using ecc_public_key = std::array<char, 33>;
/**
* EOSIO WebAuthN public key
* Открытый ключ WebAuthN в COOPOS
*
* @ingroup public_key
*/
struct webauthn_public_key {
/**
* Enumeration of the various results of a Test of User Presence
* Перечисление возможных результатов проверки присутствия пользователя
* @see https://w3c.github.io/webauthn/#test-of-user-presence
*/
enum class user_presence_t : uint8_t {
@@ -45,18 +46,18 @@ namespace eosio {
};
/**
* The ECC key material
* Материал ключа ECC
*/
ecc_public_key key;
/**
* expected result of the test of user presence for a valid signature
* Ожидаемый результат проверки присутствия пользователя для действительной подписи
* @see https://w3c.github.io/webauthn/#test-of-user-presence
*/
user_presence_t user_presence;
/**
* the Relying Party Identifier for WebAuthN
* Идентификатор доверенной стороны (Relying Party) для WebAuthN
* @see https://w3c.github.io/webauthn/#relying-party-identifier
*/
std::string rpid;
@@ -86,12 +87,12 @@ namespace eosio {
};
/**
* EOSIO Public Key
* Открытый ключ COOPOS
*
* A public key is a variant of
* 0 : a ECC K1 public key
* 1 : a ECC R1 public key
* 2 : a WebAuthN public key (requires the host chain to activate the WEBAUTHN_KEY consensus upgrade)
* Открытый ключ — вариант из:
* 0 : открытый ключ ECC K1
* 1 : открытый ключ ECC R1
* 2 : открытый ключ WebAuthN (требуется активация на цепи-хосте COOPOS консенсусного обновления WEBAUTHN_KEY)
*
* @ingroup public_key
*/
@@ -101,13 +102,13 @@ namespace eosio {
/// @cond IMPLEMENTATIONS
/**
* Serialize an eosio::webauthn_public_key into a stream
* Сериализует eosio::webauthn_public_key в поток
*
* @ingroup public_key
* @param ds - The stream to write
* @param pubkey - The value to serialize
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @param ds - Поток для записи
* @param pubkey - Значение для сериализации
* @tparam DataStream - Тип буфера потока данных
* @return DataStream& - Ссылка на поток данных
*/
template<typename DataStream>
inline DataStream& operator<<(DataStream& ds, const eosio::webauthn_public_key& pubkey) {
@@ -116,13 +117,13 @@ namespace eosio {
}
/**
* Deserialize an eosio::webauthn_public_key from a stream
* Десериализует eosio::webauthn_public_key из потока
*
* @ingroup public_key
* @param ds - The stream to read
* @param pubkey - The destination for deserialized value
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @param ds - Поток для чтения
* @param pubkey - Назначение для десериализованного значения
* @tparam DataStream - Тип буфера потока данных
* @return DataStream& - Ссылка на поток данных
*/
template<typename DataStream>
inline DataStream& operator>>(DataStream& ds, eosio::webauthn_public_key& pubkey) {
@@ -133,40 +134,40 @@ namespace eosio {
/// @endcond
/**
* @defgroup signature Signature
* @defgroup signature Подпись
* @ingroup core
* @ingroup types
* @brief Specifies signature type
* @brief Задаёт тип подписи
*/
/**
* EOSIO ECC signature data
* Данные подписи ECC в COOPOS
*
* Fixed size representation of either a K1 or R1 ECC compact signature
* Представление фиксированного размера: компактная подпись ECC K1 или R1
* @ingroup signature
*/
using ecc_signature = std::array<char, 65>;
/**
* EOSIO WebAuthN signature
* Подпись WebAuthN (формат COOPOS / совместимый с протоколом)
*
* @ingroup signature
*/
struct webauthn_signature {
/**
* The ECC signature data
* Данные подписи ECC
*/
ecc_signature compact_signature;
/**
* The Encoded Authenticator Data returned from WebAuthN ceremony
* Закодированные данные аутентификатора, возвращённые церемонией WebAuthN
* @see https://w3c.github.io/webauthn/#sctn-authenticator-data
*/
std::vector<uint8_t> auth_data;
/**
* the JSON encoded Collected Client Data from a WebAuthN ceremony
* Данные клиента в JSON из церемонии WebAuthN
* @see https://w3c.github.io/webauthn/#dictdef-collectedclientdata
*/
std::string client_json;
@@ -184,12 +185,12 @@ namespace eosio {
};
/**
* EOSIO Signature
* Подпись COOPOS
*
* A signature is a variant of
* 0 : a ECC K1 signature
* 1 : a ECC R1 signatre
* 2 : a WebAuthN signature (requires the host chain to activate the WEBAUTHN_KEY consensus upgrade)
* Подпись — вариант из:
* 0 : подпись ECC K1
* 1 : подпись ECC R1
* 2 : подпись WebAuthN (требуется активация на цепи-хосте COOPOS консенсусного обновления WEBAUTHN_KEY)
*
* @ingroup signature
*/
@@ -198,12 +199,12 @@ namespace eosio {
/// @cond IMPLEMENTATIONS
/**
* Serialize an eosio::webauthn_signature into a stream
* Сериализует eosio::webauthn_signature в поток
*
* @param ds - The stream to write
* @param sig - The value to serialize
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @param ds - Поток для записи
* @param sig - Значение для сериализации
* @tparam DataStream - Тип буфера потока данных
* @return DataStream& - Ссылка на поток данных
*/
template<typename DataStream>
inline DataStream& operator<<(DataStream& ds, const eosio::webauthn_signature& sig) {
@@ -212,12 +213,12 @@ namespace eosio {
}
/**
* Deserialize an eosio::webauthn_signature from a stream
* Десериализует eosio::webauthn_signature из потока
*
* @param ds - The stream to read
* @param sig - The destination for deserialized value
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @param ds - Поток для чтения
* @param sig - Назначение для десериализованного значения
* @tparam DataStream - Тип буфера потока данных
* @return DataStream& - Ссылка на поток данных
*/
template<typename DataStream>
inline DataStream& operator>>(DataStream& ds, eosio::webauthn_signature& sig) {
@@ -228,112 +229,132 @@ namespace eosio {
/// @endcond
/**
* @defgroup crypto Crypto
* @defgroup crypto Криптография
* @ingroup core
* @brief Defines API for calculating and checking hashes
* @brief Определяет API вычисления и проверки хешей
*/
/**
* Tests if the SHA256 hash generated from data matches the provided digest.
* Проверяет, совпадает ли SHA256-хеш данных с переданным дайджестом.
*
* @ingroup crypto
* @param data - Data you want to hash
* @param length - Data length
* @param hash - digest to compare to
* @note This method is optimized to a NO-OP when in fast evaluation mode.
* @param data - Данные для хеширования
* @param length - Длина данных
* @param hash - Дайджест для сравнения
* @note В режиме быстрой оценки этот метод сводится к NO-OP.
*/
void assert_sha256( const char* data, uint32_t length, const eosio::checksum256& hash );
/**
* Tests if the SHA1 hash generated from data matches the provided digest.
* Проверяет, совпадает ли SHA1-хеш данных с переданным дайджестом.
*
* @ingroup crypto
* @param data - Data you want to hash
* @param length - Data length
* @param hash - digest to compare to
* @note This method is optimized to a NO-OP when in fast evaluation mode.
* @param data - Данные для хеширования
* @param length - Длина данных
* @param hash - Дайджест для сравнения
* @note В режиме быстрой оценки этот метод сводится к NO-OP.
*/
void assert_sha1( const char* data, uint32_t length, const eosio::checksum160& hash );
/**
* Tests if the SHA512 hash generated from data matches the provided digest.
* Проверяет, совпадает ли SHA512-хеш данных с переданным дайджестом.
*
* @ingroup crypto
* @param data - Data you want to hash
* @param length - Data length
* @param hash - digest to compare to
* @note This method is optimized to a NO-OP when in fast evaluation mode.
* @param data - Данные для хеширования
* @param length - Длина данных
* @param hash - Дайджест для сравнения
* @note В режиме быстрой оценки этот метод сводится к NO-OP.
*/
void assert_sha512( const char* data, uint32_t length, const eosio::checksum512& hash );
/**
* Tests if the RIPEMD160 hash generated from data matches the provided digest.
* Проверяет, совпадает ли RIPEMD160-хеш данных с переданным дайджестом.
*
* @ingroup crypto
* @param data - Data you want to hash
* @param length - Data length
* @param hash - digest to compare to
* @param data - Данные для хеширования
* @param length - Длина данных
* @param hash - Дайджест для сравнения
*/
void assert_ripemd160( const char* data, uint32_t length, const eosio::checksum160& hash );
/**
* Hashes `data` using SHA256.
* Вычисляет хеш `data` алгоритмом SHA256.
*
* @ingroup crypto
* @param data - Data you want to hash
* @param length - Data length
* @return eosio::checksum256 - Computed digest
* @param data - Данные для хеширования
* @param length - Длина данных
* @return eosio::checksum256 - Вычисленный дайджест
*/
eosio::checksum256 sha256( const char* data, uint32_t length );
/**
* Hashes `data` using SHA1.
* Вычисляет хеш `data` алгоритмом SHA1.
*
* @ingroup crypto
*
* @param data - Data you want to hash
* @param length - Data length
* @return eosio::checksum160 - Computed digest
* @param data - Данные для хеширования
* @param length - Длина данных
* @return eosio::checksum160 - Вычисленный дайджест
*/
eosio::checksum160 sha1( const char* data, uint32_t length );
/**
* Hashes `data` using SHA512.
* Вычисляет хеш `data` алгоритмом SHA512.
*
* @ingroup crypto
* @param data - Data you want to hash
* @param length - Data length
* @return eosio::checksum512 - Computed digest
* @param data - Данные для хеширования
* @param length - Длина данных
* @return eosio::checksum512 - Вычисленный дайджест
*/
eosio::checksum512 sha512( const char* data, uint32_t length );
/**
* Hashes `data` using RIPEMD160.
* Вычисляет хеш `data` алгоритмом RIPEMD160.
*
* @ingroup crypto
* @param data - Data you want to hash
* @param length - Data length
* @return eosio::checksum160 - Computed digest
* @param data - Данные для хеширования
* @param length - Длина данных
* @return eosio::checksum160 - Вычисленный дайджест
*/
eosio::checksum160 ripemd160( const char* data, uint32_t length );
/**
* Calculates the public key used for a given signature on a given digest.
* Вычисляет открытый ключ по дайджесту и подписи.
*
* @ingroup crypto
* @param digest - Digest of the message that was signed
* @param sig - Signature
* @return eosio::public_key - Recovered public key
* @param digest - Дайджест подписанного сообщения
* @param sig - Подпись
* @return eosio::public_key - Восстановленный открытый ключ
*/
eosio::public_key recover_key( const eosio::checksum256& digest, const eosio::signature& sig );
/**
* Tests a given public key with the recovered public key from digest and signature.
* Сравнивает заданный открытый ключ с восстановленным по дайджесту и подписи.
*
* @ingroup crypto
* @param digest - Digest of the message that was signed
* @param sig - Signature
* @param pubkey - Public key
* @param digest - Дайджест подписанного сообщения
* @param sig - Подпись
* @param pubkey - Открытый ключ
*/
void assert_recover_key( const eosio::checksum256& digest, const eosio::signature& sig, const eosio::public_key& pubkey );
/**
* Проверяет подпись по хешу, сверяет восстановленный открытый ключ с ожидаемым
* и удостоверяется, что ключ привязан к указанному разрешению аккаунта.
*
* @ingroup crypto
* @param digest - Дайджест подписанного сообщения
* @param sig - Подпись
* @param pubkey - Ожидаемый открытый ключ
* @param account - Имя аккаунта для проверки владения ключом
* @param permission - Имя разрешения (например, "active"_n, "owner"_n)
*
* @throw eosio::check завершится ошибкой, если:
* - подпись недействительна;
* - восстановленный ключ не совпадает с ожидаемым открытым ключом;
* - аккаунт не существует;
* - разрешение не существует для аккаунта;
* - открытый ключ не принадлежит указанному разрешению аккаунта.
*/
void assert_recover_key_account( const eosio::checksum256& digest, const eosio::signature& sig, const eosio::public_key& pubkey, eosio::name account, eosio::name permission );
}
+126 -136
View File
@@ -1,6 +1,6 @@
/**
* @file
* @copyright defined in cdt/LICENSE
* @copyright см. cdt/LICENSE
*/
#pragma once
@@ -51,34 +51,34 @@ namespace eosio {
}
/**
* @defgroup crypto Crypto
* @defgroup crypto Криптография
* @ingroup core
* @brief Defines API for calculating and checking hashes which
* require activating crypto protocol feature
* @brief Определяет API вычисления и проверки хешей, для которых
* требуется активация соответствующего криптопротокольного свойства в цепи COOPOS
*/
/**
* Abstracts mutable G1 and G2 points
* Абстракция изменяемых точек G1 и G2
*
* @ingroup crypto
*/
template <std::size_t Size = 32>
struct ec_point {
/**
* Bytes of the x coordinate
* Байты координаты x
*/
std::vector<char> x;
/**
* Bytes of the y coordinate
* Байты координаты y
*/
std::vector<char> y;
/**
* Construct a point given x and y
* Создаёт точку по координатам x и y
*
* @param x_ - The x coordinate, a vector of chars
* @param y_ - The y coordinate, a vector of chars
* @param x_ - Координата x, вектор символов
* @param y_ - Координата y, вектор символов
*/
ec_point(std::vector<char>& x_, std::vector<char>& y_)
:x(x_), y(y_)
@@ -88,9 +88,9 @@ namespace eosio {
};
/**
* Construct a point given a serialized point
* Создаёт точку из сериализованного представления
*
* @param p - The serialized point
* @param p - Сериализованная точка
*/
ec_point(std::vector<char>& p)
:x(p.data(), p.data() + Size), y(p.data() + Size, p.data() + p.size())
@@ -99,7 +99,7 @@ namespace eosio {
};
/**
* Return serialzed point containing only x and y
* Возвращает сериализованную точку (только x и y)
*/
std::vector<char> serialized() const {
std::vector<char> x_and_y( x );
@@ -109,19 +109,19 @@ namespace eosio {
};
/**
* Abstracts read-only G1 and G2 points
* Абстракция точек G1 и G2 только для чтения
*
* @ingroup crypto
*/
template <std::size_t Size = 32>
struct ec_point_view {
/**
* Pointer to the x coordinate
* Указатель на координату x
*/
const char* x;
/**
* Pointer to the y coordinate
* Указатель на координату y
*/
const char* y;
@@ -131,12 +131,12 @@ namespace eosio {
uint32_t size;
/**
* Construct a point view from x and y
* Создаёт представление точки по x и y
*
* @param x_ - The x coordinate, poiter to chars
* @param x_size - x's size
* @param y_ - The y coordinate, poiter to chars
* @param y_size - y's size
* @param x_ - Координата x, указатель на байты
* @param x_size - Размер x
* @param y_ - Координата y, указатель на байты
* @param y_size - Размер y
*/
ec_point_view(const char* x_, uint32_t x_size, const char* y_, uint32_t y_size)
:x(x_), y(y_), size(x_size)
@@ -146,9 +146,9 @@ namespace eosio {
};
/**
* Construct a point view from a serialized point
* Создаёт представление точки из сериализованных данных
*
* @param p - The serialized point
* @param p - Сериализованная точка
*/
ec_point_view(const std::vector<char>& p)
:x(p.data()), y(p.data() + Size), size(Size)
@@ -157,9 +157,9 @@ namespace eosio {
};
/**
* Construct a point view from a point
* Создаёт представление точки из объекта точки
*
* @param p - The point
* @param p - Точка
*/
ec_point_view(const ec_point<Size>& p)
:x(p.x.data()), y(p.y.data()), size(Size)
@@ -167,7 +167,7 @@ namespace eosio {
};
/**
* Return serialzed point containing only x and y
* Возвращает сериализованную точку (только x и y)
*/
std::vector<char> serialized() const {
std::vector<char> x_and_y( x, x + size );
@@ -185,19 +185,19 @@ namespace eosio {
using g2_point_view = ec_point_view<g2_coordinate_size>;
/**
* Big integer.
* Большое целое.
*
* @ingroup crypto
*/
using bigint = std::vector<char>;
/**
* Addition operation on the elliptic curve `alt_bn128`
* Сложение на эллиптической кривой `alt_bn128`
*
* @ingroup crypto
* @param op1 - operand 1
* @param op2 - operand 2
* @return result of the addition operation; throw if error
* @param op1 - Операнд 1
* @param op2 - Операнд 2
* @return Результат сложения; при ошибке — исключение
*/
template <typename T>
inline g1_point alt_bn128_add( const T& op1, const T& op2 ) {
@@ -210,28 +210,28 @@ namespace eosio {
}
/**
* Addition operation on the elliptic curve `alt_bn128`
* Сложение на эллиптической кривой `alt_bn128`
*
* @ingroup crypto
* @param op1 - operand 1
* @param op1_len - size of operand 1
* @param op2 - operand 2
* @param op2_len - size of operand 2
* @param result - result of the addition operation
* @param result_len - size of result
* @return -1 if there is an error otherwise 0
* @param op1 - Операнд 1
* @param op1_len - Размер операнда 1
* @param op2 - Операнд 2
* @param op2_len - Размер операнда 2
* @param result - Результат сложения
* @param result_len - Размер результата
* @return -1 при ошибке, иначе 0
*/
inline int32_t alt_bn128_add( const char* op1, uint32_t op1_len, const char* op2, uint32_t op2_len, char* result, uint32_t result_len ) {
return internal_use_do_not_use::alt_bn128_add( op1, op1_len, op2, op2_len, result, result_len);
}
/**
* Scalar multiplication operation on the elliptic curve `alt_bn128`
* Скалярное умножение на эллиптической кривой `alt_bn128`
*
* @ingroup crypto
* @param g1 - G1 point
* @param scalar - scalar factor
* @return result of the scalar multiplication operation; throw if error
* @param g1 - Точка G1
* @param scalar - Скалярный множитель
* @return Результат умножения; при ошибке — исключение
*/
template <typename T>
inline g1_point alt_bn128_mul( const T& g1, const bigint& scalar) {
@@ -243,27 +243,27 @@ namespace eosio {
}
/**
* Scalar multiplication operation on the elliptic curve `alt_bn128`
* Скалярное умножение на эллиптической кривой `alt_bn128`
*
* @ingroup crypto
* @param g1 - G1 point
* @param g1_len - size of G1 point
* @param scalar - scalar factor
* @param scalar_len - size of scalar
* @param result - result of the scalar multiplication operation
* @param result_len - size of result
* @return -1 if there is an error otherwise 0
* @param g1 - Точка G1
* @param g1_len - Размер точки G1
* @param scalar - Скалярный множитель
* @param scalar_len - Размер скаляра
* @param result - Результат скалярного умножения
* @param result_len - Размер результата
* @return -1 при ошибке, иначе 0
*/
inline int32_t alt_bn128_mul( const char* g1, uint32_t g1_len, const char* scalar, uint32_t scalar_len, char* result, uint32_t result_len ) {
return internal_use_do_not_use::alt_bn128_mul( g1, g1_len, scalar, scalar_len, result, result_len );
}
/**
* Optimal-Ate pairing check elliptic curve `alt_bn128`
* Проверка optimal-Ate pairing на кривой `alt_bn128`
*
* @ingroup crypto
* @param pairs - g1 and g2 pairs
* @return -1 if there is an error, 1 if false and 0 if true and successful
* @param pairs - Пары точек g1 и g2
* @return -1 при ошибке, 1 если ложь, 0 если истина и успех
*/
template <typename G1_T, typename G2_T>
inline int32_t alt_bn128_pair( const std::vector<std::pair<G1_T, G2_T>>& pairs ) {
@@ -278,27 +278,27 @@ namespace eosio {
}
/**
* Optimal-Ate pairing check elliptic curve `alt_bn128`
* Проверка optimal-Ate pairing на кривой `alt_bn128`
*
* @ingroup crypto
* @param pairs - g1 and g2 pairs
* @param pairs_len - size of pairs
* @return -1 if there is an error, 1 if false and 0 if true and successful
* @param pairs - Пары g1 и g2
* @param pairs_len - Размер данных пар
* @return -1 при ошибке, 1 если ложь, 0 если истина и успех
*/
inline int32_t alt_bn128_pair( const char* pairs, uint32_t pairs_len ) {
return internal_use_do_not_use::alt_bn128_pair( pairs, pairs_len );
}
/**
* Big integer modular exponentiation
* returns an output ( BASE^EXP ) % MOD
* Модульное возведение в степень для больших целых
* Возвращает ( BASE^EXP ) % MOD
*
* @ingroup crypto
* @param base - base of the exponentiation (BASE)
* @param exp - exponent to raise to that power (EXP)
* @param mod - modulus (MOD)
* @param result - result of the modular exponentiation
* @return -1 if there is an error otherwise 0
* @param base - Основание (BASE)
* @param exp - Показатель степени (EXP)
* @param mod - Модуль (MOD)
* @param result - Результат модульного возведения в степень
* @return -1 при ошибке, иначе 0
*/
inline int32_t mod_exp( const bigint& base, const bigint& exp, const bigint& mod, bigint& result) {
@@ -308,19 +308,19 @@ namespace eosio {
}
/**
* Big integer modular exponentiation
* returns an output ( BASE^EXP ) % MOD
* Модульное возведение в степень для больших целых
* Возвращает ( BASE^EXP ) % MOD
*
* @ingroup crypto
* @param base - base of the exponentiation (BASE)
* @param base_len - size of base
* @param exp - exponent to raise to that power (EXP)
* @param exp_len - size of exp
* @param mod - modulus (MOD)
* @param mod_len - size of mod
* @param result - result of the modular exponentiation
* @param result_len - size of result
* @return -1 if there is an error otherwise 0
* @param base - Основание (BASE)
* @param base_len - Размер основания
* @param exp - Показатель степени (EXP)
* @param exp_len - Размер показателя
* @param mod - Модуль (MOD)
* @param mod_len - Размер модуля
* @param result - Результат модульного возведения в степень
* @param result_len - Размер результата
* @return -1 при ошибке, иначе 0
*/
inline int32_t mod_exp( const char* base, uint32_t base_len, const char* exp, uint32_t exp_len, const char* mod, uint32_t mod_len, char* result, uint32_t result_len ) {
@@ -330,18 +330,18 @@ namespace eosio {
static constexpr size_t blake2f_result_size = 64;
/**
* BLAKE2 compression function "F"
* Функция сжатия BLAKE2 «F»
* https://eips.ethereum.org/EIPS/eip-152
*
* @ingroup crypto
* @param rounds - the number of rounds
* @param state - state vector
* @param msg - message block vector
* @param t0_offset - offset counters
* @param t1_offset - offset counters
* @param final - final block flag
* @param result - the result of the compression
* @return -1 if there is an error otherwise 0
* @param rounds - Число раундов
* @param state - Вектор состояния
* @param msg - Вектор блока сообщения
* @param t0_offset - Смещения счётчиков
* @param t1_offset - Смещения счётчиков
* @param final - Флаг последнего блока
* @param result - Результат сжатия
* @return -1 при ошибке, иначе 0
*/
inline int32_t blake2_f( uint32_t rounds, const std::vector<char>& state, const std::vector<char>& msg, const std::vector<char>& t0_offset, const std::vector<char>& t1_offset, bool final, std::vector<char>& result) {
eosio::check( result.size() >= blake2f_result_size, "blake2_f result parameter's size must be >= 64" );
@@ -349,23 +349,23 @@ namespace eosio {
}
/**
* BLAKE2 compression function "F"
* Функция сжатия BLAKE2 «F»
* https://eips.ethereum.org/EIPS/eip-152
*
* @ingroup crypto
* @param rounds - the number of rounds
* @param state - state vector
* @param state_len - size of state vector
* @param msg - message block vector
* @param msg_len - size of message block vector
* @param t0_offset - offset counters
* @param t0_len - size of t0_offset
* @param t1_offset - offset counters
* @param t1_len - size of t1_offset
* @param final - final block flag
* @param result - the result of the compression
* @param result_len - size of result
* @return -1 if there is an error otherwise 0
* @param rounds - Число раундов
* @param state - Вектор состояния
* @param state_len - Размер вектора состояния
* @param msg - Вектор блока сообщения
* @param msg_len - Размер блока сообщения
* @param t0_offset - Смещения счётчиков
* @param t0_len - Размер t0_offset
* @param t1_offset - Смещения счётчиков
* @param t1_len - Размер t1_offset
* @param final - Флаг последнего блока
* @param result - Результат сжатия
* @param result_len - Размер результата
* @return -1 при ошибке, иначе 0
*/
inline int32_t blake2_f( uint32_t rounds, const char* state, uint32_t state_len, const char* msg, uint32_t msg_len,
const char* t0_offset, uint32_t t0_len, const char* t1_offset, uint32_t t1_len, int32_t final, char* result, uint32_t result_len) {
@@ -373,35 +373,25 @@ namespace eosio {
}
/**
* Hashes `data` using `sha3`
*
* @param data - data you want to hash
* @param length - size of data
* @param keccak - whether to use `keccak` or NIST variant; keccak = 1 and NIST == 0
* @return eosio::checksum256 - Computed digest
*
*/
/**
* Hashes `data` using SHA3 NIST.
* Вычисляет хеш `data` алгоритмом SHA3 (вариант NIST).
*
* @ingroup crypto
* @param data - Data you want to hash
* @param length - Data length
* @return eosio::checksum256 - Computed digest
* @param data - Данные для хеширования
* @param length - Длина данных
* @return eosio::checksum256 - Вычисленный дайджест
*/
inline eosio::checksum256 sha3(const char* data, uint32_t length) {
return internal_use_do_not_use::sha3_helper(data, length, false);
}
/**
* Tests if the SHA3 hash generated from data matches the provided digest.
* Проверяет, совпадает ли SHA3-хеш данных с переданным дайджестом.
*
* @ingroup crypto
* @param data - Data you want to hash
* @param length - Data length
* @param hash - digest to compare to
* @note !This method is not optimized away during replay
* @param data - Данные для хеширования
* @param length - Длина данных
* @param hash - Дайджест для сравнения
* @note Этот метод не вырезается при повторном воспроизведении
*/
inline void assert_sha3(const char* data, uint32_t length, const eosio::checksum256& hash) {
const auto& res = internal_use_do_not_use::sha3_helper(data, length, false);
@@ -409,25 +399,25 @@ namespace eosio {
}
/**
* Hashes `data` using SHA3 Keccak.
* Вычисляет хеш `data` алгоритмом SHA3 Keccak.
*
* @ingroup crypto
* @param data - Data you want to hash
* @param length - Data length
* @return eosio::checksum256 - Computed digest
* @param data - Данные для хеширования
* @param length - Длина данных
* @return eosio::checksum256 - Вычисленный дайджест
*/
inline eosio::checksum256 keccak(const char* data, uint32_t length) {
return internal_use_do_not_use::sha3_helper(data, length, true);
}
/**
* Tests if the SHA3 keccak hash generated from data matches the provided digest.
* Проверяет, совпадает ли Keccak-хеш данных с переданным дайджестом.
*
* @ingroup crypto
* @param data - Data you want to hash
* @param length - Data length
* @param hash - digest to compare to
* @note !This method is not optimized away during replay
* @param data - Данные для хеширования
* @param length - Длина данных
* @param hash - Дайджест для сравнения
* @note Этот метод не вырезается при повторном воспроизведении
*/
inline void assert_keccak(const char* data, uint32_t length, const eosio::checksum256& hash) {
const auto& res = internal_use_do_not_use::sha3_helper(data, length, true);
@@ -435,18 +425,18 @@ namespace eosio {
}
/**
* Calculates the uncompressed public key used for a given signature on a given digest.
* Вычисляет несжатый открытый ключ по подписи и дайджесту.
*
* @ingroup crypto
* @param sig - signature.
* @param sig_len - size of signature
* @param dig - digest of the message that was signed.
* @param dig_len - size of digest
* @param pub - public key result
* @param pub_len - size of public key result
* @param sig - Подпись
* @param sig_len - Размер подписи
* @param dig - Дайджест подписанного сообщения
* @param dig_len - Размер дайджеста
* @param pub - Буфер для открытого ключа
* @param pub_len - Размер буфера открытого ключа
*
* @return -1 if there was an error 0 otherwise.
*/
* @return -1 при ошибке, иначе 0
*/
inline int32_t k1_recover( const char* sig, uint32_t sig_len, const char* dig, uint32_t dig_len, char* pub, uint32_t pub_len ) {
return internal_use_do_not_use::k1_recover( sig, sig_len, dig, dig_len, pub, pub_len );
}
File diff suppressed because it is too large Load Diff
+62 -64
View File
@@ -1,6 +1,6 @@
/**
* @file
* @copyright defined in eos/LICENSE
* @copyright см. eos/LICENSE
*/
#pragma once
#include "datastream.hpp"
@@ -38,17 +38,17 @@ namespace eosio {
/// @endcond
/**
* @defgroup fixed_bytes Fixed Size Byte Array
* @defgroup fixed_bytes Массив байт фиксированного размера
* @ingroup core
* @ingroup types
* @brief Fixed size array of bytes sorted lexicographically
* @brief Массив байт фиксированного размера с лексикографическим упорядочиванием
*/
/**
* Fixed size byte array sorted lexicographically
* Массив байт фиксированного размера с лексикографическим сравнением по словам
*
* @ingroup fixed_bytes
* @tparam Size - Size of the fixed_bytes object
* @tparam Size — размер в байтах
*/
template<size_t Size>
class fixed_bytes {
@@ -94,26 +94,25 @@ namespace eosio {
typedef uint128_t word_t;
/**
* Get number of words contained in this fixed_bytes object. A word is defined to be 16 bytes in size
* Число «слов» (word_t) внутри объекта; размер слова — 16 байт (uint128_t)
*/
static constexpr size_t num_words() { return (Size + sizeof(word_t) - 1) / sizeof(word_t); }
/**
* Get number of padded bytes contained in this fixed_bytes object. Padded bytes are the remaining bytes
* inside the fixed_bytes object after all the words are allocated
* Число дополняющих (неиспользуемых) байт в последнем слове после выравнивания по word_t
*/
static constexpr size_t padded_bytes() { return num_words() * sizeof(word_t) - Size; }
/**
* Default constructor to fixed_bytes object which initializes all bytes to zero
* Конструктор по умолчанию; все байты нулевые
*/
constexpr fixed_bytes() : _data() {}
/**
* Constructor to fixed_bytes object from std::array of num_words() word_t types
* Конструктор из std::array из num_words() элементов word_t
*
* @param arr data
* @param arr — исходные данные
*/
fixed_bytes(const std::array<word_t, num_words()>& arr)
{
@@ -121,9 +120,9 @@ namespace eosio {
}
/**
* Constructor to fixed_bytes object from std::array of Word types smaller in size than word_t
* Конструктор из std::array слов Word меньше word_t (сборка в слова хранения)
*
* @param arr - Source data
* @param arr — исходные данные
*/
template<typename Word, size_t NumWords,
typename Enable = typename std::enable_if<std::is_integral<Word>::value &&
@@ -140,9 +139,9 @@ namespace eosio {
}
/**
* Constructor to fixed_bytes object from fixed-sized C array of Word types smaller in size than word_t
* Конструктор из C-массива слов Word меньше word_t
*
* @param arr - Source data
* @param arr — исходные данные
*/
template<typename Word, size_t NumWords,
typename Enable = typename std::enable_if<std::is_integral<Word>::value &&
@@ -159,12 +158,12 @@ namespace eosio {
}
/**
* Create a new fixed_bytes object from a sequence of words
* Создаёт fixed_bytes из последовательности слов (аргументы функции)
*
* @tparam FirstWord - The type of the first word in the sequence
* @tparam Rest - The type of the remaining words in the sequence
* @param first_word - The first word in the sequence
* @param rest - The remaining words in the sequence
* @tparam FirstWord — тип первого слова
* @tparam Rest — типы остальных слов
* @param first_word — первое слово
* @param rest — остальные слова
*/
template<typename FirstWord, typename... Rest>
static
@@ -188,34 +187,34 @@ namespace eosio {
}
/**
* Get the contained std::array
* Константная ссылка на внутренний std::array слов
*/
const auto& get_array()const { return _data; }
/**
* Get the underlying data of the contained std::array
* Указатель на сырые данные массива слов
*/
auto data() { return _data.data(); }
/// @cond INTERNAL
/**
* Get the underlying data of the contained std::array
* Указатель на сырые данные (const)
*/
auto data()const { return _data.data(); }
/// @endcond
/**
* Get the size of the contained std::array
* Число слов word_t во внутреннем массиве
*/
auto size()const { return _data.size(); }
/**
* Extract the contained data as an array of bytes
* Извлекает байты фиксированной длины Size в порядке старшинства для сериализации
*
* @return - the extracted data as array of bytes
* @return массив из Size байт
*/
std::array<uint8_t, Size> extract_as_byte_array()const {
std::array<uint8_t, Size> arr;
@@ -244,9 +243,8 @@ namespace eosio {
}
/**
* Prints fixed_bytes as a hexidecimal string
* Печать в шестнадцатеричном виде в лог контракта COOPOS
*
* @param val to be printed
*/
inline void print()const {
auto arr = extract_as_byte_array();
@@ -277,11 +275,11 @@ namespace eosio {
/// @cond IMPLEMENTATIONS
/**
* Lexicographically compares two fixed_bytes variables c1 and c2
* Лексикографическое сравнение: равенство
*
* @param c1 - First fixed_bytes object to compare
* @param c2 - Second fixed_bytes object to compare
* @return if c1 == c2, return true, otherwise false
* @param c1 — первый операнд
* @param c2 — второй операнд
* @return true — c1 равен c2
*/
template<size_t Size>
bool operator ==(const fixed_bytes<Size> &c1, const fixed_bytes<Size> &c2) {
@@ -289,11 +287,11 @@ namespace eosio {
}
/**
* Lexicographically compares two fixed_bytes variables c1 and c2
* Лексикографическое сравнение: неравенство
*
* @param c1 - First fixed_bytes object to compare
* @param c2 - Second fixed_bytes object to compare
* @return if c1 != c2, return true, otherwise false
* @param c1 — первый операнд
* @param c2 — второй операнд
* @return true — c1 не равен c2
*/
template<size_t Size>
bool operator !=(const fixed_bytes<Size> &c1, const fixed_bytes<Size> &c2) {
@@ -301,11 +299,11 @@ namespace eosio {
}
/**
* Lexicographically compares two fixed_bytes variables c1 and c2
* Лексикографическое сравнение: больше
*
* @param c1 - First fixed_bytes object to compare
* @param c2 - Second fixed_bytes object to compare
* @return if c1 > c2, return true, otherwise false
* @param c1 — первый операнд
* @param c2 — второй операнд
* @return true — c1 больше c2
*/
template<size_t Size>
bool operator >(const fixed_bytes<Size>& c1, const fixed_bytes<Size>& c2) {
@@ -313,11 +311,11 @@ namespace eosio {
}
/**
* Lexicographically compares two fixed_bytes variables c1 and c2
* Лексикографическое сравнение: меньше
*
* @param c1 - First fixed_bytes object to compare
* @param c2 - Second fixed_bytes object to compare
* @return if c1 < c2, return true, otherwise false
* @param c1 — первый операнд
* @param c2 — второй операнд
* @return true — c1 меньше c2
*/
template<size_t Size>
bool operator <(const fixed_bytes<Size> &c1, const fixed_bytes<Size> &c2) {
@@ -325,11 +323,11 @@ namespace eosio {
}
/**
* Lexicographically compares two fixed_bytes variables c1 and c2
* Лексикографическое сравнение: больше или равно
*
* @param c1 - First fixed_bytes object to compare
* @param c2 - Second fixed_bytes object to compare
* @return if c1 >= c2, return true, otherwise false
* @param c1 — первый операнд
* @param c2 — второй операнд
* @return true — c1 не меньше c2
*/
template<size_t Size>
bool operator >=(const fixed_bytes<Size>& c1, const fixed_bytes<Size>& c2) {
@@ -337,11 +335,11 @@ namespace eosio {
}
/**
* Lexicographically compares two fixed_bytes variables c1 and c2
* Лексикографическое сравнение: меньше или равно
*
* @param c1 - First fixed_bytes object to compare
* @param c2 - Second fixed_bytes object to compare
* @return if c1 <= c2, return true, otherwise false
* @param c1 — первый операнд
* @param c2 — второй операнд
* @return true — c1 не больше c2
*/
template<size_t Size>
bool operator <=(const fixed_bytes<Size> &c1, const fixed_bytes<Size> &c2) {
@@ -354,13 +352,13 @@ namespace eosio {
using checksum512 = fixed_bytes<64>;
/**
* Serialize a fixed_bytes into a stream
* Сериализация fixed_bytes в поток
*
* @brief Serialize a fixed_bytes
* @param ds - The stream to write
* @param d - The value to serialize
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @brief Сериализация fixed_bytes
* @param ds — поток записи
* @param d — значение
* @tparam DataStream — тип буфера потока данных
* @return DataStream& — ссылка на поток
*/
template<typename DataStream, size_t Size>
inline DataStream& operator<<(DataStream& ds, const fixed_bytes<Size>& d) {
@@ -370,13 +368,13 @@ namespace eosio {
}
/**
* Deserialize a fixed_bytes from a stream
* Десериализация fixed_bytes из потока
*
* @brief Deserialize a fixed_bytes
* @param ds - The stream to read
* @param d - The destination for deserialized value
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @brief Десериализация fixed_bytes
* @param ds — поток чтения
* @param d — приёмник значения
* @tparam DataStream — тип буфера потока данных
* @return DataStream& — ссылка на поток
*/
template<typename DataStream, size_t Size>
inline DataStream& operator>>(DataStream& ds, fixed_bytes<Size>& d) {
+23 -24
View File
@@ -4,23 +4,23 @@
namespace eosio {
/**
* @defgroup ignore
* @defgroup ignore Игнорирование типа
* @ingroup core
* @brief Enables telling the datastream to ignore this type, but allowing abi generator to add the correct type.
* @brief Указывает datastream игнорировать этот тип, сохраняя корректный тип для генератора ABI.
*/
/**
* Tells the datastream to ignore this type, but allows the abi generator to add the correct type.
* Указывает datastream игнорировать этот тип при упаковке, при этом генератор ABI может вывести корректный тип.
*
* @ingroup ignore
* @details Currently non-ignore types can not succeed an ignore type in a method definition, i.e. void foo(float, ignore<int>) is allowed and void foo(float, ignore<int>, int) is not allowed.
* @note This restriction will be relaxed in a later release. Currently non-ignore types can not succeed an ignore type in a method definition, i.e. void foo(float, ignore<int>) is allowed and void foo(float, ignore<int>, int) is not allowed.
* @details Сейчас после параметра типа ignore в сигнатуре метода не могут следовать «обычные» типы: допустимо void foo(float, ignore<int>), недопустимо void foo(float, ignore<int>, int).
* @note Ограничение может быть ослаблено в будущих версиях. Формулировка та же: после ignore<int> в списке параметров нежелательны следующие не-ignore типы.
*/
template <typename T>
struct [[eosio::ignore]] ignore {};
/**
* Wrapper class to allow sending inline actions with the correct payload
* Обёртка для корректной передачи полезной нагрузки при inline-действиях в COOPOS
*/
template <typename T>
struct ignore_wrapper {
@@ -34,13 +34,13 @@ namespace eosio {
};
/**
* Serialize an ignored_wrapper type into a stream
* Сериализация ignore_wrapper<T> в поток (пишется val.value)
*
* @brief Serialize ignored_wrapper<T>'s T value
* @param ds - The stream to write
* @param val - The value to serialize
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @brief Сериализация значения T из ignored_wrapper<T>
* @param ds — поток записи
* @param val — обёртка с полем value
* @tparam DataStream — тип буфера потока данных
* @return DataStream& — ссылка на поток
*/
template<typename DataStream, typename T>
inline DataStream& operator<<(DataStream& ds, const ::eosio::ignore_wrapper<T>& val) {
@@ -49,13 +49,13 @@ namespace eosio {
}
/**
* Serialize an ignored type into a stream
* Сериализация ignore<T> — ничего не записывает
*
* @brief Serialize an ignored type
* @param ds - The stream to write
* @param ignore - The value to serialize
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @brief Сериализация игнорируемого типа
* @param ds — поток записи
* @param val — игнорируемое значение
* @tparam DataStream — тип буфера потока данных
* @return DataStream& — ссылка на поток
*/
template<typename DataStream, typename T>
inline DataStream& operator<<(DataStream& ds, const ::eosio::ignore<T>& val) {
@@ -63,13 +63,12 @@ namespace eosio {
}
/**
* Deserialize an ignored type from a stream
* Десериализация ignore<T> — ничего не читает
*
* @brief Deserialize an ignored type
* @param ds - The stream to read
* @param ignored - The destination for deserialized value
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @brief Десериализация игнорируемого типа
* @param ds — поток чтения
* @tparam DataStream — тип буфера потока данных
* @return DataStream& — ссылка на поток
*/
template<typename DataStream, typename T>
inline DataStream& operator>>(DataStream& ds, ::eosio::ignore<T>&) {
+35 -35
View File
@@ -73,27 +73,27 @@ namespace eosio {
using key_type = std::string;
// to_key defines a conversion from a type to a sequence of bytes whose lexicograpical
// ordering is the same as the ordering of the original type.
// to_key задаёт преобразование типа в последовательность байт, лексикографический
// порядок которой совпадает с порядком исходного типа.
//
// For any two objects of type T, a and b:
// Для любых двух объектов типа T, a и b:
//
// - key(a) < key(b) iff a < b
// - key(a) is not a prefix of key(b)
// - key(a) < key(b) тогда и только тогда, когда a < b
// - key(a) не является префиксом key(b)
//
// Overloads of to_key for user-defined types can be found by Koenig (ADL) lookup.
// Перегрузки to_key для пользовательских типов находятся поиском Кёнига (ADL).
//
// to_key is specialized for the following types
// - std::string and std::string_view
// to_key специализирован для следующих типов
// - std::string и std::string_view
// - std::vector, std::list, std::deque
// - std::tuple
// - std::array
// - std::optional
// - std::variant
// - Arithmetic types
// - Scoped enumeration types
// - Reflected structs
// - All smart-contract related types defined by abieos
// - арифметические типы
// - типы областных перечислений (scoped enum)
// - рефлектируемые структуры
// - все типы, связанные со смарт-контрактами COOPOS, определённые в abieos
template <typename T, typename S>
void to_key(const T& obj, datastream<S>& stream);
@@ -176,15 +176,15 @@ void to_key(const std::optional<T>& obj, datastream<S>& stream) {
to_key_optional(obj ? &*obj : nullptr, stream);
}
// The first byte holds:
// 0-4 1's (number of additional bytes) 0 (terminator) bits
// Первый байт содержит:
// 04 единицы (число дополнительных байт), 0 (бит-терминатор)
//
// The number is represented as big-endian using the low order
// bits of the first byte and all of the remaining bytes.
// Число представляется в порядке big-endian с использованием младших
// разрядов первого байта и всех оставшихся байт.
//
// Notes:
// - values must be encoded using the minimum number of bytes,
// as non-canonical representations will break the sort order.
// Примечания:
// - значения должны кодироваться минимально возможным числом байт,
// иначе неканонические представления нарушат порядок сортировки.
template <typename S>
void to_key_varuint32(std::uint32_t obj, datastream<S>& stream) {
int num_bytes;
@@ -205,23 +205,23 @@ void to_key_varuint32(std::uint32_t obj, datastream<S>& stream) {
for (int i = num_bytes - 2; i >= 0; --i) { stream.write(static_cast<char>((obj >> i * 8) & 0xFFu)); }
}
// for non-negative values
// The first byte holds:
// 1 (signbit) 0-4 1's (number of additional bytes) 0 (terminator) bits
// The value is represented as big endian
// for negative values
// The first byte holds:
// 0 (signbit) 0-4 0's (number of additional bytes) 1 (terminator) bits
// The value is adjusted to be positive based on the range that can
// be represented with this number of bytes and then encoded as big endian.
// для неотрицательных значений
// Первый байт содержит:
// 1 (бит знака) 04 единицы (число дополнительных байт) 0 (бит-терминатор)
// Значение представляется в порядке big-endian
// для отрицательных значений
// Первый байт содержит:
// 0 (бит знака) 04 нуля (число дополнительных байт) 1 (бит-терминатор)
// Значение приводится к положительному виду в допустимом диапазоне для
// данного числа байт и затем кодируется как big-endian.
//
// Notes:
// - negative values must sort before positive values
// - For negative value, numbers that need more bytes are smaller, hence
// the encoding of the width must be opposite the encoding used for
// non-negative values.
// - A 5-byte varint can represent values in $[-2^34, 2^34)$. In this case,
// the argument will be sign-extended.
// Примечания:
// - отрицательные значения должны сортироваться раньше положительных
// - для отрицательных значений числа, требующие большего числа байт, меньше, поэтому
// кодирование ширины должно быть противоположно используемому для
// неотрицательных значений
// - 5-байтовый varint может представлять значения в диапазоне $[-2^{34}, 2^{34})$; в этом случае
// аргумент дополняется знаком (sign-extended)
template <typename S>
void to_key_varint32(std::int32_t obj, datastream<S>& stream) {
static_assert(std::is_same_v<S, void>, "to_key for varint32 has been temporarily disabled");
+43 -45
View File
@@ -1,6 +1,6 @@
/**
* @file
* @copyright defined in eos/LICENSE
* @copyright см. eos/LICENSE
*/
#pragma once
@@ -20,16 +20,15 @@ namespace eosio {
}
/**
* @defgroup name
* @defgroup name Имя
* @ingroup core
* @ingroup types
* @brief EOSIO Name Type
* @brief Тип имени COOPOS
*/
/**
* Wraps a %uint64_t to ensure it is only passed to methods that expect a %name.
* Ensures value is only passed to methods that expect a %name and that no mathematical
* operations occur. Also enables specialization of print
* Обёртка над %uint64_t для имён аккаунтов и контрактов в COOPOS: значение передаётся только там,
* где ожидается %name, без арифметики над «именем». Позволяет специализировать печать.
*
* @ingroup name
*/
@@ -38,18 +37,18 @@ namespace eosio {
enum class raw : uint64_t {};
/**
* Construct a new name
* Конструктор по умолчанию; имя с нулевым значением
*
* @brief Construct a new name object defaulting to a value of 0
* @brief Конструктор name со значением по умолчанию 0
*
*/
constexpr name() : value(0) {}
/**
* Construct a new name given a unit64_t value
* Создаёт name из uint64_t
*
* @brief Construct a new name object initialising value with v
* @param v - The unit64_t value
* @brief Конструктор name; инициализация поля value значением v
* @param v — значение uint64_t
*
*/
constexpr explicit name( uint64_t v )
@@ -57,10 +56,10 @@ namespace eosio {
{}
/**
* Construct a new name given a scoped enumerated type of raw (uint64_t).
* Создаёт name из типа name::raw
*
* @brief Construct a new name object initialising value with r
* @param r - The raw value which is a scoped enumerated type of unit64_t
* @brief Конструктор name; инициализация поля value значением r
* @param r — сырое значение (strong typedef к uint64_t)
*
*/
constexpr explicit name( name::raw r )
@@ -68,10 +67,10 @@ namespace eosio {
{}
/**
* Construct a new name given an string.
* Создаёт name из строки (правила кодирования имён COOPOS)
*
* @brief Construct a new name object initialising value with str
* @param str - The string value which validated then converted to unit64_t
* @brief Конструктор name; инициализация поля value из строки str
* @param str — строка; после проверки преобразуется в uint64_t
*
*/
constexpr explicit name( std::string_view str )
@@ -100,10 +99,10 @@ namespace eosio {
}
/**
* Converts a %name Base32 symbol into its corresponding value
* Преобразует символ алфавита имён (Base32-подобный) в числовое значение
*
* @param c - Character to be converted
* @return constexpr char - Converted value
* @param c — символ
* @return числовое значение символа
*/
static constexpr uint8_t char_to_value( char c ) {
if( c == '.')
@@ -119,7 +118,7 @@ namespace eosio {
}
/**
* Returns the length of the %name
* Длина имени в символах
*/
constexpr uint8_t length()const {
constexpr uint64_t mask = 0xF800000000000000ull;
@@ -139,7 +138,7 @@ namespace eosio {
}
/**
* Returns the suffix of the %name
* Суффикс имени после последней значащей точки
*/
constexpr name suffix()const {
uint32_t remaining_bits_after_last_actual_dot = 0;
@@ -172,7 +171,7 @@ namespace eosio {
}
/**
* Returns the prefix of the %name
* Префикс имени до последней значащей точки
*/
constexpr name prefix() const {
uint64_t result = value;
@@ -204,28 +203,28 @@ namespace eosio {
}
/**
* Casts a name to raw
* Приведение к name::raw
*
* @return Returns an instance of raw based on the value of a name
* @return значение в виде raw
*/
constexpr operator raw()const { return raw(value); }
/**
* Explicit cast to bool of the uint64_t value of the name
* Явное приведение к bool по полю value
*
* @return Returns true if the name is set to the default value of 0 else true.
* @return true — если value ≠ 0; иначе false
*/
constexpr explicit operator bool()const { return value != 0; }
/**
* Writes the %name as a string to the provided char buffer
* Записывает строковое представление %name в буфер char
*
* @pre The range [begin, end) must be a valid range of memory to write to.
* @param begin - The start of the char buffer
* @param end - Just past the end of the char buffer
* @param dry_run - If true, do not actually write anything into the range.
* @return char* - Just past the end of the last character that would be written assuming dry_run == false and end was large enough to provide sufficient space. (Meaning only applies if returned pointer >= begin.)
* @post If the output string fits within the range [begin, end) and dry_run == false, the range [begin, returned pointer) contains the string representation of the %name. Nothing is written if dry_run == true or returned pointer > end (insufficient space) or if returned pointer < begin (overflow in calculating desired end).
* @pre диапазон [begin, end) — допустимая область памяти для записи
* @param begin — начало буфера
* @param end — конец буфера (не включая end)
* @param dry_run — если true, ничего не записывать
* @return char* — указатель сразу за последним символом, который был бы записан (при достаточном буфере и dry_run == false; смысл только если возврат ≥ begin)
* @post при успехе и dry_run == false в [begin, возврат) — строка имени
*/
char* write_as_string( char* begin, char* end, bool dry_run = false )const {
static const char* charmap = ".12345abcdefghijklmnopqrstuvwxyz";
@@ -249,9 +248,9 @@ namespace eosio {
}
/**
* Returns the name as a string.
* Строковое представление имени через write_as_string()
*
* @brief Returns the name value as a string by calling write_as_string() and returning the buffer produced by write_as_string()
* @brief Возвращает имя как строку через write_as_string() и буфер, заполненный этой функцией
*/
std::string to_string()const {
char buffer[13];
@@ -260,9 +259,8 @@ namespace eosio {
}
/**
* Prints an names as base32 encoded string
* Печать имени в лог контракта COOPOS (нативный вывод)
*
* @param name to be printed
*/
inline void print()const {
internal_use_do_not_use::printn(value);
@@ -271,27 +269,27 @@ namespace eosio {
/// @cond INTERNAL
/**
* Equivalency operator. Returns true if a == b (are the same)
* Оператор равенства
*
* @return boolean - true if both provided %name values are the same
* @return true — значения совпадают
*/
friend constexpr bool operator == ( const name& a, const name& b ) {
return a.value == b.value;
}
/**
* Inverted equivalency operator. Returns true if a != b (are different)
* Оператор неравенства
*
* @return boolean - true if both provided %name values are not the same
* @return true — значения различаются
*/
friend constexpr bool operator != ( const name& a, const name& b ) {
return a.value != b.value;
}
/**
* Less than operator. Returns true if a < b.
* Оператор «меньше» по uint64_t
*
* @return boolean - true if %name `a` is less than `b`
* @return true — a меньше b
*/
friend constexpr bool operator < ( const name& a, const name& b ) {
return a.value < b.value;
@@ -315,7 +313,7 @@ namespace eosio {
/**
* @ingroup name
* @brief "foo"_n is a shortcut for name("foo")
* @brief Литерал "foo"_n — сокращение для name("foo")
*/
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu-string-literal-operator-template"
+1 -1
View File
@@ -76,7 +76,7 @@ namespace eosio {
template<uint8_t Base, typename T = uint64_t>
inline constexpr auto powers_of_base = detail::generate_array<detail::largest_power<T, Base>::exponent + 1>( detail::pow_generator<T, Base> );
/** @returns Base^exponent */
/** @return Возвращает Base в степени exponent (Base^exponent). */
template<uint8_t Base, typename T = uint64_t>
constexpr T pow( uint8_t exponent ) {
const auto& lookup_table = powers_of_base<Base, T>;
+54 -55
View File
@@ -1,6 +1,6 @@
/**
* @file
* @copyright defined in eos/LICENSE
* @copyright см. eos/LICENSE
*/
#pragma once
#include <utility>
@@ -47,62 +47,62 @@ namespace eosio {
};
/**
* @defgroup console Console
* @defgroup console Консоль
* @ingroup core
* @brief Defines C++ wrapper to log/print text messages
* @brief Определяет C++-обёртку для вывода текстовых сообщений в лог/консоль
*
* @details This API uses C++ variadic templates and type detection to
* make it easy to print any native type. You can even overload
* the `print()` method for your own custom types.
* @details Этот API использует вариадические шаблоны C++ и определение типов,
* чтобы упростить вывод любых встроенных типов. Можно перегрузить
* метод `print()` и для своих типов.
*
* **Example:**
* **Пример:**
* ```
* print( "hello world, this is a number: ", 5 );
* ```
*
* @section override Overriding Print for your Types
* @section override Перегрузка print для своих типов
*
* There are two ways to overload print:
* 1. implement void print( const T& )
* 2. implement T::print()const
* Два способа перегрузить print:
* 1. реализовать void print( const T& )
* 2. реализовать T::print() const
*/
/**
* Prints a block of bytes in hexadecimal
* Выводит блок байт в шестнадцатеричном виде
*
* @ingroup console
* @param ptr - pointer to bytes of interest
* @param size - number of bytes to print
* @param ptr - Указатель на байты
* @param size - Число байт для вывода
*/
inline void printhex( const void* ptr, uint32_t size) {
internal_use_do_not_use::printhex(ptr, size);
}
/**
* Prints string to a given length
* Выводит строку заданной длины
*
* @ingroup console
* @param ptr - a string
* @param len - number of chars to print
* @param ptr - Строка
* @param len - Число символов для вывода
*/
inline void printl( const char* ptr, size_t len ) {
internal_use_do_not_use::prints_l(ptr, len);
}
/**
* Prints string
* Выводит строку
*
* @ingroup console
* @param ptr - a null terminated string
* @param ptr - Строка с нулевым завершением
*/
inline void print( const char* ptr ) {
internal_use_do_not_use::prints(ptr);
}
/**
* Prints 8-128 bit signed integer
* Выводит знаковое целое 8128 бит
*
* @param num to be printed
* @param num Значение для вывода
*/
template <typename T, std::enable_if_t<std::is_integral<std::decay_t<T>>::value &&
std::is_signed<std::decay_t<T>>::value, int> = 0>
@@ -116,9 +116,9 @@ namespace eosio {
}
/**
* Prints 8-128 bit unsigned integer
* Выводит беззнаковое целое 8128 бит
*
* @param num to be printed
* @param num Значение для вывода
*/
template <typename T, std::enable_if_t<std::is_integral<std::decay_t<T>>::value &&
!std::is_signed<std::decay_t<T>>::value, int> = 0>
@@ -132,35 +132,35 @@ namespace eosio {
}
/**
* Prints single-precision floating point number (i.e. float)
* Выводит число с плавающей точкой одинарной точности (float)
*
* @ingroup console
* @param num to be printed
* @param num Значение для вывода
*/
inline void print( float num ) { internal_use_do_not_use::printsf( num ); }
/**
* Prints double-precision floating point number (i.e. double)
* Выводит число с плавающей точкой двойной точности (double)
*
* @ingroup console
* @param num to be printed
* @param num Значение для вывода
*/
inline void print( double num ) { internal_use_do_not_use::printdf( num ); }
/**
* Prints quadruple-precision floating point number (i.e. long double)
* Выводит число с плавающей точкой расширенной точности (long double)
*
* @ingroup console
* @param num to be printed
* @param num Значение для вывода
*/
inline void print( long double num ) { internal_use_do_not_use::printqf( &num ); }
/**
* Prints class object
* Выводит объект класса
*
* @ingroup console
* @param t to be printed
* @pre T must implements print() function
* @param t Значение для вывода
* @pre У T должна быть реализована функция print()
*/
template<typename T, std::enable_if_t<!std::is_integral<std::decay_t<T>>::value, int> = 0>
inline void print( T&& t ) {
@@ -173,25 +173,25 @@ namespace eosio {
}
/**
* Prints null terminated string
* Выводит строку с нулевым завершением
*
* @ingroup console
* @param s null terminated string to be printed
* @param s Строка с нулевым завершением
*/
inline void print_f( const char* s ) {
internal_use_do_not_use::prints(s);
}
/**
* Prints formatted string. It behaves similar to C printf/
* Выводит форматированную строку. Поведение близко к C printf.
*
* @tparam Arg - Type of the value used to replace the format specifier
* @tparam Args - Type of the value used to replace the format specifier
* @param s - Null terminated string with to be printed (it can contains format specifier)
* @param val - The value used to replace the format specifier
* @param rest - The values used to replace the format specifier
* @tparam Arg - Тип значения для подстановки вместо спецификатора формата
* @tparam Args - Типы остальных значений для подстановки
* @param s - Строка с нулевым завершением (может содержать спецификатор формата)
* @param val - Значение для первой подстановки
* @param rest - Остальные значения для подстановки
*
* Example:
* Пример:
* @code
* print_f("Number of apples: %", 10);
* @endcode
@@ -210,14 +210,14 @@ namespace eosio {
}
/**
* Print out value / list of values
* Выводит значение или список значений
*
* @tparam Arg - Type of the value used to replace the format specifier
* @tparam Args - Type of the value used to replace the format specifier
* @param a - The value to be printed
* @param args - The other values to be printed
* @tparam Arg - Тип первого значения
* @tparam Args - Типы остальных значений
* @param a - Первое значение для вывода
* @param args - Остальные значения для вывода
*
* Example:
* Пример:
*
* @code
* const char *s = "Hello World!";
@@ -235,7 +235,7 @@ namespace eosio {
}
/**
* Simulate C++ style streams
* Имитация потоков в стиле C++
*
* @ingroup console
*/
@@ -244,15 +244,14 @@ namespace eosio {
/// @cond OPERATORS
/**
* Overload c++ iostream
* Перегрузка оператора для iostream C++
*
* @tparam Arg - Type of the value used to replace the format specifier
* @tparam Args - Type of the value used to replace the format specifier
* @param out - Output strem
* @param v - The value to be printed
* @return iostream& - Reference to the input output stream
* @tparam T - Тип выводимого значения
* @param out - Выходной поток
* @param v - Значение для вывода
* @return iostream& - Ссылка на поток ввода-вывода
*
* Example:
* Пример:
*
* @code
* const char *s = "Hello World!";
+10 -10
View File
@@ -4,17 +4,17 @@
OP t.elem
/**
* @defgroup serialize Serialize
* @defgroup serialize Сериализация
* @ingroup core
* @brief Defines C++ API to serialize and deserialize object
* @brief Определяет C++ API сериализации и десериализации объектов
*/
/**
* Defines serialization and deserialization for a class
* Задаёт сериализацию и десериализацию для класса
*
* @ingroup serialize
* @param TYPE - the class to have its serialization and deserialization defined
* @param MEMBERS - a sequence of member names. (field1)(field2)(field3)
* @param TYPE - Класс, для которого задаются сериализация и десериализация
* @param MEMBERS - Последовательность имён полей: (field1)(field2)(field3)
*/
#define EOSLIB_SERIALIZE( TYPE, MEMBERS ) \
template<typename DataStream> \
@@ -27,13 +27,13 @@
}
/**
* Defines serialization and deserialization for a class which inherits from other classes that
* have their serialization and deserialization defined
* Задаёт сериализацию и десериализацию для класса, наследующего базовые классы,
* у которых сериализация и десериализация уже определены
*
* @ingroup serialize
* @param TYPE - the class to have its serialization and deserialization defined
* @param BASE - a sequence of base class names (basea)(baseb)(basec)
* @param MEMBERS - a sequence of member names. (field1)(field2)(field3)
* @param TYPE - Класс, для которого задаются сериализация и десериализация
* @param BASE - Последовательность имён базовых классов: (basea)(baseb)(basec)
* @param MEMBERS - Последовательность имён полей: (field1)(field2)(field3)
*/
#define EOSLIB_SERIALIZE_DERIVED( TYPE, BASE, MEMBERS ) \
template<typename DataStream> \
+1 -1
View File
@@ -1,6 +1,6 @@
/**
* @file
* @copyright defined in eosio.cdt/LICENSE.txt
* @copyright см. файл LICENSE в корне репозитория CDT
*/
#pragma once
+98 -99
View File
@@ -1,6 +1,6 @@
/**
* @file
* @copyright defined in eos/LICENSE
* @copyright см. eos/LICENSE
*/
#pragma once
@@ -16,13 +16,13 @@
namespace eosio {
/**
* @defgroup symbol Symbol
* @defgroup symbol Символ
* @ingroup core
* @brief Defines C++ API for managing symbols
* @brief Определяет C++ API для работы с символами
*/
/**
* Stores the symbol code as a uint64_t value
* Код символа токена, упакованный в uint64_t
*
* @ingroup symbol
*/
@@ -30,18 +30,18 @@ namespace eosio {
public:
/**
* Default constructor, construct a new symbol_code
* Конструктор по умолчанию; создаёт symbol_code со значением 0
*
* @brief Construct a new symbol_code object defaulting to a value of 0
* @brief Конструктор symbol_code со значением по умолчанию 0
*
*/
constexpr symbol_code() : value(0) {}
/**
* Construct a new symbol_code given a scoped enumerated type of raw (uint64_t).
* Создаёт symbol_code из сырого значения uint64_t.
*
* @brief Construct a new symbol_code object initialising value with raw
* @param raw - The raw value which is a scoped enumerated type of unit64_t
* @brief Конструктор symbol_code; инициализация поля value из raw
* @param raw — сырое значение (uint64_t)
*
*/
constexpr explicit symbol_code( uint64_t raw )
@@ -49,10 +49,10 @@ namespace eosio {
{}
/**
* Construct a new symbol_code given an string.
* Создаёт symbol_code из строки (до 7 заглавных букв A–Z).
*
* @brief Construct a new symbol_code object initialising value with str
* @param str - The string value which validated then converted to unit64_t
* @brief Конструктор symbol_code; инициализация поля value из строки str
* @param str — строка; после проверки преобразуется в uint64_t
*
*/
constexpr explicit symbol_code( std::string_view str )
@@ -71,8 +71,8 @@ namespace eosio {
}
/**
* Checks if the symbol code is valid
* @return true - if symbol is valid
* Проверяет корректность кода символа
* @return true — символ допустим
*/
constexpr bool is_valid()const {
auto sym = value;
@@ -92,9 +92,9 @@ namespace eosio {
}
/**
* Returns the character length of the provided symbol
* Возвращает длину кода символа в символах
*
* @return length - character length of the provided symbol
* @return length — число значащих символов
*/
constexpr uint32_t length()const {
auto sym = value;
@@ -107,31 +107,31 @@ namespace eosio {
}
/**
* Casts a symbol code to raw
* Возвращает сырое значение uint64_t
*
* @return Returns an instance of raw based on the value of a symbol_code
* @return значение поля value
*/
constexpr uint64_t raw()const { return value; }
/**
* Explicit cast to bool of the symbol_code
* Явное приведение к bool
*
* @return Returns true if the symbol_code is set to the default value of 0 else true.
* @return true — если value не равен 0; иначе false
*/
constexpr explicit operator bool()const { return value != 0; }
/**
* Writes the symbol_code as a string to the provided char buffer
* Записывает symbol_code в виде строки в буфер char
*
*
* @brief Writes the symbol_code as a string to the provided char buffer
* @brief Записывает symbol_code в виде строки в переданный буфер char
* @pre is_valid() == true
* @pre The range [begin, end) must be a valid range of memory to write to.
* @param begin - The start of the char buffer
* @param end - Just past the end of the char buffer
* @param dry_run - If true, do not actually write anything into the range.
* @return char* - Just past the end of the last character that would be written assuming dry_run == false and end was large enough to provide sufficient space. (Meaning only applies if returned pointer >= begin.)
* @post If the output string fits within the range [begin, end) and dry_run == false, the range [begin, returned pointer) contains the string representation of the symbol_code. Nothing is written if dry_run == true or returned pointer > end (insufficient space) or if returned pointer < begin (overflow in calculating desired end).
* @pre диапазон [begin, end) — допустимая область памяти для записи
* @param begin — начало буфера
* @param end — конец буфера (не включая end)
* @param dry_run — если true, ничего не записывать
* @return char* — указатель сразу за последним записанным символом (при dry_run == false и достаточном буфере; смысл только если возврат ≥ begin)
* @post при успехе и dry_run == false в [begin, возврат) — строка; иначе запись может не выполняться
*/
char* write_as_string( char* begin, char* end, bool dry_run = false )const {
constexpr uint64_t mask = 0xFFull;
@@ -153,7 +153,7 @@ namespace eosio {
}
/**
* Returns the name value as a string by calling write_as_string() and returning the buffer produced by write_as_string()
* Строковое представление кода символа через write_as_string()
*/
std::string to_string()const {
char buffer[7];
@@ -162,9 +162,8 @@ namespace eosio {
}
/**
* Prints a symbol_code
* Печать symbol_code в лог контракта COOPOS
*
* @param sym_code symbol code to be printed
*/
inline void print()const {
char buffer[7];
@@ -174,27 +173,27 @@ namespace eosio {
}
/**
* Equivalency operator. Returns true if a == b (are the same)
* Оператор равенства
*
* @return boolean - true if both provided symbol_codes are the same
* @return true — коды совпадают
*/
friend constexpr bool operator == ( const symbol_code& a, const symbol_code& b ) {
return a.value == b.value;
}
/**
* Inverted equivalency operator. Returns true if a != b (are different)
* Оператор неравенства
*
* @return boolean - true if both provided symbol_codes are not the same
* @return true — коды различаются
*/
friend constexpr bool operator != ( const symbol_code& a, const symbol_code& b ) {
return a.value != b.value;
}
/**
* Less than operator. Returns true if a < b.
* @brief Less than operator
* @return boolean - true if symbol_code `a` is less than `b`
* Оператор «меньше»
* @brief Оператор «меньше»
* @return true — значение a меньше b
*/
friend constexpr bool operator < ( const symbol_code& a, const symbol_code& b ) {
return a.value < b.value;
@@ -205,12 +204,12 @@ namespace eosio {
};
/**
* Serialize a symbol_code into a stream
* Сериализация symbol_code в поток
*
* @param ds - The stream to write
* @param sym - The value to serialize
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @param ds — поток записи
* @param sym_code — значение для сериализации
* @tparam DataStream — тип буфера потока данных
* @return DataStream& — ссылка на поток
*/
template<typename DataStream>
inline DataStream& operator<<(DataStream& ds, const eosio::symbol_code sym_code) {
@@ -220,12 +219,12 @@ namespace eosio {
}
/**
* Deserialize a symbol_code from a stream
* Десериализация symbol_code из потока
*
* @param ds - The stream to read
* @param symbol - The destination for deserialized value
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @param ds — поток чтения
* @param sym_code — приёмник значения
* @tparam DataStream — тип буфера потока данных
* @return DataStream& — ссылка на поток
*/
template<typename DataStream>
inline DataStream& operator>>(DataStream& ds, eosio::symbol_code& sym_code) {
@@ -236,68 +235,68 @@ namespace eosio {
}
/**
* Stores information about a symbol, the symbol can be 7 characters long.
* Символ токена: код (до 7 символов) и точность (число десятичных знаков).
*
* @ingroup symbol
*/
class symbol {
public:
/**
* Construct a new symbol object defaulting to a value of 0
* Конструктор по умолчанию; значение 0
*/
constexpr symbol() : value(0) {}
/**
* Construct a new symbol given a scoped enumerated type of raw (uint64_t).
* Создаёт symbol из упакованного uint64_t (код и точность).
*
* @param raw - The raw value which is a scoped enumerated type of unit64_t
* @param raw — сырое значение uint64_t
*/
constexpr explicit symbol( uint64_t raw ) : value(raw) {}
/**
* Construct a new symbol given a symbol_code and a uint8_t precision.
* Создаёт symbol по коду символа и точности.
*
* @param sc - The symbol_code
* @param precision - The number of decimal places used for the symbol
* @param sc — код символа
* @param precision — число десятичных знаков
*/
constexpr symbol( symbol_code sc, uint8_t precision )
: value( (sc.raw() << 8) | static_cast<uint64_t>(precision) )
{}
/**
* Construct a new symbol given a string and a uint8_t precision.
* Создаёт symbol по строке кода и точности.
*
* @param ss - The string containing the symbol
* @param precision - The number of decimal places used for the symbol
* @param ss — строка с кодом символа
* @param precision — число десятичных знаков
*/
constexpr symbol( std::string_view ss, uint8_t precision )
: value( (symbol_code(ss).raw() << 8) | static_cast<uint64_t>(precision) )
{}
/**
* Is this symbol valid
* Допустим ли символ
*/
constexpr bool is_valid()const { return code().is_valid(); }
/**
* This symbol's precision
* Точность символа (десятичные знаки)
*/
constexpr uint8_t precision()const { return static_cast<uint8_t>( value & 0xFFull ); }
/**
* Returns representation of symbol name
* Код символа (symbol_code)
*/
constexpr symbol_code code()const { return symbol_code{value >> 8}; }
/**
* Returns uint64_t repreresentation of the symbol
* Упакованное представление symbol в uint64_t
*/
constexpr uint64_t raw()const { return value; }
constexpr explicit operator bool()const { return value != 0; }
/**
* %Print the symbol
* Печать символа в лог контракта COOPOS
*/
void print( bool show_precision = true )const {
if( show_precision ){
@@ -310,27 +309,27 @@ namespace eosio {
}
/**
* Equivalency operator. Returns true if a == b (are the same)
* Оператор равенства
*
* @return boolean - true if both provided symbols are the same
* @return true — символы совпадают
*/
friend constexpr bool operator == ( const symbol& a, const symbol& b ) {
return a.value == b.value;
}
/**
* Inverted equivalency operator. Returns true if a != b (are different)
* Оператор неравенства
*
* @return boolean - true if both provided symbols are not the same
* @return true — символы различаются
*/
friend constexpr bool operator != ( const symbol& a, const symbol& b ) {
return a.value != b.value;
}
/**
* Less than operator. Returns true if a < b.
* @brief Less than operator
* @return boolean - true if symbol `a` is less than `b`
* Оператор «меньше»
* @brief Оператор «меньше»
* @return true — значение a меньше b
*/
friend constexpr bool operator < ( const symbol& a, const symbol& b ) {
return a.value < b.value;
@@ -341,13 +340,13 @@ namespace eosio {
};
/**
* Serialize a symbol into a stream
* Сериализация symbol в поток
*
* @brief Serialize a symbol
* @param ds - The stream to write
* @param sym - The value to serialize
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @brief Сериализация symbol
* @param ds — поток записи
* @param sym — значение для сериализации
* @tparam DataStream — тип буфера потока данных
* @return DataStream& — ссылка на поток
*/
template<typename DataStream>
inline DataStream& operator<<(DataStream& ds, const eosio::symbol sym) {
@@ -357,13 +356,13 @@ namespace eosio {
}
/**
* Deserialize a symbol from a stream
* Десериализация symbol из потока
*
* @brief Deserialize a symbol
* @param ds - The stream to read
* @param symbol - The destination for deserialized value
* @tparam DataStream - Type of datastream buffer
* @return DataStream& - Reference to the datastream
* @brief Десериализация symbol
* @param ds — поток чтения
* @param sym — приёмник значения
* @tparam DataStream — тип буфера потока данных
* @return DataStream& — ссылка на поток
*/
template<typename DataStream>
inline DataStream& operator>>(DataStream& ds, eosio::symbol& sym) {
@@ -374,7 +373,7 @@ namespace eosio {
}
/**
* Extended asset which stores the information of the owner of the symbol
* Расширенный символ: символ токена и контракт-эмитент в сети COOPOS
*
* @ingroup symbol
*/
@@ -383,36 +382,36 @@ namespace eosio {
public:
/**
* Default constructor, construct a new extended_symbol
* Конструктор по умолчанию
*/
constexpr extended_symbol() {}
/**
* Construct a new symbol_code object initialising symbol and contract with the passed in symbol and name
* Создаёт extended_symbol по символу и имени контракта
*
* @param sym - The symbol
* @param con - The name of the contract
* @param sym — символ токена
* @param con — имя контракта (эмитента)
*/
constexpr extended_symbol( symbol s, name con ) : sym(s), contract(con) {}
/**
* Returns the symbol in the extended_contract
* Символ без привязки к контракту
*
* @return symbol
*/
constexpr symbol get_symbol() const { return sym; }
/**
* Returns the name of the contract in the extended_symbol
* Имя контракта-эмитента
*
* @return name
*/
constexpr name get_contract() const { return contract; }
/**
* %Print the extended symbol
* Печать расширенного символа в лог контракта COOPOS
*
* @brief %Print the extended symbol
* @brief Вывод расширенного символа
*/
void print( bool show_precision = true )const {
sym.print( show_precision );
@@ -420,35 +419,35 @@ namespace eosio {
}
/**
* Equivalency operator. Returns true if a == b (are the same)
* Оператор равенства
*
* @return boolean - true if both provided extended_symbols are the same
* @return true — пары (символ, контракт) совпадают
*/
friend constexpr bool operator == ( const extended_symbol& a, const extended_symbol& b ) {
return std::tie( a.sym, a.contract ) == std::tie( b.sym, b.contract );
}
/**
* Inverted equivalency operator. Returns true if a != b (are different)
* Оператор неравенства
*
* @return boolean - true if both provided extended_symbols are not the same
* @return true — значения различаются
*/
friend constexpr bool operator != ( const extended_symbol& a, const extended_symbol& b ) {
return std::tie( a.sym, a.contract ) != std::tie( b.sym, b.contract );
}
/**
* Less than operator. Returns true if a < b.
* Оператор «меньше» (лексикографически по паре символ, контракт)
*
* @return boolean - true if extended_symbol `a` is less than `b`
* @return true — a меньше b
*/
friend constexpr bool operator < ( const extended_symbol& a, const extended_symbol& b ) {
return std::tie( a.sym, a.contract ) < std::tie( b.sym, b.contract );
}
private:
symbol sym; ///< the symbol
name contract; ///< the token contract hosting the symbol
symbol sym; ///< символ токена
name contract; ///< контракт, выпускающий токен
EOSLIB_SERIALIZE( extended_symbol, (sym)(contract) )
};
+6 -7
View File
@@ -9,9 +9,9 @@
namespace eosio {
/**
* @defgroup time
* @defgroup time Время
* @ingroup core
* @brief Classes for working with time.
* @brief Классы для работы со временем.
*/
@@ -99,7 +99,7 @@ namespace eosio {
};
/**
* A lower resolution time_point accurate only to seconds from 1970
* Момент времени с точностью до секунд с 1 января 1970 (UTC)
*
* @ingroup time
*/
@@ -163,9 +163,8 @@ namespace eosio {
};
/**
* This class is used in the block headers to represent the block time
* It is a parameterised class that takes an Epoch in milliseconds and
* an interval in milliseconds and computes the number of slots.
* Время блока в заголовках блоков сети COOPOS: номер слота с шагом block_interval_ms
* от эпохи block_timestamp_epoch (миллисекунды).
*
* @ingroup time
**/
@@ -223,7 +222,7 @@ namespace eosio {
bool operator !=( const block_timestamp& t )const { return slot != t.slot; }
uint32_t slot;
static constexpr int32_t block_interval_ms = 500;
static constexpr int64_t block_timestamp_epoch = 946684800000ll; // epoch is year 2000
static constexpr int64_t block_timestamp_epoch = 946684800000ll; // эпоха — 1 января 2000 UTC (мс)
/// @endcond
EOSLIB_SERIALIZE( block_timestamp, (slot) )
+175 -175
View File
@@ -1,38 +1,38 @@
/**
* @file
* @copyright defined in eos/LICENSE
* @copyright см. eos/LICENSE
*/
#pragma once
namespace eosio {
/**
* @defgroup varint Variable Length Integer Type
* @defgroup varint Целое переменной длины
* @ingroup core
* @ingroup types
* @brief Defines variable length integer type which provides more efficient serialization
* @brief Определяет тип целого переменной длины для более эффективной сериализации
*/
/**
* Variable Length Unsigned Integer. This provides more efficient serialization of 32-bit unsigned int.
* It serialuzes a 32-bit unsigned integer in as few bytes as possible
* `varuint32` is unsigned and uses [VLQ or Base-128 encoding](https://en.wikipedia.org/wiki/Variable-length_quantity)
* Целое без знака переменной длины. Обеспечивает более эффективную сериализацию 32-битного беззнакового int.
* Сериализует 32-битное беззнаковое целое минимально возможным числом байт.
* `varuint32` без знака и использует [VLQ или кодирование Base-128](https://en.wikipedia.org/wiki/Variable-length_quantity)
*
* @ingroup varint
*/
struct unsigned_int {
/**
* Construct a new unsigned int object
* Создаёт новый объект беззнакового целого
*
* @param v - Source
* @param v - Источник
*/
constexpr unsigned_int( uint32_t v = 0 ):value(v){}
/**
* Construct a new unsigned int object from a type that is convertible to uint32_t
* Создаёт новый объект беззнакового целого из типа, приводимого к uint32_t
*
* @tparam T - Type of the source
* @param v - Source
* @pre T must be convertible to uint32_t
* @tparam T - Тип источника
* @param v - Источник
* @pre T должен быть приводим к uint32_t
*/
template<typename T>
constexpr unsigned_int( T v ):value(v){}
@@ -41,10 +41,10 @@ namespace eosio {
//operator uint64_t()const { return value; }
/**
* Convert unsigned_int as T
* Приводит unsigned_int к типу T
*
* @tparam T - Target type of conversion
* @return T - Converted target
* @tparam T - Целевой тип преобразования
* @return T - Результат преобразования
*/
template<typename T>
constexpr operator T()const { return static_cast<T>(value); }
@@ -52,139 +52,139 @@ namespace eosio {
/// @cond OPERATORS
/**
* Assign 32-bit unsigned integer
* Присваивает 32-битное беззнаковое целое
*
* @param v - Soruce
* @return unsigned_int& - Reference to this object
* @param v - Источник
* @return unsigned_int& - Ссылка на этот объект
*/
constexpr unsigned_int& operator=( uint32_t v ) { value = v; return *this; }
/// @endcond
/**
* Contained value
* Содержащееся значение
*/
uint32_t value;
/// @cond OPERATORS
/**
* Check equality between a unsigned_int object and 32-bit unsigned integer
* Проверка равенства между unsigned_int и 32-битным беззнаковым целым
*
* @param i - unsigned_int object to compare
* @param v - 32-bit unsigned integer to compare
* @return true - if equal
* @return false - otherwise
* @param i - Объект unsigned_int для сравнения
* @param v - 32-битное беззнаковое целое для сравнения
* @return true - если равны
* @return false - иначе
*/
constexpr friend bool operator==( const unsigned_int& i, const uint32_t& v ) { return i.value == v; }
/**
* Check equality between 32-bit unsigned integer and a unsigned_int object
* Проверка равенства между 32-битным беззнаковым целым и unsigned_int
*
* @param i - 32-bit unsigned integer to compare
* @param v - unsigned_int object to compare
* @return true - if equal
* @return false - otherwise
* @param i - 32-битное беззнаковое целое для сравнения
* @param v - Объект unsigned_int для сравнения
* @return true - если равны
* @return false - иначе
*/
constexpr friend bool operator==( const uint32_t& i, const unsigned_int& v ) { return i == v.value; }
/**
* Check equality between two unsigned_int objects
* Проверка равенства двух объектов unsigned_int
*
* @param i - First unsigned_int object to compare
* @param v - Second unsigned_int object to compare
* @return true - if equal
* @return false - otherwise
* @param i - Первый unsigned_int для сравнения
* @param v - Второй unsigned_int для сравнения
* @return true - если равны
* @return false - иначе
*/
constexpr friend bool operator==( const unsigned_int& i, const unsigned_int& v ) { return i.value == v.value; }
/**
* Check inequality between a unsigned_int object and 32-bit unsigned integer
* Проверка неравенства между unsigned_int и 32-битным беззнаковым целым
*
* @param i - unsigned_int object to compare
* @param v - 32-bit unsigned integer to compare
* @return true - if inequal
* @return false - otherwise
* @param i - Объект unsigned_int для сравнения
* @param v - 32-битное беззнаковое целое для сравнения
* @return true - если не равны
* @return false - иначе
*/
constexpr friend bool operator!=( const unsigned_int& i, const uint32_t& v ) { return i.value != v; }
/**
* Check inequality between 32-bit unsigned integer and a unsigned_int object
* Проверка неравенства между 32-битным беззнаковым целым и unsigned_int
*
* @param i - 32-bit unsigned integer to compare
* @param v - unsigned_int object to compare
* @return true - if unequal
* @return false - otherwise
* @param i - 32-битное беззнаковое целое для сравнения
* @param v - Объект unsigned_int для сравнения
* @return true - если не равны
* @return false - иначе
*/
constexpr friend bool operator!=( const uint32_t& i, const unsigned_int& v ) { return i != v.value; }
/**
* Check inequality between two unsigned_int objects
* Проверка неравенства двух объектов unsigned_int
*
* @param i - First unsigned_int object to compare
* @param v - Second unsigned_int object to compare
* @return true - if inequal
* @return false - otherwise
* @param i - Первый unsigned_int для сравнения
* @param v - Второй unsigned_int для сравнения
* @return true - если не равны
* @return false - иначе
*/
constexpr friend bool operator!=( const unsigned_int& i, const unsigned_int& v ) { return i.value != v.value; }
/**
* Check if the given unsigned_int object is less than the given 32-bit unsigned integer
* Проверяет, меньше ли unsigned_int заданного 32-битного беззнакового целого
*
* @param i - unsigned_int object to compare
* @param v - 32-bit unsigned integer to compare
* @return true - if i less than v
* @return false - otherwise
* @param i - Объект unsigned_int для сравнения
* @param v - 32-битное беззнаковое целое для сравнения
* @return true - если i меньше v
* @return false - иначе
*/
constexpr friend bool operator<( const unsigned_int& i, const uint32_t& v ) { return i.value < v; }
/**
* Check if the given 32-bit unsigned integer is less than the given unsigned_int object
* Проверяет, меньше ли 32-битное беззнаковое целое заданного unsigned_int
*
* @param i - 32-bit unsigned integer to compare
* @param v - unsigned_int object to compare
* @return true - if i less than v
* @return false - otherwise
* @param i - 32-битное беззнаковое целое для сравнения
* @param v - Объект unsigned_int для сравнения
* @return true - если i меньше v
* @return false - иначе
*/
constexpr friend bool operator<( const uint32_t& i, const unsigned_int& v ) { return i < v.value; }
/**
* Check if the first given unsigned_int is less than the second given unsigned_int object
* Проверяет, меньше ли первый unsigned_int второго
*
* @param i - First unsigned_int object to compare
* @param v - Second unsigned_int object to compare
* @return true - if i less than v
* @return false - otherwise
* @param i - Первый unsigned_int для сравнения
* @param v - Второй unsigned_int для сравнения
* @return true - если i меньше v
* @return false - иначе
*/
constexpr friend bool operator<( const unsigned_int& i, const unsigned_int& v ) { return i.value < v.value; }
/**
* Check if the given unsigned_int object is greater or equal to the given 32-bit unsigned integer
* Проверяет, больше или равен ли unsigned_int заданному 32-битному беззнаковому целому
*
* @param i - unsigned_int object to compare
* @param v - 32-bit unsigned integer to compare
* @return true - if i is greater or equal to v
* @return false - otherwise
* @param i - Объект unsigned_int для сравнения
* @param v - 32-битное беззнаковое целое для сравнения
* @return true - если i больше или равен v
* @return false - иначе
*/
constexpr friend bool operator>=( const unsigned_int& i, const uint32_t& v ) { return i.value >= v; }
/**
* Check if the given 32-bit unsigned integer is greater or equal to the given unsigned_int object
* Проверяет, больше или равно ли 32-битное беззнаковое целое заданному unsigned_int
*
* @param i - 32-bit unsigned integer to compare
* @param v - unsigned_int object to compare
* @return true - if i is greater or equal to v
* @return false - otherwise
* @param i - 32-битное беззнаковое целое для сравнения
* @param v - Объект unsigned_int для сравнения
* @return true - если i больше или равен v
* @return false - иначе
*/
constexpr friend bool operator>=( const uint32_t& i, const unsigned_int& v ) { return i >= v.value; }
/**
* Check if the first given unsigned_int is greater or equal to the second given unsigned_int object
* Проверяет, больше или равен ли первый unsigned_int второму
*
* @param i - First unsigned_int object to compare
* @param v - Second unsigned_int object to compare
* @return true - if i is greater or equal to v
* @return false - otherwise
* @param i - Первый unsigned_int для сравнения
* @param v - Второй unsigned_int для сравнения
* @return true - если i больше или равен v
* @return false - иначе
*/
constexpr friend bool operator>=( const unsigned_int& i, const unsigned_int& v ) { return i.value >= v.value; }
@@ -194,12 +194,12 @@ namespace eosio {
/// @cond IMPLEMENTATIONS
/**
* Serialize an unsigned_int object with as few bytes as possible
* Сериализует unsigned_int минимально возможным числом байт
*
* @param ds - The stream to write
* @param v - The value to serialize
* @tparam DataStream - Type of datastream
* @return DataStream& - Reference to the datastream
* @param ds - Поток для записи
* @param v - Значение для сериализации
* @tparam DataStream - Тип потока данных
* @return DataStream& - Ссылка на поток данных
*/
template<typename DataStream>
friend DataStream& operator << ( DataStream& ds, const unsigned_int& v ){
@@ -214,12 +214,12 @@ namespace eosio {
}
/**
* Deserialize an unsigned_int object
* Десериализует unsigned_int
*
* @param ds - The stream to read
* @param vi - The destination for deserialized value
* @tparam DataStream - Type of datastream
* @return DataStream& - Reference to the datastream
* @param ds - Поток для чтения
* @param vi - Назначение для десериализованного значения
* @tparam DataStream - Тип потока данных
* @return DataStream& - Ссылка на поток данных
*/
template<typename DataStream>
friend DataStream& operator >> ( DataStream& ds, unsigned_int& vi ){
@@ -237,182 +237,182 @@ namespace eosio {
};
/**
* Variable Length Signed Integer. This provides more efficient serialization of 32-bit signed int.
* It serializes a 32-bit signed integer in as few bytes as possible.
* Целое со знаком переменной длины. Обеспечивает более эффективную сериализацию 32-битного знакового int.
* Сериализует 32-битное знаковое целое минимально возможным числом байт.
*
* @ingroup varint
* @note `varint32' is signed and uses [Zig-Zag encoding](https://developers.google.com/protocol-buffers/docs/encoding#signed-integers)
* @note `varint32` со знаком и использует [кодирование Zig-Zag](https://developers.google.com/protocol-buffers/docs/encoding#signed-integers)
*/
struct signed_int {
/**
* Construct a new signed int object
* Создаёт новый объект знакового целого
*
* @param v - Source
* @param v - Источник
*/
constexpr signed_int( int32_t v = 0 ):value(v){}
/// @cond OPERATORS
/**
* Convert signed_int to primitive 32-bit signed integer
* Приводит signed_int к примитивному 32-битному знаковому целому
*
* @return int32_t - The converted result
* @return int32_t - Результат преобразования
*/
constexpr operator int32_t()const { return value; }
/**
* Assign an object that is convertible to int32_t
* Присваивает объект, приводимый к int32_t
*
* @tparam T - Type of the assignment object
* @param v - Source
* @return unsigned_int& - Reference to this object
* @tparam T - Тип присваиваемого объекта
* @param v - Источник
* @return signed_int& - Ссылка на этот объект
*/
template<typename T>
constexpr signed_int& operator=( const T& v ) { value = v; return *this; }
/**
* Increment operator
* Оператор инкремента (постфиксный)
*
* @return signed_int - New signed_int with value incremented from the current object's value
* @return signed_int - Новый signed_int со значением, увеличенным относительно текущего
*/
constexpr signed_int operator++(int) { return value++; }
/**
* Increment operator
* Оператор инкремента (префиксный)
*
* @return signed_int - Reference to current object
* @return signed_int& - Ссылка на текущий объект
*/
constexpr signed_int& operator++(){ ++value; return *this; }
/// @endcond
/**
* Contained value
* Содержащееся значение
*/
int32_t value;
/// @cond OPERATORS
/**
* Check equality between a signed_int object and 32-bit integer
* Проверка равенства между signed_int и 32-битным целым
*
* @param i - signed_int object to compare
* @param v - 32-bit integer to compare
* @return true - if equal
* @return false - otherwise
* @param i - Объект signed_int для сравнения
* @param v - 32-битное целое для сравнения
* @return true - если равны
* @return false - иначе
*/
constexpr friend bool operator==( const signed_int& i, const int32_t& v ) { return i.value == v; }
/**
* Check equality between 32-bit integer and a signed_int object
* Проверка равенства между 32-битным целым и signed_int
*
* @param i - 32-bit integer to compare
* @param v - signed_int object to compare
* @return true - if equal
* @return false - otherwise
* @param i - 32-битное целое для сравнения
* @param v - Объект signed_int для сравнения
* @return true - если равны
* @return false - иначе
*/
constexpr friend bool operator==( const int32_t& i, const signed_int& v ) { return i == v.value; }
/**
* Check equality between two signed_int objects
* Проверка равенства двух объектов signed_int
*
* @param i - First signed_int object to compare
* @param v - Second signed_int object to compare
* @return true - if equal
* @return false - otherwise
* @param i - Первый signed_int для сравнения
* @param v - Второй signed_int для сравнения
* @return true - если равны
* @return false - иначе
*/
constexpr friend bool operator==( const signed_int& i, const signed_int& v ) { return i.value == v.value; }
/**
* Check inequality between a signed_int object and 32-bit integer
* Проверка неравенства между signed_int и 32-битным целым
*
* @param i - signed_int object to compare
* @param v - 32-bit integer to compare
* @return true - if inequal
* @return false - otherwise
* @param i - Объект signed_int для сравнения
* @param v - 32-битное целое для сравнения
* @return true - если не равны
* @return false - иначе
*/
constexpr friend bool operator!=( const signed_int& i, const int32_t& v ) { return i.value != v; }
/**
* Check inequality between 32-bit integer and a signed_int object
* Проверка неравенства между 32-битным целым и signed_int
*
* @param i - 32-bit integer to compare
* @param v - signed_int object to compare
* @return true - if unequal
* @return false - otherwise
* @param i - 32-битное целое для сравнения
* @param v - Объект signed_int для сравнения
* @return true - если не равны
* @return false - иначе
*/
constexpr friend bool operator!=( const int32_t& i, const signed_int& v ) { return i != v.value; }
/**
* Check inequality between two signed_int objects
* Проверка неравенства двух объектов signed_int
*
* @param i - First signed_int object to compare
* @param v - Second signed_int object to compare
* @return true - if inequal
* @return false - otherwise
* @param i - Первый signed_int для сравнения
* @param v - Второй signed_int для сравнения
* @return true - если не равны
* @return false - иначе
*/
constexpr friend bool operator!=( const signed_int& i, const signed_int& v ) { return i.value != v.value; }
/**
* Check if the given signed_int object is less than the given 32-bit integer
* Проверяет, меньше ли signed_int заданного 32-битного целого
*
* @param i - signed_int object to compare
* @param v - 32-bit integer to compare
* @return true - if i less than v
* @return false - otherwise
* @param i - Объект signed_int для сравнения
* @param v - 32-битное целое для сравнения
* @return true - если i меньше v
* @return false - иначе
*/
constexpr friend bool operator<( const signed_int& i, const int32_t& v ) { return i.value < v; }
/**
* Check if the given 32-bit integer is less than the given signed_int object
* Проверяет, меньше ли 32-битное целое заданного signed_int
*
* @param i - 32-bit integer to compare
* @param v - signed_int object to compare
* @return true - if i less than v
* @return false - otherwise
* @param i - 32-битное целое для сравнения
* @param v - Объект signed_int для сравнения
* @return true - если i меньше v
* @return false - иначе
*/
constexpr friend bool operator<( const int32_t& i, const signed_int& v ) { return i < v.value; }
/**
* Check if the first given signed_int is less than the second given signed_int object
* Проверяет, меньше ли первый signed_int второго
*
* @param i - First signed_int object to compare
* @param v - Second signed_int object to compare
* @return true - if i less than v
* @return false - otherwise
* @param i - Первый signed_int для сравнения
* @param v - Второй signed_int для сравнения
* @return true - если i меньше v
* @return false - иначе
*/
constexpr friend bool operator<( const signed_int& i, const signed_int& v ) { return i.value < v.value; }
/**
* Check if the given signed_int object is greater or equal to the given 32-bit integer
* Проверяет, больше или равен ли signed_int заданному 32-битному целому
*
* @param i - signed_int object to compare
* @param v - 32-bit integer to compare
* @return true - if i is greater or equal to v
* @return false - otherwise
* @param i - Объект signed_int для сравнения
* @param v - 32-битное целое для сравнения
* @return true - если i больше или равен v
* @return false - иначе
*/
constexpr friend bool operator>=( const signed_int& i, const int32_t& v ) { return i.value >= v; }
/**
* Check if the given 32-bit integer is greater or equal to the given signed_int object
* Проверяет, больше или равно ли 32-битное целое заданному signed_int
*
* @param i - 32-bit integer to compare
* @param v - signed_int object to compare
* @return true - if i is greater or equal to v
* @return false - otherwise
* @param i - 32-битное целое для сравнения
* @param v - Объект signed_int для сравнения
* @return true - если i больше или равен v
* @return false - иначе
*/
constexpr friend bool operator>=( const int32_t& i, const signed_int& v ) { return i >= v.value; }
/**
* Check if the first given signed_int is greater or equal to the second given signed_int object
* Проверяет, больше или равен ли первый signed_int второму
*
* @param i - First signed_int object to compare
* @param v - Second signed_int object to compare
* @return true - if i is greater or equal to v
* @return false - otherwise
* @param i - Первый signed_int для сравнения
* @param v - Второй signed_int для сравнения
* @return true - если i больше или равен v
* @return false - иначе
*/
constexpr friend bool operator>=( const signed_int& i, const signed_int& v ) { return i.value >= v.value; }
@@ -421,12 +421,12 @@ namespace eosio {
/// @cond IMPLEMENTATIONS
/**
* Serialize an signed_int object with as few bytes as possible
* Сериализует signed_int минимально возможным числом байт
*
* @param ds - The stream to write
* @param v - The value to serialize
* @tparam DataStream - Type of datastream
* @return DataStream& - Reference to the datastream
* @param ds - Поток для записи
* @param v - Значение для сериализации
* @tparam DataStream - Тип потока данных
* @return DataStream& - Ссылка на поток данных
*/
template<typename DataStream>
friend DataStream& operator << ( DataStream& ds, const signed_int& v ){
@@ -441,12 +441,12 @@ namespace eosio {
}
/**
* Deserialize an signed_int object
* Десериализует signed_int
*
* @param ds - The stream to read
* @param vi - The destination for deserialized value
* @tparam DataStream - Type of datastream
* @return DataStream& - Reference to the datastream
* @param ds - Поток для чтения
* @param vi - Назначение для десериализованного значения
* @tparam DataStream - Тип потока данных
* @return DataStream& - Ссылка на поток данных
*/
template<typename DataStream>
friend DataStream& operator >> ( DataStream& ds, signed_int& vi ){
+17
View File
@@ -42,6 +42,11 @@ extern "C" {
__attribute__((eosio_wasm_import))
void assert_recover_key( const capi_checksum256* digest, const char* sig,
size_t siglen, const char* pub, size_t publen );
__attribute__((eosio_wasm_import))
void assert_recover_key_account( const capi_checksum256* digest, const char* sig,
size_t siglen, const char* pub, size_t publen,
uint64_t account, uint64_t permission );
}
namespace eosio {
@@ -131,4 +136,16 @@ namespace eosio {
sig_data.data(), sig_data.size(),
pubkey_data.data(), pubkey_data.size() );
}
void assert_recover_key_account( const eosio::checksum256& digest, const eosio::signature& sig, const eosio::public_key& pubkey, eosio::name account, eosio::name permission ) {
auto digest_data = digest.extract_as_byte_array();
auto sig_data = eosio::pack(sig);
auto pubkey_data = eosio::pack(pubkey);
::assert_recover_key_account( reinterpret_cast<const capi_checksum256*>(digest_data.data()),
sig_data.data(), sig_data.size(),
pubkey_data.data(), pubkey_data.size(),
account.value, permission.value );
}
}
+11 -11
View File
@@ -96,18 +96,18 @@ namespace eosio {
template const std::array<uint64_t, 20> powers_of_base<10, uint64_t>;
/**
* Writes a number as a string to the provided char buffer
* Записывает число в виде строки в заданный символьный буфер.
*
* @brief Writes number x 10^(-num_decimal_places) (optionally negative) as a string to the provided char buffer
* @pre The range [begin, end) must be a valid range of memory to write to.
* @param begin - The start of the char buffer
* @param end - Just past the end of the char buffer
* @param dry_run - If true, do not actually write anything into the range.
* @param number - The number to print before shifting the decimal point to the left by num_decimal_places.
* @param num_decimal_places - The number of decimal places to shift the decimal point.
* @param negative - Whether to print a minus sign in the front.
* @return char* - Just past the end of the last character that would be written assuming dry_run == false and end was large enough to provide sufficient space. (Meaning only applies if returned pointer >= begin.)
* @post If the output string fits within the range [begin, end), the range [begin, returned pointer) contains the string representation of the number. Nothing is written if dry_run == true or returned pointer > end (insufficient space) or if returned pointer < begin (overflow in calculating desired end).
* @brief Записывает число x·10^(num_decimal_places) (при необходимости со знаком минус) в виде строки в заданный символьный буфер.
* @pre Диапазон [begin, end) должен быть допустимой областью памяти для записи.
* @param begin — начало символьного буфера.
* @param end — позиция сразу за концом символьного буфера.
* @param dry_run — если true, ничего не записывать в диапазон.
* @param number — число для вывода до сдвига десятичной точки влево на num_decimal_places позиций.
* @param num_decimal_places — на сколько позиций сдвинуть десятичную точку влево.
* @param negative — выводить ли знак минус в начале.
* @return char* — указатель сразу за последним символом, который был бы записан при dry_run == false и достаточном end (смысл только если возвращённый указатель >= begin).
* @post Если результирующая строка помещается в [begin, end), диапазон [begin, возвращённый указатель) содержит строковое представление числа. Ничего не записывается при dry_run == true, если возвращённый указатель > end (недостаточно места) или < begin (переполнение при расчёте нужного конца).
*/
char* write_decimal( char* begin, char* end, bool dry_run, uint64_t number, uint8_t num_decimal_places, bool negative ) {
const auto& powers_of_ten = powers_of_base<10, uint64_t>;
+6
View File
@@ -16,6 +16,9 @@
// Boilerplate
using namespace eosio::native;
extern "C" {
void get_account_ram_usage( capi_name account, int64_t* used_ram_bytes ) {
return intrinsics::get().call<intrinsics::get_account_ram_usage>(account, used_ram_bytes);
}
void get_resource_limits( capi_name account, int64_t* ram_bytes, int64_t* net_weight, int64_t* cpu_weight ) {
return intrinsics::get().call<intrinsics::get_resource_limits>(account, ram_bytes, net_weight, cpu_weight);
}
@@ -235,6 +238,9 @@ extern "C" {
int recover_key( const capi_checksum256* digest, const char* sig, size_t siglen, char* pub, size_t publen ) {
return intrinsics::get().call<intrinsics::recover_key>(digest, sig, siglen, pub, publen);
}
void assert_recover_key_account( const capi_checksum256* digest, const char* sig, size_t siglen, const char* pub, size_t publen, uint64_t account, uint64_t permission ) {
return intrinsics::get().call<intrinsics::assert_recover_key_account>(digest, sig, siglen, pub, publen, account, permission);
}
void assert_sha256( const char* data, uint32_t length, const capi_checksum256* hash ) {
return intrinsics::get().call<intrinsics::assert_sha256>(data, length, hash);
}
@@ -43,6 +43,7 @@ namespace eosio { namespace native {
}
#define INTRINSICS(intrinsic_macro) \
intrinsic_macro(get_account_ram_usage) \
intrinsic_macro(get_resource_limits) \
intrinsic_macro(set_resource_limits) \
intrinsic_macro(set_proposed_producers) \
@@ -116,6 +117,7 @@ intrinsic_macro(db_upperbound_i64) \
intrinsic_macro(db_end_i64) \
intrinsic_macro(assert_recover_key) \
intrinsic_macro(recover_key) \
intrinsic_macro(assert_recover_key_account) \
intrinsic_macro(assert_sha256) \
intrinsic_macro(assert_sha1) \
intrinsic_macro(assert_sha512) \