Search in sources :

Example 6 with ECPublicKey

use of com.radixdlt.crypto.ECPublicKey in project radixdlt by radixdlt.

the class MessageCentralBFTNetworkTest method when_send_vote__then_message_central_should_be_sent_vote_message.

@Test
public void when_send_vote__then_message_central_should_be_sent_vote_message() {
    Vote vote = mock(Vote.class);
    ECPublicKey leaderPk = ECKeyPair.generateNew().getPublicKey();
    BFTNode leader = mock(BFTNode.class);
    when(leader.getKey()).thenReturn(leaderPk);
    network.voteDispatcher().dispatch(leader, vote);
    verify(messageCentral, times(1)).send(eq(NodeId.fromPublicKey(leaderPk)), any(ConsensusEventMessage.class));
}
Also used : BFTNode(com.radixdlt.hotstuff.bft.BFTNode) Vote(com.radixdlt.hotstuff.Vote) ECPublicKey(com.radixdlt.crypto.ECPublicKey) Test(org.junit.Test)

Example 7 with ECPublicKey

use of com.radixdlt.crypto.ECPublicKey in project radixdlt by radixdlt.

the class MessageCentralValidatorSyncTest method when_send_response__then_message_central_will_send_response.

@Test
public void when_send_response__then_message_central_will_send_response() {
    VerifiedVertex vertex = mock(VerifiedVertex.class);
    when(vertex.toSerializable()).thenReturn(mock(UnverifiedVertex.class));
    ImmutableList<VerifiedVertex> vertices = ImmutableList.of(vertex);
    BFTNode node = mock(BFTNode.class);
    ECPublicKey ecPublicKey = mock(ECPublicKey.class);
    when(node.getKey()).thenReturn(ecPublicKey);
    sync.verticesResponseDispatcher().dispatch(node, new GetVerticesResponse(vertices));
    verify(messageCentral, times(1)).send(any(), any(GetVerticesResponseMessage.class));
}
Also used : VerifiedVertex(com.radixdlt.hotstuff.bft.VerifiedVertex) BFTNode(com.radixdlt.hotstuff.bft.BFTNode) GetVerticesResponse(com.radixdlt.hotstuff.sync.GetVerticesResponse) ECPublicKey(com.radixdlt.crypto.ECPublicKey) UnverifiedVertex(com.radixdlt.hotstuff.UnverifiedVertex) Test(org.junit.Test)

Example 8 with ECPublicKey

use of com.radixdlt.crypto.ECPublicKey in project radixdlt by radixdlt.

the class SimulationNodes method createBFTModule.

private Module createBFTModule(ECKeyPair self) {
    Module module = Modules.combine(new AbstractModule() {

        @Provides
        @Self
        private BFTNode self() {
            return BFTNode.create(self.getPublicKey());
        }

        @Provides
        @Self
        private ECPublicKey key() {
            return self.getPublicKey();
        }

        @Provides
        private ECKeyPair keyPair() {
            return self;
        }

        @Provides
        @LocalSigner
        HashSigner hashSigner() {
            return self::sign;
        }
    }, new NodeNetworkMessagesModule(underlyingNetwork), baseModule);
    // can break network behavior if incorrect modules are used
    if (overrideModules.containsKey(self.getPublicKey())) {
        final var nodeOverrideModules = overrideModules.get(self.getPublicKey());
        module = Modules.override(module).with(nodeOverrideModules);
    }
    return module;
}
Also used : BFTNode(com.radixdlt.hotstuff.bft.BFTNode) ECPublicKey(com.radixdlt.crypto.ECPublicKey) LocalSigner(com.radixdlt.qualifier.LocalSigner) NodeNetworkMessagesModule(com.radixdlt.harness.simulation.NodeNetworkMessagesModule) ECKeyPair(com.radixdlt.crypto.ECKeyPair) HashSigner(com.radixdlt.hotstuff.HashSigner) Self(com.radixdlt.hotstuff.bft.Self) Module(com.google.inject.Module) NodeNetworkMessagesModule(com.radixdlt.harness.simulation.NodeNetworkMessagesModule) AbstractModule(com.google.inject.AbstractModule) Provides(com.google.inject.Provides) AbstractModule(com.google.inject.AbstractModule)

Example 9 with ECPublicKey

use of com.radixdlt.crypto.ECPublicKey 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() {

        @Override
        protected void configure() {
            install(new CryptoModule());
            install(new AbstractModule() {

                @Provides
                @Singleton
                private Forks forks(Set<ForkBuilder> forkBuilders) {
                    return Forks.create(forkBuilders.stream().map(ForkBuilder::build).collect(Collectors.toSet()));
                }

                @Provides
                @Singleton
                private CurrentForkView currentForkView(Forks forks) {
                    return new CurrentForkView(forks, forks.genesisFork());
                }

                @Provides
                @Singleton
                @NewestForkConfig
                private ForkConfig newestForkConfig(Forks forks) {
                    return forks.newestFork();
                }
            });
            install(new MainnetForksModule());
            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());
        }
    }
}
Also used : IntStream(java.util.stream.IntStream) CryptoModule(com.radixdlt.modules.CryptoModule) SimpleLedgerAccumulatorAndVerifier(com.radixdlt.ledger.SimpleLedgerAccumulatorAndVerifier) TxAction(com.radixdlt.atom.TxAction) Key(com.google.inject.Key) MaxValidators(com.radixdlt.statecomputer.MaxValidators) Options(org.apache.commons.cli.Options) Security(java.security.Security) ForkBuilder(com.radixdlt.statecomputer.forks.ForkBuilder) Forks(com.radixdlt.statecomputer.forks.Forks) HelpFormatter(org.apache.commons.cli.HelpFormatter) ECPublicKey(com.radixdlt.crypto.ECPublicKey) DefaultParser(org.apache.commons.cli.DefaultParser) HashSet(java.util.HashSet) JSONObject(org.json.JSONObject) ImmutableList(com.google.common.collect.ImmutableList) CurrentForkView(com.radixdlt.statecomputer.forks.CurrentForkView) ForkConfig(com.radixdlt.statecomputer.forks.ForkConfig) CommandLine(org.apache.commons.cli.CommandLine) UInt256(com.radixdlt.utils.UInt256) Genesis(com.radixdlt.statecomputer.checkpoint.Genesis) PrivateKeys(com.radixdlt.utils.PrivateKeys) SystemCounters(com.radixdlt.counters.SystemCounters) Addressing(com.radixdlt.networks.Addressing) NewestForkConfig(com.radixdlt.statecomputer.forks.NewestForkConfig) Network(com.radixdlt.networks.Network) CommandLineParser(org.apache.commons.cli.CommandLineParser) BufferedWriter(java.io.BufferedWriter) FileWriter(java.io.FileWriter) GenesisProvider(com.radixdlt.statecomputer.checkpoint.GenesisProvider) Set(java.util.Set) REAddr(com.radixdlt.identifiers.REAddr) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) SystemCountersImpl(com.radixdlt.counters.SystemCountersImpl) List(java.util.List) Provides(com.google.inject.Provides) ECKeyPair(com.radixdlt.crypto.ECKeyPair) Bytes(com.radixdlt.utils.Bytes) MainnetForksModule(com.radixdlt.statecomputer.forks.modules.MainnetForksModule) OptionalBinder(com.google.inject.multibindings.OptionalBinder) Guice(com.google.inject.Guice) Amount(com.radixdlt.application.tokens.Amount) TypeLiteral(com.google.inject.TypeLiteral) LedgerAccumulator(com.radixdlt.ledger.LedgerAccumulator) AbstractModule(com.google.inject.AbstractModule) Singleton(com.google.inject.Singleton) Options(org.apache.commons.cli.Options) HashSet(java.util.HashSet) Set(java.util.Set) CurrentForkView(com.radixdlt.statecomputer.forks.CurrentForkView) ImmutableList(com.google.common.collect.ImmutableList) FileWriter(java.io.FileWriter) BufferedWriter(java.io.BufferedWriter) TypeLiteral(com.google.inject.TypeLiteral) MainnetForksModule(com.radixdlt.statecomputer.forks.modules.MainnetForksModule) TxAction(com.radixdlt.atom.TxAction) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) CommandLineParser(org.apache.commons.cli.CommandLineParser) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) DefaultParser(org.apache.commons.cli.DefaultParser) HashSet(java.util.HashSet) Forks(com.radixdlt.statecomputer.forks.Forks) MaxValidators(com.radixdlt.statecomputer.MaxValidators) ForkConfig(com.radixdlt.statecomputer.forks.ForkConfig) NewestForkConfig(com.radixdlt.statecomputer.forks.NewestForkConfig) LedgerAccumulator(com.radixdlt.ledger.LedgerAccumulator) CryptoModule(com.radixdlt.modules.CryptoModule) SystemCounters(com.radixdlt.counters.SystemCounters) NewestForkConfig(com.radixdlt.statecomputer.forks.NewestForkConfig) Provides(com.google.inject.Provides) ForkBuilder(com.radixdlt.statecomputer.forks.ForkBuilder) AbstractModule(com.google.inject.AbstractModule) CommandLine(org.apache.commons.cli.CommandLine) JSONObject(org.json.JSONObject) Singleton(com.google.inject.Singleton) SystemCountersImpl(com.radixdlt.counters.SystemCountersImpl) Genesis(com.radixdlt.statecomputer.checkpoint.Genesis)

Example 10 with ECPublicKey

use of com.radixdlt.crypto.ECPublicKey in project radixdlt by radixdlt.

the class ValidatorRegisterConstraintScrypt method main.

@Override
public void main(Loader os) {
    os.substate(new SubstateDefinition<>(ValidatorRegisteredCopy.class, SubstateTypeId.VALIDATOR_REGISTERED_FLAG_COPY.id(), buf -> {
        REFieldSerialization.deserializeReservedByte(buf);
        var epochUpdate = REFieldSerialization.deserializeOptionalNonNegativeLong(buf);
        var key = REFieldSerialization.deserializeKey(buf);
        var flag = REFieldSerialization.deserializeBoolean(buf);
        return new ValidatorRegisteredCopy(epochUpdate, key, flag);
    }, (s, buf) -> {
        REFieldSerialization.serializeReservedByte(buf);
        REFieldSerialization.serializeOptionalLong(buf, s.epochUpdate());
        REFieldSerialization.serializeKey(buf, s.validatorKey());
        buf.put((byte) (s.isRegistered() ? 1 : 0));
    }, buf -> REFieldSerialization.deserializeKey(buf), (k, buf) -> REFieldSerialization.serializeKey(buf, (ECPublicKey) k), k -> new ValidatorRegisteredCopy(OptionalLong.empty(), (ECPublicKey) k, false)));
    os.procedure(new DownProcedure<>(VoidReducerState.class, ValidatorRegisteredCopy.class, d -> new Authorization(PermissionLevel.USER, (r, c) -> {
        if (!c.key().map(d.validatorKey()::equals).orElse(false)) {
            throw new AuthorizationException("Key does not match.");
        }
    }), (d, s, r, c) -> {
        return ReducerResult.incomplete(new UpdatingRegisteredNeedToReadEpoch(d.validatorKey()));
    }));
    os.procedure(new ReadProcedure<>(UpdatingRegisteredNeedToReadEpoch.class, EpochData.class, u -> new Authorization(PermissionLevel.USER, (r, c) -> {
    }), (s, u, r) -> ReducerResult.incomplete(s.readEpoch(u))));
    os.procedure(new UpProcedure<>(UpdatingRegistered.class, ValidatorRegisteredCopy.class, u -> new Authorization(PermissionLevel.USER, (r, c) -> {
    }), (s, u, c, r) -> {
        s.update(u);
        return ReducerResult.complete();
    }));
}
Also used : SubstateTypeId(com.radixdlt.atom.SubstateTypeId) AuthorizationException(com.radixdlt.constraintmachine.exceptions.AuthorizationException) ReducerResult(com.radixdlt.constraintmachine.ReducerResult) ReadProcedure(com.radixdlt.constraintmachine.ReadProcedure) VoidReducerState(com.radixdlt.constraintmachine.VoidReducerState) Loader(com.radixdlt.atomos.Loader) ReducerState(com.radixdlt.constraintmachine.ReducerState) REFieldSerialization(com.radixdlt.atom.REFieldSerialization) ValidatorRegisteredCopy(com.radixdlt.application.validators.state.ValidatorRegisteredCopy) Authorization(com.radixdlt.constraintmachine.Authorization) SubstateDefinition(com.radixdlt.atomos.SubstateDefinition) PermissionLevel(com.radixdlt.constraintmachine.PermissionLevel) ECPublicKey(com.radixdlt.crypto.ECPublicKey) OptionalLong(java.util.OptionalLong) UpProcedure(com.radixdlt.constraintmachine.UpProcedure) ConstraintScrypt(com.radixdlt.atomos.ConstraintScrypt) DownProcedure(com.radixdlt.constraintmachine.DownProcedure) ProcedureException(com.radixdlt.constraintmachine.exceptions.ProcedureException) EpochData(com.radixdlt.application.system.state.EpochData) EpochData(com.radixdlt.application.system.state.EpochData) VoidReducerState(com.radixdlt.constraintmachine.VoidReducerState) AuthorizationException(com.radixdlt.constraintmachine.exceptions.AuthorizationException) Authorization(com.radixdlt.constraintmachine.Authorization) ValidatorRegisteredCopy(com.radixdlt.application.validators.state.ValidatorRegisteredCopy)

Aggregations

ECPublicKey (com.radixdlt.crypto.ECPublicKey)13 REFieldSerialization (com.radixdlt.atom.REFieldSerialization)5 SubstateTypeId (com.radixdlt.atom.SubstateTypeId)5 ConstraintScrypt (com.radixdlt.atomos.ConstraintScrypt)5 Loader (com.radixdlt.atomos.Loader)5 SubstateDefinition (com.radixdlt.atomos.SubstateDefinition)5 ProcedureException (com.radixdlt.constraintmachine.exceptions.ProcedureException)5 BFTNode (com.radixdlt.hotstuff.bft.BFTNode)5 EpochData (com.radixdlt.application.system.state.EpochData)4 Authorization (com.radixdlt.constraintmachine.Authorization)4 DownProcedure (com.radixdlt.constraintmachine.DownProcedure)4 PermissionLevel (com.radixdlt.constraintmachine.PermissionLevel)4 ReducerResult (com.radixdlt.constraintmachine.ReducerResult)4 ReducerState (com.radixdlt.constraintmachine.ReducerState)4 UpProcedure (com.radixdlt.constraintmachine.UpProcedure)4 VoidReducerState (com.radixdlt.constraintmachine.VoidReducerState)4 AbstractModule (com.google.inject.AbstractModule)3 Provides (com.google.inject.Provides)3 ReadProcedure (com.radixdlt.constraintmachine.ReadProcedure)3 AuthorizationException (com.radixdlt.constraintmachine.exceptions.AuthorizationException)3