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

The following examples show how to use org.apache.tuweni.bytes.Bytes#copyTo() . 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: RLPEncodingHelpers.java    From besu with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the result of encoding the provided value to the provided destination (which must be big
 * enough).
 */
static int writeElement(final Bytes value, final MutableBytes dest, final int destOffset) {
  final int size = value.size();
  if (isSingleRLPByte(value)) {
    dest.set(destOffset, value.get(0));
    return destOffset + 1;
  }

  if (isShortElement(value)) {
    dest.set(destOffset, (byte) (0x80 + size));
    value.copyTo(dest, destOffset + 1);
    return destOffset + 1 + size;
  }

  final int offset = writeLongMetadata(0xb7, size, dest, destOffset);
  value.copyTo(dest, offset);
  return offset + size;
}
 
Example 2
Source File: EncryptedMessage.java    From besu with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypts a message for the specified peer using ECIES.
 *
 * @param bytes The plaintext.
 * @param remoteKey The peer's remote key.
 * @return The ciphertext.
 * @throws InvalidCipherTextException Thrown if encryption failed.
 */
public static Bytes encryptMsg(final Bytes bytes, final SECP256K1.PublicKey remoteKey)
    throws InvalidCipherTextException {
  // TODO: check size.
  final ECIESEncryptionEngine engine = ECIESEncryptionEngine.forEncryption(remoteKey);

  // Do the encryption.
  final Bytes encrypted = engine.encrypt(bytes);
  final Bytes iv = engine.getIv();
  final SECP256K1.PublicKey ephPubKey = engine.getEphPubKey();

  // Create the output message by concatenating the ephemeral public key (prefixed with
  // 0x04 to designate uncompressed), IV, and encrypted bytes.
  final MutableBytes answer =
      MutableBytes.create(1 + ECIESHandshaker.PUBKEY_LENGTH + IV_SIZE + encrypted.size());

  int offset = 0;
  // Set the first byte as 0x04 to specify it's an uncompressed key.
  answer.set(offset, (byte) 0x04);
  ephPubKey.getEncodedBytes().copyTo(answer, offset += 1);
  iv.copyTo(answer, offset += ECIESHandshaker.PUBKEY_LENGTH);
  encrypted.copyTo(answer, offset + iv.size());
  return answer;
}
 
Example 3
Source File: CallDataLoadOperation.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(final MessageFrame frame) {
  final UInt256 startWord = UInt256.fromBytes(frame.popStackItem());

  // If the start index doesn't fit a int, it comes after anything in data, and so the returned
  // word should be zero.
  if (!startWord.fitsInt()) {
    frame.pushStackItem(Bytes32.ZERO);
    return;
  }

  final int offset = startWord.intValue();
  final Bytes data = frame.getInputData();
  final MutableBytes32 res = MutableBytes32.create();
  if (offset < data.size()) {
    final Bytes toCopy = data.slice(offset, Math.min(Bytes32.SIZE, data.size() - offset));
    toCopy.copyTo(res, 0);
  }
  frame.pushStackItem(res);
}
 
Example 4
Source File: AltBN128AddPrecompiledContract.java    From besu with Apache License 2.0 6 votes vote down vote up
private static Bytes computeDefault(final Bytes input) {
  final BigInteger x1 = extractParameter(input, 0, 32);
  final BigInteger y1 = extractParameter(input, 32, 32);
  final BigInteger x2 = extractParameter(input, 64, 32);
  final BigInteger y2 = extractParameter(input, 96, 32);

  final AltBn128Point p1 = new AltBn128Point(Fq.create(x1), Fq.create(y1));
  final AltBn128Point p2 = new AltBn128Point(Fq.create(x2), Fq.create(y2));
  if (!p1.isOnCurve() || !p2.isOnCurve()) {
    return null;
  }
  final AltBn128Point sum = p1.add(p2);
  final Bytes x = sum.getX().toBytes();
  final Bytes y = sum.getY().toBytes();
  final MutableBytes result = MutableBytes.create(64);
  x.copyTo(result, 32 - x.size());
  y.copyTo(result, 64 - y.size());

  return result;
}
 
Example 5
Source File: AltBN128MulPrecompiledContract.java    From besu with Apache License 2.0 6 votes vote down vote up
private static Bytes computeDefault(final Bytes input) {
  final BigInteger x = extractParameter(input, 0, 32);
  final BigInteger y = extractParameter(input, 32, 32);
  final BigInteger n = extractParameter(input, 64, 32);

  final AltBn128Point p = new AltBn128Point(Fq.create(x), Fq.create(y));
  if (!p.isOnCurve() || n.compareTo(MAX_N) > 0) {
    return null;
  }
  final AltBn128Point product = p.multiply(n);

  final Bytes xResult = product.getX().toBytes();
  final Bytes yResult = product.getY().toBytes();
  final MutableBytes result = MutableBytes.create(64);
  xResult.copyTo(result, 32 - xResult.size());
  yResult.copyTo(result, 64 - yResult.size());

  return result;
}
 
Example 6
Source File: BigIntegerModularExponentiationPrecompiledContract.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public Bytes compute(final Bytes input, final MessageFrame messageFrame) {
  final BigInteger baseLength = baseLength(input);
  final BigInteger exponentLength = exponentLength(input);
  final BigInteger modulusLength = modulusLength(input);
  final BigInteger exponentOffset = BASE_OFFSET.add(baseLength);
  final BigInteger modulusOffset = exponentOffset.add(exponentLength);
  final BigInteger base = extractParameter(input, BASE_OFFSET, baseLength.intValue());
  final BigInteger exp = extractParameter(input, exponentOffset, exponentLength.intValue());
  final BigInteger mod = extractParameter(input, modulusOffset, modulusLength.intValue());

  final Bytes modExp;
  // Result must be the length of the modulus.
  final MutableBytes result = MutableBytes.create(modulusLength.intValue());
  if (mod.compareTo(BigInteger.ZERO) == 0) {
    modExp = MutableBytes.EMPTY;
  } else {
    // BigInteger zero-pads positive values whose most significant bit is a 1 if
    // the padding was not there.
    modExp = Bytes.wrap(base.modPow(exp, mod).toByteArray()).trimLeadingZeros();
  }

  modExp.copyTo(result, result.size() - modExp.size());
  return result;
}
 
Example 7
Source File: BranchNode.java    From besu with Apache License 2.0 5 votes vote down vote up
private static <V> Optional<Node<V>> maybeFlatten(final ArrayList<Node<V>> children) {
  final int onlyChildIndex = findOnlyChild(children);
  if (onlyChildIndex >= 0) {
    // replace the path of the only child and return it
    final Node<V> onlyChild = children.get(onlyChildIndex);
    final Bytes onlyChildPath = onlyChild.getPath();
    final MutableBytes completePath = MutableBytes.create(1 + onlyChildPath.size());
    completePath.set(0, (byte) onlyChildIndex);
    onlyChildPath.copyTo(completePath, 1);
    return Optional.of(onlyChild.replacePath(completePath));
  }
  return Optional.empty();
}
 
Example 8
Source File: EncryptedMessage.java    From besu with Apache License 2.0 5 votes vote down vote up
/**
 * Encrypts a message for the specified peer using ECIES.
 *
 * @param message The plaintext.
 * @param remoteKey The peer's remote key.
 * @return The ciphertext.
 * @throws InvalidCipherTextException Thrown if encryption failed.
 */
public static Bytes encryptMsgEip8(final Bytes message, final SECP256K1.PublicKey remoteKey)
    throws InvalidCipherTextException {
  final ECIESEncryptionEngine engine = ECIESEncryptionEngine.forEncryption(remoteKey);

  // Do the encryption.
  final Bytes bytes = addPadding(message);
  final int size = bytes.size() + ECIESEncryptionEngine.ENCRYPTION_OVERHEAD;
  final byte[] sizePrefix = {(byte) (size >>> 8), (byte) size};
  final Bytes encrypted = engine.encrypt(bytes, sizePrefix);
  final Bytes iv = engine.getIv();
  final SECP256K1.PublicKey ephPubKey = engine.getEphPubKey();

  // Create the output message by concatenating the ephemeral public key (prefixed with
  // 0x04 to designate uncompressed), IV, and encrypted bytes.
  final MutableBytes answer =
      MutableBytes.create(3 + ECIESHandshaker.PUBKEY_LENGTH + IV_SIZE + encrypted.size());

  answer.set(0, sizePrefix[0]);
  answer.set(1, sizePrefix[1]);
  // Set the first byte as 0x04 to specify it's an uncompressed key.
  answer.set(2, (byte) 0x04);
  int offset = 0;
  ephPubKey.getEncodedBytes().copyTo(answer, offset += 3);
  iv.copyTo(answer, offset += ECIESHandshaker.PUBKEY_LENGTH);
  encrypted.copyTo(answer, offset + IV_SIZE);
  return answer;
}
 
Example 9
Source File: Bytes4.java    From teku with Apache License 2.0 5 votes vote down vote up
/**
 * Left pad a {@link Bytes} value with zero bytes to create a {@link Bytes4}.
 *
 * @param value The bytes value pad.
 * @return A {@link Bytes4} that exposes the left-padded bytes of {@code value}.
 * @throws IllegalArgumentException if {@code value.size() &gt; 4}.
 */
public static Bytes4 leftPad(Bytes value) {
  checkNotNull(value);
  if (value instanceof Bytes4) {
    return (Bytes4) value;
  }
  checkArgument(value.size() <= 4, "Expected at most %s bytes but got %s", 4, value.size());
  MutableBytes result = MutableBytes.create(4);
  value.copyTo(result, 4 - value.size());
  return new Bytes4(result);
}
 
Example 10
Source File: Bytes4.java    From teku with Apache License 2.0 5 votes vote down vote up
/**
 * Right pad a {@link Bytes} value with zero bytes to create a {@link Bytes4}.
 *
 * @param value The bytes value pad.
 * @return A {@link Bytes4} that exposes the right-padded bytes of {@code value}.
 * @throws IllegalArgumentException if {@code value.size() &gt; 4}.
 */
public static Bytes4 rightPad(Bytes value) {
  checkNotNull(value);
  if (value instanceof Bytes4) {
    return (Bytes4) value;
  }
  checkArgument(value.size() <= 4, "Expected at most %s bytes but got %s", 4, value.size());
  MutableBytes result = MutableBytes.create(4);
  value.copyTo(result, 0);
  return new Bytes4(result);
}