-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_config_files.py
executable file
·667 lines (569 loc) · 19 KB
/
create_config_files.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
#!/usr/bin/env python3
# Generate rippled config files, each with their own ports, database paths, and validation_seeds.
# There will be configs for shards/no_shards, main/test nets, two config files for each combination
# (so one can run in a dogfood mode while another is tested). To avoid confusion,The directory path
# will be $data_dir/{main | test}.{shard | no_shard}.{dog | test}
# The config file will reside in that directory with the name rippled.cfg
# The validators file will reside in that directory with the name validators.txt
"""
Script to test and debug sidechains.
The rippled exe location can be set through the command line or
the environment variable RIPPLED_MAINCHAIN_EXE
The configs_dir (where the config files will reside) can be set through the command line
or the environment variable RIPPLED_SIDECHAIN_CFG_DIR
"""
import argparse
from dataclasses import dataclass
import json
import os
from pathlib import Path
import sys
from typing import Dict, List, Optional, Tuple, Union
from config_file import ConfigFile
from command import ValidationCreate, WalletPropose
from common import Account, Asset, eprint, XRP
from app import App, single_client_app
mainnet_validators = """
[validator_list_sites]
https://vl.ripple.com
[validator_list_keys]
ED2677ABFFD1B33AC6FBC3062B71F1E8397C1505E1C42C64D11AD1B28FF73F4734
"""
altnet_validators = """
[validator_list_sites]
https://vl.altnet.rippletest.net
[validator_list_keys]
ED264807102805220DA0F312E71FC2C69E1552C9C5790F6C25E3729DEB573D5860
"""
node_size = "medium"
default_data_dir = "/home/swd/data/rippled"
@dataclass
class Keypair:
public_key: str
secret_key: str
account_id: Optional[str]
def generate_node_keypairs(n: int, rip: App) -> List[Keypair]:
"""
generate keypairs suitable for validator keys
"""
result = []
for i in range(n):
keys = rip(ValidationCreate())
result.append(
Keypair(
public_key=keys["validation_public_key"],
secret_key=keys["validation_seed"],
account_id=None,
)
)
return result
def generate_federator_keypairs(n: int, rip: App) -> List[Keypair]:
"""
generate keypairs suitable for federator keys
"""
result = []
for i in range(n):
keys = rip(WalletPropose(key_type="ed25519"))
result.append(
Keypair(
public_key=keys["public_key"],
secret_key=keys["master_seed"],
account_id=keys["account_id"],
)
)
return result
class Ports:
"""
Port numbers for various services.
Port numbers differ by cfg_index so different configs can run
at the same time without interfering with each other.
"""
peer_port_base = 51235
http_admin_port_base = 5005
ws_public_port_base = 6005
def __init__(self, cfg_index: int):
self.peer_port = Ports.peer_port_base + cfg_index
self.http_admin_port = Ports.http_admin_port_base + cfg_index
self.ws_public_port = Ports.ws_public_port_base + (2 * cfg_index)
# note admin port uses public port base
self.ws_admin_port = Ports.ws_public_port_base + (2 * cfg_index) + 1
class Network:
def __init__(
self, num_nodes: int, num_validators: int, start_cfg_index: int, rip: App
):
self.validator_keypairs = generate_node_keypairs(num_validators, rip)
self.ports = [Ports(start_cfg_index + i) for i in range(num_nodes)]
class SidechainNetwork(Network):
def __init__(
self,
num_nodes: int,
num_federators: int,
num_validators: int,
start_cfg_index: int,
rip: App,
):
super().__init__(num_nodes, num_validators, start_cfg_index, rip)
self.federator_keypairs = generate_federator_keypairs(num_federators, rip)
self.main_account = rip(WalletPropose(key_type="secp256k1"))
class XChainAsset:
def __init__(
self,
main_asset: Asset,
side_asset: Asset,
main_value: Union[int, float],
side_value: Union[int, float],
main_refund_penalty: Union[int, float],
side_refund_penalty: Union[int, float],
):
self.main_asset = main_asset(main_value)
self.side_asset = side_asset(side_value)
self.main_refund_penalty = main_asset(main_refund_penalty)
self.side_refund_penalty = side_asset(side_refund_penalty)
def generate_asset_stanzas(assets: Optional[Dict[str, XChainAsset]] = None) -> str:
if assets is None:
# default to xrp only at a 1:1 value
assets = {}
assets["xrp_xrp_sidechain_asset"] = XChainAsset(XRP(0), XRP(0), 1, 1, 400, 400)
index_stanza = """
[sidechain_assets]"""
asset_stanzas = []
for name, xchainasset in assets.items():
index_stanza += "\n" + name
new_stanza = f"""
[{name}]
mainchain_asset={json.dumps(xchainasset.main_asset.to_cmd_obj())}
sidechain_asset={json.dumps(xchainasset.side_asset.to_cmd_obj())}
mainchain_refund_penalty={json.dumps(xchainasset.main_refund_penalty.to_cmd_obj())}
sidechain_refund_penalty={json.dumps(xchainasset.side_refund_penalty.to_cmd_obj())}"""
asset_stanzas.append(new_stanza)
return index_stanza + "\n" + "\n".join(asset_stanzas)
# First element of the returned tuple is the sidechain stanzas
# second element is the bootstrap stanzas
def generate_sidechain_stanza(
mainchain_ports: Ports,
main_account: dict,
federators: List[Keypair],
signing_key: str,
mainchain_cfg_file: str,
xchain_assets: Optional[Dict[str, XChainAsset]] = None,
) -> Tuple[str, str]:
mainchain_ip = "127.0.0.1"
federators_stanza = """
# federator signing public keys
[sidechain_federators]
"""
federators_secrets_stanza = """
# federator signing secret keys (for standalone-mode testing only; Normally won't be in a config file)
[sidechain_federators_secrets]
"""
bootstrap_federators_stanza = """
# first value is federator signing public key, second is the signing pk account
[sidechain_federators]
"""
assets_stanzas = generate_asset_stanzas(xchain_assets)
for fed in federators:
federators_stanza += f"{fed.public_key}\n"
federators_secrets_stanza += f"{fed.secret_key}\n"
bootstrap_federators_stanza += f"{fed.public_key} {fed.account_id}\n"
sidechain_stanzas = f"""
[sidechain]
signing_key={signing_key}
mainchain_account={main_account["account_id"]}
mainchain_ip={mainchain_ip}
mainchain_port_ws={mainchain_ports.ws_public_port}
# mainchain config file is: {mainchain_cfg_file}
{assets_stanzas}
{federators_stanza}
{federators_secrets_stanza}
"""
bootstrap_stanzas = f"""
[sidechain]
mainchain_secret={main_account["master_seed"]}
{bootstrap_federators_stanza}
"""
return (sidechain_stanzas, bootstrap_stanzas)
# cfg_type will typically be either 'dog' or 'test', but can be any string. It is only used
# to create the data directories.
def generate_cfg_dir(
*,
ports: Ports,
with_shards: bool,
main_net: bool,
cfg_type: str,
sidechain_stanza: str,
sidechain_bootstrap_stanza: str,
validation_seed: Optional[str] = None,
validators: Optional[List[str]] = None,
fixed_ips: Optional[List[Ports]] = None,
data_dir: str,
full_history: bool = False,
with_hooks: bool = False,
) -> str:
ips_stanza = ""
this_ip = "127.0.0.1"
if fixed_ips:
ips_stanza = "# Fixed ips for a testnet.\n"
ips_stanza += "[ips_fixed]\n"
for i, p in enumerate(fixed_ips):
if p.peer_port == ports.peer_port:
continue
# rippled limits the number of connects per ip. So use the other loopback devices
ips_stanza += f"127.0.0.{i+1} {p.peer_port}\n"
else:
ips_stanza = (
"# Where to find some other servers speaking the Ripple protocol.\n"
)
ips_stanza += "[ips]\n"
if main_net:
ips_stanza += "r.ripple.com 51235\n"
else:
ips_stanza += "r.altnet.rippletest.net 51235\n"
disable_shards = "" if with_shards else "# "
disable_delete = "#" if full_history else ""
history_line = "full" if full_history else "256"
earliest_seq_line = ""
if sidechain_stanza:
earliest_seq_line = "earliest_seq=1"
hooks_line = "Hooks" if with_hooks else ""
validation_seed_stanza = ""
if validation_seed:
validation_seed_stanza = f"""
[validation_seed]
{validation_seed}
"""
node_size = "medium"
shard_str = "shards" if with_shards else "no_shards"
net_str = "main" if main_net else "test"
if not fixed_ips:
sub_dir = data_dir + f"/{net_str}.{shard_str}.{cfg_type}"
if sidechain_stanza:
sub_dir += ".sidechain"
else:
sub_dir = data_dir + f"/{cfg_type}"
db_path = sub_dir + "/db"
debug_logfile = sub_dir + "/debug.log"
shard_db_path = sub_dir + "/shards"
node_db_path = db_path + "/nudb"
cfg_str = f"""
[server]
port_rpc_admin_local
port_peer
port_ws_admin_local
port_ws_public
#ssl_key = /etc/ssl/private/server.key
#ssl_cert = /etc/ssl/certs/server.crt
[port_rpc_admin_local]
port = {ports.http_admin_port}
ip = {this_ip}
admin = {this_ip}
protocol = http
[port_peer]
port = {ports.peer_port}
ip = 0.0.0.0
protocol = peer
[port_ws_admin_local]
port = {ports.ws_admin_port}
ip = {this_ip}
admin = {this_ip}
protocol = ws
[port_ws_public]
port = {ports.ws_public_port}
ip = {this_ip}
protocol = ws
# protocol = wss
[node_size]
{node_size}
[ledger_history]
{history_line}
[node_db]
type=NuDB
path={node_db_path}
open_files=2000
filter_bits=12
cache_mb=256
file_size_mb=8
file_size_mult=2
{earliest_seq_line}
{disable_delete}online_delete=256
{disable_delete}advisory_delete=0
[database_path]
{db_path}
# This needs to be an absolute directory reference, not a relative one.
# Modify this value as required.
[debug_logfile]
{debug_logfile}
[sntp_servers]
time.windows.com
time.apple.com
time.nist.gov
pool.ntp.org
{ips_stanza}
[validators_file]
validators.txt
[rpc_startup]
{{ "command": "log_level", "severity": "fatal" }}
{{ "command": "log_level", "partition": "SidechainFederator", "severity": "trace" }}
[ssl_verify]
1
{validation_seed_stanza}
{disable_shards}[shard_db]
{disable_shards}type=NuDB
{disable_shards}path={shard_db_path}
{disable_shards}max_historical_shards=6
{sidechain_stanza}
[features]
{hooks_line}
PayChan
Flow
FlowCross
TickSize
fix1368
Escrow
fix1373
EnforceInvariants
SortedDirectories
fix1201
fix1512
fix1513
fix1523
fix1528
DepositAuth
Checks
fix1571
fix1543
fix1623
DepositPreauth
fix1515
fix1578
MultiSignReserve
fixTakerDryOfferRemoval
fixMasterKeyAsRegularKey
fixCheckThreading
fixPayChanRecipientOwnerDir
DeletableAccounts
fixQualityUpperBound
RequireFullyCanonicalSig
fix1781
HardenedValidations
fixAmendmentMajorityCalc
NegativeUNL
TicketBatch
FlowSortStrands
fixSTAmountCanonicalize
fixRmSmallIncreasedQOffers
CheckCashMakesTrustLine
"""
validators_str = ""
for p in [sub_dir, db_path, shard_db_path]:
Path(p).mkdir(parents=True, exist_ok=True)
# Add the validators.txt file
if validators:
validators_str = "[validators]\n"
for k in validators:
validators_str += f"{k}\n"
else:
validators_str = mainnet_validators if main_net else altnet_validators
with open(sub_dir + "/validators.txt", "w") as f:
f.write(validators_str)
# add the rippled.cfg file
with open(sub_dir + "/rippled.cfg", "w") as f:
f.write(cfg_str)
if sidechain_bootstrap_stanza:
# add the bootstrap file
with open(sub_dir + "/sidechain_bootstrap.cfg", "w") as f:
f.write(sidechain_bootstrap_stanza)
return sub_dir + "/rippled.cfg"
def generate_multinode_net(
out_dir: str,
mainnet: Network,
sidenet: SidechainNetwork,
xchain_assets: Optional[Dict[str, XChainAsset]] = None,
):
mainnet_cfgs = []
for i in range(len(mainnet.ports)):
validator_kp = mainnet.validator_keypairs[i]
ports = mainnet.ports[i]
mainchain_cfg_file = generate_cfg_dir(
ports=ports,
with_shards=False,
main_net=True,
cfg_type=f"mainchain_{i}",
sidechain_stanza="",
sidechain_bootstrap_stanza="",
validation_seed=validator_kp.secret_key,
data_dir=out_dir,
)
mainnet_cfgs.append(mainchain_cfg_file)
for i in range(len(sidenet.ports)):
validator_kp = sidenet.validator_keypairs[i]
ports = sidenet.ports[i]
mainnet_i = i % len(mainnet.ports)
sidechain_stanza, sidechain_bootstrap_stanza = generate_sidechain_stanza(
mainnet.ports[mainnet_i],
sidenet.main_account,
sidenet.federator_keypairs,
sidenet.federator_keypairs[i].secret_key,
mainnet_cfgs[mainnet_i],
xchain_assets,
)
generate_cfg_dir(
ports=ports,
with_shards=False,
main_net=True,
cfg_type=f"sidechain_{i}",
sidechain_stanza=sidechain_stanza,
sidechain_bootstrap_stanza=sidechain_bootstrap_stanza,
validation_seed=validator_kp.secret_key,
validators=[kp.public_key for kp in sidenet.validator_keypairs],
fixed_ips=sidenet.ports,
data_dir=out_dir,
full_history=True,
with_hooks=False,
)
def parse_args():
parser = argparse.ArgumentParser(
description=("Create config files for testing sidechains")
)
parser.add_argument(
"--exe",
"-e",
help=("path to rippled executable"),
)
parser.add_argument(
"--usd",
"-u",
action="store_true",
help=("include a USD/root IOU asset for cross chain transfers"),
)
parser.add_argument(
"--cfgs_dir",
"-c",
help=(
"path to configuration file dir (where the output config files will be located)"
),
)
return parser.parse_known_args()[0]
class Params:
def __init__(self):
args = parse_args()
self.exe = None
if "RIPPLED_MAINCHAIN_EXE" in os.environ:
self.exe = os.environ["RIPPLED_MAINCHAIN_EXE"]
if args.exe:
self.exe = args.exe
self.configs_dir = None
if "RIPPLED_SIDECHAIN_CFG_DIR" in os.environ:
self.configs_dir = os.environ["RIPPLED_SIDECHAIN_CFG_DIR"]
if args.cfgs_dir:
self.configs_dir = args.cfgs_dir
self.usd = False
if args.usd:
self.usd = args.usd
def check_error(self) -> str:
"""
Check for errors. Return `None` if no errors,
otherwise return a string describing the error
"""
if not self.exe:
return "Missing exe location. Either set the env variable RIPPLED_MAINCHAIN_EXE or use the --exe_mainchain command line switch"
if not self.configs_dir:
return "Missing configs directory location. Either set the env variable RIPPLED_SIDECHAIN_CFG_DIR or use the --cfgs_dir command line switch"
def main(params: Params, xchain_assets: Optional[Dict[str, XChainAsset]] = None):
if err_str := params.check_error():
eprint(err_str)
sys.exit(1)
index = 0
nonvalidator_cfg_file_name = generate_cfg_dir(
ports=Ports(index),
with_shards=False,
main_net=True,
cfg_type="non_validator",
sidechain_stanza="",
sidechain_bootstrap_stanza="",
validation_seed=None,
data_dir=params.configs_dir,
)
index = index + 1
nonvalidator_config = ConfigFile(file_name=nonvalidator_cfg_file_name)
with single_client_app(
exe=params.exe, config=nonvalidator_config, standalone=True
) as rip:
mainnet = Network(num_nodes=1, num_validators=1, start_cfg_index=index, rip=rip)
sidenet = SidechainNetwork(
num_nodes=5,
num_federators=5,
num_validators=5,
start_cfg_index=index + 1,
rip=rip,
)
generate_multinode_net(
out_dir=f"{params.configs_dir}/sidechain_testnet",
mainnet=mainnet,
sidenet=sidenet,
xchain_assets=xchain_assets,
)
index = index + 2
(Path(params.configs_dir) / "logs").mkdir(parents=True, exist_ok=True)
for with_shards in [True, False]:
for is_main_net in [True, False]:
for cfg_type in ["dog", "test", "one", "two"]:
if not is_main_net and cfg_type not in ["dog", "test"]:
continue
mainnet = Network(
num_nodes=1, num_validators=1, start_cfg_index=index, rip=rip
)
mainchain_cfg_file = generate_cfg_dir(
data_dir=params.configs_dir,
ports=mainnet.ports[0],
with_shards=with_shards,
main_net=is_main_net,
cfg_type=cfg_type,
sidechain_stanza="",
sidechain_bootstrap_stanza="",
validation_seed=mainnet.validator_keypairs[0].secret_key,
)
sidenet = SidechainNetwork(
num_nodes=1,
num_federators=5,
num_validators=1,
start_cfg_index=index + 1,
rip=rip,
)
signing_key = sidenet.federator_keypairs[0].secret_key
(
sidechain_stanza,
sizechain_bootstrap_stanza,
) = generate_sidechain_stanza(
mainnet.ports[0],
sidenet.main_account,
sidenet.federator_keypairs,
signing_key,
mainchain_cfg_file,
xchain_assets,
)
generate_cfg_dir(
data_dir=params.configs_dir,
ports=sidenet.ports[0],
with_shards=with_shards,
main_net=is_main_net,
cfg_type=cfg_type,
sidechain_stanza=sidechain_stanza,
sidechain_bootstrap_stanza=sizechain_bootstrap_stanza,
validation_seed=sidenet.validator_keypairs[0].secret_key,
)
index = index + 2
if __name__ == "__main__":
params = Params()
xchain_assets = None
if params.usd:
xchain_assets = {}
xchain_assets["xrp_xrp_sidechain_asset"] = XChainAsset(
XRP(0), XRP(0), 1, 1, 200, 200
)
root_account = Account(account_id="rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")
main_iou_asset = Asset(value=0, currency="USD", issuer=root_account)
side_iou_asset = Asset(value=0, currency="USD", issuer=root_account)
xchain_assets["iou_iou_sidechain_asset"] = XChainAsset(
main_iou_asset, side_iou_asset, 1, 1, 0.02, 0.02
)
main(params, xchain_assets)