use of com.radixdlt.counters.SystemCountersImpl in project radixdlt by radixdlt.
the class BerkeleySafetyStateStoreTest method should_be_able_to_restore_committed_state.
@Test
public void should_be_able_to_restore_committed_state() {
final var db = mock(Database.class);
final var env = mock(Environment.class);
final var dbEnv = mock(DatabaseEnvironment.class);
final var tx = mock(com.sleepycat.je.Transaction.class);
when(dbEnv.getEnvironment()).thenReturn(env);
when(env.openDatabase(any(), any(), any())).thenReturn(db);
final var store = new BerkeleySafetyStateStore(dbEnv, DefaultSerialization.getInstance(), new SystemCountersImpl());
final var safetyState = new SafetyState(randomView(), Optional.of(randomVote()));
when(env.beginTransaction(any(), any())).thenReturn(tx);
when(db.put(any(), any(), any())).thenReturn(OperationStatus.SUCCESS);
ArgumentCaptor<DatabaseEntry> entryCaptor = ArgumentCaptor.forClass(DatabaseEntry.class);
store.commitState(safetyState);
verify(db, times(1)).put(any(), any(), entryCaptor.capture());
verify(tx, times(1)).commit();
verifyNoMoreInteractions(tx);
final var cursor = mock(Cursor.class);
when(db.openCursor(any(), any())).thenReturn(cursor);
when(cursor.getLast(any(), any(), any())).thenAnswer(invocation -> {
DatabaseEntry entry = (DatabaseEntry) invocation.getArguments()[1];
entry.setData(entryCaptor.getValue().getData());
return OperationStatus.SUCCESS;
});
var state = store.get();
assertTrue(state.isPresent());
assertEquals(safetyState, state.get());
}
use of com.radixdlt.counters.SystemCountersImpl in project radixdlt by radixdlt.
the class MessageCentralFuzzyTest method fuzzy_messaged_are_not_accepted.
@Test
@SuppressWarnings("unchecked")
public void fuzzy_messaged_are_not_accepted() throws Exception {
var inboundMessages = PublishSubject.<InboundMessage>create();
var config = mock(MessageCentralConfiguration.class);
var peerControl = mock(PeerControl.class);
var peerManager = mock(PeerManager.class);
var queueFactory = mock(EventQueueFactory.class);
when(config.messagingOutboundQueueMax(anyInt())).thenReturn(1);
when(config.messagingTimeToLive(anyLong())).thenReturn(30_000L);
when(peerManager.messages()).thenReturn(inboundMessages);
when(queueFactory.createEventQueue(anyInt(), any(Comparator.class))).thenReturn(new SimplePriorityBlockingQueue<>(1, OutboundMessageEvent.comparator()));
var messageCentral = new MessageCentralImpl(config, serialization, peerManager, Time::currentTimestamp, queueFactory, new SystemCountersImpl(), () -> peerControl);
var counter = new AtomicLong(0);
var disposable = messageCentral.messagesOf(Message.class).subscribe(nextItem -> counter.incrementAndGet(), error -> fail(error.getMessage()));
// Insert single valid message to ensure whole pipeline is working properly
emitSingleValidMessage(inboundMessages);
// Insert batch of randomly generated messages
emitFuzzyMessages(inboundMessages);
disposable.dispose();
// Ensure that only one (valid) message passed through
assertEquals(1L, counter.get());
}
use of com.radixdlt.counters.SystemCountersImpl in project radixdlt by radixdlt.
the class EpochManagerTest method getExternalModule.
private Module getExternalModule() {
BFTNode self = BFTNode.create(ecKeyPair.getPublicKey());
return new AbstractModule() {
@Override
protected void configure() {
bind(HashSigner.class).toInstance(ecKeyPair::sign);
bind(BFTNode.class).annotatedWith(Self.class).toInstance(self);
bind(new TypeLiteral<EventDispatcher<LocalTimeoutOccurrence>>() {
}).toInstance(rmock(EventDispatcher.class));
bind(new TypeLiteral<EventDispatcher<BFTInsertUpdate>>() {
}).toInstance(rmock(EventDispatcher.class));
bind(new TypeLiteral<EventDispatcher<BFTRebuildUpdate>>() {
}).toInstance(rmock(EventDispatcher.class));
bind(new TypeLiteral<EventDispatcher<BFTHighQCUpdate>>() {
}).toInstance(rmock(EventDispatcher.class));
bind(new TypeLiteral<EventDispatcher<BFTCommittedUpdate>>() {
}).toInstance(rmock(EventDispatcher.class));
bind(new TypeLiteral<EventDispatcher<EpochLocalTimeoutOccurrence>>() {
}).toInstance(rmock(EventDispatcher.class));
bind(new TypeLiteral<EventDispatcher<EpochView>>() {
}).toInstance(rmock(EventDispatcher.class));
bind(new TypeLiteral<EventDispatcher<LocalSyncRequest>>() {
}).toInstance(syncLedgerRequestSender);
bind(new TypeLiteral<EventDispatcher<ViewQuorumReached>>() {
}).toInstance(rmock(EventDispatcher.class));
bind(new TypeLiteral<EventDispatcher<EpochViewUpdate>>() {
}).toInstance(rmock(EventDispatcher.class));
bind(new TypeLiteral<EventDispatcher<ViewUpdate>>() {
}).toInstance(rmock(EventDispatcher.class));
bind(new TypeLiteral<EventDispatcher<NoVote>>() {
}).toInstance(rmock(EventDispatcher.class));
bind(new TypeLiteral<EventDispatcher<LedgerUpdate>>() {
}).toInstance(rmock(EventDispatcher.class));
bind(new TypeLiteral<ScheduledEventDispatcher<GetVerticesRequest>>() {
}).toInstance(timeoutScheduler);
bind(new TypeLiteral<ScheduledEventDispatcher<ScheduledLocalTimeout>>() {
}).toInstance(rmock(ScheduledEventDispatcher.class));
bind(new TypeLiteral<ScheduledEventDispatcher<Epoched<ScheduledLocalTimeout>>>() {
}).toInstance(rmock(ScheduledEventDispatcher.class));
bind(new TypeLiteral<ScheduledEventDispatcher<VertexRequestTimeout>>() {
}).toInstance(rmock(ScheduledEventDispatcher.class));
bind(new TypeLiteral<RemoteEventDispatcher<Proposal>>() {
}).toInstance(proposalDispatcher);
bind(new TypeLiteral<RemoteEventDispatcher<Vote>>() {
}).toInstance(voteDispatcher);
bind(new TypeLiteral<RemoteEventDispatcher<GetVerticesRequest>>() {
}).toInstance(rmock(RemoteEventDispatcher.class));
bind(new TypeLiteral<RemoteEventDispatcher<GetVerticesResponse>>() {
}).toInstance(rmock(RemoteEventDispatcher.class));
bind(new TypeLiteral<RemoteEventDispatcher<GetVerticesErrorResponse>>() {
}).toInstance(rmock(RemoteEventDispatcher.class));
bind(new TypeLiteral<RemoteEventDispatcher<LedgerStatusUpdate>>() {
}).toInstance(rmock(RemoteEventDispatcher.class));
bind(PersistentSafetyStateStore.class).toInstance(mock(PersistentSafetyStateStore.class));
bind(NextTxnsGenerator.class).toInstance(nextTxnsGenerator);
bind(SystemCounters.class).toInstance(new SystemCountersImpl());
bind(Mempool.class).toInstance(mempool);
bind(StateComputer.class).toInstance(stateComputer);
bind(PersistentVertexStore.class).toInstance(mock(PersistentVertexStore.class));
bind(RateLimiter.class).annotatedWith(GetVerticesRequestRateLimit.class).toInstance(RateLimiter.create(Double.MAX_VALUE));
bindConstant().annotatedWith(BFTSyncPatienceMillis.class).to(50);
bindConstant().annotatedWith(PacemakerTimeout.class).to(10L);
bindConstant().annotatedWith(PacemakerRate.class).to(2.0);
bindConstant().annotatedWith(PacemakerMaxExponent.class).to(0);
bind(TimeSupplier.class).toInstance(System::currentTimeMillis);
bind(new TypeLiteral<Consumer<EpochViewUpdate>>() {
}).toInstance(rmock(Consumer.class));
}
@Provides
private ViewUpdate view(BFTConfiguration bftConfiguration) {
HighQC highQC = bftConfiguration.getVertexStoreState().getHighQC();
View view = highQC.highestQC().getView().next();
return ViewUpdate.create(view, highQC, self, self);
}
@Provides
BFTValidatorSet validatorSet() {
return BFTValidatorSet.from(Stream.of(BFTValidator.from(self, UInt256.ONE)));
}
@Provides
@LastProof
LedgerProof verifiedLedgerHeaderAndProof(BFTValidatorSet validatorSet) {
var accumulatorState = new AccumulatorState(0, HashUtils.zero256());
return LedgerProof.genesis(accumulatorState, validatorSet, 0);
}
@Provides
@LastEpochProof
LedgerProof lastEpochProof(BFTValidatorSet validatorSet) {
var accumulatorState = new AccumulatorState(0, HashUtils.zero256());
return LedgerProof.genesis(accumulatorState, validatorSet, 0);
}
@Provides
BFTConfiguration bftConfiguration(@Self BFTNode self, Hasher hasher, BFTValidatorSet validatorSet) {
var accumulatorState = new AccumulatorState(0, HashUtils.zero256());
var unverifiedVertex = UnverifiedVertex.createGenesis(LedgerHeader.genesis(accumulatorState, validatorSet, 0));
var verifiedVertex = new VerifiedVertex(unverifiedVertex, hasher.hash(unverifiedVertex));
var qc = QuorumCertificate.ofGenesis(verifiedVertex, LedgerHeader.genesis(accumulatorState, validatorSet, 0));
var proposerElection = new WeightedRotatingLeaders(validatorSet);
return new BFTConfiguration(proposerElection, validatorSet, VerifiedVertexStoreState.create(HighQC.from(qc), verifiedVertex, Optional.empty(), hasher));
}
};
}
use of com.radixdlt.counters.SystemCountersImpl in project radixdlt by radixdlt.
the class GenerateUniverses method main.
public static void main(String[] args) throws Exception {
Security.insertProviderAt(new BouncyCastleProvider(), 1);
Options options = new Options();
options.addOption("h", "help", false, "Show usage information (this message)");
options.addOption("p", "public-keys", true, "Specify validator keys");
options.addOption("v", "validator-count", true, "Specify number of validators to generate");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
if (!cmd.getArgList().isEmpty()) {
System.err.println("Extra arguments: " + String.join(" ", cmd.getArgList()));
usage(options);
return;
}
if (cmd.hasOption('h')) {
usage(options);
return;
}
var validatorKeys = new HashSet<ECPublicKey>();
if (cmd.getOptionValue("p") != null) {
var hexKeys = cmd.getOptionValue("p").split(",");
for (var hexKey : hexKeys) {
validatorKeys.add(ECPublicKey.fromHex(hexKey));
}
}
final int validatorsCount = cmd.getOptionValue("v") != null ? Integer.parseInt(cmd.getOptionValue("v")) : 0;
var generatedValidatorKeys = PrivateKeys.numeric(6).limit(validatorsCount).toList();
generatedValidatorKeys.stream().map(ECKeyPair::getPublicKey).forEach(validatorKeys::add);
// Issuances to mnemomic account, keys 1-5, and 1st validator
final var mnemomicKey = ECPublicKey.fromHex(mnemomicKeyHex);
final ImmutableList.Builder<TokenIssuance> tokenIssuancesBuilder = ImmutableList.builder();
tokenIssuancesBuilder.add(TokenIssuance.of(mnemomicKey, DEFAULT_ISSUANCE));
PrivateKeys.numeric(1).limit(5).map(k -> TokenIssuance.of(k.getPublicKey(), DEFAULT_ISSUANCE)).forEach(tokenIssuancesBuilder::add);
// Issue tokens to initial validators for now to support application services
validatorKeys.forEach(pk -> tokenIssuancesBuilder.add(TokenIssuance.of(pk, DEFAULT_ISSUANCE)));
// Stakes issued by mnemomic account
var stakes = validatorKeys.stream().map(pk -> new StakeTokens(REAddr.ofPubKeyAccount(mnemomicKey), pk, DEFAULT_STAKE)).collect(Collectors.toSet());
var timestamp = String.valueOf(Instant.now().getEpochSecond());
var genesisProvider = Guice.createInjector(new AbstractModule() {
@Provides
@Singleton
RERules reRules(Forks forks) {
return forks.get(0);
}
@Override
protected void configure() {
install(new CryptoModule());
install(new MainnetForkConfigsModule());
install(new ForksModule());
bind(new TypeLiteral<List<TxAction>>() {
}).annotatedWith(Genesis.class).toInstance(List.of());
bind(LedgerAccumulator.class).to(SimpleLedgerAccumulatorAndVerifier.class);
bind(SystemCounters.class).toInstance(new SystemCountersImpl());
bindConstant().annotatedWith(Genesis.class).to(timestamp);
bind(new TypeLiteral<Set<StakeTokens>>() {
}).annotatedWith(Genesis.class).toInstance(stakes);
bind(new TypeLiteral<ImmutableList<TokenIssuance>>() {
}).annotatedWith(Genesis.class).toInstance(tokenIssuancesBuilder.build());
bind(new TypeLiteral<Set<ECPublicKey>>() {
}).annotatedWith(Genesis.class).toInstance(validatorKeys);
bindConstant().annotatedWith(MaxValidators.class).to(100);
OptionalBinder.newOptionalBinder(binder(), Key.get(new TypeLiteral<List<TxAction>>() {
}, Genesis.class));
}
}).getInstance(GenesisProvider.class);
var genesis = genesisProvider.get().getTxns().get(0);
IntStream.range(0, generatedValidatorKeys.size()).forEach(i -> {
System.out.format("export RADIXDLT_VALIDATOR_%s_PRIVKEY=%s%n", i, Bytes.toBase64String(generatedValidatorKeys.get(i).getPrivateKey()));
System.out.format("export RADIXDLT_VALIDATOR_%s_PUBKEY=%s%n", i, Addressing.ofNetwork(Network.LOCALNET).forNodes().of(generatedValidatorKeys.get(i).getPublicKey()));
});
if (validatorsCount > 0) {
System.out.format("export RADIXDLT_GENESIS_TXN=%s%n", Bytes.toHexString(genesis.getPayload()));
} else {
try (var writer = new BufferedWriter(new FileWriter("genesis.json"))) {
writer.write(new JSONObject().put("genesis", Bytes.toHexString(genesis.getPayload())).toString());
}
}
}
use of com.radixdlt.counters.SystemCountersImpl in project radixdlt by radixdlt.
the class MempoolRunnerTest method createModule.
@SuppressWarnings(// The mock method doesn't support type-safe generics due to type erasure
"unchecked")
public Module createModule() {
return new AbstractModule() {
@Override
public void configure() {
bind(BFTNode.class).annotatedWith(Self.class).toInstance(BFTNode.random());
bind(LedgerProof.class).annotatedWith(LastProof.class).toInstance(mock(LedgerProof.class));
bind(StateComputer.class).toInstance(stateComputer);
bind(SystemCounters.class).toInstance(new SystemCountersImpl());
bind(RxRemoteEnvironment.class).toInstance(new RxRemoteEnvironment() {
@Override
public <T> Flowable<RemoteEvent<T>> remoteEvents(Class<T> remoteEventClass) {
return Flowable.never();
}
});
bind(LedgerAccumulator.class).toInstance(mock(LedgerAccumulator.class));
bind(LedgerAccumulatorVerifier.class).toInstance(mock(LedgerAccumulatorVerifier.class));
bind(new TypeLiteral<Comparator<LedgerProof>>() {
}).toInstance(mock(Comparator.class));
bind(Addressing.class).toInstance(Addressing.ofNetwork(Network.LOCALNET));
bind(TimeSupplier.class).toInstance(System::currentTimeMillis);
Multibinder.newSetBinder(binder(), StartProcessorOnRunner.class);
install(MempoolConfig.asModule(100, 10));
install(new MockedKeyModule());
install(new MockedCryptoModule());
install(new RxEnvironmentModule());
install(new DispatcherModule());
install(new MempoolReceiverModule());
install(new EventLoggerModule());
}
};
}
Aggregations