Skip to content

Commit 7c83bfb

Browse files
committed
Merge remote-tracking branch 'origin/controller_dev_1' into mytonctrl2_dev_1
# Conflicts: # README.md # mytoncore/mytoncore.py # mytonctrl.py # mytonctrl/resources/translate.json # mytoninstaller.py
2 parents 229adf1 + 41d522d commit 7c83bfb

File tree

7 files changed

+1850
-6
lines changed

7 files changed

+1850
-6
lines changed

docs/en/controllers.md

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
# Controllers
2+
3+
## Launching a Validator in Controller Mode
4+
5+
1. Prepare the hardware for the validator - 32 virtual cores, 64GB of memory, 1TB SSD, fixed IP address, and 1Gb/s internet speed.
6+
7+
To maintain network stability, it is recommended to place validators in different locations around the world, rather than concentrating them in a single data center. You can use [this site](https://status.toncenter.com/) to determine the load on various locations. According to the map, there is a high load on data centers in Europe, especially in Finland, Germany, and Paris. Therefore, using providers such as Hetzner and OVH is not recommended.
8+
9+
> Ensure your hardware meets or exceeds the specified configuration. Running the validator on inappropriate hardware can harm the network and result in penalties.
10+
> Since May 2021, Hetzner has prohibited mining on its servers. This rule currently applies to both PoW and PoS algorithms. Even installing a regular node will be considered a breach of contract.
11+
12+
2. Install and synchronize **mytonctrl** according to the description in [this instruction](https://github.com/ton-blockchain/mytonctrl/blob/master/docs/en/manual-ubuntu.md) — follow **only** paragraphs 1, 2, and 3.
13+
14+
You can also refer to this [Video Tutorial](https://docs.ton.org/participate/run-nodes/full-node#installation) for additional help.
15+
16+
3. Transfer 1 TON to the validator wallet address, which is displayed in the `wl` list.
17+
18+
4. Use the `aw` command to activate the validator's wallet.
19+
20+
5. Transfer enough TON to the validator wallet address.
21+
22+
6. Enable the ton-http-api service:
23+
```
24+
mytonctrl -> installer -> enable THA
25+
```
26+
Exit installer mode with `Ctrl+D`
27+
28+
7. Set the liquid pool address, which will lend TON for validation:
29+
```
30+
set liquid_pool_addr <liquid-pool-address>
31+
```
32+
33+
8. Set the lending parameters that acceptable to you:
34+
```
35+
set min_loan 41000
36+
set max_loan 43000
37+
set max_interest_percent 1.5
38+
```
39+
40+
where
41+
* `41000` is the minimum loan amount we are willing to receive from the liquid pool,
42+
* `43000` is the maximum loan amount we are willing to receive from the liquid pool,
43+
* `1.5` 1.5 is the maximum interest rate value for the liquid pool per validation cycle, which we have agreed upon.
44+
45+
9. Display the annual percentage of profit from the liquid pool:
46+
```
47+
calculate_annual_controller_percentage
48+
```
49+
50+
10. Create two controllers with a single command:
51+
52+
```
53+
new_controllers
54+
```
55+
56+
11. Enter `controllers_list` to display the controller addresses:
57+
58+
```
59+
controllers_list
60+
Address Status Balance
61+
kf89KYOeRPRRDyjt_3bPsz92cKSghRqw64efNr8mT1eeHDaS active 0.704345
62+
kf_lT8QNykLh5PN5ictNX22maiyIf9iK787fXg6nJ_zB-jbN active 0.720866
63+
```
64+
65+
12. Make a validator deposit in each controller:
66+
67+
68+
```
69+
deposit_to_controller kf89KYOeRPRRDyjt_3bPsz92cKSghRqw64efNr8mT1eeHDaS 10000
70+
deposit_to_controller kf_lT8QNykLh5PN5ictNX22maiyIf9iK787fXg6nJ_zB-jbN 10000
71+
```
72+
73+
74+
where `10000` TON is the deposit amount.
75+
76+
13. Get approval for the controllers. Each pool may have its own approval issuance policy, check with the operator.
77+
78+
14. Set controller mode:
79+
80+
```bash
81+
set useController true
82+
set stake null
83+
```
84+
85+
> (!) If you were previously using nominator pools, do not forget to disable them using the `set usePool false` command.
86+
87+
88+
## Switching a Regular Validator to Controller Operating Mode
89+
90+
1. Enter `set stake 0` to stop participating in elections.
91+
92+
2. Wait until both of your deposits have been returned from the Elector.
93+
94+
3. Follow the instructions under "Launching a Validator in Controller Mode", beginning with **Step 6**.

docs/ru/controllers.md

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# Контроллеры
2+
3+
## Запуск валидатора в режиме работы контроллеров
4+
5+
1. Подготовьте аппаратное обеспечение для валидатора - 32 виртуальных ядер, 64GB памяти, 1TB SSD, фиксированный IP-адрес, скорость интернета 1Gb/s.
6+
7+
Для поддержания стабильности сети рекомендуется разместить валидаторы в различных местах по всему миру, а не концентрировать их в одном дата-центре. Вы можете использовать [этот сайт](https://status.toncenter.com/) для определения нагрузки на различные места. Согласно карте, высокая нагрузка на дата-центры в Европе, особенно в Финляндии, Германии и Париже. Поэтому использование провайдеров, таких как Hetzner и OVH, не рекомендуется.
8+
9+
> Ваше оборудование должно соответствовать указанной конфигурации или быть выше. Запуск валидатора на слабом оборудовании негативно влияет на сеть и может привести к штрафам.
10+
11+
> С мая 2021 года Hetzner запретил майнинг на своих серверах, в настоящее время под это правило попадают алгоритмы PoW и PoS. Установка даже обычного узла будет считаться нарушением условий договора.
12+
13+
2. Установите и синхронизируйте **mytonctrl** в соответствии с описанием в [этой инструкции](https://github.com/ton-blockchain/mytonctrl/blob/master/docs/ru/manual-ubuntu.md) — следуйте **только** пунктам 1, 2 и 3.
14+
15+
Вы также можете обратиться к этой [Видеоинструкции](https://docs.ton.org/participate/run-nodes/full-node#installation) для дополнительной помощи.
16+
17+
3. Переведите 1 TON на адрес кошелька валидатора, который отображается в списке `wl`.
18+
19+
4. Используйте команду `aw` для активации кошелька валидатора.
20+
21+
5. Переведите достаточно TON на адрес кошелька валидатора.
22+
23+
6. Включите ton-http-api службу:
24+
```
25+
mytonctrl -> installer -> enable THA
26+
```
27+
Выйдите из режима установщика сочетанием клавиш `Ctrl+D`
28+
29+
7. Задайте адрес ликвидного пула, который будет одалживать TON для валидации:
30+
```
31+
set liquid_pool_addr <liquid-pool-address>
32+
```
33+
34+
8. Задайте параметры кредитования, которые вам подходят:
35+
```
36+
set min_loan 41000
37+
set max_loan 43000
38+
set max_interest_percent 1.5
39+
```
40+
41+
где
42+
* `41000` - это минимальная сумма кредита который мы готовы получить у ликвидного пула,
43+
* `43000` - это максимальная сумма кредита который мы готовы получить у ликвидного пула,
44+
* `1.5` - это максимальная процентная ставка ликвидного пула за один цикл валидации на которую мы согласны.
45+
46+
9. Отобразите годовой процент прибыли от ликвидного пула:
47+
```
48+
calculate_annual_controller_percentage
49+
```
50+
51+
10. Создайте два контроллера одной командой:
52+
53+
```
54+
new_controllers
55+
```
56+
57+
11. Введите `controllers_list` чтобы отобразить адреса контроллеров:
58+
59+
```
60+
controllers_list
61+
Address Status Balance
62+
kf89KYOeRPRRDyjt_3bPsz92cKSghRqw64efNr8mT1eeHDaS active 0.704345
63+
kf_lT8QNykLh5PN5ictNX22maiyIf9iK787fXg6nJ_zB-jbN active 0.720866
64+
```
65+
66+
12. Совершите депозит валидатора в каждый контроллер:
67+
68+
```
69+
deposit_to_controller kf89KYOeRPRRDyjt_3bPsz92cKSghRqw64efNr8mT1eeHDaS 10000
70+
deposit_to_controller kf_lT8QNykLh5PN5ictNX22maiyIf9iK787fXg6nJ_zB-jbN 10000
71+
```
72+
73+
где `10000` TON - это сумма депозита.
74+
75+
13. Получите аппрувал контроллеров. У каждого пула может быть своя политика выдачи аппруволов, уточняйте у оператора.
76+
77+
14. Активируйте режим работы контроллеров:
78+
79+
```bash
80+
set useController true
81+
set stake null
82+
```
83+
84+
> (!) Если до этого вы использовали номинатор-пулы, не забудьте отключить их использование командой `set usePool false`.
85+
86+
87+
## Переключение обычного валидатора в режим работы контроллеров
88+
89+
1. Введите `set stake 0`, чтобы отключить участие в выборах.
90+
91+
2. Дождитесь, когда оба ваших депозита вернутся от электора.
92+
93+
3. Следуйте инструкциям "Запуск валидатора в режиме работы контроллеров", начиная с **6-го шага**.

functions/session_stats.py

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf_8 -*-
3+
4+
import os
5+
import sys
6+
import time
7+
import json
8+
sys.path.append("/usr/src/mytonctrl/")
9+
from mypylib.mypylib import Dict
10+
11+
def read_session_stats(need_time_period):
12+
#print(f"read_session_stats: {need_time_period}")
13+
file_path = "/var/ton-work/log.session-stats"
14+
average_block_time = calculate_average_block_time(file_path)
15+
need_blocks = int(need_time_period/average_block_time)
16+
17+
lines = read_last_lines(file_path, need_lines=need_blocks)
18+
#lines = read_all_lines(file_path)
19+
data = lines2data(lines)
20+
21+
result = Dict()
22+
result.my_blocks = 0
23+
result.my_need_blocks = 0
24+
result.all_master_blocks = 0
25+
result.all_blocks = len(data)
26+
for buff in data:
27+
if buff.id.workchain == -1:
28+
result.all_master_blocks += 1
29+
first_producer = buff.rounds[0].producers[0]
30+
if buff.self != first_producer.id:
31+
continue
32+
result.my_need_blocks += 1
33+
if buff.self == buff.creator:
34+
result.my_blocks += 1
35+
#end for
36+
return result
37+
#end define
38+
39+
def calculate_average_block_time(file_path):
40+
blocks = 100
41+
lines = read_last_lines(file_path, need_lines=blocks)
42+
data = lines2data(lines)
43+
first_block, last_block = get_first_last_block(data)
44+
45+
diff = int(last_block.timestamp) - int(first_block.timestamp)
46+
average_block_time = round(diff/blocks, 2)
47+
#print("average_block_time:", average_block_time)
48+
return average_block_time
49+
#end define
50+
51+
def get_first_last_block(data, last_index=-1):
52+
first_block = data[0]
53+
last_block = data[last_index]
54+
if first_block.id.workchain == last_block.id.workchain:
55+
blocks = int(last_block.id.seqno) - int(first_block.id.seqno)
56+
else:
57+
first_block, last_block = get_first_last_block(data, last_index=last_index-1)
58+
return first_block, last_block
59+
#end define
60+
61+
def lines2data(lines):
62+
#start = time.time()
63+
data = list()
64+
for line in lines:
65+
try:
66+
buff = json.loads(line)
67+
data.append(Dict(buff))
68+
except json.decoder.JSONDecodeError:
69+
pass
70+
#end for
71+
72+
#end = time.time()
73+
#diff = round(end - start, 2)
74+
#print(f"lines2data completed in {diff} seconds")
75+
return data
76+
#end define
77+
78+
def read_all_lines(file_path):
79+
#start = time.time()
80+
with open(file_path, 'rt') as file:
81+
text = file.read()
82+
#end with
83+
lines = text.split('\n')
84+
85+
#end = time.time()
86+
#diff = round(end - start, 2)
87+
#print(f"read_all_lines completed in {diff} seconds")
88+
return lines
89+
#end define
90+
91+
def read_last_lines(file_path, need_lines):
92+
lines = list()
93+
max_lines = 30000
94+
if need_lines < 1:
95+
return lines
96+
elif need_lines > max_lines:
97+
need_lines = max_lines
98+
#print(f"read_last_lines: {need_lines}")
99+
#start = time.time()
100+
with open(file_path, 'rb') as file:
101+
find_last_lines(file, need_lines)
102+
for i in range(need_lines):
103+
line = file.readline().decode()
104+
lines.append(line)
105+
#end with
106+
107+
108+
#end = time.time()
109+
#diff = round(end - start, 2)
110+
#print(f"read_last_lines {len(lines)} completed in {diff} seconds")
111+
return lines
112+
#end define
113+
114+
def find_last_lines(file, need_lines):
115+
# catch OSError in case of a one line file
116+
try:
117+
find_lines = 0
118+
#file.seek(-2, os.SEEK_END)
119+
#while find_lines != need_lines:
120+
# if file.read(1) == b'\n':
121+
# find_lines += 1
122+
# file.seek(-2, os.SEEK_CUR)
123+
124+
file.seek(-100, os.SEEK_END)
125+
while find_lines != need_lines:
126+
if b'\n' in file.read(100):
127+
find_lines += 1
128+
file.seek(-200, os.SEEK_CUR)
129+
except OSError:
130+
file.seek(0)
131+
#end define
132+
133+
134+
135+
136+

0 commit comments

Comments
 (0)