Search in sources :

Example 1 with RLPException

use of org.hyperledger.besu.ethereum.rlp.RLPException in project besu by hyperledger.

the class DomainObjectDecodeUtils method decodeRawTransaction.

public static Transaction decodeRawTransaction(final String rawTransaction) throws InvalidJsonRpcRequestException {
    try {
        Bytes txnBytes = Bytes.fromHexString(rawTransaction);
        final boolean isGoQuorumCompatibilityMode = GoQuorumOptions.getGoQuorumCompatibilityMode();
        return TransactionDecoder.decodeOpaqueBytes(txnBytes, isGoQuorumCompatibilityMode);
    } catch (final IllegalArgumentException | RLPException e) {
        throw new InvalidJsonRpcRequestException("Invalid raw transaction hex", e);
    }
}
Also used : InvalidJsonRpcRequestException(org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcRequestException) Bytes(org.apache.tuweni.bytes.Bytes) RLPException(org.hyperledger.besu.ethereum.rlp.RLPException)

Example 2 with RLPException

use of org.hyperledger.besu.ethereum.rlp.RLPException in project besu by hyperledger.

the class BlockchainReferenceTestTools method executeTest.

public static void executeTest(final BlockchainReferenceTestCaseSpec spec) {
    final BlockHeader genesisBlockHeader = spec.getGenesisBlockHeader();
    final MutableWorldState worldState = spec.getWorldStateArchive().getMutable(genesisBlockHeader.getStateRoot(), genesisBlockHeader.getHash()).get();
    assertThat(worldState.rootHash()).isEqualTo(genesisBlockHeader.getStateRoot());
    final ProtocolSchedule schedule = REFERENCE_TEST_PROTOCOL_SCHEDULES.getByName(spec.getNetwork());
    final MutableBlockchain blockchain = spec.getBlockchain();
    final ProtocolContext context = spec.getProtocolContext();
    for (final BlockchainReferenceTestCaseSpec.CandidateBlock candidateBlock : spec.getCandidateBlocks()) {
        if (!candidateBlock.isExecutable()) {
            return;
        }
        try {
            final Block block = candidateBlock.getBlock();
            final ProtocolSpec protocolSpec = schedule.getByBlockNumber(block.getHeader().getNumber());
            final BlockImporter blockImporter = protocolSpec.getBlockImporter();
            final HeaderValidationMode validationMode = "NoProof".equalsIgnoreCase(spec.getSealEngine()) ? HeaderValidationMode.LIGHT : HeaderValidationMode.FULL;
            final boolean imported = blockImporter.importBlock(context, block, validationMode, validationMode);
            assertThat(imported).isEqualTo(candidateBlock.isValid());
        } catch (final RLPException e) {
            assertThat(candidateBlock.isValid()).isFalse();
        }
    }
    Assertions.assertThat(blockchain.getChainHeadHash()).isEqualTo(spec.getLastBlockHash());
}
Also used : MutableWorldState(org.hyperledger.besu.ethereum.core.MutableWorldState) ProtocolSchedule(org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule) BlockImporter(org.hyperledger.besu.ethereum.core.BlockImporter) BlockchainReferenceTestCaseSpec(org.hyperledger.besu.ethereum.referencetests.BlockchainReferenceTestCaseSpec) ProtocolSpec(org.hyperledger.besu.ethereum.mainnet.ProtocolSpec) RLPException(org.hyperledger.besu.ethereum.rlp.RLPException) ProtocolContext(org.hyperledger.besu.ethereum.ProtocolContext) Block(org.hyperledger.besu.ethereum.core.Block) MutableBlockchain(org.hyperledger.besu.ethereum.chain.MutableBlockchain) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) HeaderValidationMode(org.hyperledger.besu.ethereum.mainnet.HeaderValidationMode)

Example 3 with RLPException

use of org.hyperledger.besu.ethereum.rlp.RLPException in project besu by hyperledger.

the class LogsWrapper method readFrom.

/**
 * Creates a transaction receipt for the given RLP
 *
 * @param rlpInput the RLP-encoded transaction receipt
 * @param revertReasonAllowed whether the rlp input is allowed to have a revert reason
 * @return the transaction receipt
 */
public static TransactionReceipt readFrom(final RLPInput rlpInput, final boolean revertReasonAllowed) {
    RLPInput input = rlpInput;
    TransactionType transactionType = TransactionType.FRONTIER;
    if (!rlpInput.nextIsList()) {
        final Bytes typedTransactionReceiptBytes = input.readBytes();
        transactionType = TransactionType.of(typedTransactionReceiptBytes.get(0));
        input = new BytesValueRLPInput(typedTransactionReceiptBytes.slice(1), false);
    }
    input.enterList();
    // Get the first element to check later to determine the
    // correct transaction receipt encoding to use.
    final RLPInput firstElement = input.readAsRlp();
    final long cumulativeGas = input.readLongScalar();
    // The logs below will populate the bloom filter upon construction.
    // TODO consider validating that the logs and bloom filter match.
    final LogsBloomFilter bloomFilter = LogsBloomFilter.readFrom(input);
    final List<Log> logs = input.readList(Log::readFrom);
    final Optional<Bytes> revertReason;
    if (input.isEndOfCurrentList()) {
        revertReason = Optional.empty();
    } else {
        if (!revertReasonAllowed) {
            throw new RLPException("Unexpected value at end of TransactionReceipt");
        }
        revertReason = Optional.of(input.readBytes());
    }
    // byte for success (0x01) or failure (0x80).
    if (firstElement.raw().size() == 1) {
        final int status = firstElement.readIntScalar();
        input.leaveList();
        return new TransactionReceipt(transactionType, status, cumulativeGas, logs, bloomFilter, revertReason);
    } else {
        final Hash stateRoot = Hash.wrap(firstElement.readBytes32());
        input.leaveList();
        return new TransactionReceipt(transactionType, stateRoot, cumulativeGas, logs, bloomFilter, revertReason);
    }
}
Also used : BytesValueRLPInput(org.hyperledger.besu.ethereum.rlp.BytesValueRLPInput) RLPInput(org.hyperledger.besu.ethereum.rlp.RLPInput) TransactionType(org.hyperledger.besu.plugin.data.TransactionType) LogsBloomFilter(org.hyperledger.besu.evm.log.LogsBloomFilter) Log(org.hyperledger.besu.evm.log.Log) Hash(org.hyperledger.besu.datatypes.Hash) Bytes(org.apache.tuweni.bytes.Bytes) RLPException(org.hyperledger.besu.ethereum.rlp.RLPException) BytesValueRLPInput(org.hyperledger.besu.ethereum.rlp.BytesValueRLPInput)

Example 4 with RLPException

use of org.hyperledger.besu.ethereum.rlp.RLPException in project besu by hyperledger.

the class EthProtocolManager method processMessage.

@Override
public void processMessage(final Capability cap, final Message message) {
    checkArgument(getSupportedCapabilities().contains(cap), "Unsupported capability passed to processMessage(): " + cap);
    final MessageData messageData = message.getData();
    final int code = messageData.getCode();
    LOG.trace("Process message {}, {}", cap, code);
    final EthPeer ethPeer = ethPeers.peer(message.getConnection());
    if (ethPeer == null) {
        LOG.debug("Ignoring message received from unknown peer connection: {}", message.getConnection());
        return;
    }
    if (messageData.getSize() > 10 * 1_000_000) /*10MB*/
    {
        LOG.debug("Received message over 10MB. Disconnecting from {}", ethPeer);
        ethPeer.disconnect(DisconnectReason.BREACH_OF_PROTOCOL);
        return;
    }
    // Handle STATUS processing
    if (code == EthPV62.STATUS) {
        handleStatusMessage(ethPeer, messageData);
        return;
    } else if (!ethPeer.statusHasBeenReceived()) {
        // Peers are required to send status messages before any other message type
        LOG.debug("{} requires a Status ({}) message to be sent first.  Instead, received message {}.  Disconnecting from {}.", this.getClass().getSimpleName(), EthPV62.STATUS, code, ethPeer);
        ethPeer.disconnect(DisconnectReason.BREACH_OF_PROTOCOL);
        return;
    }
    final EthMessage ethMessage = new EthMessage(ethPeer, messageData);
    if (!ethPeer.validateReceivedMessage(ethMessage, getSupportedProtocol())) {
        LOG.debug("Unsolicited message received from, disconnecting: {}", ethPeer);
        ethPeer.disconnect(DisconnectReason.BREACH_OF_PROTOCOL);
        return;
    }
    if (isFinalized() && (code == EthPV62.NEW_BLOCK || code == EthPV62.NEW_BLOCK_HASHES)) {
        LOG.debug("disconnecting peer for sending new blocks after transition to PoS");
        ethPeer.disconnect(DisconnectReason.SUBPROTOCOL_TRIGGERED);
    }
    // This will handle responses
    ethPeers.dispatchMessage(ethPeer, ethMessage, getSupportedProtocol());
    // This will handle requests
    Optional<MessageData> maybeResponseData = Optional.empty();
    try {
        if (EthProtocol.isEth66Compatible(cap) && EthProtocol.requestIdCompatible(code)) {
            final Map.Entry<BigInteger, MessageData> requestIdAndEthMessage = ethMessage.getData().unwrapMessageData();
            maybeResponseData = ethMessages.dispatch(new EthMessage(ethPeer, requestIdAndEthMessage.getValue())).map(responseData -> responseData.wrapMessageData(requestIdAndEthMessage.getKey()));
        } else {
            maybeResponseData = ethMessages.dispatch(ethMessage);
        }
    } catch (final RLPException e) {
        LOG.debug("Received malformed message {} , disconnecting: {}", messageData.getData(), ethPeer, e);
        ethPeer.disconnect(DisconnectMessage.DisconnectReason.BREACH_OF_PROTOCOL);
    }
    maybeResponseData.ifPresent(responseData -> {
        try {
            ethPeer.send(responseData, getSupportedProtocol());
        } catch (final PeerNotConnected missingPeerException) {
        // Peer disconnected before we could respond - nothing to do
        }
    });
}
Also used : MinedBlockObserver(org.hyperledger.besu.ethereum.chain.MinedBlockObserver) StatusMessage(org.hyperledger.besu.ethereum.eth.messages.StatusMessage) RLPException(org.hyperledger.besu.ethereum.rlp.RLPException) EthPV62(org.hyperledger.besu.ethereum.eth.messages.EthPV62) NewMergeStateCallback(org.hyperledger.besu.consensus.merge.NewMergeStateCallback) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Bytes(org.apache.tuweni.bytes.Bytes) EthProtocol(org.hyperledger.besu.ethereum.eth.EthProtocol) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ImmutableList(com.google.common.collect.ImmutableList) PeerConnection(org.hyperledger.besu.ethereum.p2p.rlpx.connections.PeerConnection) Map(java.util.Map) WorldStateArchive(org.hyperledger.besu.ethereum.worldstate.WorldStateArchive) BigInteger(java.math.BigInteger) Block(org.hyperledger.besu.ethereum.core.Block) NewForkchoiceMessageListener(org.hyperledger.besu.consensus.merge.NewForkchoiceMessageListener) DisconnectReason(org.hyperledger.besu.ethereum.p2p.rlpx.wire.messages.DisconnectMessage.DisconnectReason) ProtocolManager(org.hyperledger.besu.ethereum.p2p.network.ProtocolManager) Difficulty(org.hyperledger.besu.ethereum.core.Difficulty) TransactionPool(org.hyperledger.besu.ethereum.eth.transactions.TransactionPool) Logger(org.slf4j.Logger) PeerValidatorRunner(org.hyperledger.besu.ethereum.eth.peervalidation.PeerValidatorRunner) EthProtocolConfiguration(org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration) Blockchain(org.hyperledger.besu.ethereum.chain.Blockchain) DisconnectMessage(org.hyperledger.besu.ethereum.p2p.rlpx.wire.messages.DisconnectMessage) PeerValidator(org.hyperledger.besu.ethereum.eth.peervalidation.PeerValidator) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) Message(org.hyperledger.besu.ethereum.p2p.rlpx.wire.Message) MessageData(org.hyperledger.besu.ethereum.p2p.rlpx.wire.MessageData) PeerNotConnected(org.hyperledger.besu.ethereum.p2p.rlpx.connections.PeerConnection.PeerNotConnected) Optional(java.util.Optional) Capability(org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability) VisibleForTesting(com.google.common.annotations.VisibleForTesting) BlockBroadcaster(org.hyperledger.besu.ethereum.eth.sync.BlockBroadcaster) Collections(java.util.Collections) StampedLock(java.util.concurrent.locks.StampedLock) Hash(org.hyperledger.besu.datatypes.Hash) PeerNotConnected(org.hyperledger.besu.ethereum.p2p.rlpx.connections.PeerConnection.PeerNotConnected) MessageData(org.hyperledger.besu.ethereum.p2p.rlpx.wire.MessageData) RLPException(org.hyperledger.besu.ethereum.rlp.RLPException) BigInteger(java.math.BigInteger) Map(java.util.Map)

Example 5 with RLPException

use of org.hyperledger.besu.ethereum.rlp.RLPException in project besu by hyperledger.

the class EthProtocolManager method handleStatusMessage.

private void handleStatusMessage(final EthPeer peer, final MessageData data) {
    final StatusMessage status = StatusMessage.readFrom(data);
    try {
        if (!status.networkId().equals(networkId)) {
            LOG.debug("{} has mismatched network id: {}", peer, status.networkId());
            peer.disconnect(DisconnectReason.SUBPROTOCOL_TRIGGERED);
        } else if (!forkIdManager.peerCheck(status.forkId()) && status.protocolVersion() > 63) {
            LOG.debug("{} has matching network id ({}), but non-matching fork id: {}", peer, networkId, status.forkId());
            peer.disconnect(DisconnectReason.SUBPROTOCOL_TRIGGERED);
        } else if (forkIdManager.peerCheck(status.genesisHash())) {
            LOG.debug("{} has matching network id ({}), but non-matching genesis hash: {}", peer, networkId, status.genesisHash());
            peer.disconnect(DisconnectReason.SUBPROTOCOL_TRIGGERED);
        } else if (isFinalized()) {
            long lockStamp = this.powTerminalDifficultyLock.readLock();
            try {
                if (this.powTerminalDifficulty.isPresent() && status.totalDifficulty().greaterThan(this.powTerminalDifficulty.get())) {
                    LOG.debug("Disconnecting peer with difficulty {}, likely still on PoW chain", status.totalDifficulty());
                    peer.disconnect(DisconnectReason.SUBPROTOCOL_TRIGGERED);
                }
            } finally {
                this.powTerminalDifficultyLock.unlockRead(lockStamp);
            }
        } else {
            LOG.debug("Received status message from {}: {}", peer, status);
            peer.registerStatusReceived(status.bestHash(), status.totalDifficulty(), status.protocolVersion());
        }
    } catch (final RLPException e) {
        LOG.debug("Unable to parse status message.", e);
        // Parsing errors can happen when clients broadcast network ids outside the int range,
        // So just disconnect with "subprotocol" error rather than "breach of protocol".
        peer.disconnect(DisconnectReason.SUBPROTOCOL_TRIGGERED);
    }
}
Also used : RLPException(org.hyperledger.besu.ethereum.rlp.RLPException) StatusMessage(org.hyperledger.besu.ethereum.eth.messages.StatusMessage)

Aggregations

RLPException (org.hyperledger.besu.ethereum.rlp.RLPException)30 JsonRpcErrorResponse (org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse)9 JsonRpcSuccessResponse (org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse)8 Block (org.hyperledger.besu.ethereum.core.Block)8 Hash (org.hyperledger.besu.datatypes.Hash)6 Optional (java.util.Optional)5 Bytes (org.apache.tuweni.bytes.Bytes)5 Address (org.hyperledger.besu.datatypes.Address)5 List (java.util.List)4 Transaction (org.hyperledger.besu.ethereum.core.Transaction)4 PeerConnection (org.hyperledger.besu.ethereum.p2p.rlpx.connections.PeerConnection)4 MessageData (org.hyperledger.besu.ethereum.p2p.rlpx.wire.MessageData)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4 BigInteger (java.math.BigInteger)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 ImmutableList (com.google.common.collect.ImmutableList)2 Lists (com.google.common.collect.Lists)2 Collections (java.util.Collections)2