Ton

Форк
0
/
generate-random-id.cpp 
166 строк · 6.4 Кб
1
/*
2
    This file is part of TON Blockchain source code.
3

4
    TON Blockchain is free software; you can redistribute it and/or
5
    modify it under the terms of the GNU General Public License
6
    as published by the Free Software Foundation; either version 2
7
    of the License, or (at your option) any later version.
8

9
    TON Blockchain is distributed in the hope that it will be useful,
10
    but WITHOUT ANY WARRANTY; without even the implied warranty of
11
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
    GNU General Public License for more details.
13

14
    You should have received a copy of the GNU General Public License
15
    along with TON Blockchain.  If not, see <http://www.gnu.org/licenses/>.
16

17
    In addition, as a special exception, the copyright holders give permission
18
    to link the code of portions of this program with the OpenSSL library.
19
    You must obey the GNU General Public License in all respects for all
20
    of the code used other than OpenSSL. If you modify file(s) with this
21
    exception, you may extend this exception to your version of the file(s),
22
    but you are not obligated to do so. If you do not wish to do so, delete this
23
    exception statement from your version. If you delete this exception statement
24
    from all source files in the program, then also delete it here.
25

26
    Copyright 2017-2020 Telegram Systems LLP
27
*/
28
#include <iostream>
29
#include <iomanip>
30
#include <string>
31
#include "adnl/utils.hpp"
32
#include "auto/tl/ton_api.h"
33
#include "auto/tl/ton_api_json.h"
34
#include "tl/tl_json.h"
35
#include "td/utils/OptionParser.h"
36
#include "td/utils/filesystem.h"
37
#include "keys/encryptor.h"
38
#include "git.h"
39
#include "dht/dht-node.hpp"
40

41
int main(int argc, char *argv[]) {
42
  ton::PrivateKey pk;
43
  td::optional<ton::adnl::AdnlAddressList> addr_list;
44
  td::optional<td::int32> network_id_opt;
45

46
  td::OptionParser p;
47
  p.set_description("generate random id");
48

49
  std::string mode = "";
50

51
  std::string name = "id_ton";
52

53
  p.add_option('m', "mode", "sets mode (one of id/adnl/dht/keys/adnlid)", [&](td::Slice key) { mode = key.str(); });
54
  p.add_option('h', "help", "prints this help", [&]() {
55
    char b[10240];
56
    td::StringBuilder sb(td::MutableSlice{b, 10000});
57
    sb << p;
58
    std::cout << sb.as_cslice().c_str();
59
    std::exit(2);
60
  });
61
  p.add_option('V', "version", "shows generate-random-id build information", [&]() {
62
    std::cout << "generate-random-id build information: [ Commit: " << GitMetadata::CommitSHA1() << ", Date: " << GitMetadata::CommitDate() << "]\n";
63
    std::exit(0);
64
  });
65
  p.add_option('n', "name", "path to save private keys to", [&](td::Slice arg) { name = arg.str(); });
66
  p.add_checked_option('k', "key", "path to private key to import", [&](td::Slice key) {
67
    if (!pk.empty()) {
68
      return td::Status::Error("duplicate '-k' option");
69
    }
70

71
    TRY_RESULT_PREFIX(data, td::read_file_secure(key.str()), "failed to read private key: ");
72
    TRY_RESULT_PREFIX_ASSIGN(pk, ton::PrivateKey::import(data.as_slice()), "failed to import private key: ");
73
    return td::Status::OK();
74
  });
75
  p.add_checked_option('a', "addr-list", "addr list to sign", [&](td::Slice key) {
76
    if (addr_list) {
77
      return td::Status::Error("duplicate '-a' option");
78
    }
79

80
    td::BufferSlice bs(key);
81
    TRY_RESULT_PREFIX(as_json_value, td::json_decode(bs.as_slice()), "bad addr list JSON: ");
82
    ton::tl_object_ptr<ton::ton_api::adnl_addressList> addr_list_tl;
83
    TRY_STATUS_PREFIX(td::from_json(addr_list_tl, std::move(as_json_value)), "bad addr list TL: ");
84
    TRY_RESULT_PREFIX_ASSIGN(addr_list, ton::adnl::AdnlAddressList::create(addr_list_tl), "bad addr list: ");
85
    return td::Status::OK();
86
  });
87
  p.add_checked_option('i', "network-id", "dht network id (default: -1)", [&](td::Slice key) {
88
    if (network_id_opt) {
89
      return td::Status::Error("duplicate '-i' option");
90
    }
91
    TRY_RESULT_PREFIX_ASSIGN(network_id_opt, td::to_integer_safe<td::int32>(key), "bad network id: ");
92
    return td::Status::OK();
93
  });
94

95
  auto S = p.run(argc, argv);
96

97
  if (S.is_error()) {
98
    std::cerr << S.move_as_error().message().str() << std::endl;
99
    return 2;
100
  }
101

102
  if (mode.size() == 0) {
103
    std::cerr << "'--mode' option missing" << std::endl;
104
    return 2;
105
  }
106

107
  if (pk.empty()) {
108
    pk = ton::privkeys::Ed25519::random();
109
  }
110

111
  auto pub_key = pk.compute_public_key();
112
  auto short_key = pub_key.compute_short_id();
113

114
  if (mode == "id") {
115
    std::string v;
116
    v = td::json_encode<std::string>(td::ToJson(pk.tl()));
117
    std::cout << v << std::endl;
118
    v = td::json_encode<std::string>(td::ToJson(pub_key.tl()));
119
    std::cout << v << std::endl;
120
    v = td::json_encode<std::string>(td::ToJson(ton::adnl::AdnlNodeIdShort{short_key}.tl()));
121
    std::cout << v << std::endl;
122
  } else if (mode == "adnl") {
123
    if (!addr_list) {
124
      std::cerr << "'-a' option missing" << std::endl;
125
      return 2;
126
    }
127
    auto x = ton::create_tl_object<ton::ton_api::adnl_node>(pub_key.tl(), addr_list.value().tl());
128
    auto e = pk.create_decryptor().move_as_ok();
129
    auto r = e->sign(ton::serialize_tl_object(x, true).as_slice()).move_as_ok();
130

131
    auto v = td::json_encode<std::string>(td::ToJson(x));
132
    std::cout << v << std::endl;
133
  } else if (mode == "dht") {
134
    if (!addr_list) {
135
      std::cerr << "'-a' option missing" << std::endl;
136
      return 2;
137
    }
138
    td::int32 network_id = network_id_opt ? network_id_opt.value() : -1;
139
    td::BufferSlice to_sign = ton::serialize_tl_object(
140
        ton::dht::DhtNode{ton::adnl::AdnlNodeIdFull{pub_key}, addr_list.value(), -1, network_id, td::BufferSlice{}}
141
            .tl(),
142
        true);
143
    auto e = pk.create_decryptor().move_as_ok();
144
    auto signature = e->sign(to_sign.as_slice()).move_as_ok();
145
    auto node =
146
        ton::dht::DhtNode{ton::adnl::AdnlNodeIdFull{pub_key}, addr_list.value(), -1, network_id, std::move(signature)};
147

148
    auto v = td::json_encode<std::string>(td::ToJson(node.tl()));
149
    std::cout << v << "\n";
150
  } else if (mode == "keys") {
151
    td::write_file(name, pk.export_as_slice()).ensure();
152
    td::write_file(name + ".pub", pub_key.export_as_slice().as_slice()).ensure();
153

154
    std::cout << short_key.bits256_value().to_hex() << " " << td::base64_encode(short_key.as_slice()) << std::endl;
155
  } else if (mode == "adnlid") {
156
    auto n = pk.compute_short_id();
157
    name = n.bits256_value().to_hex();
158
    td::write_file(name, pk.export_as_slice()).ensure();
159

160
    std::cout << name << " " << ton::adnl::AdnlNodeIdShort{n}.serialize() << std::endl;
161
  } else {
162
    std::cerr << "unknown mode " << mode;
163
    return 2;
164
  }
165
  return 0;
166
}
167

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

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