Search in sources :

Example 1 with UInt256

use of com.radixdlt.utils.UInt256 in project radixdlt by radixdlt.

the class ValidationState method addSignature.

/**
 * Adds key and signature to our list of signing keys and signatures. Note that it is assumed that
 * signature validation is performed elsewhere.
 *
 * @param node The node
 * @param timestamp The timestamp of the signature
 * @param signature The signature to verify
 * @return whether the key was added or not
 */
public boolean addSignature(BFTNode node, long timestamp, ECDSASignature signature) {
    if (validatorSet.containsNode(node) && !this.signedNodes.containsKey(node)) {
        this.signedNodes.computeIfAbsent(node, k -> {
            UInt256 weight = this.validatorSet.getPower(node);
            this.signedPower = this.signedPower.add(weight);
            return TimestampedECDSASignature.from(timestamp, signature);
        });
        return true;
    }
    return false;
}
Also used : UInt256(com.radixdlt.utils.UInt256)

Example 2 with UInt256

use of com.radixdlt.utils.UInt256 in project radixdlt by radixdlt.

the class EpochManagerTest method should_not_send_consensus_messages_if_not_part_of_new_epoch.

@Test
public void should_not_send_consensus_messages_if_not_part_of_new_epoch() {
    // Arrange
    epochManager.start();
    BFTValidatorSet nextValidatorSet = BFTValidatorSet.from(Stream.of(BFTValidator.from(BFTNode.random(), UInt256.ONE)));
    var accumulatorState = new AccumulatorState(0, HashUtils.zero256());
    LedgerHeader header = LedgerHeader.genesis(accumulatorState, nextValidatorSet, 0);
    UnverifiedVertex genesisVertex = UnverifiedVertex.createGenesis(header);
    VerifiedVertex verifiedGenesisVertex = new VerifiedVertex(genesisVertex, hasher.hash(genesisVertex));
    LedgerHeader nextLedgerHeader = LedgerHeader.create(header.getEpoch() + 1, View.genesis(), header.getAccumulatorState(), header.timestamp());
    var genesisQC = QuorumCertificate.ofGenesis(verifiedGenesisVertex, nextLedgerHeader);
    var proposerElection = new WeightedRotatingLeaders(nextValidatorSet);
    var bftConfiguration = new BFTConfiguration(proposerElection, nextValidatorSet, VerifiedVertexStoreState.create(HighQC.from(genesisQC), verifiedGenesisVertex, Optional.empty(), hasher));
    LedgerProof proof = mock(LedgerProof.class);
    when(proof.getEpoch()).thenReturn(header.getEpoch() + 1);
    var epochChange = new EpochChange(proof, bftConfiguration);
    var ledgerUpdate = new LedgerUpdate(mock(VerifiedTxnsAndProof.class), ImmutableClassToInstanceMap.of(EpochChange.class, epochChange));
    // Act
    epochManager.epochsLedgerUpdateEventProcessor().process(ledgerUpdate);
    // Assert
    verify(proposalDispatcher, never()).dispatch(any(Iterable.class), argThat(p -> p.getEpoch() == epochChange.getEpoch()));
    verify(voteDispatcher, never()).dispatch(any(BFTNode.class), any());
}
Also used : LedgerUpdate(com.radixdlt.ledger.LedgerUpdate) Module(com.google.inject.Module) ScheduledLocalTimeout(com.radixdlt.consensus.liveness.ScheduledLocalTimeout) GetVerticesRequest(com.radixdlt.consensus.sync.GetVerticesRequest) EpochsConsensusModule(com.radixdlt.EpochsConsensusModule) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) Inject(com.google.inject.Inject) PacemakerTimeout(com.radixdlt.consensus.bft.PacemakerTimeout) Hasher(com.radixdlt.crypto.Hasher) HashSigner(com.radixdlt.consensus.HashSigner) BFTCommittedUpdate(com.radixdlt.consensus.bft.BFTCommittedUpdate) MempoolAdd(com.radixdlt.mempool.MempoolAdd) RemoteEventDispatcher(com.radixdlt.environment.RemoteEventDispatcher) VertexRequestTimeout(com.radixdlt.consensus.sync.VertexRequestTimeout) UnverifiedVertex(com.radixdlt.consensus.UnverifiedVertex) VerifiedTxnsAndProof(com.radixdlt.ledger.VerifiedTxnsAndProof) Map(java.util.Map) ViewQuorumReached(com.radixdlt.consensus.bft.ViewQuorumReached) LedgerProof(com.radixdlt.consensus.LedgerProof) View(com.radixdlt.consensus.bft.View) HashUtils(com.radixdlt.crypto.HashUtils) SystemCounters(com.radixdlt.counters.SystemCounters) LedgerModule(com.radixdlt.LedgerModule) WeightedRotatingLeaders(com.radixdlt.consensus.liveness.WeightedRotatingLeaders) PersistentSafetyStateStore(com.radixdlt.consensus.safety.PersistentSafetyStateStore) StateComputerResult(com.radixdlt.ledger.StateComputerLedger.StateComputerResult) StateComputer(com.radixdlt.ledger.StateComputerLedger.StateComputer) GetVerticesRequestRateLimit(com.radixdlt.middleware2.network.GetVerticesRequestRateLimit) BFTRebuildUpdate(com.radixdlt.consensus.bft.BFTRebuildUpdate) LedgerHeader(com.radixdlt.consensus.LedgerHeader) SystemCountersImpl(com.radixdlt.counters.SystemCountersImpl) List(java.util.List) Stream(java.util.stream.Stream) BFTHighQCUpdate(com.radixdlt.consensus.bft.BFTHighQCUpdate) PacemakerMaxExponent(com.radixdlt.consensus.bft.PacemakerMaxExponent) Optional(java.util.Optional) ImmutableClassToInstanceMap(com.google.common.collect.ImmutableClassToInstanceMap) TypeLiteral(com.google.inject.TypeLiteral) BFTSyncPatienceMillis(com.radixdlt.consensus.sync.BFTSyncPatienceMillis) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HighQC(com.radixdlt.consensus.HighQC) ScheduledEventDispatcher(com.radixdlt.environment.ScheduledEventDispatcher) Proposal(com.radixdlt.consensus.Proposal) LocalTimeoutOccurrence(com.radixdlt.consensus.liveness.LocalTimeoutOccurrence) BFTValidatorSet(com.radixdlt.consensus.bft.BFTValidatorSet) NextTxnsGenerator(com.radixdlt.consensus.liveness.NextTxnsGenerator) PreparedTxn(com.radixdlt.ledger.StateComputerLedger.PreparedTxn) RateLimiter(com.google.common.util.concurrent.RateLimiter) TypedMocks.rmock(com.radixdlt.utils.TypedMocks.rmock) LocalSyncRequest(com.radixdlt.sync.messages.local.LocalSyncRequest) LedgerStatusUpdate(com.radixdlt.sync.messages.remote.LedgerStatusUpdate) BFTValidator(com.radixdlt.consensus.bft.BFTValidator) CryptoModule(com.radixdlt.CryptoModule) Vote(com.radixdlt.consensus.Vote) LastEpochProof(com.radixdlt.store.LastEpochProof) BFTConfiguration(com.radixdlt.consensus.BFTConfiguration) ViewUpdate(com.radixdlt.consensus.bft.ViewUpdate) AccumulatorState(com.radixdlt.ledger.AccumulatorState) UInt256(com.radixdlt.utils.UInt256) Nullable(javax.annotation.Nullable) Before(org.junit.Before) TimeSupplier(com.radixdlt.utils.TimeSupplier) EventDispatcher(com.radixdlt.environment.EventDispatcher) ConsensusModule(com.radixdlt.ConsensusModule) Txn(com.radixdlt.atom.Txn) BFTInsertUpdate(com.radixdlt.consensus.bft.BFTInsertUpdate) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) VerifiedVertexStoreState(com.radixdlt.consensus.bft.VerifiedVertexStoreState) QuorumCertificate(com.radixdlt.consensus.QuorumCertificate) Mockito.verify(org.mockito.Mockito.verify) LedgerUpdate(com.radixdlt.ledger.LedgerUpdate) Consumer(java.util.function.Consumer) Mockito.never(org.mockito.Mockito.never) Provides(com.google.inject.Provides) VerifiedVertex(com.radixdlt.consensus.bft.VerifiedVertex) ECKeyPair(com.radixdlt.crypto.ECKeyPair) NoVote(com.radixdlt.consensus.bft.NoVote) PacemakerRate(com.radixdlt.consensus.bft.PacemakerRate) Self(com.radixdlt.consensus.bft.Self) Guice(com.google.inject.Guice) BFTNode(com.radixdlt.consensus.bft.BFTNode) PersistentVertexStore(com.radixdlt.consensus.bft.PersistentVertexStore) EpochLocalTimeoutOccurrence(com.radixdlt.consensus.liveness.EpochLocalTimeoutOccurrence) Mempool(com.radixdlt.mempool.Mempool) LastProof(com.radixdlt.store.LastProof) GetVerticesErrorResponse(com.radixdlt.consensus.sync.GetVerticesErrorResponse) GetVerticesResponse(com.radixdlt.consensus.sync.GetVerticesResponse) AbstractModule(com.google.inject.AbstractModule) BFTNode(com.radixdlt.consensus.bft.BFTNode) AccumulatorState(com.radixdlt.ledger.AccumulatorState) BFTValidatorSet(com.radixdlt.consensus.bft.BFTValidatorSet) UnverifiedVertex(com.radixdlt.consensus.UnverifiedVertex) VerifiedVertex(com.radixdlt.consensus.bft.VerifiedVertex) LedgerHeader(com.radixdlt.consensus.LedgerHeader) BFTConfiguration(com.radixdlt.consensus.BFTConfiguration) VerifiedTxnsAndProof(com.radixdlt.ledger.VerifiedTxnsAndProof) LedgerProof(com.radixdlt.consensus.LedgerProof) WeightedRotatingLeaders(com.radixdlt.consensus.liveness.WeightedRotatingLeaders) Test(org.junit.Test)

Example 3 with UInt256

use of com.radixdlt.utils.UInt256 in project radixdlt by radixdlt.

the class TokensConstraintScryptV3 method defineTokenCreation.

private void defineTokenCreation(Loader os) {
    os.procedure(new UpProcedure<>(SystemConstraintScrypt.REAddrClaim.class, TokenResource.class, u -> new Authorization(PermissionLevel.USER, (r, c) -> {
    }), (s, u, c, r) -> {
        if (!u.addr().equals(s.getAddr())) {
            throw new ProcedureException("Addresses don't match");
        }
        var str = new String(s.getArg());
        if (reservedSymbols.contains(str) && c.permissionLevel() != PermissionLevel.SYSTEM) {
            throw new ReservedSymbolException(str);
        }
        if (!tokenSymbolPattern.matcher(str).matches()) {
            throw new ProcedureException("invalid token symbol: " + str);
        }
        if (u.isMutable()) {
            return ReducerResult.incomplete(new NeedMetadata(s.getArg(), u));
        }
        if (!u.granularity().equals(UInt256.ONE)) {
            throw new ProcedureException("Granularity must be one.");
        }
        return ReducerResult.incomplete(new NeedFixedTokenSupply(s.getArg(), u));
    }));
    os.procedure(new UpProcedure<>(NeedFixedTokenSupply.class, TokensInAccount.class, u -> new Authorization(PermissionLevel.USER, (r, c) -> {
    }), (s, u, c, r) -> {
        if (!u.resourceAddr().equals(s.tokenResource.addr())) {
            throw new ProcedureException("Addresses don't match.");
        }
        return ReducerResult.incomplete(new NeedMetadata(s.arg, s.tokenResource));
    }));
    os.procedure(new UpProcedure<>(NeedMetadata.class, TokenResourceMetadata.class, u -> new Authorization(PermissionLevel.USER, (r, c) -> {
    }), (s, u, c, r) -> {
        s.metadata(u, c);
        return ReducerResult.complete();
    }));
}
Also used : SubstateTypeId(com.radixdlt.atom.SubstateTypeId) TokenResourceMetadata(com.radixdlt.application.tokens.state.TokenResourceMetadata) Loader(com.radixdlt.atomos.Loader) REFieldSerialization(com.radixdlt.atom.REFieldSerialization) TokenResource(com.radixdlt.application.tokens.state.TokenResource) Set(java.util.Set) TokensInAccount(com.radixdlt.application.tokens.state.TokensInAccount) SubstateDefinition(com.radixdlt.atomos.SubstateDefinition) StandardCharsets(java.nio.charset.StandardCharsets) com.radixdlt.constraintmachine(com.radixdlt.constraintmachine) ResourceCreatedEvent(com.radixdlt.constraintmachine.REEvent.ResourceCreatedEvent) ReservedSymbolException(com.radixdlt.constraintmachine.exceptions.ReservedSymbolException) SystemConstraintScrypt(com.radixdlt.application.system.scrypt.SystemConstraintScrypt) ConstraintScrypt(com.radixdlt.atomos.ConstraintScrypt) ProcedureException(com.radixdlt.constraintmachine.exceptions.ProcedureException) Pattern(java.util.regex.Pattern) DeserializeException(com.radixdlt.serialization.DeserializeException) UInt256(com.radixdlt.utils.UInt256) TokenResource(com.radixdlt.application.tokens.state.TokenResource) TokenResourceMetadata(com.radixdlt.application.tokens.state.TokenResourceMetadata) ReservedSymbolException(com.radixdlt.constraintmachine.exceptions.ReservedSymbolException) TokensInAccount(com.radixdlt.application.tokens.state.TokensInAccount) ProcedureException(com.radixdlt.constraintmachine.exceptions.ProcedureException)

Example 4 with UInt256

use of com.radixdlt.utils.UInt256 in project radixdlt by radixdlt.

the class MempoolHandlerTest method buildSignedTxn.

private Txn buildSignedTxn(REAddr from, REAddr to) throws Exception {
    final UInt256 toTransfer = getLiquidAmount().toSubunits().subtract(Amount.ofTokens(1).toSubunits());
    var entityOperationGroups = List.of(List.of(EntityOperation.from(new AccountVaultEntity(from), ResourceOperation.withdraw(new TokenResource("xrd", REAddr.ofNativeToken()), toTransfer)), EntityOperation.from(new AccountVaultEntity(to), ResourceOperation.deposit(new TokenResource("xrd", REAddr.ofNativeToken()), toTransfer))));
    var operationTxBuilder = new OperationTxBuilder(null, entityOperationGroups, currentForkView);
    var builder = radixEngine.constructWithFees(operationTxBuilder, false, from, NotEnoughNativeTokensForFeesException::new);
    return builder.signAndBuild(hashSigner::sign);
}
Also used : OperationTxBuilder(com.radixdlt.api.core.model.OperationTxBuilder) TokenResource(com.radixdlt.api.core.model.TokenResource) NotEnoughNativeTokensForFeesException(com.radixdlt.api.core.model.NotEnoughNativeTokensForFeesException) AccountVaultEntity(com.radixdlt.api.core.model.entities.AccountVaultEntity) UInt256(com.radixdlt.utils.UInt256)

Example 5 with UInt256

use of com.radixdlt.utils.UInt256 in project radixdlt by radixdlt.

the class ProposerLoadBalancedTest method when_run_100_nodes_with_very_large_period__then_proposals_should_be_proportional.

@Test
public void when_run_100_nodes_with_very_large_period__then_proposals_should_be_proportional() {
    final int numNodes = 100;
    final long numProposals = 1_000L;
    ImmutableList<UInt256> weights = generatePrimes(100).mapToObj(UInt256::from).collect(ImmutableList.toImmutableList());
    UInt256 sum = weights.stream().reduce(UInt256.ZERO, UInt256::add);
    UInt256 numViews256 = UInt256.from(numProposals);
    long[] values = weights.stream().map(w -> w.multiply(numViews256).divide(sum)).mapToLong(v -> v.getLow().getLow()).toArray();
    ImmutableList<Long> proposals = this.run(numNodes, numProposals, EpochNodeWeightMapping.computed(numNodes, weights::get));
    // Correct number of total proposals
    assertThat(proposals.stream().mapToLong(Long::longValue).sum()).isEqualTo(numProposals);
    // Same as calculated value, +/- 1 (rounding and ordering)
    for (int i = 0; i < values.length; ++i) {
        assertThat(proposals.get(i).longValue()).isBetween(values[i] - 1, values[i] + 1);
    }
}
Also used : IntStream(java.util.stream.IntStream) EpochNodeWeightMapping(com.radixdlt.harness.deterministic.configuration.EpochNodeWeightMapping) LongStream(java.util.stream.LongStream) ScheduledLocalTimeout(com.radixdlt.hotstuff.liveness.ScheduledLocalTimeout) Test(org.junit.Test) DeterministicTest(com.radixdlt.harness.deterministic.DeterministicTest) Epoched(com.radixdlt.hotstuff.epoch.Epoched) List(java.util.List) View(com.radixdlt.hotstuff.bft.View) ImmutableList(com.google.common.collect.ImmutableList) MessageSelector(com.radixdlt.environment.deterministic.network.MessageSelector) Condition(org.assertj.core.api.Condition) Assertions(org.assertj.core.api.Assertions) MessageMutator(com.radixdlt.environment.deterministic.network.MessageMutator) CounterType(com.radixdlt.counters.SystemCounters.CounterType) UInt256(com.radixdlt.utils.UInt256) UInt256(com.radixdlt.utils.UInt256) Test(org.junit.Test) DeterministicTest(com.radixdlt.harness.deterministic.DeterministicTest)

Aggregations

UInt256 (com.radixdlt.utils.UInt256)19 Test (org.junit.Test)9 ImmutableList (com.google.common.collect.ImmutableList)8 ECKeyPair (com.radixdlt.crypto.ECKeyPair)7 Stream (java.util.stream.Stream)7 View (com.radixdlt.hotstuff.bft.View)6 List (java.util.List)6 Map (java.util.Map)6 IntStream (java.util.stream.IntStream)6 Inject (com.google.inject.Inject)4 NotEnoughNativeTokensForFeesException (com.radixdlt.api.core.model.NotEnoughNativeTokensForFeesException)4 OperationTxBuilder (com.radixdlt.api.core.model.OperationTxBuilder)4 TokenResource (com.radixdlt.api.core.model.TokenResource)4 AccountVaultEntity (com.radixdlt.api.core.model.entities.AccountVaultEntity)4 Supplier (java.util.function.Supplier)4 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)4 AbstractModule (com.google.inject.AbstractModule)3 Guice (com.google.inject.Guice)3 Module (com.google.inject.Module)3 TypeLiteral (com.google.inject.TypeLiteral)3