Java Code Examples for org.apache.tuweni.bytes.Bytes#size()
The following examples show how to use
org.apache.tuweni.bytes.Bytes#size() .
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: BytesSSZReader.java From incubator-tuweni with Apache License 2.0 | 6 votes |
private List<Bytes> readList(LongFunction<Bytes> bytesSupplier) { ensureBytes(4, () -> "SSZ encoded data is not a list"); int originalIndex = this.index; List<Bytes> elements; try { // use a long to simulate reading unsigned long listSize = consumeBytes(4).toLong(LITTLE_ENDIAN); elements = new ArrayList<>(); while (listSize > 0) { Bytes bytes = bytesSupplier.apply(listSize); elements.add(bytes); listSize -= bytes.size(); listSize -= 4; if (listSize < 0) { throw new InvalidSSZTypeException("SSZ encoded list length does not align with lengths of its elements"); } } } catch (Exception e) { this.index = originalIndex; throw e; } return elements; }
Example 2
Source File: SecureScuttlebuttStream.java From incubator-tuweni with Apache License 2.0 | 6 votes |
private Bytes encryptMessage(Bytes message, SecretBox.Key key, MutableBytes nonce) { SecretBox.Nonce headerNonce = null; SecretBox.Nonce bodyNonce = null; try { headerNonce = SecretBox.Nonce.fromBytes(nonce); bodyNonce = SecretBox.Nonce.fromBytes(nonce.increment()); nonce.increment(); Bytes encryptedBody = SecretBox.encrypt(message, key, bodyNonce); int bodySize = encryptedBody.size() - 16; Bytes encodedBodySize = Bytes.ofUnsignedInt(bodySize).slice(2); Bytes header = SecretBox.encrypt(Bytes.concatenate(encodedBodySize, encryptedBody.slice(0, 16)), key, headerNonce); return Bytes.concatenate(header, encryptedBody.slice(16)); } finally { destroyIfNonNull(headerNonce); destroyIfNonNull(bodyNonce); } }
Example 3
Source File: CliqueExtraData.java From besu with Apache License 2.0 | 6 votes |
static CliqueExtraData decodeRaw(final BlockHeader header) { final Bytes input = header.getExtraData(); if (input.size() < EXTRA_VANITY_LENGTH + Signature.BYTES_REQUIRED) { throw new IllegalArgumentException( "Invalid Bytes supplied - too short to produce a valid Clique Extra Data object."); } final int validatorByteCount = input.size() - EXTRA_VANITY_LENGTH - Signature.BYTES_REQUIRED; if ((validatorByteCount % Address.SIZE) != 0) { throw new IllegalArgumentException("Bytes is of invalid size - i.e. contains unused bytes."); } final Bytes vanityData = input.slice(0, EXTRA_VANITY_LENGTH); final List<Address> validators = extractValidators(input.slice(EXTRA_VANITY_LENGTH, validatorByteCount)); final int proposerSealStartIndex = input.size() - Signature.BYTES_REQUIRED; final Signature proposerSeal = parseProposerSeal(input.slice(proposerSealStartIndex)); return new CliqueExtraData(vanityData, proposerSeal, validators, header); }
Example 4
Source File: SecureScuttlebuttHandshakeClient.java From incubator-tuweni with Apache License 2.0 | 6 votes |
/** * Validates the initial message's MAC with our network identifier, and returns the peer ephemeral public key. * * @param message initial handshake message */ public void readHello(Bytes message) { if (message.size() != 64) { throw new HandshakeException("Invalid handshake message length: " + message.size()); } Bytes hmac = message.slice(0, 32); Bytes key = message.slice(32, 32); if (!HMACSHA512256.verify(hmac, key, networkIdentifier)) { throw new HandshakeException("MAC does not match our network identifier"); } this.serverEphemeralPublicKey = Box.PublicKey.fromBytes(key); this.sharedSecret = DiffieHelman.Secret .forKeys( DiffieHelman.SecretKey.forBoxSecretKey(ephemeralKeyPair.secretKey()), DiffieHelman.PublicKey.forBoxPublicKey(serverEphemeralPublicKey)); this.sharedSecret2 = DiffieHelman.Secret .forKeys( DiffieHelman.SecretKey.forBoxSecretKey(ephemeralKeyPair.secretKey()), DiffieHelman.PublicKey.forSignaturePublicKey(serverLongTermPublicKey)); this.sharedSecret3 = DiffieHelman.Secret .forKeys( DiffieHelman.SecretKey.forSignatureSecretKey(longTermKeyPair.secretKey()), DiffieHelman.PublicKey.forBoxPublicKey(serverEphemeralPublicKey)); }
Example 5
Source File: PrivacyReorgTest.java From besu with Apache License 2.0 | 6 votes |
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 6
Source File: BLSSecretKey.java From teku with Apache License 2.0 | 5 votes |
public Bytes toBytes() { final Bytes bytes = secretKey.toBytes(); if (bytes.size() == 48) { final int paddingLength = 48 - 32; if (bytes.slice(0, paddingLength).isZero()) { return bytes.slice(paddingLength, 32); } } return bytes; }
Example 7
Source File: CompactEncoding.java From besu with Apache License 2.0 | 5 votes |
public static Bytes pathToBytes(final Bytes path) { checkArgument(!path.isEmpty(), "Path must not be empty"); checkArgument(path.get(path.size() - 1) == LEAF_TERMINATOR, "Path must be a leaf path"); final MutableBytes bytes = MutableBytes.create((path.size() - 1) / 2); int bytesPos = 0; for (int pathPos = 0; pathPos < path.size() - 1; pathPos += 2, bytesPos += 1) { final byte high = path.get(pathPos); final byte low = path.get(pathPos + 1); if ((high & 0xf0) != 0 || (low & 0xf0) != 0) { throw new IllegalArgumentException("Invalid path: contains elements larger than a nibble"); } bytes.set(bytesPos, (byte) (high << 4 | low)); } return bytes; }
Example 8
Source File: GetVisitor.java From besu with Apache License 2.0 | 5 votes |
@Override public Node<V> visit(final LeafNode<V> leafNode, final Bytes path) { final Bytes leafPath = leafNode.getPath(); if (leafPath.commonPrefixLength(path) != leafPath.size()) { return NULL_NODE_RESULT; } return leafNode; }
Example 9
Source File: SecureScuttlebuttStream.java From incubator-tuweni with Apache License 2.0 | 5 votes |
private Bytes decrypt(Bytes message, SecretBox.Key key, MutableBytes nonce, boolean isClientToServer) { int index = 0; List<Bytes> decryptedMessages = new ArrayList<>(); Bytes messageWithBuffer; if (isClientToServer) { messageWithBuffer = Bytes.concatenate(clientToServerBuffer, message); } else { messageWithBuffer = Bytes.concatenate(serverToClientBuffer, message); } while (index < messageWithBuffer.size()) { Bytes decryptedMessage = decryptMessage(messageWithBuffer.slice(index), key, nonce); if (decryptedMessage == null) { break; } decryptedMessages.add(decryptedMessage); index += decryptedMessage.size() + 34; } if (isClientToServer) { clientToServerBuffer = messageWithBuffer.slice(index); } else { serverToClientBuffer = messageWithBuffer.slice(index); } return Bytes.concatenate(decryptedMessages.toArray(new Bytes[0])); }
Example 10
Source File: RLPEncodingHelpers.java From besu with Apache License 2.0 | 5 votes |
/** The encoded size of the provided value. */ static int elementSize(final Bytes value) { if (isSingleRLPByte(value)) return 1; if (isShortElement(value)) return 1 + value.size(); return 1 + sizeLength(value.size()) + value.size(); }
Example 11
Source File: CompactEncoding.java From incubator-tuweni with Apache License 2.0 | 5 votes |
/** * Decode a compact-encoded path to Radix-16. * * @param encoded A compact-encoded path. * @return A Radix-16 path. */ public static Bytes decode(Bytes encoded) { int size = encoded.size(); checkArgument(size > 0); byte magic = encoded.get(0); checkArgument((magic & 0xc0) == 0, "Invalid compact encoding"); boolean isLeaf = (magic & 0x20) != 0; int pathLength = ((size - 1) * 2) + (isLeaf ? 1 : 0); MutableBytes path; int i = 0; if ((magic & 0x10) != 0) { // need to use lower nibble of magic path = MutableBytes.create(pathLength + 1); path.set(i++, (byte) (magic & 0x0f)); } else { path = MutableBytes.create(pathLength); } for (int j = 1; j < size; j++) { byte b = encoded.get(j); path.set(i++, (byte) ((b >>> 4) & 0x0f)); path.set(i++, (byte) (b & 0x0f)); } if (isLeaf) { path.set(i, LEAF_TERMINATOR); } return path; }
Example 12
Source File: CompactEncoding.java From incubator-tuweni with Apache License 2.0 | 5 votes |
/** * 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 13
Source File: SnappyCompressorTest.java From teku with Apache License 2.0 | 5 votes |
@Test public void uncompress_truncatedPayload() throws CompressionException { final BeaconState state = dataStructureUtil.randomBeaconState(0); final Bytes serializedState = Bytes.wrap(SimpleOffsetSerializer.serialize(state).toArrayUnsafe()); // Compress and deliver only part of the payload final int payloadSize = serializedState.size(); final Bytes compressed = compressor.compress(serializedState.slice(1)); Decompressor decompressor = new SnappyFramedCompressor().createDecompressor(payloadSize); assertThat(decompressor.decodeOneMessage(Utils.toByteBuf(compressed))).isEmpty(); assertThatThrownBy(decompressor::complete) .isInstanceOf(PayloadSmallerThanExpectedException.class); }
Example 14
Source File: Prysm.java From teku with Apache License 2.0 | 5 votes |
private File writePrivKeyToFile(final PrivKey privKey) throws IOException { final File privKeyFile = File.createTempFile("prysm-priv-key", ".key"); privKeyFile.deleteOnExit(); // Prysm is particularly picky about how the private key is written. // It does not support the 33 byte version where a leading 0 is added to ensure the // number is always interpreted as positive. Bytes rawBytes = Bytes.wrap(privKey.raw()); if (rawBytes.size() == 33) { rawBytes = rawBytes.slice(1, 32); } // And it doesn't accept a 0x prefix so we can't just use toHexString(). Files.writeString(privKeyFile.toPath(), rawBytes.appendHexTo(new StringBuilder())); return privKeyFile; }
Example 15
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 16
Source File: RLPEncodingHelpers.java From besu with Apache License 2.0 | 4 votes |
static boolean isShortElement(final Bytes value) { return value.size() <= 55; }
Example 17
Source File: Memory.java From besu with Apache License 2.0 | 4 votes |
/** * Copy the bytes from the provided number of bytes from the provided value to memory from the * provided offset. * * <p>Note that this method will extend memory to accommodate the location assigned and bytes * copied and so never fails. * * @param memOffset the location in memory at which to start copying the bytes of {@code value}. * @param sourceOffset the location in the source to start copying. * @param numBytes the number of bytes to set in memory. Note that this value may differ from * {@code value.size()}: if {@code numBytes < value.size()} bytes, only {@code numBytes} will * be copied from {@code value}; if {@code numBytes < value.size()}, then only the bytes in * {@code value} will be copied, but the memory will be expanded if necessary to cover {@code * numBytes} (in other words, {@link #getActiveWords()} will return a value consistent with * having set {@code numBytes} bytes, even if less than that have been concretely set due to * {@code value} being smaller). * @param bytes the bytes to copy to memory from {@code location}. */ public void setBytes( final UInt256 memOffset, final UInt256 sourceOffset, final UInt256 numBytes, final Bytes bytes) { final int offset = sourceOffset.fitsInt() ? sourceOffset.intValue() : Integer.MAX_VALUE; final int length = numBytes.fitsInt() ? numBytes.intValue() : Integer.MAX_VALUE; if (offset >= bytes.size()) { clearBytes(memOffset, numBytes); return; } final Bytes toCopy = bytes.slice(offset, Math.min(length, bytes.size() - offset)); setBytes(memOffset, numBytes, toCopy); }
Example 18
Source File: SecureScuttlebuttHandshakeServer.java From incubator-tuweni with Apache License 2.0 | 4 votes |
/** * Reads the message containing the identity of the client, verifying it matches our shared secrets. * * @param message the message containing the identity of the client */ public void readIdentityMessage(Bytes message) { Bytes plaintext = SecretBox .decrypt( message, SecretBox.Key .fromHash( SHA256Hash .hash( SHA256Hash.Input .fromPointer( new Concatenate() .add(networkIdentifier) .add(sharedSecret) .add(sharedSecret2) .concatenate()))), SecretBox.Nonce.fromBytes(new byte[24])); if (plaintext == null) { throw new HandshakeException("Could not decrypt the plaintext with our shared secrets"); } if (plaintext.size() != 96) { throw new HandshakeException("Identity message should be 96 bytes long, was " + plaintext.size()); } detachedSignature = Allocated.fromBytes(plaintext.slice(0, 64)); clientLongTermPublicKey = Signature.PublicKey.fromBytes(plaintext.slice(64, 32)); boolean verified = clientLongTermPublicKey .verify( new Concatenate() .add(networkIdentifier) .add(longTermKeyPair.publicKey()) .add(SHA256Hash.hash(SHA256Hash.Input.fromSecret(sharedSecret))) .concatenate(), detachedSignature); if (!verified) { throw new HandshakeException("Identity message signature does not match"); } sharedSecret3 = DiffieHelman.Secret .forKeys( DiffieHelman.SecretKey.forBoxSecretKey(ephemeralKeyPair.secretKey()), DiffieHelman.PublicKey.forSignaturePublicKey(clientLongTermPublicKey)); }
Example 19
Source File: RemoveVisitor.java From besu with Apache License 2.0 | 4 votes |
@Override public Node<V> visit(final LeafNode<V> leafNode, final Bytes path) { final Bytes leafPath = leafNode.getPath(); final int commonPathLength = leafPath.commonPrefixLength(path); return (commonPathLength == leafPath.size()) ? NULL_NODE_RESULT : leafNode; }
Example 20
Source File: Words.java From besu with Apache License 2.0 | 2 votes |
/** * The number of words corresponding to the provided input. * * <p>In other words, this compute {@code input.size() / 32} but rounded up. * * @param input the input to check. * @return the number of (32 bytes) words that {@code input} spans. */ public static int numWords(final Bytes input) { // m/n round up == (m + n - 1)/n: http://www.cs.nott.ac.uk/~psarb2/G51MPC/slides/NumberLogic.pdf return (input.size() + Bytes32.SIZE - 1) / Bytes32.SIZE; }