Java Code Examples for org.apache.tuweni.bytes.Bytes#EMPTY

The following examples show how to use org.apache.tuweni.bytes.Bytes#EMPTY . 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: Memory.java    From besu with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a copy of bytes from memory.
 *
 * @param location The location in memory to start with.
 * @param numBytes The number of bytes to get.
 * @return A fresh copy of the bytes from memory starting at {@code location} and extending {@code
 *     numBytes}.
 */
public Bytes getBytes(final UInt256 location, final UInt256 numBytes) {
  // Note: if length == 0, we don't require any memory expansion, whatever location is. So
  // we we must call asByteIndex(location) after this check so as it doesn't throw if the location
  // is too big but the length is 0 (which is somewhat nonsensical, but is exercise by some
  // tests).
  final int length = asByteLength(numBytes);
  if (length == 0) {
    return Bytes.EMPTY;
  }

  final int start = asByteIndex(location);

  ensureCapacityForBytes(start, length);
  return Bytes.of(Arrays.copyOfRange(data, start, start + numBytes.intValue()));
}
 
Example 2
Source File: ValidatorPeersTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void onlyValidatorsAreSentAMessage() throws PeerNotConnected {
  // Only add the first Peer's address to the validators.
  validators.add(Util.publicKeyToAddress(publicKeys.get(0)));

  final ValidatorPeers peers = new ValidatorPeers(voteTallyCache);
  for (final PeerConnection peer : peerConnections) {
    peers.add(peer);
  }

  final MessageData messageToSend = new RawMessage(1, Bytes.EMPTY);
  peers.send(messageToSend);

  verify(peerConnections.get(0), times(1)).sendForProtocol("IBF", messageToSend);
  verify(peerConnections.get(1), never()).sendForProtocol(any(), any());
  verify(peerConnections.get(2), never()).sendForProtocol(any(), any());
  verify(peerConnections.get(3), never()).sendForProtocol(any(), any());
}
 
Example 3
Source File: PrivGetLogsTest.java    From besu with Apache License 2.0 5 votes vote down vote up
private LogWithMetadata logWithMetadata(final int logIndex) {
  return new LogWithMetadata(
      logIndex,
      100L,
      Hash.ZERO,
      Hash.ZERO,
      0,
      Address.fromHexString("0x0"),
      Bytes.EMPTY,
      Lists.newArrayList(),
      false);
}
 
Example 4
Source File: UInt384.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Override
public Bytes toMinimalBytes() {
  int i = 0;
  while (i < INTS_SIZE && this.ints[i] == 0) {
    ++i;
  }
  if (i == INTS_SIZE) {
    return Bytes.EMPTY;
  }
  int firstIntBytes = 4 - (Integer.numberOfLeadingZeros(this.ints[i]) / 8);
  int totalBytes = firstIntBytes + ((INTS_SIZE - (i + 1)) * 4);
  MutableBytes bytes = MutableBytes.create(totalBytes);
  int j = 0;
  switch (firstIntBytes) {
    case 4:
      bytes.set(j++, (byte) (this.ints[i] >>> 24));
      // fall through
    case 3:
      bytes.set(j++, (byte) ((this.ints[i] >>> 16) & 0xFF));
      // fall through
    case 2:
      bytes.set(j++, (byte) ((this.ints[i] >>> 8) & 0xFF));
      // fall through
    case 1:
      bytes.set(j++, (byte) (this.ints[i] & 0xFF));
  }
  ++i;
  for (; i < INTS_SIZE; ++i, j += 4) {
    bytes.setInt(j, this.ints[i]);
  }
  return bytes;
}
 
Example 5
Source File: IbftExtraDataTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyExtraDataThrowsException() {
  final Bytes bufferToInject = Bytes.EMPTY;

  assertThatThrownBy(() -> IbftExtraData.decodeRaw(bufferToInject))
      .isInstanceOf(IllegalArgumentException.class)
      .hasMessage("Invalid Bytes supplied - Ibft Extra Data required.");
}
 
Example 6
Source File: PrivGetTransactionReceiptTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void transactionReceiptContainsRevertReasonWhenInvalidTransactionOccurs() {
  final Transaction pmt = privacyMarkerTransaction();
  final PrivateTransaction privateTransaction = privateTransactionBesu();
  final ExecutedPrivateTransaction executedPrivateTransaction =
      createExecutedPrivateTransaction(pmt, privateTransaction);
  when(privacyController.findPrivateTransactionByPmtHash(eq(pmt.getHash()), any()))
      .thenReturn(Optional.of(executedPrivateTransaction));

  final PrivateTransactionReceipt privateTransactionReceiptWithRevertReason =
      new PrivateTransactionReceipt(
          1,
          Collections.emptyList(),
          Bytes.EMPTY,
          Optional.of(Bytes.wrap(new byte[] {(byte) 0x01})));
  when(privateStateStorage.getTransactionReceipt(any(Bytes32.class), any(Bytes32.class)))
      .thenReturn(Optional.of(privateTransactionReceiptWithRevertReason));

  final JsonRpcRequestContext request = requestContext(pmt.getHash());

  final JsonRpcSuccessResponse response =
      (JsonRpcSuccessResponse) privGetTransactionReceipt.response(request);
  final PrivateTransactionReceiptResult result =
      (PrivateTransactionReceiptResult) response.getResult();

  assertThat(result.getRevertReason()).isEqualTo("0x01");
}
 
Example 7
Source File: SpuriousBehaviourTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void badlyFormedRlpDoesNotPreventOngoingIbftOperation() {
  final MessageData illegalCommitMsg = new RawMessage(IbftV2.PREPARE, Bytes.EMPTY);
  peers.getNonProposing(0).injectMessage(illegalCommitMsg);

  peers.getProposer().injectProposal(roundId, proposedBlock);
  peers.verifyMessagesReceived(expectedPrepare);
}
 
Example 8
Source File: BlockHeaderMock.java    From besu with Apache License 2.0 5 votes vote down vote up
/**
 * Public constructor.
 *
 * @param coinbase The beneficiary address.
 * @param gasLimit The gas limit of the current block.
 * @param number The number to execute.
 */
@JsonCreator
public BlockHeaderMock(
    @JsonProperty("currentCoinbase") final String coinbase,
    @JsonProperty("currentDifficulty") final String difficulty,
    @JsonProperty("currentGasLimit") final String gasLimit,
    @JsonProperty("currentNumber") final String number,
    @JsonProperty("currentTimestamp") final String timestamp) {
  super(
      TestBlockchain.generateTestBlockHash(Long.decode(number) - 1),
      Hash.EMPTY, // ommersHash
      Address.fromHexString(coinbase),
      Hash.EMPTY, // stateRoot
      Hash.EMPTY, // transactionsRoot
      Hash.EMPTY, // receiptsRoot
      new LogsBloomFilter(),
      Difficulty.fromHexString(difficulty),
      Long.decode(number),
      Long.decode(gasLimit),
      0L,
      Long.decode(timestamp),
      Bytes.EMPTY,
      0L,
      Hash.ZERO,
      0L,
      new MainnetBlockHeaderFunctions());
}
 
Example 9
Source File: SpuriousBehaviourTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void messageWithIllegalMessageCodeAreDiscardedAndDoNotPreventOngoingIbftOperation() {
  final MessageData illegalCommitMsg = new RawMessage(IbftV2.MESSAGE_SPACE, Bytes.EMPTY);
  peers.getNonProposing(0).injectMessage(illegalCommitMsg);

  peers.getProposer().injectProposal(roundId, proposedBlock);
  peers.verifyMessagesReceived(expectedPrepare);
}
 
Example 10
Source File: PrivGetTransactionReceiptTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  final PrivateTransactionReceipt receipt =
      new PrivateTransactionReceipt(1, Collections.emptyList(), Bytes.EMPTY, Optional.empty());
  when(privateStateStorage.getTransactionReceipt(any(Bytes32.class), any(Bytes32.class)))
      .thenReturn(Optional.of(receipt));

  privGetTransactionReceipt =
      new PrivGetTransactionReceipt(
          privateStateStorage, privacyController, enclavePublicKeyProvider);
}
 
Example 11
Source File: PrivateTransactionProcessor.java    From besu with Apache License 2.0 5 votes vote down vote up
public static Result invalid(
    final ValidationResult<TransactionValidator.TransactionInvalidReason> validationResult) {
  return new Result(
      Status.INVALID,
      new ArrayList<>(),
      -1,
      -1,
      Bytes.EMPTY,
      validationResult,
      Optional.empty());
}
 
Example 12
Source File: ExtCodeCopyOperation.java    From besu with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(final MessageFrame frame) {
  final Address address = Words.toAddress(frame.popStackItem());
  final Account account = frame.getWorldState().get(address);
  final Bytes code = account != null ? account.getCode() : Bytes.EMPTY;

  final UInt256 memOffset = UInt256.fromBytes(frame.popStackItem());
  final UInt256 sourceOffset = UInt256.fromBytes(frame.popStackItem());
  final UInt256 numBytes = UInt256.fromBytes(frame.popStackItem());

  frame.writeMemory(memOffset, sourceOffset, numBytes, code);
}
 
Example 13
Source File: PrivGetFilterLogsTest.java    From besu with Apache License 2.0 5 votes vote down vote up
private LogWithMetadata logWithMetadata() {
  return new LogWithMetadata(
      0,
      100L,
      Hash.ZERO,
      Hash.ZERO,
      0,
      Address.fromHexString("0x0"),
      Bytes.EMPTY,
      Lists.newArrayList(),
      false);
}
 
Example 14
Source File: DebugTraceTransactionTest.java    From besu with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldTraceTheTransactionUsingTheTransactionTracer() {
  final TransactionWithMetadata transactionWithMetadata =
      new TransactionWithMetadata(transaction, 12L, blockHash, 2);
  final Map<String, Boolean> map = new HashMap<>();
  map.put("disableStorage", true);
  final Object[] params = new Object[] {transactionHash, map};
  final JsonRpcRequestContext request =
      new JsonRpcRequestContext(new JsonRpcRequest("2.0", "debug_traceTransaction", params));
  final Result result = mock(Result.class);

  final Bytes32[] stackBytes =
      new Bytes32[] {
        Bytes32.fromHexString(
            "0x0000000000000000000000000000000000000000000000000000000000000001")
      };
  final Bytes[] memoryBytes =
      new Bytes[] {
        Bytes.fromHexString("0x0000000000000000000000000000000000000000000000000000000000000002")
      };
  final TraceFrame traceFrame =
      new TraceFrame(
          12,
          "NONE",
          Gas.of(45),
          Optional.of(Gas.of(56)),
          Gas.ZERO,
          2,
          Optional.empty(),
          null,
          Wei.ZERO,
          Bytes.EMPTY,
          Bytes.EMPTY,
          Optional.of(stackBytes),
          Optional.of(memoryBytes),
          Optional.empty(),
          null,
          Optional.of(Bytes.fromHexString("0x1122334455667788")),
          Optional.empty(),
          Optional.empty(),
          0,
          Optional.empty(),
          false,
          Optional.empty(),
          Optional.empty());
  final List<TraceFrame> traceFrames = Collections.singletonList(traceFrame);
  final TransactionTrace transactionTrace =
      new TransactionTrace(transaction, result, traceFrames);
  when(transaction.getGasLimit()).thenReturn(100L);
  when(result.getGasRemaining()).thenReturn(27L);
  when(result.getOutput()).thenReturn(Bytes.fromHexString("1234"));
  when(blockHeader.getNumber()).thenReturn(12L);
  when(blockchain.headBlockNumber()).thenReturn(12L);
  when(blockchain.transactionByHash(transactionHash))
      .thenReturn(Optional.of(transactionWithMetadata));
  when(transactionTracer.traceTransaction(eq(blockHash), eq(transactionHash), any()))
      .thenReturn(Optional.of(transactionTrace));
  final JsonRpcSuccessResponse response =
      (JsonRpcSuccessResponse) debugTraceTransaction.response(request);
  final DebugTraceTransactionResult transactionResult =
      (DebugTraceTransactionResult) response.getResult();

  assertThat(transactionResult.getGas()).isEqualTo(73);
  assertThat(transactionResult.getReturnValue()).isEqualTo("1234");
  final List<StructLog> expectedStructLogs = Collections.singletonList(new StructLog(traceFrame));
  assertThat(transactionResult.getStructLogs()).isEqualTo(expectedStructLogs);
  assertThat(transactionResult.getStructLogs().size()).isEqualTo(1);
  assertThat(transactionResult.getStructLogs().get(0).stack().length).isEqualTo(1);
  assertThat(transactionResult.getStructLogs().get(0).stack()[0])
      .isEqualTo(stackBytes[0].toUnprefixedHexString());
  assertThat(transactionResult.getStructLogs().get(0).memory().length).isEqualTo(1);
  assertThat(transactionResult.getStructLogs().get(0).memory()[0])
      .isEqualTo(memoryBytes[0].toUnprefixedHexString());
}
 
Example 15
Source File: EmptyMessage.java    From besu with Apache License 2.0 4 votes vote down vote up
@Override
public Bytes getData() {
  return Bytes.EMPTY;
}
 
Example 16
Source File: DebugTraceBlockByNumberTest.java    From besu with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldReturnCorrectResponse() {
  final long blockNumber = 1L;
  final Object[] params = new Object[] {Long.toHexString(blockNumber)};
  final JsonRpcRequestContext request =
      new JsonRpcRequestContext(new JsonRpcRequest("2.0", "debug_traceBlockByNumber", params));

  final TraceFrame traceFrame =
      new TraceFrame(
          12,
          "NONE",
          Gas.of(45),
          Optional.of(Gas.of(56)),
          Gas.ZERO,
          2,
          Optional.empty(),
          null,
          Wei.ZERO,
          Bytes.EMPTY,
          Bytes.EMPTY,
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          null,
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          0,
          Optional.empty(),
          false,
          Optional.empty(),
          Optional.empty());

  final TransactionProcessor.Result transaction1Result = mock(TransactionProcessor.Result.class);
  final TransactionProcessor.Result transaction2Result = mock(TransactionProcessor.Result.class);

  final TransactionTrace transaction1Trace = mock(TransactionTrace.class);
  final TransactionTrace transaction2Trace = mock(TransactionTrace.class);

  final BlockTrace blockTrace = new BlockTrace(asList(transaction1Trace, transaction2Trace));

  when(transaction1Trace.getTraceFrames()).thenReturn(singletonList(traceFrame));
  when(transaction2Trace.getTraceFrames()).thenReturn(singletonList(traceFrame));
  when(transaction1Trace.getResult()).thenReturn(transaction1Result);
  when(transaction2Trace.getResult()).thenReturn(transaction2Result);
  when(transaction1Result.getOutput()).thenReturn(Bytes.fromHexString("1234"));
  when(transaction2Result.getOutput()).thenReturn(Bytes.fromHexString("1234"));
  when(blockchain.getBlockHashByNumber(blockNumber)).thenReturn(Optional.of(blockHash));
  when(blockTracer.trace(eq(blockHash), any())).thenReturn(Optional.of(blockTrace));

  final JsonRpcSuccessResponse response =
      (JsonRpcSuccessResponse) debugTraceBlockByNumber.response(request);
  final Collection<DebugTraceTransactionResult> result = getResult(response);
  assertThat(result)
      .usingFieldByFieldElementComparator()
      .isEqualTo(DebugTraceTransactionResult.of(blockTrace.getTransactionTraces()));
}
 
Example 17
Source File: DebugTraceTransactionTest.java    From besu with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldNotTraceTheTransactionIfNotFound() {
  final Map<String, Boolean> map = new HashMap<>();
  map.put("disableStorage", true);
  final Object[] params = new Object[] {transactionHash, map};
  final JsonRpcRequestContext request =
      new JsonRpcRequestContext(new JsonRpcRequest("2.0", "debug_traceTransaction", params));
  final Result result = mock(Result.class);

  final TraceFrame traceFrame =
      new TraceFrame(
          12,
          "NONE",
          Gas.of(45),
          Optional.of(Gas.of(56)),
          Gas.ZERO,
          2,
          Optional.empty(),
          null,
          Wei.ZERO,
          Bytes.EMPTY,
          Bytes.EMPTY,
          Optional.empty(),
          Optional.empty(),
          Optional.empty(),
          null,
          Optional.of(Bytes.fromHexString("0x1122334455667788")),
          Optional.empty(),
          Optional.empty(),
          0,
          Optional.empty(),
          false,
          Optional.empty(),
          Optional.empty());
  final List<TraceFrame> traceFrames = Collections.singletonList(traceFrame);
  final TransactionTrace transactionTrace =
      new TransactionTrace(transaction, result, traceFrames);
  when(transaction.getGasLimit()).thenReturn(100L);
  when(result.getGasRemaining()).thenReturn(27L);
  when(result.getOutput()).thenReturn(Bytes.fromHexString("1234"));
  when(blockHeader.getNumber()).thenReturn(12L);
  when(blockchain.headBlockNumber()).thenReturn(12L);
  when(blockchain.transactionByHash(transactionHash)).thenReturn(Optional.empty());
  when(transactionTracer.traceTransaction(eq(blockHash), eq(transactionHash), any()))
      .thenReturn(Optional.of(transactionTrace));
  final JsonRpcSuccessResponse response =
      (JsonRpcSuccessResponse) debugTraceTransaction.response(request);

  assertThat(response.getResult()).isNull();
}
 
Example 18
Source File: RequestManagerTest.java    From besu with Apache License 2.0 4 votes vote down vote up
private EthMessage mockMessage(final EthPeer peer) {
  return new EthMessage(peer, new RawMessage(1, Bytes.EMPTY));
}
 
Example 19
Source File: OnChainPrivacyPrecompiledContract.java    From besu with Apache License 2.0 4 votes vote down vote up
@Override
public Bytes compute(final Bytes input, final MessageFrame messageFrame) {

  if (isMining(messageFrame)) {
    return Bytes.EMPTY;
  }

  final Hash pmtHash = messageFrame.getTransactionHash();

  final String key = input.slice(0, 32).toBase64String();

  final ReceiveResponse receiveResponse;
  try {
    receiveResponse = getReceiveResponse(key);
  } catch (final EnclaveClientException e) {
    LOG.debug("Can not fetch private transaction payload with key {}", key, e);
    return Bytes.EMPTY;
  }

  final BytesValueRLPInput bytesValueRLPInput =
      new BytesValueRLPInput(
          Bytes.wrap(Base64.getDecoder().decode(receiveResponse.getPayload())), false);
  final VersionedPrivateTransaction versionedPrivateTransaction =
      VersionedPrivateTransaction.readFrom(bytesValueRLPInput);
  final PrivateTransaction privateTransaction =
      versionedPrivateTransaction.getPrivateTransaction();
  final Bytes32 version = versionedPrivateTransaction.getVersion();

  final Optional<Bytes> maybeGroupId = privateTransaction.getPrivacyGroupId();
  if (maybeGroupId.isEmpty()) {
    return Bytes.EMPTY;
  }

  final Bytes32 privacyGroupId = Bytes32.wrap(maybeGroupId.get());

  LOG.debug("Processing private transaction {} in privacy group {}", pmtHash, privacyGroupId);

  final ProcessableBlockHeader currentBlockHeader = messageFrame.getBlockHeader();
  final Hash currentBlockHash = ((BlockHeader) currentBlockHeader).getHash();

  final Hash lastRootHash =
      privateStateRootResolver.resolveLastStateRoot(privacyGroupId, currentBlockHash);

  final MutableWorldState disposablePrivateState =
      privateWorldStateArchive.getMutable(lastRootHash).get();

  final WorldUpdater privateWorldStateUpdater = disposablePrivateState.updater();

  maybeInjectDefaultManagementAndProxy(
      lastRootHash, disposablePrivateState, privateWorldStateUpdater);

  final Blockchain blockchain = messageFrame.getBlockchain();
  final WorldUpdater publicWorldState = messageFrame.getWorldState();

  if (!canExecute(
      messageFrame,
      currentBlockHeader,
      privateTransaction,
      version,
      publicWorldState,
      privacyGroupId,
      blockchain,
      disposablePrivateState,
      privateWorldStateUpdater)) {
    return Bytes.EMPTY;
  }

  final PrivateTransactionProcessor.Result result =
      processPrivateTransaction(
          messageFrame, privateTransaction, privacyGroupId, privateWorldStateUpdater);

  if (result.isInvalid() || !result.isSuccessful()) {
    LOG.error(
        "Failed to process private transaction {}: {}",
        pmtHash,
        result.getValidationResult().getErrorMessage());
    return Bytes.EMPTY;
  }

  if (messageFrame.isPersistingPrivateState()) {
    persistPrivateState(
        pmtHash,
        currentBlockHash,
        privateTransaction,
        privacyGroupId,
        disposablePrivateState,
        privateWorldStateUpdater,
        result);
  }

  return result.getOutput();
}
 
Example 20
Source File: MessageFrame.java    From besu with Apache License 2.0 4 votes vote down vote up
private MessageFrame(
    final Type type,
    final Blockchain blockchain,
    final Deque<MessageFrame> messageFrameStack,
    final ReturnStack returnStack,
    final WorldUpdater worldState,
    final Gas initialGas,
    final Address recipient,
    final Address originator,
    final Address contract,
    final int contractAccountVersion,
    final Wei gasPrice,
    final Bytes inputData,
    final Address sender,
    final Wei value,
    final Wei apparentValue,
    final Code code,
    final ProcessableBlockHeader blockHeader,
    final int depth,
    final boolean isStatic,
    final Consumer<MessageFrame> completer,
    final Address miningBeneficiary,
    final BlockHashLookup blockHashLookup,
    final Boolean isPersistingPrivateState,
    final Hash transactionHash,
    final Optional<Bytes> revertReason,
    final int maxStackSize) {
  this.type = type;
  this.blockchain = blockchain;
  this.messageFrameStack = messageFrameStack;
  this.returnStack = returnStack;
  this.worldState = worldState;
  this.gasRemaining = initialGas;
  this.blockHashLookup = blockHashLookup;
  this.maxStackSize = maxStackSize;
  this.pc = 0;
  this.memory = new Memory();
  this.stack = new PreAllocatedOperandStack(maxStackSize);
  this.output = Bytes.EMPTY;
  this.returnData = Bytes.EMPTY;
  this.logs = new ArrayList<>();
  this.gasRefund = Gas.ZERO;
  this.selfDestructs = new HashSet<>();
  this.refunds = new HashMap<>();
  this.recipient = recipient;
  this.originator = originator;
  this.contract = contract;
  this.contractAccountVersion = contractAccountVersion;
  this.gasPrice = gasPrice;
  this.inputData = inputData;
  this.sender = sender;
  this.value = value;
  this.apparentValue = apparentValue;
  this.code = code;
  this.blockHeader = blockHeader;
  this.depth = depth;
  this.state = State.NOT_STARTED;
  this.isStatic = isStatic;
  this.completer = completer;
  this.miningBeneficiary = miningBeneficiary;
  this.isPersistingPrivateState = isPersistingPrivateState;
  this.transactionHash = transactionHash;
  this.revertReason = revertReason;
}