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

The following examples show how to use org.apache.tuweni.bytes.Bytes#get() . 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: RPCMessage.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
/**
 * Default constructor
 *
 * @param messageBytes the bytes of the encoded message.
 */
public RPCMessage(Bytes messageBytes) {
  rpcFlags = messageBytes.get(0);
  stream = RPCFlag.Stream.STREAM.isApplied(rpcFlags);
  lastMessageOrError = RPCFlag.EndOrError.END.isApplied(rpcFlags);
  if (RPCFlag.BodyType.JSON.isApplied(rpcFlags)) {
    bodyType = RPCFlag.BodyType.JSON;
  } else if (RPCFlag.BodyType.UTF_8_STRING.isApplied(rpcFlags)) {
    bodyType = RPCFlag.BodyType.UTF_8_STRING;
  } else {
    bodyType = RPCFlag.BodyType.BINARY;
  }

  int bodySize = messageBytes.slice(1, 4).toInt();

  requestNumber = messageBytes.slice(5, 4).toInt();

  if (messageBytes.size() < bodySize + 9) {
    throw new IllegalArgumentException(
        "Message body " + (messageBytes.size() - 9) + " is less than body size " + bodySize);
  }

  body = messageBytes.slice(9, bodySize);
}
 
Example 2
Source File: PrivacyReorgTest.java    From besu with Apache License 2.0 6 votes vote down vote up
private Bytes getEnclaveKey(final URI enclaveURI) {
  final Enclave enclave = new EnclaveFactory(Vertx.vertx()).createVertxEnclave(enclaveURI);
  final SendResponse sendResponse =
      sendRequest(enclave, PRIVATE_TRANSACTION, ENCLAVE_PUBLIC_KEY.toBase64String());
  final Bytes payload = Bytes.fromBase64String(sendResponse.getKey());

  // If the key has 0 bytes generate a new key.
  // This is to keep the gasUsed constant allowing
  // hard-coded receipt roots in the block headers
  for (int i = 0; i < payload.size(); i++) {
    if (payload.get(i) == 0) {
      return getEnclaveKey(enclaveURI);
    }
  }

  return payload;
}
 
Example 3
Source File: TrieIterator.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public Node<V> visit(final BranchNode<V> node, final Bytes searchPath) {
  byte iterateFrom = 0;
  Bytes remainingPath = searchPath;
  if (state == State.SEARCHING) {
    iterateFrom = searchPath.get(0);
    if (iterateFrom == CompactEncoding.LEAF_TERMINATOR) {
      return node;
    }
    remainingPath = searchPath.slice(1);
  }
  paths.push(node.getPath());
  for (byte i = iterateFrom; i < BranchNode.RADIX && state.continueIterating(); i++) {
    paths.push(Bytes.of(i));
    node.child(i).accept(this, remainingPath);
    paths.pop();
  }
  paths.pop();
  return node;
}
 
Example 4
Source File: Bitvector.java    From teku with Apache License 2.0 6 votes vote down vote up
public static Bitvector fromBytes(Bytes bytes, int size) {
  checkArgument(
      bytes.size() == sszSerializationLength(size),
      "Incorrect data size (%s) for Bitvector of size %s",
      bytes.size(),
      size);
  BitSet bitset = new BitSet(size);

  for (int i = size - 1; i >= 0; i--) {
    if (((bytes.get(i / 8) >>> (i % 8)) & 0x01) == 1) {
      bitset.set(i);
    }
  }

  return new Bitvector(bitset, size);
}
 
Example 5
Source File: RLPxConnectionFactory.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
static Bytes decryptMessage(Bytes msgBytes, SecretKey ourKey) {
  Bytes commonMac = msgBytes.slice(0, 2);
  int size = (commonMac.get(1) & 0xFF) + ((commonMac.get(0) & 0xFF) << 8);
  PublicKey ephemeralPublicKey = PublicKey.fromBytes(msgBytes.slice(3, 64));
  Bytes iv = msgBytes.slice(67, 16);
  Bytes encrypted = msgBytes.slice(83, size - 81);

  EthereumIESEncryptionEngine decryptor = forDecryption(ourKey, ephemeralPublicKey, iv, commonMac);
  byte[] result;
  try {
    result = decryptor.processBlock(encrypted.toArrayUnsafe(), 0, encrypted.size());
  } catch (InvalidCipherTextException e) {
    throw new InvalidMACException(e);
  }
  return Bytes.wrap(result);
}
 
Example 6
Source File: FrontierGasCalculator.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public Gas transactionIntrinsicGasCost(final Transaction transaction) {
  final Bytes payload = transaction.getPayload();
  int zeros = 0;
  for (int i = 0; i < payload.size(); i++) {
    if (payload.get(i) == 0) {
      ++zeros;
    }
  }
  final int nonZeros = payload.size() - zeros;

  Gas cost =
      Gas.ZERO
          .plus(TX_BASE_COST)
          .plus(TX_DATA_ZERO_COST.times(zeros))
          .plus(TX_DATA_NON_ZERO_COST.times(nonZeros));

  if (transaction.isContractCreation()) {
    cost = cost.plus(txCreateExtraGasCost());
  }

  return cost;
}
 
Example 7
Source File: BLAKE2BFPrecompileContract.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public Gas gasRequirement(final Bytes input) {
  if (input.size() != MESSAGE_LENGTH_BYTES) {
    // Input is malformed, we can't read the number of rounds.
    // Precompile can't be executed so we set its price to 0.
    return Gas.ZERO;
  }
  if ((input.get(212) & 0xFE) != 0) {
    // Input is malformed, F value can be only 0 or 1
    return Gas.ZERO;
  }

  final byte[] roundsBytes = copyOfRange(input.toArray(), 0, 4);
  final BigInteger rounds = new BigInteger(1, roundsBytes);
  return Gas.of(rounds);
}
 
Example 8
Source File: IstanbulGasCalculator.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public Gas transactionIntrinsicGasCost(final Transaction transaction) {
  final Bytes payload = transaction.getPayload();
  int zeros = 0;
  for (int i = 0; i < payload.size(); i++) {
    if (payload.get(i) == 0) {
      ++zeros;
    }
  }
  final int nonZeros = payload.size() - zeros;

  Gas cost =
      Gas.ZERO
          .plus(TX_BASE_COST)
          .plus(TX_DATA_ZERO_COST.times(zeros))
          .plus(TX_DATA_NON_ZERO_COST.times(nonZeros));

  if (transaction.isContractCreation()) {
    cost = cost.plus(txCreateExtraGasCost());
  }

  return cost;
}
 
Example 9
Source File: Packet.java    From besu with Apache License 2.0 5 votes vote down vote up
private static SECP256K1.Signature decodeSignature(final Bytes encodedSignature) {
  checkArgument(
      encodedSignature != null && encodedSignature.size() == 65, "encodedSignature is 65 bytes");
  final BigInteger r = encodedSignature.slice(0, 32).toUnsignedBigInteger();
  final BigInteger s = encodedSignature.slice(32, 32).toUnsignedBigInteger();
  final int recId = encodedSignature.get(64);
  return SECP256K1.Signature.create(r, s, (byte) recId);
}
 
Example 10
Source File: LogsBloomFilter.java    From besu with Apache License 2.0 5 votes vote down vote up
/**
 * Discover the low order 11-bits, of the first three double-bytes, of the SHA3 hash, of each
 * value and update the bloom filter accordingly.
 *
 * @param hashValue The hash of the log item.
 */
private void setBits(final Bytes hashValue) {
  for (int counter = 0; counter < 6; counter += 2) {
    final int setBloomBit =
        ((hashValue.get(counter) & LEAST_SIGNIFICANT_THREE_BITS) << BITS_IN_BYTE)
            + (hashValue.get(counter + 1) & LEAST_SIGNIFICANT_BYTE);
    setBit(setBloomBit);
  }
}
 
Example 11
Source File: CompactEncoding.java    From besu with Apache License 2.0 5 votes vote down vote up
public static Bytes bytesToPath(final Bytes bytes) {
  final MutableBytes path = MutableBytes.create(bytes.size() * 2 + 1);
  int j = 0;
  for (int i = 0; i < bytes.size(); i += 1, j += 2) {
    final byte b = bytes.get(i);
    path.set(j, (byte) ((b >>> 4) & 0x0f));
    path.set(j + 1, (byte) (b & 0x0f));
  }
  path.set(j, LEAF_TERMINATOR);
  return path;
}
 
Example 12
Source File: TracingUtils.java    From besu with Apache License 2.0 5 votes vote down vote up
private static int trailingZeros(final Bytes bytes) {
  for (int i = bytes.size() - 1; i > 0; i--) {
    if (bytes.get(i) != 0) {
      return bytes.size() - i;
    }
  }
  return bytes.size();
}
 
Example 13
Source File: InitiatorHandshakeMessageV1.java    From besu with Apache License 2.0 5 votes vote down vote up
/**
 * Decodes this message.
 *
 * @param bytes The raw bytes.
 * @param nodeKey The nodeKey used to calculate ECDH key agreements.
 * @return The decoded message.
 */
public static InitiatorHandshakeMessageV1 decode(final Bytes bytes, final NodeKey nodeKey) {
  checkState(bytes.size() == MESSAGE_LENGTH);

  int offset = 0;
  final SECP256K1.Signature signature =
      SECP256K1.Signature.decode(bytes.slice(offset, ECIESHandshaker.SIGNATURE_LENGTH));
  final Bytes32 ephPubKeyHash =
      Bytes32.wrap(
          bytes.slice(
              offset += ECIESHandshaker.SIGNATURE_LENGTH, ECIESHandshaker.HASH_EPH_PUBKEY_LENGTH),
          0);
  final SECP256K1.PublicKey pubKey =
      SECP256K1.PublicKey.create(
          bytes.slice(
              offset += ECIESHandshaker.HASH_EPH_PUBKEY_LENGTH, ECIESHandshaker.PUBKEY_LENGTH));
  final Bytes32 nonce =
      Bytes32.wrap(
          bytes.slice(offset += ECIESHandshaker.PUBKEY_LENGTH, ECIESHandshaker.NONCE_LENGTH), 0);
  final boolean token = bytes.get(offset) == 0x01;

  final Bytes32 staticSharedSecret = nodeKey.calculateECDHKeyAgreement(pubKey);
  final SECP256K1.PublicKey ephPubKey =
      SECP256K1.PublicKey.recoverFromSignature(staticSharedSecret.xor(nonce), signature)
          .orElseThrow(() -> new RuntimeException("Could not recover public key from signature"));

  return new InitiatorHandshakeMessageV1(
      pubKey, signature, ephPubKey, ephPubKeyHash, nonce, token);
}
 
Example 14
Source File: SECP256K1.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
/**
 * Create a signature from bytes.
 *
 * @param bytes The signature bytes.
 * @return The signature.
 */
public static Signature fromBytes(Bytes bytes) {
  checkNotNull(bytes);
  checkArgument(bytes.size() == 65, "Signature must be 65 bytes, but got %s instead", bytes.size());
  BigInteger r = bytes.slice(0, 32).toUnsignedBigInteger();
  BigInteger s = bytes.slice(32, 32).toUnsignedBigInteger();
  return new Signature(bytes.get(64), r, s);
}
 
Example 15
Source File: SecureScuttlebuttStream.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
private Bytes decryptMessage(Bytes message, SecretBox.Key key, MutableBytes nonce) {
  if (message.size() < 34) {
    return null;
  }

  SecretBox.Nonce headerNonce = null;
  SecretBox.Nonce bodyNonce = null;
  try {
    MutableBytes snapshotNonce = nonce.mutableCopy();
    headerNonce = SecretBox.Nonce.fromBytes(snapshotNonce);
    bodyNonce = SecretBox.Nonce.fromBytes(snapshotNonce.increment());
    Bytes decryptedHeader = SecretBox.decrypt(message.slice(0, 34), key, headerNonce);

    if (decryptedHeader == null) {
      throw new StreamException("Failed to decrypt message header");
    }

    int bodySize = ((decryptedHeader.get(0) & 0xFF) << 8) + (decryptedHeader.get(1) & 0xFF);
    if (message.size() < bodySize + 34) {
      return null;
    }
    Bytes body = message.slice(34, bodySize);
    Bytes decryptedBody = SecretBox.decrypt(Bytes.concatenate(decryptedHeader.slice(2), body), key, bodyNonce);
    if (decryptedBody == null) {
      throw new StreamException("Failed to decrypt message");
    }
    nonce.increment().increment();
    return decryptedBody;
  } finally {
    destroyIfNonNull(headerNonce);
    destroyIfNonNull(bodyNonce);
  }
}
 
Example 16
Source File: CompactEncoding.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate a RADIX-16 path for a given byte sequence.
 *
 * @param bytes The byte sequence to calculate the path for.
 * @return The Radix-16 path.
 */
public static Bytes bytesToPath(Bytes bytes) {
  MutableBytes path = MutableBytes.create(bytes.size() * 2 + 1);
  int j = 0;
  for (int i = 0; i < bytes.size(); i += 1, j += 2) {
    byte b = bytes.get(i);
    path.set(j, (byte) ((b >>> 4) & 0x0f));
    path.set(j + 1, (byte) (b & 0x0f));
  }
  path.set(j, LEAF_TERMINATOR);
  return path;
}
 
Example 17
Source File: SECP256K1.java    From besu with Apache License 2.0 5 votes vote down vote up
public static Signature decode(final Bytes bytes) {
  checkArgument(
      bytes.size() == BYTES_REQUIRED, "encoded SECP256K1 signature must be 65 bytes long");

  final BigInteger r = bytes.slice(0, 32).toUnsignedBigInteger();
  final BigInteger s = bytes.slice(32, 32).toUnsignedBigInteger();
  final byte recId = bytes.get(64);
  return SECP256K1.Signature.create(r, s, recId);
}
 
Example 18
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 19
Source File: RLPxConnection.java    From incubator-tuweni with Apache License 2.0 4 votes vote down vote up
public RLPxMessage readFrame(Bytes messageFrame) {
  if (messageFrame.size() < 32) {
    return null;
  }
  Integer frameSize = lastFrameSize;
  if (frameSize == null) {

    Bytes macBytes = messageFrame.slice(16, 16);
    Bytes headerBytes = messageFrame.slice(0, 16);

    Bytes decryptedHeader = Bytes.wrap(new byte[16]);
    decryptionCipher.processBytes(headerBytes.toArrayUnsafe(), 0, 16, decryptedHeader.toArrayUnsafe(), 0);
    frameSize = decryptedHeader.get(0) & 0xff;
    frameSize = (frameSize << 8) + (decryptedHeader.get(1) & 0xff);
    frameSize = (frameSize << 8) + (decryptedHeader.get(2) & 0xff);

    Bytes expectedMac = calculateMac(headerBytes, true);

    if (!macBytes.equals(expectedMac)) {
      throw new InvalidMACException(
          String
              .format(
                  "Header MAC did not match expected MAC; expected: %s, received: %s",
                  expectedMac.toHexString(),
                  macBytes.toHexString()));
    }
  }
  int pad = frameSize % 16 == 0 ? 0 : 16 - frameSize % 16;
  if (messageFrame.size() < 32 + frameSize + pad + 16) {
    lastFrameSize = frameSize;
    return null;
  } else {
    lastFrameSize = null;
  }



  Bytes frameData = messageFrame.slice(32, frameSize + pad);
  Bytes frameMac = messageFrame.slice(32 + frameSize + pad, 16);

  Bytes newFrameMac = Bytes.wrap(new byte[16]);
  Bytes frameMacSeed = updateIngress(messageFrame.slice(32, frameSize + pad));
  macEncryptionEngine.processBlock(frameMacSeed.toArrayUnsafe(), 0, newFrameMac.toArrayUnsafe(), 0);
  Bytes expectedFrameMac = updateIngress(newFrameMac.xor(frameMacSeed.slice(0, 16))).slice(0, 16);
  if (!expectedFrameMac.equals(frameMac)) {
    throw new InvalidMACException(
        String
            .format(
                "Frame MAC did not match expected MAC; expected: %s, received: %s",
                expectedFrameMac.toHexString(),
                frameMac.toHexString()));
  }

  Bytes decryptedFrameData = Bytes.wrap(new byte[frameData.size()]);
  decryptionCipher
      .processBytes(frameData.toArrayUnsafe(), 0, frameData.size(), decryptedFrameData.toArrayUnsafe(), 0);

  int messageType = RLP.decodeInt(decryptedFrameData.slice(0, 1));

  Bytes messageData = decryptedFrameData.slice(1, decryptedFrameData.size() - 1 - pad);
  if (applySnappyCompression) {
    try {
      messageData = Bytes.wrap(Snappy.uncompress(messageData.toArrayUnsafe()));
    } catch (IOException e) {
      throw new IllegalArgumentException(e);
    }
  }

  return new RLPxMessage(messageType, messageData, 32 + frameSize + pad + 16);
}
 
Example 20
Source File: BeaconStateUtil.java    From teku with Apache License 2.0 4 votes vote down vote up
/**
 * Return shuffled indices in a pseudorandom permutation `0...list_size-1` with ``seed`` as
 * entropy.
 *
 * <p>Utilizes 'swap or not' shuffling found in
 * https://link.springer.com/content/pdf/10.1007%2F978-3-642-32009-5_1.pdf See the 'generalized
 * domain' algorithm on page 3.
 *
 * <p>The result of this should be the same as calling get_permuted_index() for each index in the
 * list
 *
 * @param list_size The size of the list from which the element is taken. Must not exceed 2^31.
 * @param seed Initial seed value used for randomization.
 * @return The permuted arrays of indices
 */
public static int[] shuffle(int list_size, Bytes32 seed) {

  if (list_size == 0) {
    return new int[0];
  }

  //  In the following, great care is needed around signed and unsigned values.
  //  Note that the % (modulo) operator in Java behaves differently from the
  //  modulo operator in python:
  //    Python -1 % 13 = 12
  //    Java   -1 % 13 = -1

  //  Using UnsignedLong doesn't help us as some quantities can legitimately be negative.

  // Note: this should be faster than manually creating the list in a for loop
  // https://stackoverflow.com/questions/10242380/how-can-i-generate-a-list-or-array-of-sequential-integers-in-java
  int[] indices = IntStream.rangeClosed(0, list_size - 1).toArray();

  // int[] indices = new int[list_size];
  // for (int i = 0; i < list_size; i++) {
  //   indices[i] = i;
  // }

  byte[] powerOfTwoNumbers = {1, 2, 4, 8, 16, 32, 64, (byte) 128};

  for (int round = 0; round < SHUFFLE_ROUND_COUNT; round++) {

    Bytes roundAsByte = Bytes.of((byte) round);

    Bytes hashBytes = Bytes.EMPTY;
    for (int i = 0; i < (list_size + 255) / 256; i++) {
      Bytes iAsBytes4 = int_to_bytes(i, 4);
      hashBytes = Bytes.wrap(hashBytes, Hash.sha2_256(Bytes.wrap(seed, roundAsByte, iAsBytes4)));
    }

    // This needs to be unsigned modulo.
    int pivot =
        toIntExact(
            Long.remainderUnsigned(
                bytes_to_int(Hash.sha2_256(Bytes.wrap(seed, roundAsByte)).slice(0, 8)),
                list_size));

    for (int i = 0; i < list_size; i++) {

      int flip = (pivot - indices[i]) % list_size;
      if (flip < 0) {
        // Account for flip being negative
        flip += list_size;
      }

      int hashPosition = (indices[i] < flip) ? flip : indices[i];
      byte theByte = hashBytes.get(hashPosition / 8);
      byte theMask = powerOfTwoNumbers[hashPosition % 8];
      if ((theByte & theMask) != 0) {
        indices[i] = flip;
      }
    }
  }

  return indices;
}