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

The following examples show how to use org.apache.tuweni.bytes.Bytes32#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: PrivateWorldStateReaderTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void absentAccountReturnsEmpty() {
  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.of(privateWorldState));
  when(privateWorldState.get(eq(contractAddress))).thenReturn(null);

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

  assertThat(maybeContractCode).isNotPresent();
}
 
Example 2
Source File: TrieIterator.java    From besu with Apache License 2.0 5 votes vote down vote up
private Bytes32 keyHash() {
  final Iterator<Bytes> iterator = paths.descendingIterator();
  Bytes fullPath = iterator.next();
  while (iterator.hasNext()) {
    fullPath = Bytes.wrap(fullPath, iterator.next());
  }
  return fullPath.isZero()
      ? Bytes32.ZERO
      : Bytes32.wrap(CompactEncoding.pathToBytes(fullPath), 0);
}
 
Example 3
Source File: ECPointUtil.java    From besu with Apache License 2.0 5 votes vote down vote up
public static ECPoint fromBouncyCastleECPoint(
    final org.bouncycastle.math.ec.ECPoint bouncyCastleECPoint) {
  final ECFieldElement xCoord = bouncyCastleECPoint.getAffineXCoord();
  final ECFieldElement yCoord = bouncyCastleECPoint.getAffineYCoord();

  final Bytes32 xEncoded = Bytes32.wrap(xCoord.getEncoded());
  final Bytes32 yEncoded = Bytes32.wrap(yCoord.getEncoded());

  final BigInteger x = xEncoded.toUnsignedBigInteger();
  final BigInteger y = yEncoded.toUnsignedBigInteger();

  return new ECPoint(x, y);
}
 
Example 4
Source File: Hash.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
/**
 * Digest using SHA3-256.
 *
 * @param input The value to encode.
 * @return A digest.
 */
public static Bytes32 sha3_256(Bytes input) {
  try {
    return Bytes32.wrap(digestUsingAlgorithm(input, SHA3_256).toArrayUnsafe());
  } catch (NoSuchAlgorithmException e) {
    throw new IllegalStateException("Algorithm should be available but was not", e);
  }
}
 
Example 5
Source File: VersionProvider.java    From teku with Apache License 2.0 5 votes vote down vote up
public static Bytes32 getDefaultGraffiti() {
  final String graffitiVersionString = CLIENT_IDENTITY + "/" + IMPLEMENTATION_VERSION;
  final Bytes versionBytes = Bytes.wrap(graffitiVersionString.getBytes(StandardCharsets.UTF_8));
  if (versionBytes.size() <= Bytes32.SIZE) {
    return Bytes32.rightPad(versionBytes);
  } else {
    return Bytes32.wrap(versionBytes.slice(0, Bytes32.SIZE));
  }
}
 
Example 6
Source File: SimpleOffsetSerializer.java    From teku with Apache License 2.0 5 votes vote down vote up
private static Object deserializePrimitive(
    Class classInfo, SSZReader reader, MutableInt bytePointer) {
  switch (classInfo.getSimpleName()) {
    case "UnsignedLong":
      bytePointer.add(8);
      return UnsignedLong.fromLongBits(reader.readUInt64());
    case "ArrayWrappingBytes32":
    case "Bytes32":
      bytePointer.add(32);
      return Bytes32.wrap(reader.readFixedBytes(32));
    case "Bytes4":
      bytePointer.add(4);
      return new Bytes4(reader.readFixedBytes(4));
    case "BLSSignature":
      bytePointer.add(96);
      return BLSSignature.fromBytes(reader.readFixedBytes(96));
    case "BLSPublicKey":
      bytePointer.add(48);
      return BLSPublicKey.fromBytes(reader.readFixedBytes(48));
    case "Boolean":
    case "boolean":
      bytePointer.add(1);
      return reader.readBoolean();
    default:
      throw new IllegalArgumentException("Unable to deserialize " + classInfo.getSimpleName());
  }
}
 
Example 7
Source File: PrivateTransaction.java    From besu with Apache License 2.0 5 votes vote down vote up
/**
 * Determines the privacy group id. Either returning the value of privacyGroupId field if it
 * exists or calculating the EEA privacyGroupId from the privateFrom and privateFor fields.
 *
 * @return the privacyGroupId
 */
public Bytes32 determinePrivacyGroupId() {
  if (getPrivacyGroupId().isPresent()) {
    return Bytes32.wrap(getPrivacyGroupId().get());
  } else {
    final List<Bytes> privateFor = getPrivateFor().orElse(Lists.newArrayList());
    return PrivacyGroupUtil.calculateEeaPrivacyGroupId(getPrivateFrom(), privateFor);
  }
}
 
Example 8
Source File: ECIESHandshaker.java    From besu with Apache License 2.0 5 votes vote down vote up
@Override
public void prepareResponder(final NodeKey nodeKey) {
  checkState(
      status.compareAndSet(
          Handshaker.HandshakeStatus.UNINITIALIZED, Handshaker.HandshakeStatus.IN_PROGRESS),
      "handshake was already prepared");

  this.initiator = false;
  this.nodeKey = nodeKey;
  this.ephKeyPair = SECP256K1.KeyPair.generate();
  this.responderNonce = Bytes32.wrap(random(32), 0);
  LOG.trace("Prepared ECIES handshake under RESPONDER role");
}
 
Example 9
Source File: RLPxConnectionFactory.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a RLPxConnection in response to a handshake initiation message.
 *
 * @param initiatorMessageBytes the initiation message raw bytes
 * @param keyPair our key pair
 * @param responseHandler a function to respond back to the peer that we acknowledged the connection
 * @return a valid RLPxConnection
 */
public static RLPxConnection respondToHandshake(
    Bytes initiatorMessageBytes,
    KeyPair keyPair,
    Consumer<Bytes> responseHandler) {
  InitiatorHandshakeMessage initiatorHandshakeMessage = read(initiatorMessageBytes, keyPair.secretKey());
  Bytes32 nonce = Bytes32.wrap(new byte[32]);
  random.nextBytes(nonce.toArrayUnsafe());
  KeyPair ephemeralKeyPair = KeyPair.random();

  PublicKey initiatorPublicKey = initiatorHandshakeMessage.publicKey();

  ResponderHandshakeMessage responderMessage = ResponderHandshakeMessage.create(ephemeralKeyPair.publicKey(), nonce);
  Bytes responseBytes = encryptMessage(responderMessage.encode(), initiatorPublicKey);
  responseHandler.accept(responseBytes);

  return createConnection(
      false,
      initiatorMessageBytes,
      responseBytes,
      ephemeralKeyPair.secretKey(),
      initiatorHandshakeMessage.ephemeralPublicKey(),
      initiatorHandshakeMessage.nonce(),
      nonce,
      keyPair.publicKey(),
      initiatorPublicKey);
}
 
Example 10
Source File: ResponderHandshakeMessageV1.java    From besu with Apache License 2.0 5 votes vote down vote up
public static ResponderHandshakeMessageV1 decode(final Bytes bytes) {
  checkArgument(bytes.size() == MESSAGE_LENGTH);

  final Bytes pubk = bytes.slice(0, ECIESHandshaker.PUBKEY_LENGTH);
  final SECP256K1.PublicKey ephPubKey = SECP256K1.PublicKey.create(pubk);
  final Bytes32 nonce =
      Bytes32.wrap(bytes.slice(ECIESHandshaker.PUBKEY_LENGTH, ECIESHandshaker.NONCE_LENGTH), 0);
  final boolean token =
      bytes.get(ECIESHandshaker.PUBKEY_LENGTH + ECIESHandshaker.NONCE_LENGTH) == 0x01;
  return new ResponderHandshakeMessageV1(ephPubKey, nonce, token);
}
 
Example 11
Source File: SECP256K1.java    From besu with Apache License 2.0 5 votes vote down vote up
private static Signature signNative(final Bytes32 dataHash, final KeyPair keyPair) {
  final LibSecp256k1.secp256k1_ecdsa_recoverable_signature signature =
      new secp256k1_ecdsa_recoverable_signature();
  // sign in internal form
  if (LibSecp256k1.secp256k1_ecdsa_sign_recoverable(
          LibSecp256k1.CONTEXT,
          signature,
          dataHash.toArrayUnsafe(),
          keyPair.privateKey.getEncoded(),
          null,
          null)
      == 0) {
    throw new RuntimeException(
        "Could not natively sign. Private Key is invalid or default nonce generation failed.");
  }

  // encode to compact form
  final ByteBuffer compactSig = ByteBuffer.allocate(64);
  final IntByReference recId = new IntByReference(0);
  LibSecp256k1.secp256k1_ecdsa_recoverable_signature_serialize_compact(
      LibSecp256k1.CONTEXT, compactSig, recId, signature);
  compactSig.flip();
  final byte[] sig = compactSig.array();

  // wrap in signature object
  final Bytes32 r = Bytes32.wrap(sig, 0);
  final Bytes32 s = Bytes32.wrap(sig, 32);
  return Signature.create(
      r.toUnsignedBigInteger(), s.toUnsignedBigInteger(), (byte) recId.getValue());
}
 
Example 12
Source File: DepositGenerator.java    From teku with Apache License 2.0 4 votes vote down vote up
private Bytes32 createWithdrawalCredentials(final BLSPublicKey withdrawalPublicKey) {
  final Bytes publicKeyHash = sha256(withdrawalPublicKey.toBytesCompressed());
  final Bytes credentials = Bytes.wrap(BLS_WITHDRAWAL_PREFIX, publicKeyHash.slice(1));
  return Bytes32.wrap(credentials);
}
 
Example 13
Source File: RLPxConnectionFactory.java    From incubator-tuweni with Apache License 2.0 4 votes vote down vote up
/**
 * Generates a new random 32 byte array.
 *
 * @return a new Bytes32 object filled with random bytes
 */
public static Bytes32 generateRandomBytes32() {
  Bytes32 nonce = Bytes32.wrap(new byte[32]);
  random.nextBytes(nonce.toArrayUnsafe());
  return nonce;
}
 
Example 14
Source File: TestDataUtils.java    From teku with Apache License 2.0 4 votes vote down vote up
public static Bytes32 loadBytes32FromSsz(
    final TestDefinition testDefinition, final String fileName) throws IOException {
  final Path path = testDefinition.getTestDirectory().resolve(fileName);
  return Bytes32.wrap(Files.readAllBytes(path));
}
 
Example 15
Source File: PeerStatusFactory.java    From teku with Apache License 2.0 4 votes vote down vote up
private final Bytes32 randomBytes32() {
  return Bytes32.wrap(randomBytes(32));
}
 
Example 16
Source File: BeaconStateUtil.java    From teku with Apache License 2.0 4 votes vote down vote up
public static Bytes32 int_to_bytes32(long value) {
  return Bytes32.wrap(int_to_bytes(value, 32));
}
 
Example 17
Source File: PatchworkIntegrationTest.java    From incubator-tuweni with Apache License 2.0 4 votes vote down vote up
@Disabled
@Test
void runWithPatchWork(@VertxInstance Vertx vertx) throws Exception {
  String host = "localhost";
  int port = 8008;

  Optional<String> ssbDir = Optional.fromNullable(System.getenv().get("ssb_dir"));
  Optional<String> homePath =
      Optional.fromNullable(System.getProperty("user.home")).transform(home -> home + "/.ssb");

  Optional<String> path = ssbDir.or(homePath);

  if (!path.isPresent()) {
    throw new Exception("Cannot find ssb directory config value");
  }

  String secretPath = path.get() + "/secret";
  File file = new File(secretPath);

  if (!file.exists()) {
    throw new Exception("Secret file does not exist");
  }

  Scanner s = new Scanner(file, UTF_8.name());
  s.useDelimiter("\n");

  ArrayList<String> list = new ArrayList<String>();
  while (s.hasNext()) {
    String next = s.next();

    // Filter out the comment lines
    if (!next.startsWith("#")) {
      list.add(next);
    }
  }

  String secretJSON = String.join("", list);

  ObjectMapper mapper = new ObjectMapper();

  HashMap<String, String> values = mapper.readValue(secretJSON, new TypeReference<Map<String, String>>() {});
  String pubKey = values.get("public").replace(".ed25519", "");
  String privateKey = values.get("private").replace(".ed25519", "");

  Bytes pubKeyBytes = Base64.decode(pubKey);
  Bytes privKeyBytes = Base64.decode(privateKey);

  Signature.PublicKey pub = Signature.PublicKey.fromBytes(pubKeyBytes);
  Signature.SecretKey secretKey = Signature.SecretKey.fromBytes(privKeyBytes);

  Signature.KeyPair keyPair = new Signature.KeyPair(pub, secretKey);
  String networkKeyBase64 = "1KHLiKZvAvjbY1ziZEHMXawbCEIM6qwjCDm3VYRan/s=";

  String serverPublicKey = pubKey; // TODO use your own identity public key here.
  Signature.PublicKey publicKey = Signature.PublicKey.fromBytes(Base64.decode(serverPublicKey));

  Bytes32 networkKeyBytes32 = Bytes32.wrap(Base64.decode(networkKeyBase64));

  SecureScuttlebuttVertxClient secureScuttlebuttVertxClient =
      new SecureScuttlebuttVertxClient(vertx, keyPair, networkKeyBytes32);

  AsyncResult<ClientHandler> onConnect =
      secureScuttlebuttVertxClient.connectTo(port, host, publicKey, MyClientHandler::new);

  MyClientHandler clientHandler = (MyClientHandler) onConnect.get();
  assertTrue(onConnect.isDone());
  assertFalse(onConnect.isCompletedExceptionally());
  Thread.sleep(1000);
  assertNotNull(clientHandler);
  // An RPC command that just tells us our public key (like ssb-server whoami on the command line.)
  String rpcRequestBody = "{\"name\": [\"whoami\"],\"type\": \"async\",\"args\":[]}";
  Bytes rpcRequest = RPCCodec.encodeRequest(rpcRequestBody, RPCFlag.BodyType.JSON);

  System.out.println("Attempting RPC request...");
  clientHandler.sendMessage(rpcRequest);
  for (int i = 0; i < 10; i++) {
    clientHandler.sendMessage(RPCCodec.encodeRequest(rpcRequestBody, RPCFlag.BodyType.JSON));
  }

  Thread.sleep(10000);

  secureScuttlebuttVertxClient.stop().join();
}
 
Example 18
Source File: Hash.java    From incubator-tuweni with Apache License 2.0 2 votes vote down vote up
/**
 * Create a Hash from Bytes.
 *
 * <p>
 * The hash must be exactly 32 bytes.
 *
 * @param bytes The bytes for this hash.
 * @return A hash.
 * @throws IllegalArgumentException If {@code bytes.size() != 32}.
 */
public static Hash fromBytes(Bytes bytes) {
  requireNonNull(bytes);
  checkArgument(bytes.size() == SIZE, "Expected %s bytes but got %s", SIZE, bytes.size());
  return new Hash(Bytes32.wrap(bytes));
}
 
Example 19
Source File: Hash.java    From besu with Apache License 2.0 2 votes vote down vote up
/**
 * Digest using SHA2-256.
 *
 * @param input The input bytes to produce the digest for.
 * @return A digest.
 */
public static Bytes32 sha256(final Bytes input) {
  return Bytes32.wrap(digestUsingAlgorithm(input, SHA256_ALG));
}
 
Example 20
Source File: Hash.java    From besu with Apache License 2.0 2 votes vote down vote up
/**
 * Digest using keccak-256.
 *
 * @param input The input bytes to produce the digest for.
 * @return A digest.
 */
public static Bytes32 keccak256(final Bytes input) {
  return Bytes32.wrap(digestUsingAlgorithm(input, KECCAK256_ALG));
}