Java Code Examples for org.apache.tuweni.bytes.Bytes32#ZERO

The following examples show how to use org.apache.tuweni.bytes.Bytes32#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: 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 2
Source File: HashTreeUtil.java    From teku with Apache License 2.0 6 votes vote down vote up
public static Bytes32 hash_tree_root(SSZTypes sszType, Bytes... bytes) {
  switch (sszType) {
    case BASIC:
      return hash_tree_root_basic_type(bytes);
    case BITLIST:
      throw new UnsupportedOperationException(
          "Use HashTreeUtil.hash_tree_root(SSZType.BITLIST, int, Bytes...) for a bitlist type.");
    case VECTOR_OF_BASIC:
      return hash_tree_root_vector_of_basic_type(bytes);
    case VECTOR_OF_COMPOSITE:
      throw new UnsupportedOperationException(
          "Use HashTreeUtil.hash_tree_root(SSZTypes.TUPLE_OF_COMPOSITE, List) for a fixed length list of composite SSZ types.");
    case LIST_OF_BASIC:
      throw new UnsupportedOperationException(
          "Use HashTreeUtil.hash_tree_root(SSZType.LIST_OF_BASIC, int, Bytes...) for a variable length list of basic SSZ type.");
    case LIST_OF_COMPOSITE:
      throw new UnsupportedOperationException(
          "Use HashTreeUtil.hash_tree_root(SSZTypes.LIST_COMPOSITE, List) for a variable length list of composite SSZ types.");
    case CONTAINER:
      throw new UnsupportedOperationException(
          "hash_tree_root of SSZ Containers (often implemented by POJOs) must be done by the container POJO itself, as its individual fields cannot be enumerated without reflection.");
    default:
      break;
  }
  return Bytes32.ZERO;
}
 
Example 3
Source File: AttestationTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeDependentOnTargetBlockAndBeaconBlockRoot() {
  final Bytes32 targetRoot = Bytes32.fromHexString("0x01");
  final Bytes32 beaconBlockRoot = Bytes32.fromHexString("0x02");

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

  assertThat(attestation.getDependentBlockRoots())
      .containsExactlyInAnyOrder(targetRoot, beaconBlockRoot);
}
 
Example 4
Source File: BlockValidatorTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReturnSavedForFutureForBlockWithParentUnavailable() throws Exception {
  final UnsignedLong nextSlot = recentChainData.getBestSlot().plus(ONE);
  beaconChainUtil.setSlot(nextSlot);

  final SignedBeaconBlock signedBlock = beaconChainUtil.createBlockAtSlot(nextSlot);
  final UnsignedLong proposerIndex = signedBlock.getMessage().getProposer_index();
  final BeaconBlock block =
      new BeaconBlock(
          signedBlock.getSlot(),
          proposerIndex,
          Bytes32.ZERO,
          signedBlock.getMessage().getState_root(),
          signedBlock.getMessage().getBody());

  BLSSignature blockSignature =
      new Signer(beaconChainUtil.getSigner(proposerIndex.intValue()))
          .signBlock(block, recentChainData.getBestState().get().getForkInfo())
          .join();
  final SignedBeaconBlock blockWithNoParent = new SignedBeaconBlock(block, blockSignature);

  InternalValidationResult result = blockValidator.validate(blockWithNoParent);
  assertThat(result).isEqualTo(InternalValidationResult.SAVE_FOR_FUTURE);
}
 
Example 5
Source File: TrieIterator.java    From besu with Apache License 2.0 5 votes vote down vote up
private Bytes32 keyHash() {
  final Iterator<Bytes> iterator = paths.descendingIterator();
  Bytes fullPath = iterator.next();
  while (iterator.hasNext()) {
    fullPath = Bytes.wrap(fullPath, iterator.next());
  }
  return fullPath.isZero()
      ? Bytes32.ZERO
      : Bytes32.wrap(CompactEncoding.pathToBytes(fullPath), 0);
}
 
Example 6
Source File: HashTreeUtil.java    From teku with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
public static Bytes32 hash_tree_root(SSZTypes sszType, SSZImmutableCollection bytes) {
  switch (sszType) {
    case LIST_OF_BASIC:
      throw new UnsupportedOperationException(
          "Use HashTreeUtil.hash_tree_root(SSZTypes.LIST_OF_BASIC, int, List) for a variable length list of basic SSZ types.");
    case LIST_OF_COMPOSITE:
      throw new UnsupportedOperationException(
          "Use HashTreeUtil.hash_tree_root(SSZTypes.LIST_OF_COMPOSITE, int, List) for a variable length list of composite SSZ types.");
    case VECTOR_OF_COMPOSITE:
      if (!bytes.isEmpty() && bytes.get(0) instanceof Bytes32) {
        return hash_tree_root_vector_composite_type((SSZVector<Bytes32>) bytes);
      }
      break;
    case BASIC:
      throw new UnsupportedOperationException(
          "Use HashTreeUtil.hash_tree_root(SSZType.BASIC, Bytes...) for a basic SSZ type.");
    case VECTOR_OF_BASIC:
      throw new UnsupportedOperationException(
          "Use HashTreeUtil.hash_tree_root(SSZTypes.TUPLE_BASIC, Bytes...) for a fixed length tuple of basic SSZ types.");
    case CONTAINER:
      throw new UnsupportedOperationException(
          "hash_tree_root of SSZ Containers (often implemented by POJOs) must be done by the container POJO itself, as its individual fields cannot be enumerated without reflection.");
    default:
  }
  return Bytes32.ZERO;
}
 
Example 7
Source File: GenesisGenerator.java    From teku with Apache License 2.0 5 votes vote down vote up
public GenesisGenerator() {
  Bytes32 latestBlockRoot = new BeaconBlockBody().hash_tree_root();
  final UnsignedLong genesisSlot = UnsignedLong.valueOf(Constants.GENESIS_SLOT);
  BeaconBlockHeader beaconBlockHeader =
      new BeaconBlockHeader(
          genesisSlot, UnsignedLong.ZERO, Bytes32.ZERO, Bytes32.ZERO, latestBlockRoot);
  state.setLatest_block_header(beaconBlockHeader);
  state.setFork(
      new Fork(GENESIS_FORK_VERSION, GENESIS_FORK_VERSION, UnsignedLong.valueOf(GENESIS_EPOCH)));
}
 
Example 8
Source File: BeaconBlockBody.java    From teku with Apache License 2.0 5 votes vote down vote up
public BeaconBlockBody() {
  this.randao_reveal = BLSSignature.empty();
  this.eth1_data = new Eth1Data();
  this.graffiti = Bytes32.ZERO;
  this.proposer_slashings = BeaconBlockBodyLists.createProposerSlashings();
  this.attester_slashings = BeaconBlockBodyLists.createAttesterSlashings();
  this.attestations = BeaconBlockBodyLists.createAttestations();
  this.deposits = BeaconBlockBodyLists.createDeposits();
  this.voluntary_exits = BeaconBlockBodyLists.createVoluntaryExits();
}
 
Example 9
Source File: BeaconBlock.java    From teku with Apache License 2.0 5 votes vote down vote up
public BeaconBlock(Bytes32 state_root) {
  this.slot = UnsignedLong.ZERO;
  this.proposer_index = UnsignedLong.ZERO;
  this.parent_root = Bytes32.ZERO;
  this.state_root = state_root;
  this.body = new BeaconBlockBody();
}
 
Example 10
Source File: BeaconBlock.java    From teku with Apache License 2.0 5 votes vote down vote up
public BeaconBlock() {
  this.slot = UnsignedLong.ZERO;
  this.proposer_index = UnsignedLong.ZERO;
  this.parent_root = Bytes32.ZERO;
  this.state_root = Bytes32.ZERO;
  this.body = new BeaconBlockBody();
}
 
Example 11
Source File: CommitteeUtilTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void testListShuffleAndShuffledIndexCompatibility() {
  Bytes32 seed = Bytes32.ZERO;
  int index_count = 3333;
  int[] indexes = IntStream.range(0, index_count).toArray();

  CommitteeUtil.shuffle_list(indexes, seed);
  assertThat(indexes)
      .isEqualTo(
          IntStream.range(0, index_count)
              .map(i -> CommitteeUtil.compute_shuffled_index(i, indexes.length, seed))
              .toArray());
}
 
Example 12
Source File: AttestationDataTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void shouldNotBeProcessableBeforeSlotAfterCreationSlot() {
  final AttestationData data =
      new AttestationData(
          UnsignedLong.valueOf(60),
          UnsignedLong.ZERO,
          Bytes32.ZERO,
          new Checkpoint(ONE, Bytes32.ZERO),
          new Checkpoint(ONE, Bytes32.ZERO));

  assertThat(data.getEarliestSlotForForkChoice()).isEqualTo(UnsignedLong.valueOf(61));
}
 
Example 13
Source File: PrivateTransactionDataFixture.java    From besu with Apache License 2.0 5 votes vote down vote up
public static Bytes encodePrivateTransaction(
    final PrivateTransaction privateTransaction, final Optional<Bytes32> version) {
  final BytesValueRLPOutput output = new BytesValueRLPOutput();
  if (version.isEmpty()) {
    privateTransaction.writeTo(output);
  } else {
    final VersionedPrivateTransaction versionedPrivateTransaction =
        new VersionedPrivateTransaction(privateTransaction, Bytes32.ZERO);
    versionedPrivateTransaction.writeTo(output);
  }
  return output.encoded();
}
 
Example 14
Source File: PrivateTransactionDataFixture.java    From besu with Apache License 2.0 5 votes vote down vote up
public static ReceiveResponse generateVersionedReceiveResponse(
    final PrivateTransaction privateTransaction) {
  final VersionedPrivateTransaction versionedPrivateTransaction =
      new VersionedPrivateTransaction(privateTransaction, Bytes32.ZERO);
  final BytesValueRLPOutput rlpOutput = new BytesValueRLPOutput();
  versionedPrivateTransaction.writeTo(rlpOutput);
  return new ReceiveResponse(
      rlpOutput.encoded().toBase64String().getBytes(UTF_8),
      privateTransaction.getPrivacyGroupId().isPresent()
          ? privateTransaction.getPrivacyGroupId().get().toBase64String()
          : "",
      null);
}
 
Example 15
Source File: DepositData.java    From teku with Apache License 2.0 4 votes vote down vote up
public DepositData() {
  this.pubkey = BLSPublicKey.empty();
  this.withdrawal_credentials = Bytes32.ZERO;
  this.amount = UnsignedLong.ZERO;
  this.signature = BLSSignature.empty();
}
 
Example 16
Source File: StatusMessage.java    From teku with Apache License 2.0 4 votes vote down vote up
private static Bytes4 createPreGenesisForkDigest() {
  final Bytes4 genesisFork = Constants.GENESIS_FORK_VERSION;
  final Bytes32 emptyValidatorsRoot = Bytes32.ZERO;
  return compute_fork_digest(genesisFork, emptyValidatorsRoot);
}
 
Example 17
Source File: BlockProposalUtil.java    From teku with Apache License 2.0 4 votes vote down vote up
public BeaconBlockAndState createNewUnsignedBlock(
    final UnsignedLong newSlot,
    final int proposerIndex,
    final BLSSignature randaoReveal,
    final BeaconState preState,
    final Bytes32 parentBlockSigningRoot,
    final Eth1Data eth1Data,
    final Bytes32 graffiti,
    final SSZList<Attestation> attestations,
    final SSZList<ProposerSlashing> proposerSlashings,
    final SSZList<AttesterSlashing> attesterSlashings,
    final SSZList<Deposit> deposits,
    final SSZList<SignedVoluntaryExit> voluntaryExits)
    throws StateTransitionException {
  // Create block body
  BeaconBlockBody beaconBlockBody =
      new BeaconBlockBody(
          randaoReveal,
          eth1Data,
          graffiti,
          proposerSlashings,
          attesterSlashings,
          attestations,
          deposits,
          voluntaryExits);

  // Create initial block with some stubs
  final Bytes32 tmpStateRoot = Bytes32.ZERO;
  BeaconBlock newBlock =
      new BeaconBlock(
          newSlot,
          UnsignedLong.valueOf(proposerIndex),
          parentBlockSigningRoot,
          tmpStateRoot,
          beaconBlockBody);

  // Run state transition and set state root
  final BeaconState newState =
      stateTransition.initiate(
          preState, new SignedBeaconBlock(newBlock, BLSSignature.empty()), false);

  Bytes32 stateRoot = newState.hash_tree_root();
  newBlock.setState_root(stateRoot);

  return new BeaconBlockAndState(newBlock, newState);
}
 
Example 18
Source File: VoteTracker.java    From teku with Apache License 2.0 4 votes vote down vote up
public static VoteTracker Default() {
  return new VoteTracker(Bytes32.ZERO, Bytes32.ZERO, UnsignedLong.ZERO);
}
 
Example 19
Source File: StubForkChoiceStrategy.java    From teku with Apache License 2.0 4 votes vote down vote up
@Override
public Bytes32 findHead(final MutableStore store) {
  return Bytes32.ZERO;
}
 
Example 20
Source File: DebugAccountRange.java    From besu with Apache License 2.0 4 votes vote down vote up
@Override
public JsonRpcResponse response(final JsonRpcRequestContext requestContext) {
  final BlockParameterOrBlockHash blockParameterOrBlockHash =
      requestContext.getRequiredParameter(0, BlockParameterOrBlockHash.class);
  final String addressHash = requestContext.getRequiredParameter(2, String.class);
  final int maxResults = requestContext.getRequiredParameter(3, Integer.TYPE);

  final Optional<Hash> blockHashOptional = hashFromParameter(blockParameterOrBlockHash);
  if (blockHashOptional.isEmpty()) {
    return emptyResponse(requestContext);
  }
  final Hash blockHash = blockHashOptional.get();
  final Optional<BlockHeader> blockHeaderOptional =
      blockchainQueries.get().blockByHash(blockHash).map(BlockWithMetadata::getHeader);
  if (blockHeaderOptional.isEmpty()) {
    return emptyResponse(requestContext);
  }

  // TODO deal with mid-block locations

  final Optional<MutableWorldState> state =
      blockchainQueries.get().getWorldState(blockHeaderOptional.get().getNumber());

  if (state.isEmpty()) {
    return emptyResponse(requestContext);
  } else {
    final List<StreamableAccount> accounts =
        state
            .get()
            .streamAccounts(Bytes32.fromHexStringLenient(addressHash), maxResults + 1)
            .collect(Collectors.toList());
    Bytes32 nextKey = Bytes32.ZERO;
    if (accounts.size() == maxResults + 1) {
      nextKey = accounts.get(maxResults).getAddressHash();
      accounts.remove(maxResults);
    }

    return new JsonRpcSuccessResponse(
        requestContext.getRequest().getId(),
        new DebugAccountRangeAtResult(
            accounts.stream()
                .collect(
                    Collectors.toMap(
                        account -> account.getAddressHash().toString(),
                        account -> account.getAddress().orElse(Address.ZERO).toString())),
            nextKey.toString()));
  }
}