下面列出了com.fasterxml.jackson.annotation.JsonGetter#org.apache.tuweni.bytes.Bytes 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
void testSerialization() {
KeyPair keyPair = KeyPair.random();
byte[] message = "Hello".getBytes(UTF_8);
Signature signature = BLS12381.sign(keyPair, message, 48).signature();
Bytes sigTobytes = signature.encode();
Signature sigFromBytes = Signature.decode(sigTobytes);
assertEquals(signature, sigFromBytes);
assertEquals(signature.hashCode(), sigFromBytes.hashCode());
PublicKey pubKey = keyPair.publicKey();
byte[] pubKeyTobytes = pubKey.toByteArray();
PublicKey pubKeyFromBytes = PublicKey.fromBytes(pubKeyTobytes);
assertEquals(pubKey, pubKeyFromBytes);
assertEquals(pubKey.hashCode(), pubKeyFromBytes.hashCode());
}
@Test
void streamExchange() {
SHA256Hash.Hash clientToServerKey = SHA256Hash.hash(SHA256Hash.Input.fromBytes(Bytes32.random()));
Bytes clientToServerNonce = Bytes.random(24);
SHA256Hash.Hash serverToClientKey = SHA256Hash.hash(SHA256Hash.Input.fromBytes(Bytes32.random()));
Bytes serverToClientNonce = Bytes.random(24);
SecureScuttlebuttStream clientToServer =
new SecureScuttlebuttStream(clientToServerKey, clientToServerNonce, serverToClientKey, serverToClientNonce);
SecureScuttlebuttStream serverToClient =
new SecureScuttlebuttStream(clientToServerKey, clientToServerNonce, serverToClientKey, serverToClientNonce);
Bytes encrypted = clientToServer.sendToServer(Bytes.fromHexString("deadbeef"));
assertEquals(Bytes.fromHexString("deadbeef").size() + 34, encrypted.size());
Bytes decrypted = serverToClient.readFromClient(encrypted);
assertEquals(Bytes.fromHexString("deadbeef"), decrypted);
Bytes response = serverToClient.sendToClient(Bytes.fromHexString("deadbeef"));
assertEquals(Bytes.fromHexString("deadbeef").size() + 34, response.size());
Bytes responseDecrypted = clientToServer.readFromServer(response);
assertEquals(Bytes.fromHexString("deadbeef"), responseDecrypted);
}
private static Stream<Arguments> toBytesProvider() {
return Stream
.of(
Arguments
.of(
hv("0x00"),
Bytes.fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")),
Arguments
.of(
hv("0x01000000"),
Bytes.fromHexString("0x0000000000000000000000000000000000000000000000000000000001000000")),
Arguments
.of(
hv("0x0100000000"),
Bytes.fromHexString("0x0000000000000000000000000000000000000000000000000000000100000000")),
Arguments
.of(
hv("0xf100000000ab"),
Bytes.fromHexString("0x0000000000000000000000000000000000000000000000000000f100000000ab")),
Arguments
.of(
hv("0x0400000000000000000000000000000000000000000000000000f100000000ab"),
Bytes.fromHexString("0x0400000000000000000000000000000000000000000000000000f100000000ab")));
}
@Test
public void ecPointWithBigIntegerAs32ShouldBeEncoded() {
final BigInteger xCoord =
Bytes.fromHexString("0x1575de790d7d00623a3f7e6ec2d0b69d65c5c183f8773a033d2c20dd20008271")
.toBigInteger();
final BigInteger yCoord =
Bytes.fromHexString("0x61772e076283d628beb591a23412c7d906d11b011ca66f188d4052db1e2ad615")
.toBigInteger();
final Bytes expectedEncoded =
Bytes.fromHexString(
"0x1575de790d7d00623a3f7e6ec2d0b69d65c5c183f8773a033d2c20dd2000827161772e076283d628beb591a23412c7d906d11b011ca66f188d4052db1e2ad615");
assertThat(xCoord.toByteArray()).hasSize(32);
assertThat(yCoord.toByteArray()).hasSize(32);
final ECPoint ecPoint = new ECPoint(xCoord, yCoord);
final Bytes encodedBytes = ECPointUtil.getEncodedBytes(ecPoint);
assertThat(encodedBytes.toArray()).hasSize(64);
assertThat(encodedBytes).isEqualByComparingTo(expectedEncoded);
}
public Node<V> replaceChild(final byte index, final Node<V> updatedChild) {
final ArrayList<Node<V>> newChildren = new ArrayList<>(children);
newChildren.set(index, updatedChild);
if (updatedChild == NULL_NODE) {
if (value.isPresent() && !hasChildren()) {
return nodeFactory.createLeaf(Bytes.of(index), value.get());
} else if (!value.isPresent()) {
final Optional<Node<V>> flattened = maybeFlatten(newChildren);
if (flattened.isPresent()) {
return flattened.get();
}
}
}
return nodeFactory.createBranch(newChildren, value);
}
/**
* Public constructor.
*
* @param code The code to be executed.
* @param account The address of the currently executing account.
* @param caller The caller address.
* @param origin The sender address of the original transaction.
* @param data The data of the current environment that pertains to the input data passed with the
* message call instruction or transaction.
* @param value The deposited value by the instruction/transaction responsible for this execution.
* @param gasPrice The gas price specified by the originating transaction.
*/
@JsonCreator
public EnvironmentInformation(
@JsonProperty("address") final String account,
@JsonProperty("balance") final String balance,
@JsonProperty("caller") final String caller,
@JsonProperty("code") final CodeMock code,
@JsonProperty("data") final String data,
@JsonProperty("gas") final String gas,
@JsonProperty("gasPrice") final String gasPrice,
@JsonProperty("origin") final String origin,
@JsonProperty("value") final String value,
@JsonProperty("version") final String version) {
this(
code,
0,
account == null ? null : Address.fromHexString(account),
balance == null ? Wei.ZERO : Wei.fromHexString(balance),
caller == null ? null : Address.fromHexString(caller),
origin == null ? null : Address.fromHexString(origin),
data == null ? null : Bytes.fromHexString(data),
value == null ? null : Wei.fromHexString(value),
gasPrice == null ? null : Wei.fromHexString(gasPrice),
gas == null ? null : Gas.fromHexString(gas),
version == null ? Account.DEFAULT_VERSION : Integer.decode(version));
}
@Test
public void readFrom_withExtraFields() {
final int version = 4;
final Endpoint from = new Endpoint("127.0.0.1", 30303, OptionalInt.of(30303));
final Endpoint to = new Endpoint("127.0.0.2", 30303, OptionalInt.empty());
final long time = System.currentTimeMillis();
final BytesValueRLPOutput out = new BytesValueRLPOutput();
out.startList();
out.writeIntScalar(version);
from.encodeStandalone(out);
to.encodeStandalone(out);
out.writeLongScalar(time);
// Add extra field
out.writeLongScalar(11);
out.endList();
final Bytes serialized = out.encoded();
final PingPacketData deserialized = PingPacketData.readFrom(RLP.input(serialized));
assertThat(deserialized.getFrom()).isEqualTo(from);
assertThat(deserialized.getTo()).isEqualTo(to);
assertThat(deserialized.getExpiration()).isEqualTo(time);
}
private PrivateTransactionProcessor mockPrivateTxProcessor() {
final PrivateTransactionProcessor mockPrivateTransactionProcessor =
mock(PrivateTransactionProcessor.class);
final List<Log> logs = new ArrayList<>();
final PrivateTransactionProcessor.Result result =
PrivateTransactionProcessor.Result.successful(
logs, 0, 0, Bytes.fromHexString(DEFAULT_OUTPUT), null);
when(mockPrivateTransactionProcessor.processTransaction(
nullable(Blockchain.class),
nullable(WorldUpdater.class),
nullable(WorldUpdater.class),
nullable(ProcessableBlockHeader.class),
nullable((Hash.class)),
nullable(PrivateTransaction.class),
nullable(Address.class),
nullable(OperationTracer.class),
nullable(BlockHashLookup.class),
nullable(Bytes.class)))
.thenReturn(result);
return mockPrivateTransactionProcessor;
}
private Set<Bytes> collectWorldStateNodes(final Hash stateRootHash, final Set<Bytes> collector) {
final List<Hash> storageRoots = new ArrayList<>();
final MerklePatriciaTrie<Bytes32, Bytes> stateTrie = createStateTrie(stateRootHash);
// Collect storage roots and code
stateTrie
.entriesFrom(Bytes32.ZERO, 1000)
.forEach(
(key, val) -> {
final StateTrieAccountValue accountValue =
StateTrieAccountValue.readFrom(RLP.input(val));
stateStorage
.get(accountValue.getCodeHash().toArray())
.ifPresent(v -> collector.add(Bytes.wrap(v)));
storageRoots.add(accountValue.getStorageRoot());
});
// Collect state nodes
collectTrieNodes(stateTrie, collector);
// Collect storage nodes
for (Hash storageRoot : storageRoots) {
final MerklePatriciaTrie<Bytes32, Bytes> storageTrie = createStorageTrie(storageRoot);
collectTrieNodes(storageTrie, collector);
}
return collector;
}
@Test
public void handleMessage_invalidSSZ() {
Bytes serialized = Bytes.fromHexString("0x1234");
final ValidationResult result = topicHandler.handleMessage(serialized);
assertThat(result).isEqualTo(ValidationResult.Invalid);
verifyNoInteractions(consumer);
}
private boolean validateExtraData(final Bytes extraData) {
if (extraData.size() > maxExtraDataBytes) {
LOG.trace(
"Invalid block header: extra data field length {} is greater {}",
extraData.size(),
maxExtraDataBytes);
return false;
}
return true;
}
private LogWithMetadata logWithMetadata() {
return new LogWithMetadata(
0,
100L,
Hash.ZERO,
Hash.ZERO,
0,
Address.fromHexString("0x0"),
Bytes.EMPTY,
Lists.newArrayList(),
false);
}
@Test
void disconnectIfNoHelloReceived() {
AtomicReference<RLPxMessage> capturedDisconnect = new AtomicReference<>();
DefaultWireConnection conn =
new DefaultWireConnection("abc", nodeId, peerNodeId, capturedDisconnect::set, helloMessage -> {
}, () -> {
}, new LinkedHashMap<>(), 4, "abc", 10000, AsyncResult.incomplete());
conn.sendHello();
conn.messageReceived(new RLPxMessage(45, Bytes.EMPTY));
assertEquals(1, capturedDisconnect.get().messageId());
DisconnectMessage msg = DisconnectMessage.read(capturedDisconnect.get().content());
assertEquals(2, msg.reason());
}
@Override
public AsyncResult<Optional<QueryPrivacyGroupPayload>> get(final String key) {
final Bytes keyBytes = Bytes.wrap(key.getBytes(UTF_8));
return store.getAsync(keyBytes).thenApply(
maybeBytes -> Optional.ofNullable(maybeBytes).map(
bytes -> Serializer
.deserialize(HttpContentType.CBOR, QueryPrivacyGroupPayload.class, bytes.toArrayUnsafe())));
}
@Override
public Bytes toMinimalBytes() {
int requiredBytes = 8 - (Long.numberOfLeadingZeros(this.value) / 8);
MutableBytes bytes = MutableBytes.create(requiredBytes);
int j = 0;
switch (requiredBytes) {
case 8:
bytes.set(j++, (byte) (this.value >>> 56));
// fall through
case 7:
bytes.set(j++, (byte) ((this.value >>> 48) & 0xFF));
// fall through
case 6:
bytes.set(j++, (byte) ((this.value >>> 40) & 0xFF));
// fall through
case 5:
bytes.set(j++, (byte) ((this.value >>> 32) & 0xFF));
// fall through
case 4:
bytes.set(j++, (byte) ((this.value >>> 24) & 0xFF));
// fall through
case 3:
bytes.set(j++, (byte) ((this.value >>> 16) & 0xFF));
// fall through
case 2:
bytes.set(j++, (byte) ((this.value >>> 8) & 0xFF));
// fall through
case 1:
bytes.set(j, (byte) (this.value & 0xFF));
}
return bytes;
}
private static Stream<Arguments> toMinimalBytesProvider() {
return Stream
.of(
Arguments.of(hv("0x00"), Bytes.EMPTY),
Arguments.of(hv("0x01000000"), Bytes.fromHexString("0x01000000")),
Arguments.of(hv("0x0100000000"), Bytes.fromHexString("0x0100000000")),
Arguments.of(hv("0xf100000000ab"), Bytes.fromHexString("0xf100000000ab")),
Arguments
.of(
hv("0x0400000000000000000000000000000000000000000000000000f100000000ab"),
Bytes.fromHexString("0x0400000000000000000000000000000000000000000000000000f100000000ab")));
}
public static Result failed(
final long gasUsedByTransaction,
final long gasRemaining,
final ValidationResult<TransactionValidator.TransactionInvalidReason> validationResult,
final Optional<Bytes> revertReason) {
return new Result(
Status.FAILED,
new ArrayList<>(),
gasUsedByTransaction,
gasRemaining,
Bytes.EMPTY,
validationResult,
revertReason);
}
public static Bytes encodeVarInt(final int value) {
try {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(output);
codedOutputStream.writeUInt32NoTag(value);
codedOutputStream.flush();
return Bytes.wrap(output.toByteArray());
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
@Test
void shouldWriteEmptyStrings() {
ByteBuffer buffer = ByteBuffer.allocate(64);
SSZ.encodeTo(buffer, writer -> writer.writeString(""));
buffer.flip();
assertEquals(fromHexString("00000000"), Bytes.wrapByteBuffer(buffer));
}
@Test
void testSplitBranchExtension() throws Exception {
final Bytes key1 = Bytes.of(1, 5, 9);
final Bytes key2 = Bytes.of(1, 5, 2);
final Bytes key3 = Bytes.of(1, 9, 1);
trie.putAsync(key1, "value1").join();
trie.putAsync(key2, "value2").join();
trie.putAsync(key3, "value3").join();
assertEquals("value1", trie.getAsync(key1).get());
assertEquals("value2", trie.getAsync(key2).get());
assertEquals("value3", trie.getAsync(key3).get());
}
private Transaction createTransaction(final int transactionNumber) {
return Transaction.builder()
.gasLimit(100)
.gasPrice(Wei.ZERO)
.nonce(1)
.payload(Bytes.EMPTY)
.to(Address.ID)
.value(Wei.of(transactionNumber))
.sender(Address.ID)
.chainId(BigInteger.ONE)
.signAndBuild(keyPair);
}
static ResponderHandshakeMessage decode(Bytes payload) {
return RLP
.decodeList(
payload,
reader -> new ResponderHandshakeMessage(
PublicKey.fromBytes(reader.readValue()),
Bytes32.wrap(reader.readValue())));
}
private SortedMap<UInt256, Proof<Bytes>> getStorageProofs(
final StateTrieAccountValue account, final List<UInt256> accountStorageKeys) {
final MerklePatriciaTrie<Bytes32, Bytes> storageTrie =
newAccountStorageTrie(account.getStorageRoot());
final NavigableMap<UInt256, Proof<Bytes>> storageProofs = new TreeMap<>();
accountStorageKeys.forEach(
key -> storageProofs.put(key, storageTrie.getValueWithProof(Hash.hash(key.toBytes()))));
return storageProofs;
}
/**
* Decrypt a message using a password and a detached message authentication code, using {@link PasswordHash} for the
* key generation.
*
* @param cipherText The cipher text to decrypt.
* @param mac The message authentication code.
* @param password The password that was used for encryption.
* @param opsLimit The opsLimit that was used for encryption.
* @param memLimit The memLimit that was used for encryption.
* @param algorithm The algorithm that was used for encryption.
* @return The decrypted data, or {@code null} if verification failed.
*/
@Nullable
public static Bytes decryptDetached(
Bytes cipherText,
Bytes mac,
String password,
long opsLimit,
long memLimit,
PasswordHash.Algorithm algorithm) {
byte[] bytes =
decryptDetached(cipherText.toArrayUnsafe(), mac.toArrayUnsafe(), password, opsLimit, memLimit, algorithm);
return (bytes != null) ? Bytes.wrap(bytes) : null;
}
private void processAccountState(final Bytes value) {
final StateTrieAccountValue accountValue = StateTrieAccountValue.readFrom(RLP.input(value));
markNode(accountValue.getCodeHash());
createStorageTrie(accountValue.getStorageRoot())
.visitAll(storageNode -> markNode(storageNode.getHash()));
}
public static BLSPublicKey fromBytes(Bytes bytes) {
checkArgument(
bytes.size() == BLS_PUBKEY_SIZE,
"Expected " + BLS_PUBKEY_SIZE + " bytes but received %s.",
bytes.size());
return SSZ.decode(
bytes,
reader ->
new BLSPublicKey(
PublicKey.fromBytesCompressed(reader.readFixedBytes(BLS_PUBKEY_SIZE))));
}
public Bytes uncompress(final Bytes compressedData) throws DecodingException {
try {
return Bytes.wrap(Snappy.uncompress(compressedData.toArrayUnsafe()));
} catch (IOException e) {
throw new DecodingException("Failed to uncompress", e);
}
}
@Test
void testBranchWithValue() throws Exception {
final Bytes key1 = Bytes.of(5);
final Bytes key2 = Bytes.EMPTY;
trie.putAsync(key1, "value1").join();
trie.putAsync(key2, "value2").join();
assertEquals("value1", trie.getAsync(key1).get());
assertEquals("value2", trie.getAsync(key2).get());
}
private static String validPrivateTransactionRlpPrivacyGroup() {
final PrivateTransaction.Builder privateTransactionBuilder =
PrivateTransaction.builder()
.nonce(0)
.gasPrice(Wei.of(1))
.gasLimit(21000)
.value(Wei.ZERO)
.payload(Bytes.EMPTY)
.to(Address.fromHexString("0x095e7baea6a6c7c4c2dfeb977efac326af552d87"))
.chainId(BigInteger.ONE)
.privateFrom(Bytes.fromBase64String("S28yYlZxRCtuTmxOWUw1RUU3eTNJZE9udmlmdGppaXp="))
.privacyGroupId(Bytes.fromBase64String("DyAOiF/ynpc+JXa2YAGB0bCitSlOMNm+ShmB/7M6C4w="))
.restriction(Restriction.RESTRICTED);
return rlpEncodeTransaction(privateTransactionBuilder);
}
/**
* Read a {@link UInt256} value from the RLP source.
*
* @param lenient If {@code false}, an exception will be thrown if the integer is not minimally encoded.
* @return A {@link UInt256} value.
* @throws InvalidRLPEncodingException If there is an error decoding the RLP source, or the integer is not minimally
* encoded and `lenient` is {@code false}.
* @throws InvalidRLPTypeException If the next RLP value cannot be represented as a long.
* @throws EndOfRLPException If there are no more RLP values to read.
*/
default UInt256 readUInt256(boolean lenient) {
Bytes bytes = readValue();
if (!lenient && bytes.hasLeadingZeroByte()) {
throw new InvalidRLPEncodingException("Integer value was not minimally encoded");
}
try {
return UInt256.fromBytes(bytes);
} catch (IllegalArgumentException e) {
throw new InvalidRLPTypeException("Value is too large to be represented as a UInt256");
}
}