Java Code Examples for org.apache.tuweni.bytes.Bytes32#random()

The following examples show how to use org.apache.tuweni.bytes.Bytes32#random() . 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: SecureScuttlebuttHandshakeClientTest.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
@Test
void acceptMessageExchanged() {
  Signature.KeyPair clientLongTermKeyPair = Signature.KeyPair.random();
  Signature.KeyPair serverLongTermKeyPair = Signature.KeyPair.random();
  Bytes32 networkIdentifier = Bytes32.random();
  SecureScuttlebuttHandshakeClient client = SecureScuttlebuttHandshakeClient
      .create(clientLongTermKeyPair, networkIdentifier, serverLongTermKeyPair.publicKey());
  SecureScuttlebuttHandshakeServer server =
      SecureScuttlebuttHandshakeServer.create(serverLongTermKeyPair, networkIdentifier);
  Bytes initialMessage = client.createHello();
  server.readHello(initialMessage);
  client.readHello(server.createHello());
  server.readIdentityMessage(client.createIdentityMessage());
  client.readAcceptMessage(server.createAcceptMessage());
  assertEquals(client.sharedSecret(), server.sharedSecret());
  assertEquals(client.sharedSecret2(), server.sharedSecret2());
  assertEquals(client.sharedSecret3(), server.sharedSecret3());
}
 
Example 2
Source File: PrivateTransactionLocatorTest.java    From besu with Apache License 2.0 6 votes vote down vote up
private ExecutedPrivateTransaction createExecutedPrivateTransactionFromAddBlob(
    final Transaction pmt, final PrivateTransaction privateTransaction) {
  final BlockHeader blockHeader = createBlockHeader();
  final TransactionLocation pmtLocation = createPmtLocation(pmt, blockHeader);
  final String privacyGroupId =
      privateTransaction.getPrivacyGroupId().orElseThrow().toBase64String();

  mockStorageWithPrivacyGroupBlockHeaderMap(privacyGroupId, blockHeader);

  final Bytes32 addDataKey = Bytes32.random();
  when(privateStateStorage.getAddDataKey(any(Bytes32.class))).thenReturn(Optional.of(addDataKey));

  mockEnclaveForNonExistingPayload(pmt);
  mockEnclaveForAddBlob(pmt, privateTransaction, addDataKey);

  return new ExecutedPrivateTransaction(
      blockHeader.getHash(),
      blockHeader.getNumber(),
      pmt.getHash(),
      pmtLocation.getTransactionIndex(),
      privacyGroupId,
      privateTransaction);
}
 
Example 3
Source File: ChainDataProviderTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@Test
void getStateByBlockRoot_shouldReturnBeaconStateWhenFound()
    throws ExecutionException, InterruptedException {
  final ChainDataProvider provider =
      new ChainDataProvider(recentChainData, mockCombinedChainDataClient);
  final Bytes32 blockRoot = Bytes32.random();

  final SafeFuture<Optional<tech.pegasys.teku.datastructures.state.BeaconState>>
      futureBeaconState = completedFuture(Optional.of(beaconStateInternal));

  when(mockCombinedChainDataClient.isStoreAvailable()).thenReturn(true);
  when(mockCombinedChainDataClient.getStateByBlockRoot(blockRoot)).thenReturn(futureBeaconState);
  final SafeFuture<Optional<BeaconState>> future = provider.getStateByBlockRoot(blockRoot);
  verify(mockCombinedChainDataClient).getStateByBlockRoot(blockRoot);

  final BeaconState result = future.get().get();
  assertThat(result).usingRecursiveComparison().isEqualTo(beaconState);
}
 
Example 4
Source File: TransactionReceiptTest.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
@Test
void testRLPRoundtrip() {
  List<Log> logs = Collections
      .singletonList(
          new Log(
              Address.fromBytes(Bytes.random(20)),
              Bytes.of(1, 2, 3),
              Arrays.asList(Bytes32.random(), Bytes32.random())));

  LogsBloomFilter filter = LogsBloomFilter.compute(logs);

  TransactionReceipt transactionReceipt = new TransactionReceipt(Bytes32.random(), 2, filter, logs);
  Bytes rlp = RLP.encode(transactionReceipt::writeTo);
  TransactionReceipt read = RLP.decode(rlp, TransactionReceipt::readFrom);
  assertEquals(transactionReceipt, read);
}
 
Example 5
Source File: AttestationDataTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void equalsReturnsFalseWhenSourceRootsAreDifferent() {
  Checkpoint newSource = new Checkpoint(source.getEpoch(), Bytes32.random());
  AttestationData testAttestationData =
      new AttestationData(slot, index, beaconBlockRoot, newSource, target);

  assertNotEquals(attestationData, testAttestationData);
}
 
Example 6
Source File: SSZListTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void add1Test() {
  SSZMutableList<Bytes32> list = SSZList.createMutable(Bytes32.class, 10);

  Bytes32 randomBytes32 = Bytes32.random();
  list.add(randomBytes32);

  assertTrue(randomBytes32.equals(list.get(0)));
}
 
Example 7
Source File: EncryptedKeystoreWriter.java    From teku with Apache License 2.0 5 votes vote down vote up
private KeyStoreData generateKeystoreData(final BLSKeyPair key, final String password) {
  final KdfParam kdfParam = new SCryptParam(32, Bytes32.random(secureRandom));
  final Cipher cipher = new Cipher(CipherFunction.AES_128_CTR, Bytes.random(16, secureRandom));
  return KeyStore.encrypt(
      key.getSecretKey().toBytes(),
      key.getPublicKey().toBytesCompressed(),
      password,
      "",
      kdfParam,
      cipher);
}
 
Example 8
Source File: SingleQueryParameterUtilsTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void getParameterAsBytes32_shouldParseHex32String() {
  Bytes32 bytes32 = Bytes32.random();
  Map<String, List<String>> data = Map.of(KEY, List.of(bytes32.toHexString()));
  Bytes32 result = getParameterValueAsBytes32(data, KEY);
  assertEquals(bytes32, result);
}
 
Example 9
Source File: GetHeadTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnBeaconHead() throws Exception {
  GetHead handler = new GetHead(provider, jsonProvider);
  Bytes32 blockRoot = Bytes32.random();
  BeaconHead head = new BeaconHead(bestSlot, blockRoot, rootState.hash_tree_root());
  when(provider.getBeaconHead()).thenReturn(Optional.of(head));

  handler.handle(context);

  verify(context).header(Header.CACHE_CONTROL, CACHE_NONE);
  verify(context).result(jsonProvider.objectToJSON(head));
}
 
Example 10
Source File: JsonProviderTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void bytes32ShouldSerializeToJsonAndBack() throws JsonProcessingException {
  Bytes32 data = Bytes32.random();
  String serialized = jsonProvider.objectToJSON(data);
  assertEquals(Q + data.toHexString().toLowerCase() + Q, serialized);

  Bytes32 deserialize = jsonProvider.jsonToObject(serialized, Bytes32.class);
  assertEquals(data, deserialize);
}
 
Example 11
Source File: BeaconStateUtilTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void succeedsWhenGetPermutedIndexReturnsAPermutation() {
  Bytes32 seed = Bytes32.random();
  int listSize = 1000;
  boolean[] done = new boolean[listSize]; // Initialized to false
  for (int i = 0; i < listSize; i++) {
    int idx = CommitteeUtil.compute_shuffled_index(i, listSize, seed);
    assertFalse(done[idx]);
    done[idx] = true;
  }
}
 
Example 12
Source File: AttestationDataTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void equalsReturnsFalseWhenTargetRootsAreDifferent() {
  Checkpoint newTarget = new Checkpoint(target.getEpoch(), Bytes32.random());
  AttestationData testAttestationData =
      new AttestationData(slot, index, beaconBlockRoot, source, newTarget);

  assertNotEquals(attestationData, testAttestationData);
}
 
Example 13
Source File: AttestationDataTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void equalsReturnsFalseWhenBlockRootsAreDifferent() {
  AttestationData testAttestationData =
      new AttestationData(slot, index, Bytes32.random(), source, target);

  assertNotEquals(attestationData, testAttestationData);
}
 
Example 14
Source File: PrivateWorldStateReaderTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void getPrivateTransactionReceiptReturnEmptyIfReceiptDoesNotExist() {
  final Bytes32 blockHash = Bytes32.random();
  final Bytes32 transactionHash = Bytes32.random();

  when(privateStateStorage.getTransactionReceipt(blockHash, transactionHash))
      .thenReturn(Optional.empty());

  final Optional<PrivateTransactionReceipt> privateTransactionReceipt =
      privateWorldStateReader.getPrivateTransactionReceipt(
          Hash.hash(blockHash), Hash.hash(transactionHash));

  assertThat(privateTransactionReceipt).isEmpty();
}
 
Example 15
Source File: SecureScuttlebuttHandshakeClientTest.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Test
void identityMessageExchanged() {
  Signature.KeyPair clientLongTermKeyPair = Signature.KeyPair.random();
  Signature.KeyPair serverLongTermKeyPair = Signature.KeyPair.random();
  Bytes32 networkIdentifier = Bytes32.random();
  SecureScuttlebuttHandshakeClient client = SecureScuttlebuttHandshakeClient
      .create(clientLongTermKeyPair, networkIdentifier, serverLongTermKeyPair.publicKey());
  SecureScuttlebuttHandshakeServer server =
      SecureScuttlebuttHandshakeServer.create(serverLongTermKeyPair, networkIdentifier);
  Bytes initialMessage = client.createHello();
  server.readHello(initialMessage);
  client.readHello(server.createHello());
  server.readIdentityMessage(client.createIdentityMessage());
  assertEquals(clientLongTermKeyPair.publicKey(), server.clientLongTermPublicKey());
}
 
Example 16
Source File: DataStructureUtil.java    From teku with Apache License 2.0 4 votes vote down vote up
public Bytes32 randomBytes32() {
  final Random random = new Random(nextSeed());
  return Bytes32.random(random);
}
 
Example 17
Source File: HashTreeRootTest.java    From incubator-tuweni with Apache License 2.0 4 votes vote down vote up
@Test
void hashBytes32() {
  Bytes32 someBytes = Bytes32.random();
  assertEquals(someBytes, SSZ.hashTreeRoot(someBytes));
}
 
Example 18
Source File: VertxIntegrationTest.java    From incubator-tuweni with Apache License 2.0 4 votes vote down vote up
@Test
void connectToServer(@VertxInstance Vertx vertx) throws Exception {
  Signature.KeyPair serverKeyPair = Signature.KeyPair.random();
  Bytes32 networkIdentifier = Bytes32.random();
  AtomicReference<MyServerHandler> serverHandlerRef = new AtomicReference<>();
  SecureScuttlebuttVertxServer server = new SecureScuttlebuttVertxServer(
      vertx,
      new InetSocketAddress("localhost", 20000),
      serverKeyPair,
      networkIdentifier,
      (streamServer, fn) -> {
        serverHandlerRef.set(new MyServerHandler());
        return serverHandlerRef.get();
      });

  server.start().join();

  SecureScuttlebuttVertxClient client =
      new SecureScuttlebuttVertxClient(vertx, Signature.KeyPair.random(), networkIdentifier);
  MyClientHandler handler =
      client.connectTo(20000, "localhost", serverKeyPair.publicKey(), MyClientHandler::new).get();

  Thread.sleep(1000);
  assertNotNull(handler);

  String rpcRequestBody = "{\"name\": [\"whoami\"],\"type\": \"async\",\"args\":[]}";
  Bytes rpcRequest = RPCCodec.encodeRequest(rpcRequestBody, RPCFlag.BodyType.JSON);

  handler.sendMessage(rpcRequest);

  Thread.sleep(1000);
  MyServerHandler serverHandler = serverHandlerRef.get();

  Bytes receivedBytes = serverHandler.received;
  Bytes receivedBody = receivedBytes.slice(9);

  Bytes requestBody = rpcRequest.slice(9);

  assertEquals(requestBody, receivedBody);

  handler.closeStream();
  Thread.sleep(1000);
  assertTrue(serverHandler.closed);

  client.stop();
  server.stop();

}