org.apache.tuweni.bytes.Bytes32 Java Examples

The following examples show how to use org.apache.tuweni.bytes.Bytes32. 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: TestStoreFactory.java    From teku with Apache License 2.0 6 votes vote down vote up
MutableStoreImpl(
    final UnsignedLong time,
    final UnsignedLong genesis_time,
    final Checkpoint justified_checkpoint,
    final Checkpoint finalized_checkpoint,
    final Checkpoint best_justified_checkpoint,
    final Map<Bytes32, SignedBeaconBlock> blocks,
    final Map<Bytes32, BeaconState> block_states,
    final Map<Checkpoint, BeaconState> checkpoint_states,
    final Map<UnsignedLong, VoteTracker> votes) {
  super(
      time,
      genesis_time,
      justified_checkpoint,
      finalized_checkpoint,
      best_justified_checkpoint,
      blocks,
      block_states,
      checkpoint_states,
      votes);
}
 
Example #2
Source File: BeaconChainUtil.java    From teku with Apache License 2.0 6 votes vote down vote up
private SignedBlockAndState createBlockAndStateAtSlot(
    final UnsignedLong slot,
    boolean withValidProposer,
    Optional<SSZList<Attestation>> attestations,
    Optional<SSZList<Deposit>> deposits,
    Optional<SSZList<SignedVoluntaryExit>> exits,
    Optional<Eth1Data> eth1Data)
    throws Exception {
  checkState(
      withValidProposer || validatorKeys.size() > 1,
      "Must have >1 validator in order to create a block from an invalid proposer.");
  final Bytes32 bestBlockRoot = recentChainData.getBestBlockRoot().orElseThrow();
  final BeaconBlock bestBlock = recentChainData.getStore().getBlock(bestBlockRoot);
  final BeaconState preState = recentChainData.getBestState().orElseThrow();
  checkArgument(bestBlock.getSlot().compareTo(slot) < 0, "Slot must be in the future.");

  final int correctProposerIndex = blockCreator.getProposerIndexForSlot(preState, slot);
  final int proposerIndex =
      withValidProposer ? correctProposerIndex : getWrongProposerIndex(correctProposerIndex);

  final MessageSignerService signer = getSigner(proposerIndex);
  return blockCreator.createBlock(
      signer, slot, preState, bestBlockRoot, attestations, deposits, exits, eth1Data);
}
 
Example #3
Source File: DataStructureUtil.java    From teku with Apache License 2.0 6 votes vote down vote up
public BeaconBlockBody randomBeaconBlockBody() {
  return new BeaconBlockBody(
      randomSignature(),
      randomEth1Data(),
      Bytes32.ZERO,
      randomSSZList(
          ProposerSlashing.class, Constants.MAX_PROPOSER_SLASHINGS, this::randomProposerSlashing),
      randomSSZList(
          AttesterSlashing.class, Constants.MAX_ATTESTER_SLASHINGS, this::randomAttesterSlashing),
      randomSSZList(Attestation.class, Constants.MAX_ATTESTATIONS, this::randomAttestation),
      randomSSZList(Deposit.class, Constants.MAX_DEPOSITS, this::randomDepositWithoutIndex),
      randomSSZList(
          SignedVoluntaryExit.class,
          Constants.MAX_VOLUNTARY_EXITS,
          this::randomSignedVoluntaryExit));
}
 
Example #4
Source File: DefaultPrivacyController.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<String> buildAndSendAddPayload(
    final PrivateTransaction privateTransaction,
    final Bytes32 privacyGroupId,
    final String enclavePublicKey) {
  if (isGroupAdditionTransaction(privateTransaction)) {
    final List<PrivateTransactionMetadata> privateTransactionMetadataList =
        buildTransactionMetadataList(privacyGroupId);
    if (privateTransactionMetadataList.size() > 0) {
      final List<PrivateTransactionWithMetadata> privateTransactionWithMetadataList =
          retrievePrivateTransactions(
              privacyGroupId, privateTransactionMetadataList, enclavePublicKey);
      final Bytes bytes = serializeAddToGroupPayload(privateTransactionWithMetadataList);
      final List<String> privateFor =
          getParticipantsFromParameter(privateTransaction.getPayload());
      return Optional.of(
          enclave.send(bytes.toBase64String(), enclavePublicKey, privateFor).getKey());
    }
  }
  return Optional.empty();
}
 
Example #5
Source File: PrivateGroupRehydrationBlockProcessor.java    From besu with Apache License 2.0 6 votes vote down vote up
private void updatePrivateBlockMetadata(
    final Hash markerTransactionHash,
    final Hash currentBlockHash,
    final Bytes32 privacyGroupId,
    final Hash rootHash,
    final PrivateStateStorage.Updater privateStateUpdater,
    final PrivateStateStorage privateStateStorage) {
  final PrivateBlockMetadata privateBlockMetadata =
      privateStateStorage
          .getPrivateBlockMetadata(currentBlockHash, Bytes32.wrap(privacyGroupId))
          .orElseGet(PrivateBlockMetadata::empty);
  privateBlockMetadata.addPrivateTransactionMetadata(
      new PrivateTransactionMetadata(markerTransactionHash, rootHash));
  privateStateUpdater.putPrivateBlockMetadata(
      Bytes32.wrap(currentBlockHash), Bytes32.wrap(privacyGroupId), privateBlockMetadata);
}
 
Example #6
Source File: GenesisGenerator.java    From teku with Apache License 2.0 6 votes vote down vote up
public void updateCandidateState(
    Bytes32 eth1BlockHash, UnsignedLong eth1Timestamp, List<? extends Deposit> deposits) {
  updateGenesisTime(eth1Timestamp);

  state.setEth1_data(
      new Eth1Data(
          Bytes32.ZERO,
          UnsignedLong.valueOf(depositDataList.size() + deposits.size()),
          eth1BlockHash));

  // Process deposits
  deposits.forEach(
      deposit -> {
        LOG.trace("About to process deposit: {}", depositDataList::size);
        depositDataList.add(deposit.getData());

        // Skip verifying the merkle proof as these deposits come directly from an Eth1 event.
        // We do still verify the signature
        process_deposit_without_checking_merkle_proof(state, deposit, keyCache);

        processActivation(deposit);
      });
}
 
Example #7
Source File: FetchBlockTaskTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@Test
public void run_successful() {
  final SignedBeaconBlock block = dataStructureUtil.randomSignedBeaconBlock(10);
  final Bytes32 blockRoot = block.getMessage().hash_tree_root();
  FetchBlockTask task = FetchBlockTask.create(eth2Network, blockRoot);
  assertThat(task.getBlockRoot()).isEqualTo(blockRoot);

  final Eth2Peer peer = registerNewPeer(1);
  when(peer.requestBlockByRoot(blockRoot)).thenReturn(SafeFuture.completedFuture(block));

  final SafeFuture<FetchBlockResult> result = task.run();
  assertThat(result).isDone();
  final FetchBlockResult fetchBlockResult = result.getNow(null);
  assertThat(fetchBlockResult.isSuccessful()).isTrue();
  assertThat(fetchBlockResult.getBlock()).isEqualTo(block);
}
 
Example #8
Source File: StoredNodeFactory.java    From besu with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private BranchNode<V> decodeBranch(final RLPInput nodeRLPs, final Supplier<String> errMessage) {
  final ArrayList<Node<V>> children = new ArrayList<>(BranchNode.RADIX);
  for (int i = 0; i < BranchNode.RADIX; ++i) {
    if (nodeRLPs.nextIsNull()) {
      nodeRLPs.skipNext();
      children.add(NULL_NODE);
    } else if (nodeRLPs.nextIsList()) {
      final Node<V> child = decode(nodeRLPs, errMessage);
      children.add(child);
    } else {
      final Bytes32 childHash = nodeRLPs.readBytes32();
      children.add(new StoredNode<>(this, childHash));
    }
  }

  final Optional<V> value;
  if (nodeRLPs.nextIsNull()) {
    nodeRLPs.skipNext();
    value = Optional.empty();
  } else {
    value = Optional.of(decodeValue(nodeRLPs, errMessage));
  }

  return new BranchNode<>(children, value, this, valueSerializer);
}
 
Example #9
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 #10
Source File: PrivateStateRootResolverTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void resolveExpectedRootHashWhenCommitmentForPrivacyGroupExists() {
  final PrivateStateStorage.Updater updater = privateStateStorage.updater();
  updater.putPrivateBlockMetadata(
      BLOCKCHAIN.getBlockByNumber(16).get().getHash(),
      Bytes32.wrap(privacyGroupId),
      new PrivateBlockMetadata(
          Collections.singletonList(
              new PrivateTransactionMetadata(
                  BLOCK_GENERATOR.transaction().getHash(), pmt1StateHash))));
  updater.putPrivacyGroupHeadBlockMap(
      BLOCKCHAIN.getChainHeadHash(),
      new PrivacyGroupHeadBlockMap(
          Collections.singletonMap(
              Bytes32.wrap(privacyGroupId), BLOCKCHAIN.getBlockByNumber(16).get().getHash())));
  updater.commit();
  final PrivateStateRootResolver privateStateRootResolver =
      new PrivateStateRootResolver(privateStateStorage);
  assertThat(
          privateStateRootResolver.resolveLastStateRoot(
              privacyGroupId, BLOCKCHAIN.getChainHeadHash()))
      .isEqualTo(pmt1StateHash);
}
 
Example #11
Source File: PrivateStateRootResolver.java    From besu with Apache License 2.0 6 votes vote down vote up
private Hash resolveLastStateRoot(
    final Bytes32 privacyGroupId, final PrivacyGroupHeadBlockMap privacyGroupHeadBlockMap) {
  final Hash lastRootHash;
  if (privacyGroupHeadBlockMap.containsKey(privacyGroupId)) {
    // Check this PG head block is being tracked
    final Hash blockHashForLastBlockWithTx = privacyGroupHeadBlockMap.get(privacyGroupId);
    lastRootHash =
        privateStateStorage
            .getPrivateBlockMetadata(blockHashForLastBlockWithTx, privacyGroupId)
            .flatMap(PrivateBlockMetadata::getLatestStateRoot)
            .orElse(EMPTY_ROOT_HASH);
  } else {
    // First transaction for this PG
    lastRootHash = EMPTY_ROOT_HASH;
  }
  return lastRootHash;
}
 
Example #12
Source File: PeerChainValidatorTest.java    From teku with Apache License 2.0 6 votes vote down vote up
private void setupRemoteStatusAndValidator(final Checkpoint remoteFinalizedCheckpoint) {

    final Bytes32 headRoot = Bytes32.fromHexString("0xeeee");
    // Set a head slot some distance beyond the finalized epoch
    final UnsignedLong headSlot =
        remoteFinalizedCheckpoint
            .getEpoch()
            .times(UnsignedLong.valueOf(Constants.SLOTS_PER_EPOCH))
            .plus(UnsignedLong.valueOf(10L));

    final PeerStatus status =
        new PeerStatus(
            remoteFork,
            remoteFinalizedCheckpoint.getRoot(),
            remoteFinalizedCheckpoint.getEpoch(),
            headRoot,
            headSlot);
    when(peer.getStatus()).thenReturn(status);

    remoteStatus = status;
    peerChainValidator =
        PeerChainValidator.create(recentChainData, historicalChainData, peer, status);
  }
 
Example #13
Source File: ProofOfWorkValidationRuleTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void passesBlockWithOneValuedDifficulty() {
  final BlockHeaderBuilder headerBuilder =
      BlockHeaderBuilder.fromHeader(blockHeader)
          .difficulty(Difficulty.ONE)
          .blockHeaderFunctions(mainnetBlockHashFunction())
          .timestamp(1);
  final BlockHeader preHeader = headerBuilder.buildBlockHeader();
  final byte[] hashBuffer = new byte[64];
  final Hash headerHash = validationRule.hashHeader(preHeader);
  ProofOfWorkValidationRule.HASHER.hash(
      hashBuffer, preHeader.getNonce(), preHeader.getNumber(), headerHash.toArray());

  final BlockHeader header =
      headerBuilder
          .mixHash(Hash.wrap(Bytes32.leftPad(Bytes.wrap(hashBuffer).slice(0, Bytes32.SIZE))))
          .buildBlockHeader();

  assertThat(validationRule.validate(header, parentHeader)).isTrue();
}
 
Example #14
Source File: AttestationUtil.java    From teku with Apache License 2.0 6 votes vote down vote up
public static AttestationData getGenericAttestationData(
    UnsignedLong slot, BeaconState state, BeaconBlock block, final UnsignedLong committeeIndex) {
  UnsignedLong epoch = compute_epoch_at_slot(slot);
  // Get variables necessary that can be shared among Attestations of all validators
  Bytes32 beacon_block_root = block.hash_tree_root();
  UnsignedLong start_slot = compute_start_slot_at_epoch(epoch);
  Bytes32 epoch_boundary_block_root =
      start_slot.compareTo(slot) == 0 || state.getSlot().compareTo(start_slot) <= 0
          ? block.hash_tree_root()
          : get_block_root_at_slot(state, start_slot);
  Checkpoint source = state.getCurrent_justified_checkpoint();
  Checkpoint target = new Checkpoint(epoch, epoch_boundary_block_root);

  // Set attestation data
  return new AttestationData(slot, committeeIndex, beacon_block_root, source, target);
}
 
Example #15
Source File: RLPxConnectionFactoryTest.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Test
void roundtripPayload() {
  KeyPair exampleKeyPair = SECP256K1.KeyPair
      .fromSecretKey(
          SecretKey
              .fromBytes(
                  Bytes32.fromHexString("0xEE647A774DF811AB577BA5F397D56BE6567DA58AF7A65368F01DD7A8313812D8")));

  Bytes payload = Bytes
      .fromHexString(
          "0xF8A7B84135A22239600070940908090D5F051B2C597981B090E386360B87163A8AF1EDF0434A84AA31A582DF93A0396D4CC2E3574C919B0E8D47DCEA095647446C88B36D01B840B8497006E23B1F35BD6E988EC53EE759BC852162049972F777B92B5E029B840BE8BE93F513DA55B81AEE463254930EE30667825B0B6FE30938FFFA7024A03C5AA02B310D67A36F599EAB6B8D03FECB9D782CC7A0EB12FECBFF454A4094557A2EB704");
  InitiatorHandshakeMessage initial = InitiatorHandshakeMessage.decode(payload, exampleKeyPair.secretKey());
  Bytes encoded = initial.encode();
  assertEquals(payload, encoded);
}
 
Example #16
Source File: PrunerIntegrationTest.java    From besu with Apache License 2.0 5 votes vote down vote up
private void collectTrieNodes(
    final MerklePatriciaTrie<Bytes32, Bytes> trie, final Set<Bytes> collector) {
  final Bytes32 rootHash = trie.getRootHash();
  trie.visitAll(
      (node) -> {
        if (node.isReferencedByHash() || node.getHash().equals(rootHash)) {
          collector.add(node.getRlp());
        }
      });
}
 
Example #17
Source File: MinimumGenesisTimeBlockFinder.java    From teku with Apache License 2.0 5 votes vote down vote up
static void notifyMinGenesisTimeBlockReached(
    Eth1EventsChannel eth1EventsChannel, EthBlock.Block block) {
  MinGenesisTimeBlockEvent event =
      new MinGenesisTimeBlockEvent(
          UnsignedLong.valueOf(block.getTimestamp()),
          UnsignedLong.valueOf(block.getNumber()),
          Bytes32.fromHexString(block.getHash()));
  eth1EventsChannel.onMinGenesisTimeBlock(event);
  LOG.debug("Notifying BeaconChainService of MinGenesisTimeBlock: {}", event);
}
 
Example #18
Source File: ECIESHandshaker.java    From besu with Apache License 2.0 5 votes vote down vote up
/** Computes the secrets from the two exchanged messages. */
void computeSecrets() {
  final Bytes agreedSecret =
      SECP256K1.calculateECDHKeyAgreement(ephKeyPair.getPrivateKey(), partyEphPubKey);

  final Bytes sharedSecret =
      keccak256(
          concatenate(agreedSecret, keccak256(concatenate(responderNonce, initiatorNonce))));

  final Bytes32 aesSecret = keccak256(concatenate(agreedSecret, sharedSecret));
  final Bytes32 macSecret = keccak256(concatenate(agreedSecret, aesSecret));
  final Bytes32 token = keccak256(sharedSecret);

  final HandshakeSecrets secrets =
      new HandshakeSecrets(aesSecret.toArray(), macSecret.toArray(), token.toArray());

  final Bytes initiatorMac = concatenate(macSecret.xor(responderNonce), initiatorMsgEnc);
  final Bytes responderMac = concatenate(macSecret.xor(initiatorNonce), responderMsgEnc);

  if (initiator) {
    secrets.updateEgress(initiatorMac.toArray());
    secrets.updateIngress(responderMac.toArray());
  } else {
    secrets.updateIngress(initiatorMac.toArray());
    secrets.updateEgress(responderMac.toArray());
  }

  this.secrets = secrets;
}
 
Example #19
Source File: StoredNodeFactory.java    From besu with Apache License 2.0 5 votes vote down vote up
public Optional<Node<V>> retrieve(final Bytes32 hash) throws MerkleTrieException {
  return nodeLoader
      .getNode(hash)
      .map(
          rlp -> {
            final Node<V> node = decode(rlp, () -> format("Invalid RLP value for hash %s", hash));
            // recalculating the node.hash() is expensive, so we only do this as an assertion
            assert (hash.equals(node.getHash()))
                : "Node hash " + node.getHash() + " not equal to expected " + hash;
            return node;
          });
}
 
Example #20
Source File: AbstractCombinedChainDataClientTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void getBlockAtSlotExact_unknownRoot() {
  final SignedBlockAndState genesis = chainUpdater.initializeGenesis();
  final UnsignedLong querySlot = genesis.getSlot().plus(UnsignedLong.ONE);

  final SafeFuture<Optional<SignedBeaconBlock>> result =
      client.getBlockAtSlotExact(querySlot, Bytes32.ZERO);
  assertThat(result).isCompletedWithValue(Optional.empty());
}
 
Example #21
Source File: RLPxConnectionFactory.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a RLPxConnection based off the complete handshake exchange.
 *
 * @param initiator whether we initiated the handshake
 * @param initiatorMessage the bytes of the initiation message
 * @param responderMessage the bytes of the response message
 * @param ourEphemeralPrivateKey our ephemeral private key
 * @param peerEphemeralPublicKey the peer ephemeral public key
 * @param initiatorNonce the initiation random nonce
 * @param responderNonce the responder random nonce
 * @param ourPublicKey our public key
 * @param peerPublicKey the public key of the peer
 * @return a valid RPLx connection to communicate between peers
 */
public static RLPxConnection createConnection(
    boolean initiator,
    Bytes initiatorMessage,
    Bytes responderMessage,
    SecretKey ourEphemeralPrivateKey,
    PublicKey peerEphemeralPublicKey,
    Bytes32 initiatorNonce,
    Bytes32 responderNonce,
    PublicKey ourPublicKey,
    PublicKey peerPublicKey) {

  Bytes agreedSecret = calculateKeyAgreement(ourEphemeralPrivateKey, peerEphemeralPublicKey);
  Bytes sharedSecret = keccak256(concatenate(agreedSecret, keccak256(concatenate(responderNonce, initiatorNonce))));

  Bytes32 aesSecret = keccak256(concatenate(agreedSecret, sharedSecret));
  Bytes32 macSecret = keccak256(concatenate(agreedSecret, aesSecret));
  Bytes32 token = keccak256(sharedSecret);

  Bytes initiatorMac = concatenate(macSecret.xor(responderNonce), initiatorMessage);
  Bytes responderMac = concatenate(macSecret.xor(initiatorNonce), responderMessage);

  if (initiator) {
    return new RLPxConnection(aesSecret, macSecret, token, initiatorMac, responderMac, ourPublicKey, peerPublicKey);
  } else {
    return new RLPxConnection(aesSecret, macSecret, token, responderMac, initiatorMac, ourPublicKey, peerPublicKey);
  }
}
 
Example #22
Source File: PrivateWorldStateReaderTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void absentPrivateWorldStateReturnsEmpty() {
  final Bytes32 privacyGroupBytes = Bytes32.wrap(Bytes.fromBase64String(PRIVACY_GROUP_ID));
  final Address contractAddress = Address.ZERO;

  when(privateStateRootResolver.resolveLastStateRoot(eq(privacyGroupBytes), eq(blockHash)))
      .thenReturn(stateRootHash);
  when(privateWorldStateArchive.get(eq(stateRootHash))).thenReturn(Optional.empty());

  final Optional<Bytes> maybecontractCode =
      privateWorldStateReader.getContractCode(PRIVACY_GROUP_ID, blockHash, contractAddress);

  assertThat(maybecontractCode).isNotPresent();
}
 
Example #23
Source File: RLPxConnectionFactoryTest.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Test
void roundtripResponseHandshakeBytes() {
  KeyPair keyPair = KeyPair.random();
  KeyPair peerKeyPair = KeyPair.random();
  byte[] nonce = new byte[32];
  new SecureRandom().nextBytes(nonce);

  Bytes payload = RLPxConnectionFactory.init(keyPair, peerKeyPair.publicKey(), KeyPair.random(), Bytes32.wrap(nonce));

  AtomicReference<Bytes> ref = new AtomicReference<>();
  RLPxConnectionFactory.respondToHandshake(payload, peerKeyPair, ref::set);
  HandshakeMessage responder = RLPxConnectionFactory.readResponse(ref.get(), keyPair.secretKey());
  assertNotNull(responder);
}
 
Example #24
Source File: DepositProviderTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void shouldDelegateOnEth1BlockToEth1DataCache() {
  final Bytes32 blockHash = dataStructureUtil.randomBytes32();
  final UnsignedLong blockTimestamp = dataStructureUtil.randomUnsignedLong();
  depositProvider.onEth1Block(blockHash, blockTimestamp);
  verify(eth1DataCache).onEth1Block(blockHash, blockTimestamp);
}
 
Example #25
Source File: MemoryTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetMemoryWhenLengthGreaterThanSourceLength() {
  final Bytes value = Bytes.concatenate(WORD1, WORD2);
  memory.setBytes(UInt256.ZERO, UInt256.valueOf(96), value);
  assertThat(memory.getWord(UInt256.ZERO)).isEqualTo(WORD1);
  assertThat(memory.getWord(UInt256.valueOf(32))).isEqualTo(WORD2);
  assertThat(memory.getWord(UInt256.valueOf(64))).isEqualTo(Bytes32.ZERO);
}
 
Example #26
Source File: MockPacketDataFactory.java    From besu with Apache License 2.0 5 votes vote down vote up
static Packet mockPongPacket(final DiscoveryPeer from, final Bytes pingHash) {
  final Packet packet = mock(Packet.class);

  final PongPacketData pongPacketData = PongPacketData.create(from.getEndpoint(), pingHash);
  when(packet.getPacketData(any())).thenReturn(Optional.of(pongPacketData));
  final Bytes id = from.getId();
  when(packet.getNodeId()).thenReturn(id);
  when(packet.getType()).thenReturn(PacketType.PONG);
  when(packet.getHash()).thenReturn(Bytes32.ZERO);

  return packet;
}
 
Example #27
Source File: DepositProcessingControllerTest.java    From teku with Apache License 2.0 5 votes vote down vote up
private ArgumentMatcher<MinGenesisTimeBlockEvent> isEvent(
    final String expectedBlockHash,
    final long expectedBlockNumber,
    final long expectedTimestamp) {
  return argument ->
      argument.getTimestamp().longValue() == expectedTimestamp
          && argument.getBlockNumber().longValue() == expectedBlockNumber
          && argument.getBlockHash().equals(Bytes32.fromHexString(expectedBlockHash));
}
 
Example #28
Source File: PrivateWorldStateReader.java    From besu with Apache License 2.0 5 votes vote down vote up
public List<PrivateTransactionMetadata> getPrivateTransactionMetadataList(
    final String privacyGroupId, final Hash blockHash) {
  final Bytes32 privacyGroupIdBytes = Bytes32.wrap(Bytes.fromBase64String(privacyGroupId));
  final Optional<PrivateBlockMetadata> privateBlockMetadata =
      privateStateStorage.getPrivateBlockMetadata(blockHash, privacyGroupIdBytes);

  return privateBlockMetadata
      .map(PrivateBlockMetadata::getPrivateTransactionMetadataList)
      .orElse(Collections.emptyList());
}
 
Example #29
Source File: Eth1Data.java    From teku with Apache License 2.0 5 votes vote down vote up
@JsonCreator
public Eth1Data(
    @JsonProperty("deposit_root") final Bytes32 deposit_root,
    @JsonProperty("deposit_count") final UnsignedLong deposit_count,
    @JsonProperty("block_hash") final Bytes32 block_hash) {
  this.deposit_root = deposit_root;
  this.deposit_count = deposit_count;
  this.block_hash = block_hash;
}
 
Example #30
Source File: DepositsFromBlockEventSerializer.java    From teku with Apache License 2.0 5 votes vote down vote up
@Override
public DepositsFromBlockEvent deserialize(final byte[] data) {
  return SSZ.decode(
      Bytes.of(data),
      reader -> {
        final UnsignedLong blockNumber = UnsignedLong.fromLongBits(reader.readUInt64());
        final Bytes32 blockHash = Bytes32.wrap(reader.readFixedBytes(Bytes32.SIZE));
        final UnsignedLong blockTimestamp = UnsignedLong.fromLongBits(reader.readUInt64());
        final List<Deposit> deposits =
            reader.readBytesList().stream().map(this::decodeDeposit).collect(toList());
        return new DepositsFromBlockEvent(blockNumber, blockHash, blockTimestamp, deposits);
      });
}