Java Code Examples for org.apache.tuweni.bytes.Bytes#concatenate()

The following examples show how to use org.apache.tuweni.bytes.Bytes#concatenate() . 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: MemoryTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldClearMemoryAfterSourceDataWhenLengthGreaterThanSourceLengthWithMemoryOffset() {
  memory.setWord(UInt256.valueOf(64), WORD3);
  memory.setWord(UInt256.valueOf(96), WORD4);
  assertThat(memory.getWord(UInt256.valueOf(64))).isEqualTo(WORD3);
  assertThat(memory.getWord(UInt256.valueOf(96))).isEqualTo(WORD4);

  final Bytes value = Bytes.concatenate(WORD1, WORD2);
  memory.setBytes(UInt256.valueOf(10), UInt256.valueOf(96), value);
  assertThat(memory.getWord(UInt256.valueOf(10))).isEqualTo(WORD1);
  assertThat(memory.getWord(UInt256.valueOf(42))).isEqualTo(WORD2);
  assertThat(memory.getWord(UInt256.valueOf(74))).isEqualTo(Bytes32.ZERO);
  // Word 4 got partially cleared because of the starting offset.
  assertThat(memory.getWord(UInt256.valueOf(106)))
      .isEqualTo(
          Bytes32.fromHexString(
              "0x4444444444444444444444444444444444444444444400000000000000000000"));
}
 
Example 2
Source File: G2Point.java    From teku with Apache License 2.0 6 votes vote down vote up
/**
 * Serialize the point into compressed form
 *
 * <p>In compressed form we (a) pass only the X coordinate, and (b) include flags in the higher
 * order bits per the Eth2 BLS spec. We also take care about encoding the real and imaginary parts
 * in the correct order: [Im, Re]
 *
 * <p>The standard follows the ZCash format for serialization documented here:
 * https://github.com/zkcrypto/pairing/blob/master/src/bls12_381/README.md#serialization
 *
 * @return the serialized compressed form of the point
 */
@VisibleForTesting
public Bytes toBytesCompressed() {
  byte[] xReBytes = new byte[fpPointSize];
  byte[] xImBytes = new byte[fpPointSize];
  point.getX().getA().toBytes(xReBytes);
  point.getX().getB().toBytes(xImBytes);

  // Serialization flags as defined in the documentation
  boolean b1 = point.is_infinity();
  boolean a1 = !b1 && calculateYFlag(point.getY().getB());

  // c1 is always true for compressed points
  byte flags = (byte) ((4 | (b1 ? 2 : 0) | (a1 ? 1 : 0)) << 5);
  byte mask = (byte) 31;
  xImBytes[0] &= mask;
  xImBytes[0] |= flags;
  xReBytes[0] &= mask;

  return Bytes.concatenate(Bytes.wrap(xImBytes), Bytes.wrap(xReBytes));
}
 
Example 3
Source File: RPCCodec.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
/**
 * Encode a message as a RPC request.
 * 
 * @param body the body to encode as a RPC request
 * @param requestNumber the number of the request. Must be equal or greater than one.
 * @param flags the flags of the RPC request
 * @return the message encoded as a RPC request
 */
public static Bytes encodeRequest(Bytes body, int requestNumber, RPCFlag... flags) {
  if (requestNumber < 1) {
    throw new IllegalArgumentException("Invalid request number");
  }
  byte encodedFlags = 0;
  for (RPCFlag flag : flags) {
    encodedFlags = flag.apply(encodedFlags);
  }
  return Bytes
      .concatenate(
          Bytes.of(encodedFlags),
          Bytes.ofUnsignedInt(body.size()),
          Bytes.ofUnsignedInt(requestNumber),
          body);
}
 
Example 4
Source File: SecureScuttlebuttStream.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
private Bytes decrypt(Bytes message, SecretBox.Key key, MutableBytes nonce, boolean isClientToServer) {
  int index = 0;
  List<Bytes> decryptedMessages = new ArrayList<>();
  Bytes messageWithBuffer;
  if (isClientToServer) {
    messageWithBuffer = Bytes.concatenate(clientToServerBuffer, message);
  } else {
    messageWithBuffer = Bytes.concatenate(serverToClientBuffer, message);
  }

  while (index < messageWithBuffer.size()) {
    Bytes decryptedMessage = decryptMessage(messageWithBuffer.slice(index), key, nonce);
    if (decryptedMessage == null) {
      break;
    }
    decryptedMessages.add(decryptedMessage);
    index += decryptedMessage.size() + 34;
  }

  if (isClientToServer) {
    clientToServerBuffer = messageWithBuffer.slice(index);
  } else {
    serverToClientBuffer = messageWithBuffer.slice(index);
  }

  return Bytes.concatenate(decryptedMessages.toArray(new Bytes[0]));
}
 
Example 5
Source File: MemoryTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldClearMemoryAfterSourceDataWhenSourceOffsetPlusLengthGreaterThanSourceLength() {
  memory.setWord(UInt256.valueOf(64), WORD3);
  assertThat(memory.getWord(UInt256.valueOf(64))).isEqualTo(WORD3);

  final Bytes value = Bytes.concatenate(WORD1, WORD2);
  memory.setBytes(UInt256.ZERO, UInt256.valueOf(32), UInt256.valueOf(64), value);
  assertThat(memory.getWord(UInt256.ZERO)).isEqualTo(WORD2);
  assertThat(memory.getWord(UInt256.valueOf(32))).isEqualTo(Bytes32.ZERO);
  assertThat(memory.getWord(UInt256.valueOf(64))).isEqualTo(WORD3);
}
 
Example 6
Source File: AltBN128PairingPrecompiledContractTest.java    From besu with Apache License 2.0 5 votes vote down vote up
public Bytes validPointBytes() {
  final Bytes g1Point0 =
      Bytes.concatenate(
          Bytes.fromHexString(
              "0x0000000000000000000000000000000000000000000000000000000000000001"),
          Bytes.fromHexString(
              "0x0000000000000000000000000000000000000000000000000000000000000002"));
  final Bytes g2Point0 =
      Bytes.concatenate(
          Bytes.fromHexString(
              "0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2"),
          Bytes.fromHexString(
              "0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed"),
          Bytes.fromHexString(
              "0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b"),
          Bytes.fromHexString(
              "0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa"));
  final Bytes g1Point1 =
      Bytes.concatenate(
          Bytes.fromHexString(
              "0x0000000000000000000000000000000000000000000000000000000000000001"),
          Bytes.fromHexString(
              "0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd45"));
  final Bytes g2Point1 =
      Bytes.concatenate(
          Bytes.fromHexString(
              "0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2"),
          Bytes.fromHexString(
              "0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed"),
          Bytes.fromHexString(
              "0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b"),
          Bytes.fromHexString(
              "0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa"));

  return Bytes.concatenate(g1Point0, g2Point0, g1Point1, g2Point1);
}
 
Example 7
Source File: MemoryTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetMemoryWhenLengthEqualToSourceLength() {
  final Bytes value = Bytes.concatenate(WORD1, WORD2, WORD3);
  memory.setBytes(UInt256.ZERO, UInt256.valueOf(value.size()), value);
  assertThat(memory.getWord(UInt256.ZERO)).isEqualTo(WORD1);
  assertThat(memory.getWord(UInt256.valueOf(32))).isEqualTo(WORD2);
  assertThat(memory.getWord(UInt256.valueOf(64))).isEqualTo(WORD3);
}
 
Example 8
Source File: VertxGossipServer.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
void handle(Buffer data) {
  buffer = Bytes.concatenate(buffer, Bytes.wrapBuffer(data));
  while (!buffer.isEmpty()) {
    Message message;
    try {
      JsonParser parser = mapper.getFactory().createParser(buffer.toArrayUnsafe());
      message = parser.readValueAs(Message.class);
      buffer = buffer.slice((int) parser.getCurrentLocation().getByteOffset());
    } catch (IOException e) {
      return;
    }

    switch (message.verb) {
      case IHAVE:
        state.receiveIHaveMessage(peer, Bytes.fromHexString(message.hash));
        break;
      case GOSSIP:
        state
            .receiveGossipMessage(
                peer,
                message.attributes,
                Bytes.fromHexString(message.payload),
                Bytes.fromHexString(message.hash));
        break;
      case GRAFT:
        state.receiveGraftMessage(peer, Bytes.fromHexString(message.payload));
        break;
      case PRUNE:
        state.receivePruneMessage(peer);
        break;
    }
  }
}
 
Example 9
Source File: SecureScuttlebuttStream.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
private Bytes encrypt(Bytes message, SecretBox.Key clientToServerKey, MutableBytes clientToServerNonce) {
  int messages = (int) Math.ceil((double) message.size() / 4096d);

  ArrayList<Bytes> bytes = breakIntoParts(message);

  List<Bytes> segments = bytes
      .stream()
      .map(slice -> encryptMessage(slice, clientToServerKey, clientToServerNonce))
      .collect(Collectors.toList());

  return Bytes.concatenate(segments.toArray(new Bytes[] {}));
}
 
Example 10
Source File: DefaultPrivacyController.java    From besu with Apache License 2.0 5 votes vote down vote up
private CallParameter buildCallParams(final Bytes enclavePublicKey, final Bytes methodCall) {
  return new CallParameter(
      Address.ZERO,
      Address.ONCHAIN_PRIVACY_PROXY,
      3000000,
      Wei.of(1000),
      Wei.ZERO,
      Bytes.concatenate(methodCall, enclavePublicKey));
}
 
Example 11
Source File: CliqueExtraData.java    From besu with Apache License 2.0 5 votes vote down vote up
private static Bytes encode(
    final Bytes vanityData,
    final List<Address> validators,
    final Optional<Signature> proposerSeal) {
  final Bytes validatorData = Bytes.concatenate(validators.toArray(new Bytes[0]));
  return Bytes.concatenate(
      vanityData,
      validatorData,
      proposerSeal
          .map(Signature::encodedBytes)
          .orElse(Bytes.wrap(new byte[Signature.BYTES_REQUIRED])));
}
 
Example 12
Source File: AbstractGossipEncodingTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void decode_extraDataAppended() {
  final BeaconBlock block = dataStructureUtil.randomBeaconBlock(1);

  final Bytes encoded = Bytes.concatenate(encoding.encode(block), Bytes.fromHexString("0x01"));
  assertThatThrownBy(() -> encoding.decode(encoded, BeaconStateImpl.class))
      .isInstanceOf(DecodingException.class);
}
 
Example 13
Source File: EthHash.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
/**
 * Generates the EthHash cache for given parameters.
 *
 * @param cacheSize Size of the cache to generate
 * @param block Block Number to generate cache for
 * @return EthHash Cache
 */
public static UInt32[] mkCache(int cacheSize, long block) {
  int rows = cacheSize / HASH_BYTES;
  List<Bytes> cache = new ArrayList<>(rows);
  cache.add(Hash.keccak512(dagSeed(block)));

  for (int i = 1; i < rows; ++i) {
    cache.add(Hash.keccak512(cache.get(i - 1)));
  }

  Bytes completeCache = Bytes.concatenate(cache.toArray(new Bytes[cache.size()]));

  byte[] temp = new byte[HASH_BYTES];
  for (int i = 0; i < CACHE_ROUNDS; ++i) {
    for (int j = 0; j < rows; ++j) {
      int offset = j * HASH_BYTES;
      for (int k = 0; k < HASH_BYTES; ++k) {
        temp[k] = (byte) (completeCache.get((j - 1 + rows) % rows * HASH_BYTES + k)
            ^ (completeCache
                .get(
                    Integer.remainderUnsigned(completeCache.getInt(offset, ByteOrder.LITTLE_ENDIAN), rows)
                        * HASH_BYTES
                        + k)));
      }
      temp = Hash.keccak512(temp);
      System.arraycopy(temp, 0, completeCache.toArrayUnsafe(), offset, HASH_BYTES);
    }
  }
  UInt32[] result = new UInt32[completeCache.size() / 4];
  for (int i = 0; i < result.length; i++) {
    result[i] = UInt32.fromBytes(completeCache.slice(i * 4, 4).reverse());
  }

  return result;
}
 
Example 14
Source File: BeaconStateUtil.java    From teku with Apache License 2.0 4 votes vote down vote up
public static Bytes compute_domain(final Bytes4 domain_type, final Bytes32 fork_data_root) {
  return Bytes.concatenate(domain_type.getWrappedBytes(), fork_data_root.slice(0, 28));
}
 
Example 15
Source File: SECP256K1.java    From incubator-tuweni with Apache License 2.0 4 votes vote down vote up
/**
 * Computes the public key as a point on the elliptic curve.
 *
 * @return the public key as a BouncyCastle elliptic curve point
 */
public ECPoint asEcPoint() {
  // 0x04 is the prefix for uncompressed keys.
  Bytes val = Bytes.concatenate(Bytes.of(0x04), keyBytes);
  return CURVE.getCurve().decodePoint(val.toArrayUnsafe());
}
 
Example 16
Source File: TransactionSmartContractPermissioningController.java    From besu with Apache License 2.0 4 votes vote down vote up
private static Bytes encodeBytes(final Bytes value) {
  final Bytes dynamicParameterOffset = encodeLong(192);
  final Bytes length = encodeLong(value.size());
  final Bytes padding = Bytes.wrap(new byte[(32 - (value.size() % 32))]);
  return Bytes.concatenate(dynamicParameterOffset, length, value, padding);
}
 
Example 17
Source File: MockStartValidatorKeyPairFactory.java    From teku with Apache License 2.0 4 votes vote down vote up
private Bytes padLeft(Bytes input, int targetLength) {
  return Bytes.concatenate(Bytes.wrap(new byte[targetLength - input.size()]), input);
}
 
Example 18
Source File: TransactionSmartContractPermissioningController.java    From besu with Apache License 2.0 4 votes vote down vote up
private static Bytes encodeAddress(final Address address) {
  return Bytes.concatenate(Bytes.wrap(new byte[12]), address);
}
 
Example 19
Source File: SECP256K1.java    From besu with Apache License 2.0 2 votes vote down vote up
/**
 * Returns this public key as an {@link ECPoint} of Bouncy Castle, to facilitate cryptographic
 * operations.
 *
 * @return This public key represented as an Elliptic Curve point.
 */
public ECPoint asEcPoint() {
  // 0x04 is the prefix for uncompressed keys.
  final Bytes val = Bytes.concatenate(Bytes.of(0x04), encoded);
  return CURVE.getCurve().decodePoint(val.toArrayUnsafe());
}
 
Example 20
Source File: RPCCodec.java    From incubator-tuweni with Apache License 2.0 2 votes vote down vote up
/**
 * Encode a message as an RPC request.
 *
 * @param body the body to encode as an RPC request
 * @param requestNumber the request number
 * @param flags the flags of the RPC request (already encoded.)
 * @return the message encoded as an RPC request
 */
public static Bytes encodeRequest(Bytes body, int requestNumber, byte flags) {
  return Bytes
      .concatenate(Bytes.of(flags), Bytes.ofUnsignedInt(body.size()), Bytes.ofUnsignedInt(requestNumber), body);
}