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

The following examples show how to use org.apache.tuweni.bytes.Bytes#wrap() . 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: SECP256K1.java    From besu with Apache License 2.0 6 votes vote down vote up
private static boolean verifyDefault(
    final Bytes data, final Signature signature, final PublicKey pub) {
  final ECDSASigner signer = new ECDSASigner();
  final Bytes toDecode = Bytes.wrap(Bytes.of((byte) 4), pub.getEncodedBytes());
  final ECPublicKeyParameters params =
      new ECPublicKeyParameters(CURVE.getCurve().decodePoint(toDecode.toArrayUnsafe()), CURVE);
  signer.init(false, params);
  try {
    return signer.verifySignature(data.toArrayUnsafe(), signature.r, signature.s);
  } catch (final NullPointerException e) {
    // Bouncy Castle contains a bug that can cause NPEs given specially crafted signatures. Those
    // signatures
    // are inherently invalid/attack sigs so we just fail them here rather than crash the thread.
    return false;
  }
}
 
Example 2
Source File: EthHashTest.java    From besu with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies hashing against block 300005 of the public Ethereum chain.
 *
 * @throws Exception On Failure
 */
@Test
public void hashimotoLight() throws Exception {
  final RLPInput input =
      new BytesValueRLPInput(
          Bytes.wrap(Resources.toByteArray(EthHashTest.class.getResource("block_300005.blocks"))),
          false);
  input.enterList();
  final BlockHeader header = BlockHeader.readFrom(input, new MainnetBlockHeaderFunctions());
  final long blockNumber = header.getNumber();
  final long epoch = EthHash.epoch(blockNumber);
  final long datasetSize = EthHash.datasetSize(epoch);
  final long cacheSize = EthHash.cacheSize(epoch);
  Assertions.assertThat(datasetSize).isEqualTo(1157627776);
  Assertions.assertThat(cacheSize).isEqualTo(18087488);
  final int[] cache = EthHash.mkCache((int) cacheSize, blockNumber);
  Assertions.assertThat(
          Hash.wrap(
              Bytes32.wrap(
                  Arrays.copyOf(
                      EthHash.hashimotoLight(
                          datasetSize, cache, EthHash.hashHeader(header), header.getNonce()),
                      32))))
      .isEqualTo(header.getMixHash());
}
 
Example 3
Source File: IbftExtraDataTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void fullyPopulatedDataIsEncodedAndDecodedCorrectly() {
  final List<Address> validators =
      Arrays.asList(Address.fromHexString("1"), Address.fromHexString("2"));
  final Optional<Vote> vote = Optional.of(Vote.authVote(Address.fromHexString("1")));
  final int round = 0x00FEDCBA;
  final List<Signature> committerSeals =
      Arrays.asList(
          Signature.create(BigInteger.ONE, BigInteger.TEN, (byte) 0),
          Signature.create(BigInteger.TEN, BigInteger.ONE, (byte) 0));

  // Create a byte buffer with no data.
  final byte[] vanity_bytes = createNonEmptyVanityData();
  final Bytes vanity_data = Bytes.wrap(vanity_bytes);

  IbftExtraData expectedExtraData =
      new IbftExtraData(vanity_data, committerSeals, vote, round, validators);

  IbftExtraData actualExtraData = IbftExtraData.decodeRaw(expectedExtraData.encode());

  assertThat(actualExtraData).isEqualToComparingFieldByField(expectedExtraData);
}
 
Example 4
Source File: GossipHandler.java    From teku with Apache License 2.0 6 votes vote down vote up
@Override
public SafeFuture<ValidationResult> apply(final MessageApi message) {
  final int messageSize = message.getData().capacity();
  if (messageSize > GOSSIP_MAX_SIZE) {
    LOG.trace(
        "Rejecting gossip message of length {} which exceeds maximum size of {}",
        messageSize,
        GOSSIP_MAX_SIZE);
    return VALIDATION_FAILED;
  }
  byte[] arr = new byte[message.getData().readableBytes()];
  message.getData().slice().readBytes(arr);
  Bytes bytes = Bytes.wrap(arr);
  if (!processedMessages.add(bytes)) {
    // We've already seen this message, skip processing
    LOG.trace("Ignoring duplicate message for topic {}: {} bytes", topic, bytes.size());
    return VALIDATION_IGNORED;
  }
  LOG.trace("Received message for topic {}: {} bytes", topic, bytes.size());

  final ValidationResult result = handler.handleMessage(bytes);
  return SafeFuture.completedFuture(result);
}
 
Example 5
Source File: CliqueExtraDataTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void parseRinkebyGenesisBlockExtraData() {
  // Rinkeby genesis block extra data text found @ rinkeby.io
  final byte[] genesisBlockExtraData =
      Hex.decode(
          "52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");

  final Bytes bufferToInject = Bytes.wrap(genesisBlockExtraData);

  final CliqueExtraData extraData =
      CliqueExtraData.decodeRaw(
          new BlockHeaderTestFixture()
              .number(BlockHeader.GENESIS_BLOCK_NUMBER)
              .blockHeaderFunctions(new CliqueBlockHeaderFunctions())
              .extraData(bufferToInject)
              .buildHeader());
  assertThat(extraData.getProposerSeal()).isEmpty();
  assertThat(extraData.getValidators().size()).isEqualTo(3);
}
 
Example 6
Source File: IbftExtraData.java    From besu with Apache License 2.0 5 votes vote down vote up
public Bytes encode() {
  final BytesValueRLPOutput encoder = new BytesValueRLPOutput();
  encoder.startList();
  encoder.writeList(validators, (validator, rlp) -> rlp.writeBytes(validator));
  if (proposerSeal != null) {
    encoder.writeBytes(proposerSeal.encodedBytes());
  } else {
    encoder.writeNull();
  }
  encoder.writeList(seals, (committer, rlp) -> rlp.writeBytes(committer.encodedBytes()));
  encoder.endList();

  return Bytes.wrap(vanityData, encoder.encoded());
}
 
Example 7
Source File: EncryptedMessageTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void eip8RoundTrip() throws InvalidCipherTextException {
  final SECP256K1.KeyPair keyPair = SECP256K1.KeyPair.generate();
  final byte[] message = new byte[288];
  ThreadLocalRandom.current().nextBytes(message);
  final Bytes initial = Bytes.wrap(message);
  final Bytes encrypted = EncryptedMessage.encryptMsgEip8(initial, keyPair.getPublicKey());
  final Bytes decrypted =
      EncryptedMessage.decryptMsgEIP8(encrypted, NodeKeyUtils.createFrom(keyPair));
  Assertions.assertThat(decrypted.slice(0, 288)).isEqualTo(initial);
}
 
Example 8
Source File: CliqueExtraDataTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void insufficientDataResultsInAnIllegalArgumentException() {
  final Bytes illegalData =
      Bytes.wrap(new byte[Signature.BYTES_REQUIRED + CliqueExtraData.EXTRA_VANITY_LENGTH - 1]);

  assertThatThrownBy(() -> CliqueExtraData.decodeRaw(createHeaderWithExtraData(illegalData)))
      .isInstanceOf(IllegalArgumentException.class)
      .hasMessage(
          "Invalid Bytes supplied - too short to produce a valid Clique Extra Data object.");
}
 
Example 9
Source File: ValidationTestUtils.java    From besu with Apache License 2.0 5 votes vote down vote up
public static Block readBlock(final long num) throws IOException {
  final RLPInput input =
      new BytesValueRLPInput(
          Bytes.wrap(
              Resources.toByteArray(
                  EthHashTest.class.getResource(String.format("block_%d.blocks", num)))),
          false);
  input.enterList();
  final BlockHeader header = BlockHeader.readFrom(input, new MainnetBlockHeaderFunctions());
  final List<Transaction> transactions = input.readList(Transaction::readFrom);
  final List<BlockHeader> ommers =
      input.readList(rlp -> BlockHeader.readFrom(rlp, new MainnetBlockHeaderFunctions()));
  final BlockBody body = new BlockBody(transactions, ommers);
  return new Block(header, body);
}
 
Example 10
Source File: BLSSignatureTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void succeedsIfDeserializationOfEmptySignatureIsCorrect() {
  BLSSignature emptySignature = BLSSignature.empty();
  Bytes zeroBytes = Bytes.wrap(new byte[96]);
  Bytes emptyBytesSsz = SSZ.encode(writer -> writer.writeFixedBytes(zeroBytes));
  BLSSignature deserializedSignature = BLSSignature.fromBytes(emptyBytesSsz);
  assertEquals(emptySignature, deserializedSignature);
}
 
Example 11
Source File: BLSPerformanceRunner.java    From teku with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest()
@MethodSource("singleAggregationCountOrder4")
void testSigning(Integer i) {
  Bytes message = Bytes.wrap("Hello, world!".getBytes(UTF_8));

  BLSKeyPair keyPair1 = BLSKeyPair.random(1);

  Long time = executeRun(() -> BLS.sign(keyPair1.getSecretKey(), message), i);
  LOG.info("Time for i: {}, time: {}", i, time);
}
 
Example 12
Source File: SSZ.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
static void encodeStringListTo(List<String> elements, Consumer<Bytes> appender) {
  Bytes[] elementBytes = new Bytes[elements.size()];
  for (int i = 0; i < elements.size(); ++i) {
    elementBytes[i] = Bytes.wrap(elements.get(i).getBytes(UTF_8));
  }
  encodeBytesListTo(elementBytes, appender);
}
 
Example 13
Source File: BLS12381Test.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void signAndVerifyDifferentMessage() {
  KeyPair keyPair = KeyPair.random(117);
  Bytes message1 = Bytes.wrap("Hello, world!".getBytes(UTF_8));
  Bytes message2 = Bytes.wrap("Hello, world?".getBytes(UTF_8));
  Signature signature = BLS12381.sign(keyPair.secretKey(), message1);
  assertFalse(BLS12381.verify(keyPair.publicKey(), message2, signature));
}
 
Example 14
Source File: G1Point.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
Bytes toBytes() {
  // Size of the byte array representing compressed ECP point for BLS12-381 is
  // 49 bytes in milagro
  // size of the point = 48 bytes
  // meta information (parity bit, curve type etc) = 1 byte
  byte[] bytes = new byte[fpPointSize + 1];
  point.toBytes(bytes, true);
  return Bytes.wrap(bytes);
}
 
Example 15
Source File: DefaultDetachedEncryptionResult.java    From incubator-tuweni with Apache License 2.0 4 votes vote down vote up
@Override
public Bytes mac() {
  return Bytes.wrap(mac);
}
 
Example 16
Source File: LibP2PNodeId.java    From teku with Apache License 2.0 4 votes vote down vote up
@Override
public Bytes toBytes() {
  return Bytes.wrap(peerId.getBytes());
}
 
Example 17
Source File: MockStartValidatorKeyPairFactory.java    From teku with Apache License 2.0 4 votes vote down vote up
private Bytes sha256(final Bytes indexBytes) {
  final MessageDigest sha256Digest = getSha256Digest();
  indexBytes.update(sha256Digest);
  return Bytes.wrap(sha256Digest.digest());
}
 
Example 18
Source File: DefaultDetachedEncryptionResult.java    From incubator-tuweni with Apache License 2.0 4 votes vote down vote up
@Override
public Bytes cipherText() {
  return Bytes.wrap(cipherText);
}
 
Example 19
Source File: Base32.java    From incubator-tuweni with Apache License 2.0 2 votes vote down vote up
/**
 * Decode a base32 encoded string to bytes.
 *
 * @param b32 The base32 encoded string.
 * @return The decoded bytes.
 */
public static Bytes decode(String b32) {
  return Bytes.wrap(decodeBytes(b32));
}
 
Example 20
Source File: AES256GCM.java    From incubator-tuweni with Apache License 2.0 2 votes vote down vote up
/**
 * Encrypt a message.
 *
 * @param message The message to encrypt.
 * @param data Extra non-confidential data that will be included with the encrypted payload.
 * @param nonce A unique nonce.
 * @return The encrypted data.
 */
public Bytes encrypt(Bytes message, Bytes data, Nonce nonce) {
  return Bytes.wrap(encrypt(message.toArrayUnsafe(), data.toArrayUnsafe(), nonce));
}