Java Code Examples for com.google.common.primitives.UnsignedLong#ZERO

The following examples show how to use com.google.common.primitives.UnsignedLong#ZERO . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Generator.java    From teku with Apache License 2.0 6 votes vote down vote up
String getCommittees(BeaconState state) {
  UnsignedLong cnt = get_committee_count_at_slot(state, state.getSlot());
  List<List<Integer>> committees = new ArrayList<>();
  for (UnsignedLong index = UnsignedLong.ZERO;
      index.compareTo(cnt) < 0;
      index = index.plus(UnsignedLong.ONE)) {

    committees.add(get_beacon_committee(state, state.getSlot(), index));
  }

  return "["
      + committees.stream()
          .map(com -> com.stream().map(i -> "" + i).collect(Collectors.joining(",")))
          .collect(Collectors.joining("],["))
      + "]";
}
 
Example 2
Source File: AttestationTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeDependentOnSingleBlockWhenTargetBlockAndBeaconBlockRootAreEqual() {
  final Bytes32 root = Bytes32.fromHexString("0x01");

  final Attestation attestation =
      new Attestation(
          aggregationBitfield,
          new AttestationData(
              UnsignedLong.valueOf(1),
              UnsignedLong.ZERO,
              root,
              new Checkpoint(UnsignedLong.ONE, Bytes32.ZERO),
              new Checkpoint(UnsignedLong.valueOf(10), root)),
          BLSSignature.empty());

  assertThat(attestation.getDependentBlockRoots()).containsExactlyInAnyOrder(root);
}
 
Example 3
Source File: PostDutiesTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHandleMissingResultForFinalizedEpoch() throws Exception {
  final UnsignedLong epoch = UnsignedLong.ZERO;
  final String body =
      String.format("{\"epoch\":%s, \"pubkeys\":[\"%s\"]}", epoch, pubKeys.get(0));

  PostDuties handler = new PostDuties(provider, jsonProvider);
  when(provider.isStoreAvailable()).thenReturn(true);
  when(context.body()).thenReturn(body);
  when(provider.isEpochFinalized(epoch)).thenReturn(true);
  when(provider.getValidatorDutiesByRequest(any()))
      .thenReturn(SafeFuture.completedFuture(Optional.empty()));
  handler.handle(context);

  verify(context).result(args.capture());
  verify(context).header(Header.CACHE_CONTROL, CACHE_NONE);
  verify(context).status(SC_GONE);
  SafeFuture<String> data = args.getValue();
  assertThat(data.get()).isNull();
}
 
Example 4
Source File: CommitteeAssignmentUtil.java    From teku with Apache License 2.0 6 votes vote down vote up
/**
 * Return the committee assignment in the ``epoch`` for ``validator_index``. ``assignment``
 * returned is a tuple of the following form: ``assignment[0]`` is the list of validators in the
 * committee ``assignment[1]`` is the index to which the committee is assigned ``assignment[2]``
 * is the slot at which the committee is assigned Return None if no assignment.
 *
 * @param state the BeaconState.
 * @param epoch either on or between previous or current epoch.
 * @param validator_index the validator that is calling this function.
 * @return Optional.of(CommitteeAssignment).
 */
public static Optional<CommitteeAssignment> get_committee_assignment(
    BeaconState state, UnsignedLong epoch, int validator_index) {
  UnsignedLong next_epoch = get_current_epoch(state).plus(UnsignedLong.ONE);
  checkArgument(
      epoch.compareTo(next_epoch) <= 0, "get_committee_assignment: Epoch number too high");

  UnsignedLong start_slot = compute_start_slot_at_epoch(epoch);

  for (UnsignedLong slot = start_slot;
      slot.compareTo(start_slot.plus(UnsignedLong.valueOf(SLOTS_PER_EPOCH))) < 0;
      slot = slot.plus(UnsignedLong.ONE)) {

    final UnsignedLong committeeCountAtSlot = get_committee_count_at_slot(state, slot);
    for (UnsignedLong index = UnsignedLong.ZERO;
        index.compareTo(committeeCountAtSlot) < 0;
        index = index.plus(UnsignedLong.ONE)) {
      final List<Integer> committee = get_beacon_committee(state, slot, index);
      if (committee.contains(validator_index)) {
        return Optional.of(new CommitteeAssignment(committee, index, slot));
      }
    }
  }
  return Optional.empty();
}
 
Example 5
Source File: SimpleOffsetSerializer.java    From teku with Apache License 2.0 6 votes vote down vote up
public static Bytes serializeVariableCompositeList(
    SSZList<? extends SimpleOffsetSerializable> values) {
  List<Bytes> parts =
      values.stream().map(SimpleOffsetSerializer::serialize).collect(Collectors.toList());
  List<UnsignedLong> fixed_lengths = Collections.nCopies(values.size(), BYTES_PER_LENGTH_OFFSET);
  List<Bytes> variable_parts = new ArrayList<>();
  List<Bytes> fixed_parts = new ArrayList<>();
  UnsignedLong offset = UnsignedLong.ZERO;
  for (UnsignedLong length : fixed_lengths) {
    offset = offset.plus(length);
  }
  for (Bytes part : parts) {
    fixed_parts.add(SSZ.encodeUInt32(offset.longValue()));
    variable_parts.add(part);
    offset = offset.plus(UnsignedLong.valueOf(part.size()));
  }
  return Bytes.wrap(
      Bytes.concatenate(fixed_parts.toArray(new Bytes[0])),
      Bytes.concatenate(variable_parts.toArray(new Bytes[0])));
}
 
Example 6
Source File: AttestationDataTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void shouldNotBeProcessableBeforeFirstSlotOfTargetEpoch() {
  final Checkpoint target = new Checkpoint(UnsignedLong.valueOf(10), Bytes32.ZERO);
  final AttestationData data =
      new AttestationData(
          UnsignedLong.valueOf(1),
          UnsignedLong.ZERO,
          Bytes32.ZERO,
          new Checkpoint(ONE, Bytes32.ZERO),
          target);

  assertThat(data.getEarliestSlotForForkChoice()).isEqualTo(target.getEpochStartSlot());
}
 
Example 7
Source File: UnsignedLongSerializerTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void roundTrip_zero() {
  final UnsignedLong value = UnsignedLong.ZERO;
  final byte[] bytes = serializer.serialize(value);
  final UnsignedLong deserialized = serializer.deserialize(bytes);
  assertThat(deserialized).isEqualTo(value);
}
 
Example 8
Source File: FixedReceiverAmountPaymentTracker.java    From quilt with Apache License 2.0 5 votes vote down vote up
/**
 * Required-args Constructor.
 *
 * @param amountToDeliver An {@link UnsignedLong} representing the amount to send, in the receiver's units.
 * @param rateCalculator  An {@link ExchangeRateCalculator} that informs this tracker which amounts to use is
 *                        subsequent operations, depending on market exchange rates, observed path rates, and possibly
 *                        other data.
 */
public FixedReceiverAmountPaymentTracker(
    final UnsignedLong amountToDeliver, final ExchangeRateCalculator rateCalculator
) {
  this.amountToDeliver = Objects.requireNonNull(amountToDeliver);
  this.rateCalculator = Objects.requireNonNull(rateCalculator);

  amountLeftToDeliver = new AtomicReference<>(amountToDeliver);
  sentAmount = new AtomicReference<>(UnsignedLong.ZERO);
  deliveredAmount = new AtomicReference<>(UnsignedLong.ZERO);
}
 
Example 9
Source File: PeerSync.java    From teku with Apache License 2.0 5 votes vote down vote up
private UnsignedLong calculateNumberOfBlocksToRequest(
    final UnsignedLong nextSlot, final PeerStatus status) {
  if (nextSlot.compareTo(status.getHeadSlot()) > 0) {
    // We've synced the advertised head, nothing left to request
    return UnsignedLong.ZERO;
  }

  final UnsignedLong diff = status.getHeadSlot().minus(nextSlot).plus(UnsignedLong.ONE);
  return diff.compareTo(MAX_BLOCK_BY_RANGE_REQUEST_SIZE) > 0
      ? MAX_BLOCK_BY_RANGE_REQUEST_SIZE
      : diff;
}
 
Example 10
Source File: DiscoveryNetworkTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void setForkInfoShouldAddPredicateToConnectionManager() {
  final ForkInfo currentForkInfo = dataStructureUtil.randomForkInfo();
  discoveryNetwork.setForkInfo(currentForkInfo, Optional.empty());

  final EnrForkId expectedEnrForkId =
      new EnrForkId(
          currentForkInfo.getForkDigest(),
          currentForkInfo.getFork().getCurrent_version(),
          FAR_FUTURE_EPOCH);
  Bytes encodedForkId = SimpleOffsetSerializer.serialize(expectedEnrForkId);
  verify(discoveryService).updateCustomENRField("eth2", encodedForkId);
  ArgumentCaptor<Predicate<DiscoveryPeer>> peerPredicateArgumentCaptor =
      ArgumentCaptor.forClass(Predicate.class);
  verify(connectionManager).addPeerPredicate(peerPredicateArgumentCaptor.capture());

  DiscoveryPeer peer1 = createDiscoveryPeer(Optional.of(encodedForkId));
  assertThat(peerPredicateArgumentCaptor.getValue().test(peer1)).isTrue();

  final EnrForkId newEnrForkId1 =
      new EnrForkId(
          currentForkInfo.getForkDigest(), Bytes4.fromHexString("0xdeadbeef"), UnsignedLong.ZERO);
  Bytes newEncodedForkId1 = SimpleOffsetSerializer.serialize(newEnrForkId1);
  DiscoveryPeer peer2 = createDiscoveryPeer(Optional.of(newEncodedForkId1));
  assertThat(peerPredicateArgumentCaptor.getValue().test(peer2)).isTrue();

  final EnrForkId newEnrForkId2 =
      new EnrForkId(
          Bytes4.fromHexString("0xdeadbeef"),
          Bytes4.fromHexString("0xdeadbeef"),
          UnsignedLong.ZERO);
  Bytes newEncodedForkId2 = SimpleOffsetSerializer.serialize(newEnrForkId2);
  DiscoveryPeer peer3 = createDiscoveryPeer(Optional.of(newEncodedForkId2));
  assertThat(peerPredicateArgumentCaptor.getValue().test(peer3)).isFalse();
}
 
Example 11
Source File: StatusMessage.java    From teku with Apache License 2.0 5 votes vote down vote up
public static StatusMessage createPreGenesisStatus() {
  return new StatusMessage(
      createPreGenesisForkDigest(),
      Bytes32.ZERO,
      UnsignedLong.ZERO,
      Bytes32.ZERO,
      UnsignedLong.ZERO);
}
 
Example 12
Source File: PostBlockTest.java    From teku with Apache License 2.0 4 votes vote down vote up
private SyncingStatus buildSyncStatus(final boolean isSyncing) {
  return new SyncingStatus(
      isSyncing, new SyncStatus(UnsignedLong.ZERO, UnsignedLong.ONE, UnsignedLong.MAX_VALUE));
}
 
Example 13
Source File: SimpleOffsetSerializer.java    From teku with Apache License 2.0 4 votes vote down vote up
public static Bytes serialize(SimpleOffsetSerializable value) {
  // TODO assert sum(fixed_lengths + variable_lengths) < 2**(BYTES_PER_LENGTH_OFFSET *
  // BITS_PER_BYTE)
  // List<UnsignedLong> variable_lengths = new ArrayList<>();
  List<UnsignedLong> variable_offsets = new ArrayList<>();
  List<Bytes> interleaved_values = new ArrayList<>();
  UnsignedLong fixedLengthSum = UnsignedLong.ZERO;
  UnsignedLong varLengthSum = UnsignedLong.ZERO;

  // System.out.println("Fixed Part Size: " + value.get_fixed_parts().size());
  // System.out.println("Var Part Size: " + value.get_variable_parts().size());
  for (Bytes fixedPart : value.get_fixed_parts()) {
    UnsignedLong fixedPartSize = UnsignedLong.valueOf(fixedPart.size());
    if (fixedPartSize.equals(UnsignedLong.ZERO)) {
      fixedPartSize = UnsignedLong.valueOf(4L);
    }
    fixedLengthSum = fixedLengthSum.plus(fixedPartSize);
  }

  variable_offsets.add(fixedLengthSum);
  for (Bytes varPart : value.get_variable_parts()) {
    UnsignedLong varPartSize = UnsignedLong.valueOf(varPart.size());
    varLengthSum = varLengthSum.plus(varPartSize);
    variable_offsets.add(fixedLengthSum.plus(varLengthSum));
  }

  int interleavingIndex = 0;
  for (Bytes element : value.get_fixed_parts()) {
    if (!element.equals(Bytes.EMPTY)) {
      interleaved_values.add(element);
    } else {
      interleaved_values.add(
          SSZ.encodeUInt32(variable_offsets.get(interleavingIndex).longValue()));
    }
    ++interleavingIndex;
  }

  return Bytes.wrap(
      Bytes.concatenate(interleaved_values.toArray(new Bytes[0])),
      Bytes.concatenate(value.get_variable_parts().toArray(new Bytes[0])));
}
 
Example 14
Source File: IldcpRequestPacket.java    From quilt with Apache License 2.0 4 votes vote down vote up
/**
 * The destination of an ILP packet for IL-DCP is {@code 0} by default, but can be adjusted.
 */
@Override
default UnsignedLong getAmount() {
  return UnsignedLong.ZERO;
}
 
Example 15
Source File: MetadataMessage.java    From teku with Apache License 2.0 4 votes vote down vote up
public MetadataMessage() {
  this(UnsignedLong.ZERO, new Bitvector(Constants.ATTESTATION_SUBNET_COUNT));
}
 
Example 16
Source File: RecentChainData.java    From teku with Apache License 2.0 4 votes vote down vote up
public UnsignedLong getBestJustifiedEpoch() {
  return store == null ? UnsignedLong.ZERO : store.getBestJustifiedCheckpoint().getEpoch();
}
 
Example 17
Source File: ValidatorsUtil.java    From teku with Apache License 2.0 3 votes vote down vote up
/**
 * Decrease validator balance by ``delta`` with underflow protection.
 *
 * @param state
 * @param index
 * @param delta
 * @see
 *     <a>https://github.com/ethereum/eth2.0-specs/blob/v0.8.0/specs/core/0_beacon-chain.md#decrease_balance</a>
 */
public static void decrease_balance(MutableBeaconState state, int index, UnsignedLong delta) {
  UnsignedLong newBalance =
      delta.compareTo(state.getBalances().get(index)) > 0
          ? UnsignedLong.ZERO
          : state.getBalances().get(index).minus(delta);
  state.getBalances().set(index, newBalance);
}
 
Example 18
Source File: BeaconStateUtil.java    From teku with Apache License 2.0 3 votes vote down vote up
/**
 * Return the combined effective balance of the ``indices``. (EFFECTIVE_BALANCE_INCREMENT Gwei
 * minimum to avoid divisions by zero.)
 *
 * @param state
 * @param indices
 * @return
 * @see
 *     <a>https://github.com/ethereum/eth2.0-specs/blob/v0.8.0/specs/core/0_beacon-chain.md#get_total_balance</a>
 */
public static UnsignedLong get_total_balance(BeaconState state, Collection<Integer> indices) {
  UnsignedLong sum = UnsignedLong.ZERO;
  SSZList<Validator> validator_registry = state.getValidators();
  for (Integer index : indices) {
    sum = sum.plus(validator_registry.get(index).getEffective_balance());
  }
  return max(sum, EFFECTIVE_BALANCE_INCREMENT);
}
 
Example 19
Source File: StreamMoneyBlockedFrame.java    From quilt with Apache License 2.0 2 votes vote down vote up
/**
 * Total amount, denominated in the units of the endpoint sending this frame, that the endpoint has sent already.
 *
 * @return An {@link UnsignedLong} containing the total amount sent on this stream.
 */
@Value.Default
default UnsignedLong totalSent() {
  return UnsignedLong.ZERO;
}
 
Example 20
Source File: IldcpRequest.java    From quilt with Apache License 2.0 2 votes vote down vote up
/**
 * The destination of an ILP packet for IL-DCP is {@code 0} by default, but can be adjusted.
 *
 * @return An {@link UnsignedLong} value containing the amount in the {@link IldcpRequest}
 *         if an amount value exists, else default at {@code UnsignedLong.ZERO}.
 */
default UnsignedLong getAmount() {
  return UnsignedLong.ZERO;
}