org.apache.tuweni.bytes.Bytes Java Examples
The following examples show how to use
org.apache.tuweni.bytes.Bytes.
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: PingPacketDataTest.java From besu with Apache License 2.0 | 6 votes |
@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); }
Example #2
Source File: ECPointUtilTest.java From besu with Apache License 2.0 | 6 votes |
@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); }
Example #3
Source File: PrivacyPrecompiledContractTest.java From besu with Apache License 2.0 | 6 votes |
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; }
Example #4
Source File: BaseUInt256ValueTest.java From incubator-tuweni with Apache License 2.0 | 6 votes |
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"))); }
Example #5
Source File: SignatureTest.java From incubator-tuweni with Apache License 2.0 | 6 votes |
@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()); }
Example #6
Source File: BranchNode.java From besu with Apache License 2.0 | 6 votes |
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); }
Example #7
Source File: SecureScuttlebuttStreamTest.java From incubator-tuweni with Apache License 2.0 | 6 votes |
@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); }
Example #8
Source File: EnvironmentInformation.java From besu with Apache License 2.0 | 6 votes |
/** * 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)); }
Example #9
Source File: QueryPrivacyGroupStorage.java From orion with Apache License 2.0 | 5 votes |
@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()))); }
Example #10
Source File: SecretBox.java From incubator-tuweni with Apache License 2.0 | 5 votes |
/** * 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; }
Example #11
Source File: UInt64.java From incubator-tuweni with Apache License 2.0 | 5 votes |
@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; }
Example #12
Source File: BLSPublicKey.java From teku with Apache License 2.0 | 5 votes |
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)))); }
Example #13
Source File: MarkSweepPruner.java From besu with Apache License 2.0 | 5 votes |
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())); }
Example #14
Source File: SnappyBlockCompressor.java From teku with Apache License 2.0 | 5 votes |
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); } }
Example #15
Source File: BaseUInt384ValueTest.java From incubator-tuweni with Apache License 2.0 | 5 votes |
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"))); }
Example #16
Source File: MerklePatriciaTrieJavaTest.java From incubator-tuweni with Apache License 2.0 | 5 votes |
@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()); }
Example #17
Source File: EeaSendRawTransactionTest.java From besu with Apache License 2.0 | 5 votes |
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); }
Example #18
Source File: MockPacketDataFactory.java From besu with Apache License 2.0 | 5 votes |
static Packet mockFindNeighborsPacket(final Peer from, final long exparationMs) { final Packet packet = mock(Packet.class); final Bytes target = Bytes.fromHexString( "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f40"); final FindNeighborsPacketData packetData = FindNeighborsPacketData.create(target, exparationMs); when(packet.getPacketData(any())).thenReturn(Optional.of(packetData)); final Bytes id = from.getId(); when(packet.getNodeId()).thenReturn(id); when(packet.getType()).thenReturn(PacketType.FIND_NEIGHBORS); when(packet.getHash()).thenReturn(Bytes32.ZERO); return packet; }
Example #19
Source File: RLPReader.java From incubator-tuweni with Apache License 2.0 | 5 votes |
/** * 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"); } }
Example #20
Source File: ValidatorLoaderTest.java From teku with Apache License 2.0 | 5 votes |
@Test void initializeValidatorsWithBothLocalAndExternalSigners(@TempDir Path tempDir) throws IOException { final Path validatorKeyFile = tempDir.resolve("validatorKeyFile"); Files.writeString(validatorKeyFile, VALIDATOR_KEY_FILE); final TekuConfiguration tekuConfiguration = TekuConfiguration.builder() .setValidatorExternalSignerUrl("http://localhost:9000") .setValidatorExternalSignerPublicKeys(Collections.singletonList(PUBLIC_KEY2)) .setValidatorKeyFile(validatorKeyFile.toAbsolutePath().toString()) .setValidatorKeystoreFiles(emptyList()) .setValidatorKeystorePasswordFiles(emptyList()) .build(); final Map<BLSPublicKey, Validator> validators = ValidatorLoader.initializeValidators(tekuConfiguration); assertThat(validators).hasSize(2); final BLSPublicKey key1 = BLSPublicKey.fromBytes(Bytes.fromHexString(PUBLIC_KEY1)); final Validator validator1 = validators.get(key1); assertThat(validator1).isNotNull(); assertThat(validator1.getPublicKey()).isEqualTo(key1); assertThat(validator1.getSigner().getMessageSignerService()) .isInstanceOf(LocalMessageSignerService.class); final BLSPublicKey key2 = BLSPublicKey.fromBytes(Bytes.fromHexString(PUBLIC_KEY2)); final Validator validator2 = validators.get(key2); assertThat(validator2).isNotNull(); assertThat(validator2.getPublicKey()).isEqualTo(key2); assertThat(validator2.getSigner().getMessageSignerService()) .isInstanceOf(ExternalMessageSignerService.class); }
Example #21
Source File: PeerReputationManagerTest.java From besu with Apache License 2.0 | 5 votes |
private PeerConnection generatePeerConnection() { final Bytes nodeId = Peer.randomId(); final PeerConnection conn = mock(PeerConnection.class); final PeerInfo peerInfo = mock(PeerInfo.class); final Peer peer = generatePeer(); when(peerInfo.getNodeId()).thenReturn(nodeId); when(conn.getPeerInfo()).thenReturn(peerInfo); when(conn.getPeer()).thenReturn(peer); return conn; }
Example #22
Source File: EthCallTest.java From besu with Apache License 2.0 | 5 votes |
private void mockTransactionProcessorSuccessResult(final Bytes output) { final TransactionSimulatorResult result = mock(TransactionSimulatorResult.class); when(result.getValidationResult()).thenReturn(ValidationResult.valid()); when(result.getOutput()).thenReturn(output); when(transactionSimulator.process(any(), anyLong())).thenReturn(Optional.of(result)); }
Example #23
Source File: PeerTable.java From besu with Apache License 2.0 | 5 votes |
private void buildBloomFilter() { final BloomFilter<Bytes> bf = BloomFilter.create((id, val) -> val.putBytes(id.toArray()), maxEntriesCnt, 0.001); streamAllPeers().map(Peer::getId).forEach(bf::put); this.evictionCnt = 0; this.idBloom = bf; }
Example #24
Source File: SszTestExecutor.java From teku with Apache License 2.0 | 5 votes |
@Override public void runTest(final TestDefinition testDefinition) throws Exception { final Path testDirectory = testDefinition.getTestDirectory(); final Bytes inputData = Bytes.wrap(Files.readAllBytes(testDirectory.resolve("serialized.ssz"))); final Bytes32 expectedRoot = TestDataUtils.loadYaml(testDefinition, "roots.yaml", Roots.class).getRoot(); final T result = SimpleOffsetSerializer.deserialize(inputData, clazz); // Deserialize assertThat(result.hash_tree_root()).isEqualTo(expectedRoot); // Serialize assertThat(SimpleOffsetSerializer.serialize(result)).isEqualTo(inputData); }
Example #25
Source File: AggregateAndProof.java From teku with Apache License 2.0 | 5 votes |
@Override public List<Bytes> get_variable_parts() { List<Bytes> variablePartsList = new ArrayList<>(); variablePartsList.add(Bytes.EMPTY); variablePartsList.add(SimpleOffsetSerializer.serialize(aggregate)); variablePartsList.addAll(Collections.nCopies(selection_proof.getSSZFieldCount(), Bytes.EMPTY)); return variablePartsList; }
Example #26
Source File: Hash.java From incubator-tuweni with Apache License 2.0 | 5 votes |
/** * Digest using SHA3-512. * * @param input The value to encode. * @return A digest. */ public static Bytes sha3_512(Bytes input) { try { return Bytes.wrap(digestUsingAlgorithm(input, SHA3_512).toArrayUnsafe()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Algorithm should be available but was not", e); } }
Example #27
Source File: EthGetFilterLogsTest.java From besu with Apache License 2.0 | 5 votes |
private List<LogWithMetadata> logs() { return Collections.singletonList( new LogWithMetadata( 0, 100L, Hash.ZERO, Hash.ZERO, 0, Address.fromHexString("0x0"), Bytes.EMPTY, Lists.newArrayList(), false)); }
Example #28
Source File: DisconnectMessageTest.java From besu with Apache License 2.0 | 5 votes |
@Test public void readFromWithNoReason() { MessageData messageData = new RawMessage(WireMessageCodes.DISCONNECT, Bytes.fromHexString("0xC180")); DisconnectMessage disconnectMessage = DisconnectMessage.readFrom(messageData); DisconnectReason reason = disconnectMessage.getReason(); assertThat(reason).isEqualTo(DisconnectReason.UNKNOWN); }
Example #29
Source File: TracingUtils.java From besu with Apache License 2.0 | 5 votes |
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 #30
Source File: IbftVanityDataValidationRuleTest.java From besu with Apache License 2.0 | 5 votes |
public boolean headerWithVanityDataOfSize(final int extraDataSize) { final IbftExtraData extraData = new IbftExtraData( Bytes.wrap(new byte[extraDataSize]), emptyList(), empty(), 0, emptyList()); final BlockHeader header = new BlockHeaderTestFixture().extraData(extraData.encode()).buildHeader(); return validationRule.validate(header, null, null); }