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

The following examples show how to use org.apache.tuweni.bytes.Bytes#fromHexString() . 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: BlockchainReferenceTestCaseSpec.java    From besu with Apache License 2.0 6 votes vote down vote up
@JsonCreator
public CandidateBlock(
    @JsonProperty("rlp") final String rlp,
    @JsonProperty("blockHeader") final Object blockHeader,
    @JsonProperty("transactions") final Object transactions,
    @JsonProperty("uncleHeaders") final Object uncleHeaders) {
  Boolean valid = true;
  // The BLOCK__WrongCharAtRLP_0 test has an invalid character in its rlp string.
  Bytes rlpAttempt = null;
  try {
    rlpAttempt = Bytes.fromHexString(rlp);
  } catch (final IllegalArgumentException e) {
    valid = false;
  }
  this.rlp = rlpAttempt;

  if (blockHeader == null && transactions == null && uncleHeaders == null) {
    valid = false;
  }

  this.valid = valid;
}
 
Example 2
Source File: DisconnectMessageTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void readFromWithInvalidReason() {
  String[] invalidReasons = {
    "0xC10C",
    "0xC155",
    // List containing a byte > 128 (negative valued)
    "0xC281FF",
    // List containing a multi-byte reason
    "0xC3820101"
  };

  for (String invalidReason : invalidReasons) {
    MessageData messageData =
        new RawMessage(WireMessageCodes.DISCONNECT, Bytes.fromHexString(invalidReason));
    DisconnectMessage disconnectMessage = DisconnectMessage.readFrom(messageData);
    DisconnectReason reason = disconnectMessage.getReason();
    assertThat(reason).isEqualTo(DisconnectReason.UNKNOWN);
  }
}
 
Example 3
Source File: SimpleOffsetSerializer.java    From teku with Apache License 2.0 5 votes vote down vote up
public static Bytes serializeFixedCompositeList(
    SSZList<? extends SimpleOffsetSerializable> values) {
  return Bytes.fromHexString(
      values.stream()
          .map(item -> serialize(item).toHexString().substring(2))
          .collect(Collectors.joining()));
}
 
Example 4
Source File: MultiaddrUtilTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void fromDiscoveryPeer_shouldConvertRealPeer() throws Exception {
  final DiscoveryPeer peer =
      new DiscoveryPeer(
          Bytes.fromHexString(
              "0x03B86ED9F747A7FA99963F39E3B176B45E9E863108A2D145EA3A4E76D8D0935194"),
          new InetSocketAddress(InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), 9000),
          ENR_FORK_ID);
  final Multiaddr expectedMultiAddr =
      Multiaddr.fromString(
          "/ip4/127.0.0.1/tcp/9000/p2p/16Uiu2HAmR4wQRGWgCNy5uzx7HfuV59Q6X1MVzBRmvreuHgEQcCnF");
  assertThat(MultiaddrUtil.fromDiscoveryPeer(peer)).isEqualTo(expectedMultiAddr);
}
 
Example 5
Source File: TransactionIntegrationTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecodeAndEncodeTransactionCorrectly() {
  final String encodedString =
      "0xf9025780843b9aca00832dc6c08080b90202608060405234801561001057600080fd5b506040516020806101e283398101604052516000556101ae806100346000396000f30060806040526004361061006c5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416632113522a81146100715780632a1afcd9146100af5780633bc5de30146100d657806360fe47b1146100eb578063db613e8114610105575b600080fd5b34801561007d57600080fd5b5061008661011a565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b3480156100bb57600080fd5b506100c4610136565b60408051918252519081900360200190f35b3480156100e257600080fd5b506100c461013c565b3480156100f757600080fd5b50610103600435610142565b005b34801561011157600080fd5b50610086610166565b60015473ffffffffffffffffffffffffffffffffffffffff1681565b60005481565b60005490565b6000556001805473ffffffffffffffffffffffffffffffffffffffff191633179055565b60015473ffffffffffffffffffffffffffffffffffffffff16905600a165627a7a723058208293fac83e9cc01039adf5e41eefd557d1324a3a4c830a4802fa1dd2515227a20029000000000000000000000000000000000000000000000000000000000000000c830628cba0482ba9b1136cd9337408938eea6b991fd153900a014867da2f4bb113d4003888a00c5a2f8f279fe2c86831afb5c9578dd1c3be457e3aca3abe439b1a5dd122e676";
  final Bytes encoded = Bytes.fromHexString(encodedString);
  final RLPInput input = RLP.input(encoded);
  final Transaction transaction = Transaction.readFrom(input);
  final BytesValueRLPOutput output = new BytesValueRLPOutput();
  transaction.writeTo(output);
  assertThat(output.encoded().toString()).isEqualTo(encodedString);
}
 
Example 6
Source File: KeyValueStorageWorldStateStorageTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void getAccountStorageTrieNode_saveAndGetRegularValue() {
  final Bytes bytes = Bytes.fromHexString("0x123456");
  final WorldStateKeyValueStorage storage = emptyStorage();
  storage.updater().putAccountStorageTrieNode(Hash.hash(bytes), bytes).commit();

  assertThat(storage.getAccountStateTrieNode(Hash.hash(bytes))).contains(bytes);
}
 
Example 7
Source File: SignerTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSignAttestationData() {
  final AttestationData attestationData = dataStructureUtil.randomAttestationData();
  final BLSSignature signature = dataStructureUtil.randomSignature();
  final Bytes expectedSigningRoot =
      Bytes.fromHexString("0xc9e1788b5b1864e701e69969418d635ac48f1e7b6ab65113f981798d55f305cc");
  when(signerService.signAttestation(expectedSigningRoot))
      .thenReturn(SafeFuture.completedFuture(signature));

  final SafeFuture<BLSSignature> result = signer.signAttestationData(attestationData, fork);

  verify(signerService).signAttestation(expectedSigningRoot);
  assertThat(result).isCompletedWithValue(signature);
}
 
Example 8
Source File: VMReferenceTestCaseSpec.java    From besu with Apache License 2.0 5 votes vote down vote up
@JsonCreator
public VMReferenceTestCaseSpec(
    @JsonProperty("exec") final EnvironmentInformation exec,
    @JsonProperty("env") final BlockHeaderMock env,
    @JsonProperty("gas") final String finalGas,
    @JsonProperty("out") final String out,
    @JsonProperty("pre") final WorldStateMock initialWorldState,
    @JsonProperty("post") final WorldStateMock finalWorldState) {
  this.exec = exec;
  this.initialWorldState = initialWorldState;
  this.initialWorldState.persist();
  exec.setBlockHeader(env);

  if (finalGas != null && out != null && finalWorldState != null) {
    this.finalGas = Gas.fromHexString(finalGas);
    this.finalWorldState = finalWorldState;
    this.out = Bytes.fromHexString(out);
    this.exceptionalHaltExpected = false;
  } else {
    this.exceptionalHaltExpected = true;
    // These values should never be checked if this is a test case that
    // exceptionally halts.
    this.finalGas = null;
    this.finalWorldState = null;
    this.out = null;
  }
}
 
Example 9
Source File: SignerTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSignBlock() {
  final BeaconBlock block = dataStructureUtil.randomBeaconBlock(10);
  final BLSSignature signature = dataStructureUtil.randomSignature();
  final Bytes expectedSigningRoot =
      Bytes.fromHexString("0x4f8543ecbb40d4f3b492fb1a890b9a569abc88b9cb1c3eac9f7c824623a3879d");
  when(signerService.signBlock(expectedSigningRoot))
      .thenReturn(SafeFuture.completedFuture(signature));

  final SafeFuture<BLSSignature> result = signer.signBlock(block, fork);

  verify(signerService).signBlock(expectedSigningRoot);
  assertThat(result).isCompletedWithValue(signature);
}
 
Example 10
Source File: HashTreeUtilTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void testMerkleize() {
  final List<Bytes32> input =
      Arrays.asList(
          Bytes32.fromHexString(
              "0xA99A76ED7796F7BE22D5B7E85DEEB7C5677E88E511E0B337618F8C4EB61349B4"),
          Bytes32.fromHexString(
              "0xBF2D153F649F7B53359FE8B94A38E44C00000000000000000000000000000000"));

  final Bytes expected =
      Bytes.fromHexString("0x89E40BFF069E391CA393901DA3287BBE35DC429265927ABE3C3F06BEC8E0B9CD");
  assertEquals(expected, HashTreeUtil.merkleize(input));
}
 
Example 11
Source File: DisconnectMessageTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void readFromWithReason() {
  MessageData messageData =
      new RawMessage(WireMessageCodes.DISCONNECT, Bytes.fromHexString("0xC103"));
  DisconnectMessage disconnectMessage = DisconnectMessage.readFrom(messageData);

  DisconnectReason reason = disconnectMessage.getReason();
  assertThat(reason).isEqualTo(DisconnectReason.USELESS_PEER);
}
 
Example 12
Source File: SimpleOffsetSerializerTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void deserialize_extraDataAppended() {
  final Checkpoint checkpoint = dataStructureUtil.randomCheckpoint();
  final Bytes extraData = Bytes.fromHexString("0x00");

  final Bytes checkpointData = SimpleOffsetSerializer.serialize(checkpoint);
  final Bytes encoded = Bytes.concatenate(checkpointData, extraData);
  assertThatThrownBy(() -> SimpleOffsetSerializer.deserialize(encoded, Checkpoint.class))
      .isInstanceOf(IllegalStateException.class)
      .hasMessageContaining("Unread data detected");
}
 
Example 13
Source File: SignatureTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
void succeedsWhenEqualsReturnsTrueForInvalidSignatures() {
  final Bytes rawData = Bytes.fromHexString("1".repeat(HEX_CHARS_REQUIRED));
  final Signature signature1 = Signature.fromBytes(rawData);
  final Signature signature2 = Signature.fromBytes(rawData);
  assertEquals(signature1, signature2);
  assertEquals(signature1.hashCode(), signature2.hashCode());
}
 
Example 14
Source File: BlockTopicHandlerTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void handleMessage_invalidBlock_invalidSSZ() {
  Bytes serialized = Bytes.fromHexString("0x1234");

  final ValidationResult result = topicHandler.handleMessage(serialized);
  assertThat(result).isEqualTo(ValidationResult.Invalid);
}
 
Example 15
Source File: MultiaddrUtilTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void fromDiscoveryPeerAsUdp_shouldConvertDiscoveryPeer() throws Exception {
  final DiscoveryPeer peer =
      new DiscoveryPeer(
          Bytes.fromHexString(
              "0x03B86ED9F747A7FA99963F39E3B176B45E9E863108A2D145EA3A4E76D8D0935194"),
          new InetSocketAddress(InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), 9000),
          ENR_FORK_ID);
  final Multiaddr expectedMultiAddr =
      Multiaddr.fromString(
          "/ip4/127.0.0.1/udp/9000/p2p/16Uiu2HAmR4wQRGWgCNy5uzx7HfuV59Q6X1MVzBRmvreuHgEQcCnF");
  assertThat(MultiaddrUtil.fromDiscoveryPeerAsUdp(peer)).isEqualTo(expectedMultiAddr);
}
 
Example 16
Source File: KeyFormatterTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldShowFirstSevenBytesOfPublicKey() {
  Bytes keyBytes =
      Bytes.fromHexString(
          "0xab10fc693d038b73d67279127501a05f0072cbb7147c68650ef6ac4e0a413e5cabd1f35c8711e1f7d9d885bbc3b8eddc");
  BLSPublicKey blsPublicKey = BLSPublicKey.fromBytes(keyBytes);
  assertThat(KeyFormatter.shortPublicKey(blsPublicKey)).isEqualTo("ab10fc6");
}
 
Example 17
Source File: IdentityTest.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Test
void testKeyPairAndPublicKey() {
  Signature.KeyPair kp = Signature.KeyPair.random();
  Identity id = Identity.fromKeyPair(kp);
  Identity idWithPk = Identity.fromPublicKey(kp.publicKey());
  assertEquals(id.toCanonicalForm(), idWithPk.toCanonicalForm());
  assertEquals(id.toString(), idWithPk.toString());
  Bytes message = Bytes.fromHexString("deadbeef");
  Bytes signature = id.sign(message);
  assertTrue(idWithPk.verify(signature, message));
  assertEquals(kp.publicKey(), id.ed25519PublicKey());
}
 
Example 18
Source File: Address.java    From besu with Apache License 2.0 5 votes vote down vote up
/**
 * Parse an hexadecimal string representing an account address.
 *
 * @param str An hexadecimal string representing a valid account address (strictly 20 bytes).
 * @return The parsed address.
 * @throws IllegalArgumentException if the provided string is {@code null}.
 * @throws IllegalArgumentException if the string is either not hexadecimal, or not the valid
 *     representation of a 20 byte address.
 */
public static Address fromHexStringStrict(final String str) {
  checkArgument(str != null);
  final Bytes value = Bytes.fromHexString(str);
  checkArgument(
      value.size() == SIZE,
      "An account address must be be %s bytes long, got %s",
      SIZE,
      value.size());
  return new Address(value);
}
 
Example 19
Source File: PeerDiscoveryControllerDistanceCalculatorTest.java    From besu with Apache License 2.0 4 votes vote down vote up
@Test
public void distance2() {
  final Bytes id1 = Bytes.fromHexString("0x8f19400000");
  final Bytes id2 = Bytes.fromHexString("0x8f19400002");
  assertThat(distance(id1, id2)).isEqualTo(2);
}
 
Example 20
Source File: GossipHandlerTest.java    From teku with Apache License 2.0 4 votes vote down vote up
@Test
public void gossip_newMessage() {
  final Bytes message = Bytes.fromHexString("0x01");
  gossipHandler.gossip(message);
  verify(publisher).publish(toByteBuf(message), topic);
}