### Install Apache Tuweni Units Library
Source: https://github.com/consensys/tuweni/blob/main/units/README.md
Instructions for adding the Apache Tuweni units library to your project using Maven or Gradle.
```xml
org.apache.tuweni
units
2.3.1
```
```groovy
implementation("org.apache.tuweni:units:2.3.1") // replace with latest release
```
--------------------------------
### Initialize Ethereum DevP2P Discovery Service
Source: https://context7.com/consensys/tuweni/llms.txt
Demonstrates how to initialize and start the DevP2P discovery service using a Vert.x instance. It includes setting up node keys, bootstrap nodes, and advertising ENR data.
```java
import org.apache.tuweni.devp2p.DiscoveryService;
import org.apache.tuweni.devp2p.Peer;
import org.apache.tuweni.devp2p.PeerRepository;
import org.apache.tuweni.devp2p.EphemeralPeerRepository;
import org.apache.tuweni.crypto.SECP256K1;
import org.apache.tuweni.bytes.Bytes;
import io.vertx.core.Vertx;
import java.net.URI;
import java.util.List;
import java.util.Map;
Vertx vertx = Vertx.vertx();
SECP256K1.KeyPair keyPair = SECP256K1.KeyPair.random();
List bootstrapNodes = List.of(
URI.create("enode://d860a01f9722d78051619d1e2351aba3f43f943f6f00718d1b9baa4101932a1f5011f16bb2b1bb35db20d6fe28fa0bf09636d26a87d31de9ec6203eeedb1f666@18.138.108.67:30303"),
URI.create("enode://22a8232c3abc76a16ae9d6c3b164f98775fe226f0917b0ca871128a74a8e9630b458460865bab457221f1d448dd9791d24c4e5d88786180ac185df813a68d4de@3.209.45.79:30303")
);
Map enrData = Map.of(
"eth", Bytes.fromHexString("0xc984fc64ec04"),
"snap", Bytes.fromHexString("0x01")
);
DiscoveryService discovery = DiscoveryService.open(
vertx,
keyPair,
30303,
"0.0.0.0",
System.currentTimeMillis(),
enrData,
bootstrapNodes,
new EphemeralPeerRepository(),
null,
null,
null
);
```
--------------------------------
### Install Apache Tuweni Bytes Library
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Configuration snippets for adding the Apache Tuweni Bytes dependency to Maven or Gradle projects.
```xml
org.apache.tuweni
bytes
2.3.1
```
```groovy
implementation("org.apache.tuweni:bytes:2.3.1")
```
--------------------------------
### Utilize Concurrent Async Result Utilities in Java
Source: https://context7.com/consensys/tuweni/llms.txt
Provides examples of using the Apache Tuweni concurrent module for asynchronous programming in Java. It demonstrates creating completed, failed, and incomplete async results, chaining transformations, combining multiple results, handling completions, executing blocking operations asynchronously, and retrieving results with timeouts.
```java
import org.apache.tuweni.concurrent.AsyncResult;
import org.apache.tuweni.concurrent.AsyncCompletion;
import org.apache.tuweni.concurrent.CompletableAsyncResult;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
// Create completed result
AsyncResult completed = AsyncResult.completed("success");
// Create failed result
AsyncResult failed = AsyncResult.exceptional(new RuntimeException("error"));
// Create incomplete result (to be completed later)
CompletableAsyncResult incomplete = AsyncResult.incomplete();
// Complete the result asynchronously
new Thread(() -> {
try {
Thread.sleep(100);
incomplete.complete(42);
} catch (Exception e) {
incomplete.completeExceptionally(e);
}
}).start();
// Chain transformations
AsyncResult transformed = completed
.thenApply(s -> s.toUpperCase())
.thenApply(s -> s + "!");
// Combine multiple results
AsyncResult result1 = AsyncResult.completed(10);
AsyncResult result2 = AsyncResult.completed(20);
AsyncResult combined = result1.thenCombine(result2, (a, b) -> a + b);
// Wait for all results
AsyncCompletion allComplete = AsyncResult.allOf(result1, result2, completed);
// Combine results into a list
List> results = List.of(
AsyncResult.completed(1),
AsyncResult.completed(2),
AsyncResult.completed(3)
);
AsyncResult> combinedList = AsyncResult.combine(results);
// Handle completion
completed.whenComplete((value, error) -> {
if (error != null) {
System.err.println("Failed: " + error.getMessage());
} else {
System.out.println("Success: " + value);
}
});
// Execute blocking operation asynchronously
AsyncResult blocking = AsyncResult.executeBlocking(() -> {
// Perform blocking I/O
Thread.sleep(100);
return "done";
});
// Get result with timeout
try {
String value = completed.get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
System.err.println("Operation timed out");
}
```
--------------------------------
### Get Common Prefix of Bytes Objects in Java
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Demonstrates the `commonPrefix` method, which returns a new Bytes object containing the common bytes that both the current Bytes object and the argument start with.
```java
import org.apache.tuweni.bytes.Bytes;
// Assuming 'bytes1' and 'bytes2' are existing Bytes objects
// Bytes bytes1 = ...;
// Bytes bytes2 = ...;
// Get the common prefix (conceptually, actual method not shown here)
// Bytes common = bytes1.commonPrefix(bytes2);
```
--------------------------------
### Hash - Cryptographic Hashing Functions (Java)
Source: https://context7.com/consensys/tuweni/llms.txt
Provides examples of using the Hash class for various cryptographic hashing algorithms like SHA-2 variants, SHA-3, and Keccak. Demonstrates hashing byte arrays and Bytes objects, and generating an Ethereum-style address from a public key.
```Java
import org.apache.tuweni.crypto.Hash;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
// Input data
Bytes input = Bytes.fromHexString("0x68656c6c6f"); // "hello" in hex
byte[] inputBytes = "hello world".getBytes();
// SHA2-256 (standard SHA-256)
Bytes32 sha256Hash = Hash.sha2_256(input);
byte[] sha256Bytes = Hash.sha2_256(inputBytes);
// SHA2-512/256
Bytes32 sha512_256Hash = Hash.sha2_512_256(input);
// Keccak-256 (used by Ethereum for addresses, etc.)
Bytes32 keccak256Hash = Hash.keccak256(input);
byte[] keccak256Bytes = Hash.keccak256(inputBytes);
// Keccak-512
Bytes keccak512Hash = Hash.keccak512(input);
// SHA3-256 (NIST standard)
Bytes32 sha3_256Hash = Hash.sha3_256(input);
// SHA3-512
Bytes sha3_512Hash = Hash.sha3_512(input);
// Example: Generate Ethereum-style address from public key
Bytes publicKeyBytes = Bytes.random(64); // 64-byte uncompressed public key
Bytes32 hashedKey = Hash.keccak256(publicKeyBytes);
Bytes address = hashedKey.slice(12, 20); // Last 20 bytes
System.out.println("Address: " + address.toHexString());
```
--------------------------------
### Encode and Decode SSZ Data in Java
Source: https://context7.com/consensys/tuweni/llms.txt
Covers the SSZ module for Ethereum 2.0 serialization. Includes examples for encoding basic types, using SSZWriter for complex structures, and calculating hash tree roots.
```java
import org.apache.tuweni.ssz.SSZ;
import org.apache.tuweni.ssz.SSZReader;
import org.apache.tuweni.ssz.SSZWriter;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
Bytes encodedInt32 = SSZ.encodeInt(12345, 32);
Bytes hashRoot = SSZ.hashTreeRoot(Bytes.fromHexString("0x01"), Bytes.fromHexString("0x02"));
SSZ.decode(encodedInt32, reader -> reader.readInt(32));
```
--------------------------------
### Get Single Byte from Bytes Object in Java
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Shows how to retrieve the byte at a specific index `i` from a Bytes object using the `get(i)` method.
```java
import org.apache.tuweni.bytes.Bytes;
// Assuming 'bytes' is an existing Bytes object
// Bytes bytes = ...;
// Get the byte at index i
// byte singleByte = bytes.get(i);
```
--------------------------------
### Extract Integers and Longs at Specific Index in Java
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Demonstrates extracting 4-byte integers (`getInt(i)`) and 8-byte longs (`getLong(i)`) starting from a specified index `i` within a Bytes object. An optional ByteOrder can be specified.
```java
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.ByteOrder;
// Assuming 'bytes' is an existing Bytes object
// Bytes bytes = ...;
// Get int starting at index i
// int intValueAtIndex = bytes.getInt(i);
// Get long starting at index i
// long longValueAtIndex = bytes.getLong(i);
// Get int with specific byte order
// int intValueAtIndexLE = bytes.getInt(i, ByteOrder.LITTLE_ENDIAN);
```
--------------------------------
### Set Bytes sequence at a specific offset in MutableBytes
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Illustrates setting a sequence of bytes from another Bytes object into the MutableBytes object starting at a specified offset. This allows for copying byte data between different Bytes instances.
```java
MutableBytes target = MutableBytes.create(10);
Bytes source = Bytes.fromHexString("0xabcdef");
target.set(2, source);
```
--------------------------------
### Java: Create and Wrap Bytes with Tuweni
Source: https://context7.com/consensys/tuweni/llms.txt
Demonstrates various methods to create and wrap byte sequences using Tuweni's Bytes interface. Supports creation from byte arrays, hex strings, base64, primitive types, and random generation. It also shows how to create fixed-size Bytes32 and concatenate or wrap multiple byte values efficiently.
```java
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.bytes.MutableBytes;
// Create from byte array (wraps without copying)
byte[] rawBytes = new byte[] {0x01, 0x02, 0x03, 0x04};
Bytes bytes = Bytes.wrap(rawBytes);
// Create from hex string
Bytes fromHex = Bytes.fromHexString("0xdeadbeef");
Bytes fromHexLenient = Bytes.fromHexStringLenient("1FF2A"); // handles odd-length strings
// Create from base64
Bytes fromBase64 = Bytes.fromBase64String("ZGVhZGJlZWY=");
// Create from primitive types
Bytes fromOf = Bytes.of(0x00, 0x01, 0xff, 0x2a);
Bytes fromInt = Bytes.ofUnsignedInt(42);
Bytes fromLong = Bytes.ofUnsignedLong(123456789L);
Bytes fromShort = Bytes.ofUnsignedShort(65535);
// Create random bytes
Bytes random = Bytes.random(32);
// Create fixed-size Bytes32 (commonly used for hashes)
Bytes32 hash = Bytes32.wrap(new byte[32]);
Bytes32 padded = Bytes32.rightPad(Bytes.fromHexString("0x1234"));
// Concatenate multiple byte values
Bytes concatenated = Bytes.concatenate(bytes, fromHex, random);
// Wrap multiple values as a view (no copy)
Bytes wrapped = Bytes.wrap(bytes, fromHex);
```
--------------------------------
### Run Staged Release Build
Source: https://github.com/consensys/tuweni/blob/main/RELEASE.md
This command executes the Gradle wrapper to perform a staged release. It requires setting environment variables to enable release building and signing.
```bash
export BUILD_RELEASE=true
export ENABLE_SIGNING=true
./gradlew stage
```
--------------------------------
### Parse TOML Configuration Files with Java
Source: https://context7.com/consensys/tuweni/llms.txt
Demonstrates how to parse TOML configuration files using the Apache Tuweni library in Java. It covers parsing from strings, accessing values with type safety, handling nested tables and arrays of tables, and parsing dotted keys. It also includes error handling for parsing issues.
```java
import org.apache.tuweni.toml.Toml;
import org.apache.tuweni.toml.TomlParseResult;
import org.apache.tuweni.toml.TomlTable;
import org.apache.tuweni.toml.TomlArray;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
// Parse TOML from string
String tomlContent = """
title = \"Server Configuration\"
[server]
host = \"localhost\"
port = 8080
enabled = true
[database]
connection_string = \"postgres://localhost/db\"
pool_size = 10
[[services]]
name = \"api\"
port = 3000
[[services]]
name = \"web\"
port = 80
""";
TomlParseResult result = Toml.parse(tomlContent);
// Check for parse errors
if (result.hasErrors()) {
result.errors().forEach(error ->
System.err.println("Error at " + error.position() + ": " + error.getMessage())
);
}
// Access values with type safety
String title = result.getString("title");
String host = result.getString("server.host");
Long port = result.getLong("server.port");
Boolean enabled = result.getBoolean("server.enabled");
// Access nested tables
TomlTable serverConfig = result.getTable("server");
if (serverConfig != null) {
String serverHost = serverConfig.getString("host");
Long serverPort = serverConfig.getLong("port");
}
// Access arrays of tables
TomlArray services = result.getArray("services");
if (services != null) {
for (int i = 0; i < services.size(); i++) {
TomlTable service = services.getTable(i);
System.out.println("Service: " + service.getString("name") +
" on port " + service.getLong("port"));
}
}
// Parse from file
Path configFile = Paths.get("/path/to/config.toml");
// TomlParseResult fileResult = Toml.parse(configFile);
// Parse dotted keys
List keyParts = Toml.parseDottedKey("server.database.host");
// Returns: ["server", "database", "host"]
// Join key path back to dotted string
String dottedKey = Toml.joinKeyPath(keyParts);
```
--------------------------------
### Initialize UInt256 from various types
Source: https://github.com/consensys/tuweni/blob/main/units/README.md
Demonstrates how to create UInt256 instances using static `valueOf` method with integers, longs, BigIntegers, and from byte arrays or hexadecimal strings.
```java
UInt256 value = UInt256.valueOf(42);
UInt256 value = UInt256.valueOf(42L);
UInt256 value = UInt256.valueOf(BigInteger.ONE);
```
```java
UInt256 value = UInt256.fromBytes(Bytes.wrap(new byte[] {0x01, 0x02, 0x03}));
```
```java
UInt256 value = UInt256.fromHexString("0xdeadbeef");
```
--------------------------------
### Implement Kademlia DHT Routing Table
Source: https://context7.com/consensys/tuweni/llms.txt
Shows how to create and manage a Kademlia routing table for peer storage and distance calculation. It defines a custom peer structure and configures bucket sizes for efficient lookups.
```java
import org.apache.tuweni.kademlia.KademliaRoutingTable;
import org.apache.tuweni.bytes.Bytes;
import java.util.function.Function;
record NetworkPeer(byte[] nodeId, String address, int port) {}
byte[] selfId = new byte[32];
new java.security.SecureRandom().nextBytes(selfId);
int k = 16;
int maxReplacements = 16;
KademliaRoutingTable routingTable = KademliaRoutingTable.create(
selfId,
k,
maxReplacements,
(Function) peer -> peer.nodeId(),
(Function) peer -> {
int distance = 0;
for (int i = 0; i < selfId.length; i++) {
int xor = (selfId[i] ^ peer.nodeId()[i]) & 0xff;
if (xor != 0) {
distance = (selfId.length - i) * 8 - Integer.numberOfLeadingZeros(xor) + 24;
break;
}
}
return distance;
}
);
```
--------------------------------
### Configure Vert.x Server for Client Authentication and TOFU (Java)
Source: https://github.com/consensys/tuweni/blob/main/net/README.md
This Java code configures a Vert.x HTTP server to use SSL, require client authentication, and trust clients on first access (TOFU) using the VertxTrustOptions API. It sets various server options including idle timeout and address/port reuse.
```java
HttpServerOptions options = new HttpServerOptions();
options.setSsl(true)
.setClientAuth(ClientAuth.REQUIRED)
.setPemKeyCertOptions(serverCert.keyCertOptions())
.setTrustOptions(VertxTrustOptions.trustClientOnFirstAccess(knownClientsFile))
.setIdleTimeout(1500)
.setReuseAddress(true)
.setReusePort(true);
httpServer = vertx.createHttpServer(options);
```
--------------------------------
### Configure Gradle Properties for Signing
Source: https://github.com/consensys/tuweni/blob/main/RELEASE.md
This snippet shows the properties to be added to the `~/.gradle/gradle.properties` file for Nexus and GPG signing configuration. It requires Nexus credentials and a GPG key ID.
```properties
nexusUsername=${Nexus username}
nexusPassword=${Nexus password}
signing.keyId=${GPG key ID}
signing.gnupg.keyName=${GPG key ID}
```
--------------------------------
### Add Tweni Net Dependency (Maven/Gradle)
Source: https://github.com/consensys/tuweni/blob/main/net/README.md
Instructions for adding the Tweni Net library to your project using Maven or Gradle build tools. This is the first step to using the library's networking capabilities.
```xml
org.apache.tuweni
net
{{site.data.project.latest_release}}
```
```groovy
implementation("org.apache.tuweni:net:{{site.data.project.latest_release}}")
```
--------------------------------
### Create Random Bytes Objects in Java
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Demonstrates how to create random Bytes objects of a specified length using the Bytes.random() method. It also shows how to use a custom Random implementation for generating these bytes.
```java
import org.apache.tuweni.bytes.Bytes;
import java.util.Random;
import java.security.SecureRandom;
// create a Bytes object of 20 bytes:
Bytes randomBytes = Bytes.random(20);
// Create a Bytes object with a custom Random implementation:
Random customRandom = new SecureRandom();
Bytes randomBytesWithCustom = Bytes.random(20, customRandom);
```
--------------------------------
### Java: Manipulate and Operate Bytes with Tuweni
Source: https://context7.com/consensys/tuweni/llms.txt
Illustrates common manipulation and operation methods provided by Tuweni's Bytes library. Covers slicing, copying, bitwise operations (XOR, AND, OR, NOT), bit shifting, extracting primitive values (int, long, BigInteger), string conversions (hex, base64), and handling leading/trailing zeros.
```java
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.MutableBytes;
import java.math.BigInteger;
Bytes value = Bytes.fromHexString("0xdeadbeefcafe");
// Slicing (creates a view, not a copy)
Bytes slice = value.slice(2); // from index 2 to end
Bytes portion = value.slice(1, 3); // 3 bytes starting at index 1
// Copying (creates independent copy)
Bytes copied = value.copy();
// Bitwise operations
Bytes a = Bytes.fromHexString("0x01000001");
Bytes b = Bytes.fromHexString("0x01000000");
Bytes xorResult = a.xor(b); // 0x00000001
Bytes andResult = a.and(b); // 0x01000000
Bytes orResult = a.or(b); // 0x01000001
Bytes notResult = a.not(); // 0xfefffffe
// Bit shifting
Bytes shifted = value.shiftRight(8);
Bytes leftShifted = value.shiftLeft(4);
// Extract values
int intValue = value.slice(0, 4).toInt();
long longValue = value.slice(0, 8).toLong();
BigInteger bigInt = value.toUnsignedBigInteger();
// String conversions
String hexString = value.toHexString(); // "0xdeadbeefcafe"
String unprefixed = value.toUnprefixedHexString(); // "deadbeefcafe"
String shortened = value.toShortHexString(); // removes leading zeros
String base64 = value.toBase64String();
// Leading/trailing zero handling
Bytes trimmed = value.trimLeadingZeros();
int leadingZeros = value.numberOfLeadingZeroBytes();
boolean isZero = value.isZero();
```
--------------------------------
### Create TrustManagerFactory to Record Server Fingerprints (Java)
Source: https://github.com/consensys/tuweni/blob/main/net/README.md
This Java code snippet shows how to create a TrustManagerFactory that records server fingerprints for unknown servers, with an option to exclude servers with CA-signed certificates. This is useful for implementing Trust On First Use (TOFU) security.
```java
TrustManagerFactories.recordServerFingerprints(knownServersFile, false);
```
--------------------------------
### Create a Custom UInt256 Domain Class
Source: https://github.com/consensys/tuweni/blob/main/units/README.md
Shows how to implement a custom class by extending BaseUInt256Value. This is useful for creating domain-specific units like Wei.
```java
public final class Wei extends BaseUInt256Value {
private Wei(UInt256 bytes) {
super(bytes, Wei::new);
}
}
```
--------------------------------
### Parse TOML files using Tuweni-Toml
Source: https://github.com/consensys/tuweni/blob/main/toml/README.md
This snippet demonstrates how to parse a TOML file from a given path and retrieve values using dotted keys. It also shows how to iterate over and print any parsing errors encountered during the process.
```java
Path source = Paths.get("/path/to/file.toml");
TomlParseResult result = Toml.parse(source);
result.errors().forEach(error -> System.err.println(error.toString()));
String value = result.getString("a. dotted . key");
```
--------------------------------
### Configure Vert.x HTTP Client for Whitelisted Servers (Java)
Source: https://github.com/consensys/tuweni/blob/main/net/README.md
This Java code configures a Vert.x HTTP client to only communicate with servers that are present in a whitelist, using VertxTrustOptions. It also disables trust for CA-signed certificates and sets connection timeout and address/port reuse options.
```java
HttpClientOptions options = new HttpClientOptions();
options.setSsl(true)
.setTrustOptions(VertxTrustOptions.whitelistServers(knownServersFile, false))
.setConnectTimeout(1500)
.setReuseAddress(true)
.setReusePort(true);
client = vertx.createHttpClient(options);
```
--------------------------------
### Encode and Decode RLP Data in Java
Source: https://context7.com/consensys/tuweni/llms.txt
Demonstrates how to use the RLP module to encode simple values, lists, and nested structures. It also shows how to decode these structures back into Java objects using RLPReader.
```java
import org.apache.tuweni.rlp.RLP;
import org.apache.tuweni.rlp.RLPReader;
import org.apache.tuweni.rlp.RLPWriter;
import org.apache.tuweni.bytes.Bytes;
import java.math.BigInteger;
import java.util.List;
import java.util.ArrayList;
Bytes encodedInt = RLP.encodeInt(42);
Bytes encodedList = RLP.encodeList(writer -> {
writer.writeString("cat");
writer.writeString("dog");
writer.writeInt(100);
});
int decodedInt = RLP.decode(encodedInt, RLPReader::readInt);
List strings = RLP.decodeList(encodedList, reader -> {
List result = new ArrayList<>();
while (!reader.isComplete()) {
result.add(reader.readString());
}
return result;
});
```
--------------------------------
### Publish Website Changes
Source: https://github.com/consensys/tuweni/blob/main/RELEASE.md
This script is used to publish changes to the Tuweni website. It is typically run from the `tuweni-website` repository after making necessary modifications.
```bash
./publish.sh
```
--------------------------------
### Perform Arithmetic Division on UInt256
Source: https://github.com/consensys/tuweni/blob/main/units/README.md
Demonstrates standard division and ceiling division using the UInt256 class. These methods allow for precise integer arithmetic operations.
```java
UInt256 result = UInt256.valueOf(12L).divide(UInt256.valueOf(5L)); // returns 2
UInt256 resultCeiling = UInt256.valueOf(12L).divideCeil(UInt256.valueOf(5L)); // returns 3
```
--------------------------------
### Create Bytes from Arrays and Strings
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Methods to instantiate Bytes objects from native byte arrays, hexadecimal strings, and base64 encoded strings.
```java
Bytes bytes = Bytes.wrap(new byte[] {1, 2, 3, 4});
Bytes bytesOffset = Bytes.wrap(new byte[] {1, 2, 3, 4}, 2, 1);
Bytes hexBytes = Bytes.fromHexString("0xdeadbeef");
Bytes lenientHex = Bytes.fromHexStringLenient("1FF2A");
Bytes base64Bytes = Bytes.fromBase64String("deadbeefISDAbest");
```
--------------------------------
### Add Bouncy Castle Security Provider (Java)
Source: https://github.com/consensys/tuweni/blob/main/net/README.md
This Java code snippet demonstrates how to add the Bouncy Castle security provider, which is a required dependency for certain cryptographic operations within the Tweni Net library.
```java
Security.addProvider(new BouncyCastleProvider());
```
--------------------------------
### Copy and Slice Bytes Objects in Java
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Explains how to copy and slice Bytes objects. Slicing creates a view of the original bytes, which will reflect changes in the underlying object. Copying creates an independent new object.
```java
import org.apache.tuweni.bytes.Bytes;
// Assuming 'bytes' is an existing Bytes object
// Bytes bytes = ...;
// slice from the second byte:
// Bytes slicedFromSecond = bytes.slice(2);
// slice from the second byte to the fifth byte:
// Bytes slicedRange = bytes.slice(2, 5);
// Copying bytes (conceptually, actual method not shown here)
// Bytes copiedBytes = bytes.copy();
```
--------------------------------
### Shift Bits in Bytes Objects in Java
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Demonstrates how to perform bitwise right and left shifts on Bytes objects by a specified distance. This is analogous to the '<<<' and '>>>' operators in Java.
```java
import org.apache.tuweni.bytes.Bytes;
// Assuming 'bytes' is an existing Bytes object
// Bytes bytes = ...;
// Shift right by a distance (conceptually, actual method not shown here)
// Bytes shiftedRight = bytes.shiftRight(distance);
// Shift left by a distance (conceptually, actual method not shown here)
// Bytes shiftedLeft = bytes.shiftLeft(distance);
```
--------------------------------
### Convert Bytes to BigInteger in Java
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Shows how to convert Bytes objects into `BigInteger` objects. `toUnsignedBigInteger()` creates an unsigned representation, while `toBigInteger()` uses two's-complement for signed representation.
```java
import org.apache.tuweni.bytes.Bytes;
import java.math.BigInteger;
// Assuming 'bytes' is an existing Bytes object
// Bytes bytes = ...;
// Convert to unsigned BigInteger
// BigInteger unsignedBigInt = bytes.toUnsignedBigInteger();
// Convert to signed BigInteger (two's-complement)
// BigInteger signedBigInt = bytes.toBigInteger();
```
--------------------------------
### Create and Push Release Branch
Source: https://github.com/consensys/tuweni/blob/main/RELEASE.md
This command sequence creates a new Git release branch based on the major.minor version number and pushes it to the origin. This is used for new major or minor releases.
```bash
git checkout -b 1.0
git push origin 1.0
```
--------------------------------
### Concatenate and Wrap Bytes Objects in Java
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Illustrates the concepts of concatenating and wrapping Bytes objects. Concatenation copies underlying data into a new object, while wrapping creates a view, making it more memory-efficient.
```java
import org.apache.tuweni.bytes.Bytes;
// Example of concatenation (conceptually, actual method not shown here)
// Bytes concatenatedBytes = Bytes.concatenate(bytes1, bytes2);
// Example of wrapping (conceptually, actual method not shown here)
// Bytes wrappedBytes = Bytes.wrap(bytes1, bytes2);
```
--------------------------------
### Wrap External Buffer Objects
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Utility methods to wrap Netty ByteBuf, Java ByteBuffer, and Vert.x Buffer objects into the Tuweni Bytes interface.
```java
Bytes.wrapByteBuf(buffer);
Bytes.wrapByteBuffer(buffer);
Bytes.wrapBuffer(buffer);
```
--------------------------------
### Perform Arithmetic Operations on UInt256
Source: https://github.com/consensys/tuweni/blob/main/units/README.md
Shows how to perform addition and subtraction on UInt256 objects, including methods that handle potential overflows and underflows.
```java
// Addition and subtraction (may overflow/underflow)
UInt256 resultAdd = value.add(other);
UInt256 resultSub = value.subtract(other);
// Exact addition and subtraction (throws exceptions on overflow/underflow)
UInt256 resultAddExact = value.addExact(other);
UInt256 resultSubExact = value.subtractExact(other);
```
--------------------------------
### Create Bytes from Primitives
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Convenience methods to create Bytes objects from individual bytes or unsigned primitive integer types.
```java
Bytes value = Bytes.of(0x00, 0x01, 0xff, 0x2a);
Bytes unsignedInt = Bytes.ofUnsignedInt(42);
```
--------------------------------
### Perform Boolean Operations on Bytes Objects in Java
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Shows how to apply bitwise XOR, OR, and AND operations to Bytes objects. These operations return a new Bytes object representing the result. Padding is applied to shorter operands.
```java
import org.apache.tuweni.bytes.Bytes;
import static org.junit.jupiter.api.Assertions.assertEquals;
Bytes value1 = Bytes.fromHexString("0x01000001");
Bytes value2 = Bytes.fromHexString("0x01000000");
// XOR operation
Bytes xorResult = value1.xor(value2);
assertEquals(Bytes.fromHexString("0x00000001"), xorResult);
// OR operation (conceptually, actual method not shown here)
// Bytes orResult = value1.or(value2);
// AND operation (conceptually, actual method not shown here)
// Bytes andResult = value1.and(value2);
```
--------------------------------
### SECP256K1 - Elliptic Curve Cryptography (Java)
Source: https://context7.com/consensys/tuweni/llms.txt
Illustrates the use of the SECP256K1 module for elliptic curve operations, including key pair generation, signing and verifying messages (both direct and pre-hashed), and ECIES encryption/decryption. This is crucial for Bitcoin and Ethereum.
```Java
import org.apache.tuweni.crypto.SECP256K1;
import org.apache.tuweni.crypto.SECP256K1.KeyPair;
import org.apache.tuweni.crypto.SECP256K1.PublicKey;
import org.apache.tuweni.crypto.SECP256K1.SecretKey;
import org.apache.tuweni.crypto.SECP256K1.Signature;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
// Generate a new key pair
KeyPair keyPair = KeyPair.random();
SecretKey secretKey = keyPair.secretKey();
PublicKey publicKey = keyPair.publicKey();
// Access key bytes
Bytes32 secretKeyBytes = secretKey.bytes();
Bytes publicKeyBytes = publicKey.bytes(); // 64 bytes (uncompressed, no prefix)
// Sign data (automatically hashes with keccak256)
Bytes message = Bytes.fromHexString("0x68656c6c6f");
Signature signature = SECP256K1.sign(message, keyPair);
// Sign pre-hashed data
Bytes32 messageHash = Bytes32.wrap(Hash.keccak256(message.toArrayUnsafe()));
Signature signatureFromHash = SECP256K1.signHashed(messageHash, keyPair);
// Verify signature
boolean isValid = SECP256K1.verify(message, signature, publicKey);
boolean isValidHashed = SECP256K1.verifyHashed(messageHash, signature, publicKey);
// Recover public key from signature (useful for Ethereum transactions)
// Signature contains v, r, s components
byte v = signature.v();
java.math.BigInteger r = signature.r();
java.math.BigInteger s = signature.s();
// Encrypt data with public key (ECIES)
Bytes plaintext = Bytes.wrap("secret message".getBytes());
Bytes encrypted = SECP256K1.encrypt(publicKey, plaintext);
// Decrypt with secret key
Bytes decrypted = SECP256K1.decrypt(secretKey, encrypted);
```
--------------------------------
### MutableBytes - In-place Byte Array Modification (Java)
Source: https://context7.com/consensys/tuweni/llms.txt
Demonstrates how to create, modify, and convert MutableBytes objects for performance-sensitive operations. Covers setting individual bytes, integers, longs, copying, filling, clearing, and converting back to immutable Bytes.
```Java
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.MutableBytes;
import org.apache.tuweni.bytes.MutableBytes32;
// Create mutable bytes
MutableBytes mutable = MutableBytes.create(32);
MutableBytes32 mutable32 = MutableBytes32.create();
// Create from existing bytes
MutableBytes copy = Bytes.fromHexString("0xdeadbeef").mutableCopy();
// Set individual bytes
mutable.set(0, (byte) 0xff);
// Set integers and longs at positions
mutable.setInt(4, 12345678);
mutable.setLong(8, 9876543210L);
// Set bytes from another value
mutable.set(16, Bytes.fromHexString("0xcafe"));
// Fill entire buffer
MutableBytes filled = MutableBytes.create(4);
filled.fill((byte) 0xaa);
// Result: 0xaaaaaaaa
// Clear all bytes
mutable.clear();
// Convert back to immutable
Bytes immutable = mutable.copy();
```
--------------------------------
### Fill MutableBytes with a specific byte value
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Demonstrates how to fill a MutableBytes object with a repeating byte value using the fill method. This is useful for initializing byte arrays with a consistent pattern. It takes a byte value as input and modifies the MutableBytes object in place.
```java
MutableBytes bytes = MutableBytes.create(2);
bytes.fill((byte) 34);
assertEquals(Bytes.fromHexString("0x2222"), bytes);
```
--------------------------------
### Convert Bytes to Array in Java
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Explains the `toArray()` and `toArrayUnsafe()` methods for converting Bytes objects into byte arrays. `toArray()` creates a new copy, while `toArrayUnsafe()` provides direct access to the underlying array for performance gains.
```java
import org.apache.tuweni.bytes.Bytes;
// Assuming 'bytes' is an existing Bytes object
// Bytes bytes = ...;
// Create a new byte array copy
// byte[] byteArrayCopy = bytes.toArray();
// Get direct access to the underlying byte array (unsafe)
// byte[] unsafeArray = bytes.toArrayUnsafe();
```
--------------------------------
### Bitwise NOT Operation on Bytes Objects in Java
Source: https://github.com/consensys/tuweni/blob/main/bytes/README.md
Illustrates the bitwise NOT operation on a Bytes object, which returns a new Bytes object representing the bitwise complement of the original value.
```java
import org.apache.tuweni.bytes.Bytes;
import static org.junit.jupiter.api.Assertions.assertEquals;
Bytes value = Bytes.fromHexString("0x01000001").not();
assertEquals(Bytes.fromHexString("0xfefffffe"), value);
```