Search in sources :

Example 11 with UInt256

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

the class ConstructionParseTransferTest method buildUnsignedTransferTxn.

private byte[] buildUnsignedTransferTxn(REAddr from, REAddr to) throws Exception {
    final UInt256 toTransfer = transferAmount();
    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);
    var unsignedTransaction = builder.buildForExternalSign();
    return unsignedTransaction.blob();
}
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 12 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) BFTHighQCUpdate(com.radixdlt.hotstuff.bft.BFTHighQCUpdate) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) Inject(com.google.inject.Inject) PersistentSafetyStateStore(com.radixdlt.hotstuff.safety.PersistentSafetyStateStore) Hasher(com.radixdlt.crypto.Hasher) HighQC(com.radixdlt.hotstuff.HighQC) EpochLocalTimeoutOccurrence(com.radixdlt.hotstuff.liveness.EpochLocalTimeoutOccurrence) VerifiedVertexStoreState(com.radixdlt.hotstuff.bft.VerifiedVertexStoreState) MempoolAdd(com.radixdlt.mempool.MempoolAdd) RemoteEventDispatcher(com.radixdlt.environment.RemoteEventDispatcher) QuorumCertificate(com.radixdlt.hotstuff.QuorumCertificate) LedgerHeader(com.radixdlt.hotstuff.LedgerHeader) EpochsConsensusModule(com.radixdlt.modules.EpochsConsensusModule) VerifiedTxnsAndProof(com.radixdlt.ledger.VerifiedTxnsAndProof) Map(java.util.Map) PersistentVertexStore(com.radixdlt.hotstuff.bft.PersistentVertexStore) PacemakerTimeout(com.radixdlt.hotstuff.bft.PacemakerTimeout) GetVerticesErrorResponse(com.radixdlt.hotstuff.sync.GetVerticesErrorResponse) BFTRebuildUpdate(com.radixdlt.hotstuff.bft.BFTRebuildUpdate) HashUtils(com.radixdlt.crypto.HashUtils) BFTSyncPatienceMillis(com.radixdlt.hotstuff.sync.BFTSyncPatienceMillis) BFTInsertUpdate(com.radixdlt.hotstuff.bft.BFTInsertUpdate) SystemCounters(com.radixdlt.counters.SystemCounters) Vote(com.radixdlt.hotstuff.Vote) ConsensusModule(com.radixdlt.modules.ConsensusModule) NextTxnsGenerator(com.radixdlt.hotstuff.liveness.NextTxnsGenerator) StateComputerResult(com.radixdlt.ledger.StateComputerLedger.StateComputerResult) VerifiedVertex(com.radixdlt.hotstuff.bft.VerifiedVertex) ViewUpdate(com.radixdlt.hotstuff.bft.ViewUpdate) StateComputer(com.radixdlt.ledger.StateComputerLedger.StateComputer) GetVerticesRequestRateLimit(com.radixdlt.middleware2.network.GetVerticesRequestRateLimit) PacemakerRate(com.radixdlt.hotstuff.bft.PacemakerRate) SystemCountersImpl(com.radixdlt.counters.SystemCountersImpl) List(java.util.List) Stream(java.util.stream.Stream) PacemakerMaxExponent(com.radixdlt.hotstuff.bft.PacemakerMaxExponent) LedgerModule(com.radixdlt.modules.LedgerModule) Optional(java.util.Optional) ImmutableClassToInstanceMap(com.google.common.collect.ImmutableClassToInstanceMap) TypeLiteral(com.google.inject.TypeLiteral) Proposal(com.radixdlt.hotstuff.Proposal) ViewQuorumReached(com.radixdlt.hotstuff.bft.ViewQuorumReached) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BFTCommittedUpdate(com.radixdlt.hotstuff.bft.BFTCommittedUpdate) CryptoModule(com.radixdlt.modules.CryptoModule) BFTValidatorSet(com.radixdlt.hotstuff.bft.BFTValidatorSet) ScheduledEventDispatcher(com.radixdlt.environment.ScheduledEventDispatcher) LedgerProof(com.radixdlt.hotstuff.LedgerProof) WeightedRotatingLeaders(com.radixdlt.hotstuff.liveness.WeightedRotatingLeaders) GetVerticesResponse(com.radixdlt.hotstuff.sync.GetVerticesResponse) PreparedTxn(com.radixdlt.ledger.StateComputerLedger.PreparedTxn) RateLimiter(com.google.common.util.concurrent.RateLimiter) TypedMocks.rmock(com.radixdlt.utils.TypedMocks.rmock) HashSigner(com.radixdlt.hotstuff.HashSigner) LocalSyncRequest(com.radixdlt.sync.messages.local.LocalSyncRequest) LedgerStatusUpdate(com.radixdlt.sync.messages.remote.LedgerStatusUpdate) View(com.radixdlt.hotstuff.bft.View) LastEpochProof(com.radixdlt.store.LastEpochProof) BFTConfiguration(com.radixdlt.hotstuff.BFTConfiguration) 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) ScheduledLocalTimeout(com.radixdlt.hotstuff.liveness.ScheduledLocalTimeout) NoVote(com.radixdlt.hotstuff.bft.NoVote) Txn(com.radixdlt.atom.Txn) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) UnverifiedVertex(com.radixdlt.hotstuff.UnverifiedVertex) BFTNode(com.radixdlt.hotstuff.bft.BFTNode) VertexRequestTimeout(com.radixdlt.hotstuff.sync.VertexRequestTimeout) LedgerUpdate(com.radixdlt.ledger.LedgerUpdate) Consumer(java.util.function.Consumer) Mockito.never(org.mockito.Mockito.never) Provides(com.google.inject.Provides) ECKeyPair(com.radixdlt.crypto.ECKeyPair) GetVerticesRequest(com.radixdlt.hotstuff.sync.GetVerticesRequest) BFTValidator(com.radixdlt.hotstuff.bft.BFTValidator) LocalTimeoutOccurrence(com.radixdlt.hotstuff.liveness.LocalTimeoutOccurrence) Guice(com.google.inject.Guice) Self(com.radixdlt.hotstuff.bft.Self) Mempool(com.radixdlt.mempool.Mempool) LastProof(com.radixdlt.store.LastProof) AbstractModule(com.google.inject.AbstractModule) BFTNode(com.radixdlt.hotstuff.bft.BFTNode) AccumulatorState(com.radixdlt.ledger.AccumulatorState) BFTValidatorSet(com.radixdlt.hotstuff.bft.BFTValidatorSet) UnverifiedVertex(com.radixdlt.hotstuff.UnverifiedVertex) VerifiedVertex(com.radixdlt.hotstuff.bft.VerifiedVertex) LedgerHeader(com.radixdlt.hotstuff.LedgerHeader) BFTConfiguration(com.radixdlt.hotstuff.BFTConfiguration) VerifiedTxnsAndProof(com.radixdlt.ledger.VerifiedTxnsAndProof) LedgerProof(com.radixdlt.hotstuff.LedgerProof) WeightedRotatingLeaders(com.radixdlt.hotstuff.liveness.WeightedRotatingLeaders) Test(org.junit.Test)

Example 13 with UInt256

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

the class WeightedRotatingLeadersTest method when_validators_distributed_by_fibonacci__then_leaders_also_distributed_in_fibonacci.

@Test
public void when_validators_distributed_by_fibonacci__then_leaders_also_distributed_in_fibonacci() {
    // fibonacci sequence can quickly explode so keep sizes small
    final int validatorSetSize = 8;
    final int sizeOfCache = 4;
    final Supplier<IntStream> fibonacci = () -> Stream.iterate(new int[] { 1, 1 }, t -> new int[] { t[1], t[0] + t[1] }).mapToInt(t -> t[0]).limit(validatorSetSize);
    final int sumOfPower = fibonacci.get().sum();
    this.validatorsInOrder = fibonacci.get().mapToObj(p -> BFTValidator.from(BFTNode.random(), UInt256.from(p))).collect(ImmutableList.toImmutableList());
    BFTValidatorSet validatorSet = BFTValidatorSet.from(validatorsInOrder);
    this.weightedRotatingLeaders = new WeightedRotatingLeaders(validatorSet, sizeOfCache);
    Map<BFTNode, UInt256> proposerCounts = Stream.iterate(View.of(0), View::next).limit(sumOfPower).map(this.weightedRotatingLeaders::getProposer).collect(groupingBy(p -> p, collectingAndThen(counting(), UInt256::from)));
    Map<BFTNode, UInt256> expected = validatorsInOrder.stream().collect(toMap(BFTValidator::getNode, BFTValidator::getPower));
    assertThat(proposerCounts).isEqualTo(expected);
}
Also used : IntStream(java.util.stream.IntStream) BFTValidatorSet(com.radixdlt.hotstuff.bft.BFTValidatorSet) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Collectors.counting(java.util.stream.Collectors.counting) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) Test(org.junit.Test) Collectors.collectingAndThen(java.util.stream.Collectors.collectingAndThen) Supplier(java.util.function.Supplier) BFTNode(com.radixdlt.hotstuff.bft.BFTNode) ECKeyPair(com.radixdlt.crypto.ECKeyPair) View(com.radixdlt.hotstuff.bft.View) Stream(java.util.stream.Stream) Collectors.toMap(java.util.stream.Collectors.toMap) ImmutableList(com.google.common.collect.ImmutableList) BFTValidator(com.radixdlt.hotstuff.bft.BFTValidator) Map(java.util.Map) KeyComparator(com.radixdlt.utils.KeyComparator) Comparator(java.util.Comparator) UInt256(com.radixdlt.utils.UInt256) BFTNode(com.radixdlt.hotstuff.bft.BFTNode) BFTValidatorSet(com.radixdlt.hotstuff.bft.BFTValidatorSet) IntStream(java.util.stream.IntStream) UInt256(com.radixdlt.utils.UInt256) Test(org.junit.Test)

Example 14 with UInt256

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

the class ProposerLoadBalancedTest method when_run_3_nodes_with_large_lcm_weighting__then_proposals_should_be_proportional.

@Test
public void when_run_3_nodes_with_large_lcm_weighting__then_proposals_should_be_proportional() {
    final int numNodes = 3;
    final long numProposals = 100_000L;
    ImmutableList<UInt256> weights = ImmutableList.of(// Some large primes with product/LCM > 2^64 but < 2^256
    UInt256.from("941083981"), UInt256.from("961748927"), UInt256.from("982451653"));
    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)

Example 15 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)

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