github.com/line/ostracon@v1.0.10-0.20230328032236-7f20145f065d/test/e2e/generator/generate.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"math/rand"
     6  	"sort"
     7  	"strings"
     8  	"time"
     9  
    10  	e2e "github.com/line/ostracon/test/e2e/pkg"
    11  )
    12  
    13  var (
    14  	// testnetCombinations defines global testnet options, where we generate a
    15  	// separate testnet for each combination (Cartesian product) of options.
    16  	testnetCombinations = map[string][]interface{}{
    17  		"topology":      {"single", "quad", "large"},
    18  		"initialHeight": {0, 1000},
    19  		"initialState": {
    20  			map[string]string{},
    21  			map[string]string{"initial01": "a", "initial02": "b", "initial03": "c"},
    22  		},
    23  		"validators": {"genesis", "initchain"},
    24  	}
    25  	nodeVersions = weightedChoice{
    26  		"": 2,
    27  	}
    28  	// The following specify randomly chosen values for testnet nodes.
    29  	nodeDatabases = uniformChoice{"goleveldb", "cleveldb", "rocksdb", "boltdb", "badgerdb"}
    30  	ipv6          = uniformChoice{false, true}
    31  	// FIXME: grpc disabled due to https://github.com/tendermint/tendermint/issues/5439
    32  	nodeABCIProtocols    = uniformChoice{"unix", "tcp", "builtin"} // "grpc"
    33  	nodePrivvalProtocols = uniformChoice{"file", "unix", "tcp"}
    34  	// FIXME: v2 disabled due to flake
    35  	nodeFastSyncs         = uniformChoice{"v0"} // "v2"
    36  	nodeStateSyncs        = uniformChoice{false, true}
    37  	nodePersistIntervals  = uniformChoice{0, 1, 5}
    38  	nodeSnapshotIntervals = uniformChoice{0, 3}
    39  	nodeRetainBlocks      = uniformChoice{
    40  		0,
    41  		2 * int(e2e.EvidenceAgeHeight),
    42  		4 * int(e2e.EvidenceAgeHeight),
    43  	}
    44  	abciDelays        = uniformChoice{"none", "small", "large"}
    45  	nodePerturbations = probSetChoice{
    46  		"disconnect": 0.1,
    47  		"pause":      0.1,
    48  		"kill":       0.1,
    49  		"restart":    0.1,
    50  	}
    51  )
    52  
    53  // Generate generates random testnets using the given RNG.
    54  func Generate(r *rand.Rand, multiversion string) ([]e2e.Manifest, error) {
    55  	if multiversion != "" {
    56  		nodeVersions[multiversion] = 1
    57  	}
    58  	manifests := []e2e.Manifest{}
    59  	for _, opt := range combinations(testnetCombinations) {
    60  		manifest, err := generateTestnet(r, opt)
    61  		if err != nil {
    62  			return nil, err
    63  		}
    64  		manifests = append(manifests, manifest)
    65  	}
    66  	return manifests, nil
    67  }
    68  
    69  // generateTestnet generates a single testnet with the given options.
    70  func generateTestnet(r *rand.Rand, opt map[string]interface{}) (e2e.Manifest, error) {
    71  	manifest := e2e.Manifest{
    72  		IPv6:             ipv6.Choose(r).(bool),
    73  		ABCIProtocol:     nodeABCIProtocols.Choose(r).(string),
    74  		InitialHeight:    int64(opt["initialHeight"].(int)),
    75  		InitialState:     opt["initialState"].(map[string]string),
    76  		Validators:       &map[string]int64{},
    77  		ValidatorUpdates: map[string]map[string]int64{},
    78  		Nodes:            map[string]*e2e.ManifestNode{},
    79  	}
    80  
    81  	switch abciDelays.Choose(r).(string) {
    82  	case "none":
    83  	case "small":
    84  		manifest.PrepareProposalDelay = 100 * time.Millisecond
    85  		manifest.ProcessProposalDelay = 100 * time.Millisecond
    86  	case "large":
    87  		manifest.PrepareProposalDelay = 200 * time.Millisecond
    88  		manifest.ProcessProposalDelay = 200 * time.Millisecond
    89  		manifest.CheckTxDelay = 20 * time.Millisecond
    90  	}
    91  
    92  	var numSeeds, numValidators, numFulls, numLightClients int
    93  	switch opt["topology"].(string) {
    94  	case "single":
    95  		numValidators = 1
    96  	case "quad":
    97  		numValidators = 4
    98  	case "large":
    99  		// FIXME Networks are kept small since large ones use too much CPU.
   100  		numSeeds = r.Intn(2)
   101  		numLightClients = r.Intn(3)
   102  		numValidators = 4 + r.Intn(4)
   103  		numFulls = r.Intn(4)
   104  	default:
   105  		return manifest, fmt.Errorf("unknown topology %q", opt["topology"])
   106  	}
   107  
   108  	// First we generate seed nodes, starting at the initial height.
   109  	for i := 1; i <= numSeeds; i++ {
   110  		manifest.Nodes[fmt.Sprintf("seed%02d", i)] = generateNode(
   111  			r, e2e.ModeSeed, 0, manifest.InitialHeight, false)
   112  	}
   113  
   114  	// Next, we generate validators. We make sure a BFT quorum of validators start
   115  	// at the initial height, and that we have two archive nodes. We also set up
   116  	// the initial validator set, and validator set updates for delayed nodes.
   117  	nextStartAt := manifest.InitialHeight + 5
   118  	quorum := numValidators*2/3 + 1
   119  	for i := 1; i <= numValidators; i++ {
   120  		startAt := int64(0)
   121  		if i > quorum {
   122  			startAt = nextStartAt
   123  			nextStartAt += 5
   124  		}
   125  		name := fmt.Sprintf("validator%02d", i)
   126  		manifest.Nodes[name] = generateNode(
   127  			r, e2e.ModeValidator, startAt, manifest.InitialHeight, i <= 2)
   128  
   129  		if startAt == 0 {
   130  			(*manifest.Validators)[name] = int64(30 + r.Intn(71))
   131  		} else {
   132  			manifest.ValidatorUpdates[fmt.Sprint(startAt+5)] = map[string]int64{
   133  				name: int64(30 + r.Intn(71)),
   134  			}
   135  		}
   136  	}
   137  
   138  	// Move validators to InitChain if specified.
   139  	switch opt["validators"].(string) {
   140  	case "genesis":
   141  	case "initchain":
   142  		manifest.ValidatorUpdates["0"] = *manifest.Validators
   143  		manifest.Validators = &map[string]int64{}
   144  	default:
   145  		return manifest, fmt.Errorf("invalid validators option %q", opt["validators"])
   146  	}
   147  
   148  	// Finally, we generate random full nodes.
   149  	for i := 1; i <= numFulls; i++ {
   150  		startAt := int64(0)
   151  		if r.Float64() >= 0.5 {
   152  			startAt = nextStartAt
   153  			nextStartAt += 5
   154  		}
   155  		manifest.Nodes[fmt.Sprintf("full%02d", i)] = generateNode(
   156  			r, e2e.ModeFull, startAt, manifest.InitialHeight, false)
   157  	}
   158  
   159  	// We now set up peer discovery for nodes. Seed nodes are fully meshed with
   160  	// each other, while non-seed nodes either use a set of random seeds or a
   161  	// set of random peers that start before themselves.
   162  	var seedNames, peerNames, lightProviders []string
   163  	for name, node := range manifest.Nodes {
   164  		if node.Mode == string(e2e.ModeSeed) {
   165  			seedNames = append(seedNames, name)
   166  		} else {
   167  			// if the full node or validator is an ideal candidate, it is added as a light provider.
   168  			// There are at least two archive nodes so there should be at least two ideal candidates
   169  			if (node.StartAt == 0 || node.StartAt == manifest.InitialHeight) && node.RetainBlocks == 0 {
   170  				lightProviders = append(lightProviders, name)
   171  			}
   172  			peerNames = append(peerNames, name)
   173  		}
   174  	}
   175  
   176  	for _, name := range seedNames {
   177  		for _, otherName := range seedNames {
   178  			if name != otherName {
   179  				manifest.Nodes[name].Seeds = append(manifest.Nodes[name].Seeds, otherName)
   180  			}
   181  		}
   182  	}
   183  
   184  	sort.Slice(peerNames, func(i, j int) bool {
   185  		iName, jName := peerNames[i], peerNames[j]
   186  		switch {
   187  		case manifest.Nodes[iName].StartAt < manifest.Nodes[jName].StartAt:
   188  			return true
   189  		case manifest.Nodes[iName].StartAt > manifest.Nodes[jName].StartAt:
   190  			return false
   191  		default:
   192  			return strings.Compare(iName, jName) == -1
   193  		}
   194  	})
   195  	for i, name := range peerNames {
   196  		if len(seedNames) > 0 && (i == 0 || r.Float64() >= 0.5) {
   197  			manifest.Nodes[name].Seeds = uniformSetChoice(seedNames).Choose(r)
   198  		} else if i > 0 {
   199  			manifest.Nodes[name].PersistentPeers = uniformSetChoice(peerNames[:i]).Choose(r)
   200  		}
   201  	}
   202  
   203  	// lastly, set up the light clients
   204  	for i := 1; i <= numLightClients; i++ {
   205  		startAt := manifest.InitialHeight + 5
   206  		manifest.Nodes[fmt.Sprintf("light%02d", i)] = generateLightNode(
   207  			r, startAt+(5*int64(i)), lightProviders,
   208  		)
   209  	}
   210  
   211  	return manifest, nil
   212  }
   213  
   214  // generateNode randomly generates a node, with some constraints to avoid
   215  // generating invalid configurations. We do not set Seeds or PersistentPeers
   216  // here, since we need to know the overall network topology and startup
   217  // sequencing.
   218  func generateNode(
   219  	r *rand.Rand, mode e2e.Mode, startAt int64, initialHeight int64, forceArchive bool,
   220  ) *e2e.ManifestNode {
   221  	node := e2e.ManifestNode{
   222  		Version:          nodeVersions.Choose(r).(string),
   223  		Mode:             string(mode),
   224  		StartAt:          startAt,
   225  		Database:         nodeDatabases.Choose(r).(string),
   226  		PrivvalProtocol:  nodePrivvalProtocols.Choose(r).(string),
   227  		FastSync:         nodeFastSyncs.Choose(r).(string),
   228  		StateSync:        nodeStateSyncs.Choose(r).(bool) && startAt > 0,
   229  		PersistInterval:  ptrUint64(uint64(nodePersistIntervals.Choose(r).(int))),
   230  		SnapshotInterval: uint64(nodeSnapshotIntervals.Choose(r).(int)),
   231  		RetainBlocks:     uint64(nodeRetainBlocks.Choose(r).(int)),
   232  		Perturb:          nodePerturbations.Choose(r),
   233  	}
   234  
   235  	// If this node is forced to be an archive node, retain all blocks and
   236  	// enable state sync snapshotting.
   237  	if forceArchive {
   238  		node.RetainBlocks = 0
   239  		node.SnapshotInterval = 3
   240  	}
   241  
   242  	// If a node which does not persist state also does not retain blocks, randomly
   243  	// choose to either persist state or retain all blocks.
   244  	if node.PersistInterval != nil && *node.PersistInterval == 0 && node.RetainBlocks > 0 {
   245  		if r.Float64() > 0.5 {
   246  			node.RetainBlocks = 0
   247  		} else {
   248  			node.PersistInterval = ptrUint64(node.RetainBlocks)
   249  		}
   250  	}
   251  
   252  	// If either PersistInterval or SnapshotInterval are greater than RetainBlocks,
   253  	// expand the block retention time.
   254  	if node.RetainBlocks > 0 {
   255  		if node.PersistInterval != nil && node.RetainBlocks < *node.PersistInterval {
   256  			node.RetainBlocks = *node.PersistInterval
   257  		}
   258  		if node.RetainBlocks < node.SnapshotInterval {
   259  			node.RetainBlocks = node.SnapshotInterval
   260  		}
   261  	}
   262  
   263  	return &node
   264  }
   265  
   266  func generateLightNode(r *rand.Rand, startAt int64, providers []string) *e2e.ManifestNode {
   267  	return &e2e.ManifestNode{
   268  		Mode:            string(e2e.ModeLight),
   269  		StartAt:         startAt,
   270  		Database:        nodeDatabases.Choose(r).(string),
   271  		PersistInterval: ptrUint64(0),
   272  		PersistentPeers: providers,
   273  	}
   274  }
   275  
   276  func ptrUint64(i uint64) *uint64 {
   277  	return &i
   278  }