Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
55c9441
add controller
igroman787 May 29, 2023
3b01f11
Update mytoncore.py
igroman787 Jun 14, 2023
998f509
add controller checks
igroman787 Jun 20, 2023
fd1bfd2
Update controllers.md
igroman787 Jun 21, 2023
f2b4203
Update controllers.md
igroman787 Jun 21, 2023
e2f0972
controllers_translate_added
reveloper Jun 21, 2023
f70d86a
Merge pull request #132 from reveloper/controller
igroman787 Jun 21, 2023
c292552
add `calculate_annual_controller_percentage`
igroman787 Jul 1, 2023
6591e36
bugfix
igroman787 Jul 1, 2023
a095227
bugfix
igroman787 Jul 1, 2023
fde7460
bugfix
igroman787 Jul 2, 2023
121ff31
add `ton-http-api` service
igroman787 Jul 5, 2023
518da35
update `controllers.md`
igroman787 Jul 5, 2023
8abb5fb
bugfix
igroman787 Jul 9, 2023
906cdf7
withdraw_from_controller bugfix
igroman787 Jul 9, 2023
a8abde0
add error display when requested to ton-http-api
igroman787 Jul 9, 2023
aa91b52
ton_http_api installet bugfix
igroman787 Jul 10, 2023
446a6a6
add SignElectionRequestWithController log
igroman787 Jul 12, 2023
318b637
update controller balance and stake difference
igroman787 Jul 12, 2023
c484dca
add `add_controller` and `stop_controller` commands
igroman787 Jul 15, 2023
a8cd483
add `check_liquid_pool` command
igroman787 Jul 15, 2023
987b09e
Add seamless transition to new controllers
igroman787 Jul 18, 2023
da61de8
Update mytoncore.py
igroman787 Jul 18, 2023
3dfd068
controllerData bugfix
igroman787 Jul 18, 2023
e421d48
add error text for controller
igroman787 Jul 19, 2023
47055a1
bugfix
igroman787 Jul 19, 2023
2c5217b
rename controllers vars
igroman787 Jul 19, 2023
42976f5
fix a defaulted loan
igroman787 Jul 27, 2023
ac484ec
bugfix
igroman787 Aug 2, 2023
b3be300
WithdrawFromControllerProcess bugfix
igroman787 Aug 21, 2023
a82ffd8
update `mypylib`
igroman787 Sep 14, 2023
25df7de
Create session_stats.py
igroman787 Sep 14, 2023
f2ece10
Update mytoncore.py
igroman787 Sep 14, 2023
351c15d
Update mytonctrl.py
igroman787 Sep 14, 2023
e995600
Update mytonctrl.py
igroman787 Sep 14, 2023
5866bb1
debug CalculateLoanAmount
igroman787 Jan 25, 2024
56a1039
debug CalculateLoanAmount
igroman787 Jan 25, 2024
8037490
bugfix
igroman787 Jan 25, 2024
9c574c3
bugfix
igroman787 Jan 25, 2024
41d522d
bugfix
igroman787 Jan 25, 2024
7c83bfb
Merge remote-tracking branch 'origin/controller_dev_1' into mytonctrl…
yungwine Feb 29, 2024
319be9a
bugfix
yungwine Feb 29, 2024
0db8293
add controllecrs to mytonctrl.py
yungwine Feb 29, 2024
a5f19f3
Merge pull request #193 from yungwine/mytonctrl2_dev_1
igroman787 Feb 29, 2024
f5c470b
Merge pull request #196 from yungwine/mytonctrl2_dev
igroman787 Feb 29, 2024
a4969d6
Delete mytoninstaller.py
igroman787 Mar 1, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions docs/en/controllers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Controllers

## Launching a Validator in Controller Mode

1. Prepare the hardware for the validator - 32 virtual cores, 64GB of memory, 1TB SSD, fixed IP address, and 1Gb/s internet speed.

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.

> Ensure your hardware meets or exceeds the specified configuration. Running the validator on inappropriate hardware can harm the network and result in penalties.
> 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.

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.

You can also refer to this [Video Tutorial](https://docs.ton.org/participate/run-nodes/full-node#installation) for additional help.

3. Transfer 1 TON to the validator wallet address, which is displayed in the `wl` list.

4. Use the `aw` command to activate the validator's wallet.

5. Transfer enough TON to the validator wallet address.

6. Enable the ton-http-api service:
```
mytonctrl -> installer -> enable THA
```
Exit installer mode with `Ctrl+D`

7. Set the liquid pool address, which will lend TON for validation:
```
set liquid_pool_addr <liquid-pool-address>
```

8. Set the lending parameters that acceptable to you:
```
set min_loan 41000
set max_loan 43000
set max_interest_percent 1.5
```

where
* `41000` is the minimum loan amount we are willing to receive from the liquid pool,
* `43000` is the maximum loan amount we are willing to receive from the liquid pool,
* `1.5` 1.5 is the maximum interest rate value for the liquid pool per validation cycle, which we have agreed upon.

9. Display the annual percentage of profit from the liquid pool:
```
calculate_annual_controller_percentage
```

10. Create two controllers with a single command:

```
new_controllers
```

11. Enter `controllers_list` to display the controller addresses:

```
controllers_list
Address Status Balance
kf89KYOeRPRRDyjt_3bPsz92cKSghRqw64efNr8mT1eeHDaS active 0.704345
kf_lT8QNykLh5PN5ictNX22maiyIf9iK787fXg6nJ_zB-jbN active 0.720866
```

12. Make a validator deposit in each controller:


```
deposit_to_controller kf89KYOeRPRRDyjt_3bPsz92cKSghRqw64efNr8mT1eeHDaS 10000
deposit_to_controller kf_lT8QNykLh5PN5ictNX22maiyIf9iK787fXg6nJ_zB-jbN 10000
```


where `10000` TON is the deposit amount.

13. Get approval for the controllers. Each pool may have its own approval issuance policy, check with the operator.

14. Set controller mode:

```bash
set useController true
set stake null
```

> (!) If you were previously using nominator pools, do not forget to disable them using the `set usePool false` command.


## Switching a Regular Validator to Controller Operating Mode

1. Enter `set stake 0` to stop participating in elections.

2. Wait until both of your deposits have been returned from the Elector.

3. Follow the instructions under "Launching a Validator in Controller Mode", beginning with **Step 6**.
93 changes: 93 additions & 0 deletions docs/ru/controllers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# Контроллеры

## Запуск валидатора в режиме работы контроллеров

1. Подготовьте аппаратное обеспечение для валидатора - 32 виртуальных ядер, 64GB памяти, 1TB SSD, фиксированный IP-адрес, скорость интернета 1Gb/s.

Для поддержания стабильности сети рекомендуется разместить валидаторы в различных местах по всему миру, а не концентрировать их в одном дата-центре. Вы можете использовать [этот сайт](https://status.toncenter.com/) для определения нагрузки на различные места. Согласно карте, высокая нагрузка на дата-центры в Европе, особенно в Финляндии, Германии и Париже. Поэтому использование провайдеров, таких как Hetzner и OVH, не рекомендуется.

> Ваше оборудование должно соответствовать указанной конфигурации или быть выше. Запуск валидатора на слабом оборудовании негативно влияет на сеть и может привести к штрафам.

> С мая 2021 года Hetzner запретил майнинг на своих серверах, в настоящее время под это правило попадают алгоритмы PoW и PoS. Установка даже обычного узла будет считаться нарушением условий договора.

2. Установите и синхронизируйте **mytonctrl** в соответствии с описанием в [этой инструкции](https://github.com/ton-blockchain/mytonctrl/blob/master/docs/ru/manual-ubuntu.md) — следуйте **только** пунктам 1, 2 и 3.

Вы также можете обратиться к этой [Видеоинструкции](https://docs.ton.org/participate/run-nodes/full-node#installation) для дополнительной помощи.

3. Переведите 1 TON на адрес кошелька валидатора, который отображается в списке `wl`.

4. Используйте команду `aw` для активации кошелька валидатора.

5. Переведите достаточно TON на адрес кошелька валидатора.

6. Включите ton-http-api службу:
```
mytonctrl -> installer -> enable THA
```
Выйдите из режима установщика сочетанием клавиш `Ctrl+D`

7. Задайте адрес ликвидного пула, который будет одалживать TON для валидации:
```
set liquid_pool_addr <liquid-pool-address>
```

8. Задайте параметры кредитования, которые вам подходят:
```
set min_loan 41000
set max_loan 43000
set max_interest_percent 1.5
```

где
* `41000` - это минимальная сумма кредита который мы готовы получить у ликвидного пула,
* `43000` - это максимальная сумма кредита который мы готовы получить у ликвидного пула,
* `1.5` - это максимальная процентная ставка ликвидного пула за один цикл валидации на которую мы согласны.

9. Отобразите годовой процент прибыли от ликвидного пула:
```
calculate_annual_controller_percentage
```

10. Создайте два контроллера одной командой:

```
new_controllers
```

11. Введите `controllers_list` чтобы отобразить адреса контроллеров:

```
controllers_list
Address Status Balance
kf89KYOeRPRRDyjt_3bPsz92cKSghRqw64efNr8mT1eeHDaS active 0.704345
kf_lT8QNykLh5PN5ictNX22maiyIf9iK787fXg6nJ_zB-jbN active 0.720866
```

12. Совершите депозит валидатора в каждый контроллер:

```
deposit_to_controller kf89KYOeRPRRDyjt_3bPsz92cKSghRqw64efNr8mT1eeHDaS 10000
deposit_to_controller kf_lT8QNykLh5PN5ictNX22maiyIf9iK787fXg6nJ_zB-jbN 10000
```

где `10000` TON - это сумма депозита.

13. Получите аппрувал контроллеров. У каждого пула может быть своя политика выдачи аппруволов, уточняйте у оператора.

14. Активируйте режим работы контроллеров:

```bash
set useController true
set stake null
```

> (!) Если до этого вы использовали номинатор-пулы, не забудьте отключить их использование командой `set usePool false`.


## Переключение обычного валидатора в режим работы контроллеров

1. Введите `set stake 0`, чтобы отключить участие в выборах.

2. Дождитесь, когда оба ваших депозита вернутся от электора.

3. Следуйте инструкциям "Запуск валидатора в режиме работы контроллеров", начиная с **6-го шага**.
136 changes: 136 additions & 0 deletions functions/session_stats.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
#!/usr/bin/env python3
# -*- coding: utf_8 -*-

import os
import sys
import time
import json
sys.path.append("/usr/src/mytonctrl/")
from mypylib.mypylib import Dict

def read_session_stats(need_time_period):
#print(f"read_session_stats: {need_time_period}")
file_path = "/var/ton-work/log.session-stats"
average_block_time = calculate_average_block_time(file_path)
need_blocks = int(need_time_period/average_block_time)

lines = read_last_lines(file_path, need_lines=need_blocks)
#lines = read_all_lines(file_path)
data = lines2data(lines)

result = Dict()
result.my_blocks = 0
result.my_need_blocks = 0
result.all_master_blocks = 0
result.all_blocks = len(data)
for buff in data:
if buff.id.workchain == -1:
result.all_master_blocks += 1
first_producer = buff.rounds[0].producers[0]
if buff.self != first_producer.id:
continue
result.my_need_blocks += 1
if buff.self == buff.creator:
result.my_blocks += 1
#end for
return result
#end define

def calculate_average_block_time(file_path):
blocks = 100
lines = read_last_lines(file_path, need_lines=blocks)
data = lines2data(lines)
first_block, last_block = get_first_last_block(data)

diff = int(last_block.timestamp) - int(first_block.timestamp)
average_block_time = round(diff/blocks, 2)
#print("average_block_time:", average_block_time)
return average_block_time
#end define

def get_first_last_block(data, last_index=-1):
first_block = data[0]
last_block = data[last_index]
if first_block.id.workchain == last_block.id.workchain:
blocks = int(last_block.id.seqno) - int(first_block.id.seqno)
else:
first_block, last_block = get_first_last_block(data, last_index=last_index-1)
return first_block, last_block
#end define

def lines2data(lines):
#start = time.time()
data = list()
for line in lines:
try:
buff = json.loads(line)
data.append(Dict(buff))
except json.decoder.JSONDecodeError:
pass
#end for

#end = time.time()
#diff = round(end - start, 2)
#print(f"lines2data completed in {diff} seconds")
return data
#end define

def read_all_lines(file_path):
#start = time.time()
with open(file_path, 'rt') as file:
text = file.read()
#end with
lines = text.split('\n')

#end = time.time()
#diff = round(end - start, 2)
#print(f"read_all_lines completed in {diff} seconds")
return lines
#end define

def read_last_lines(file_path, need_lines):
lines = list()
max_lines = 30000
if need_lines < 1:
return lines
elif need_lines > max_lines:
need_lines = max_lines
#print(f"read_last_lines: {need_lines}")
#start = time.time()
with open(file_path, 'rb') as file:
find_last_lines(file, need_lines)
for i in range(need_lines):
line = file.readline().decode()
lines.append(line)
#end with


#end = time.time()
#diff = round(end - start, 2)
#print(f"read_last_lines {len(lines)} completed in {diff} seconds")
return lines
#end define

def find_last_lines(file, need_lines):
# catch OSError in case of a one line file
try:
find_lines = 0
#file.seek(-2, os.SEEK_END)
#while find_lines != need_lines:
# if file.read(1) == b'\n':
# find_lines += 1
# file.seek(-2, os.SEEK_CUR)

file.seek(-100, os.SEEK_END)
while find_lines != need_lines:
if b'\n' in file.read(100):
find_lines += 1
file.seek(-200, os.SEEK_CUR)
except OSError:
file.seek(0)
#end define





Loading