Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
try {
String input = request.getReader().lines()
.collect(Collectors.joining(System.lineSeparator()));
String trx = JSONObject.parseObject(input).getString("transaction");
String trx = Util.parseJsonBody(input).getString("transaction");
byte[] raw = ByteArray.fromHexString(trx);
try {
ProtobufAdmissionGuard.checkTransaction(raw,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.tron.core.Wallet;
import org.tron.core.actuator.TransactionFactory;
import org.tron.core.exception.ContractValidateException;
import org.tron.core.exception.InvalidHttpParameterException;
import org.tron.core.services.http.HttpApi;
import org.tron.core.services.http.HttpApi.Access;
import org.tron.core.services.http.HttpApi.Surface;
Expand All @@ -25,6 +26,10 @@
surfaces = {Surface.FULL})
public class CreateCommonTransactionServlet extends RateLimiterServlet {

static final String MISSING_CONTRACT_TYPE = "Field 'contractType' is missing";
static final String INVALID_CONTRACT_TYPE =
"invalid contractType: expect a ContractType name";

@Autowired
private Wallet wallet;

Expand All @@ -33,7 +38,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
PostParams params = PostParams.getPostParams(request);
String contract = params.getParams();
boolean visible = params.isVisible();
ContractType type = ContractType.valueOf(Util.getContractType(contract));
ContractType type = parseContractType(Util.getContractType(contract));
Message.Builder build = getBuilder(type);
JsonFormat.merge(contract, build, visible);
Transaction tx = wallet.createTransactionCapsule(build.build(), type).getInstance();
Expand All @@ -45,6 +50,17 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
}
}

private static ContractType parseContractType(String name) {
if (name == null) {
throw new InvalidHttpParameterException(MISSING_CONTRACT_TYPE);
}
try {
return ContractType.valueOf(name);
} catch (IllegalArgumentException e) {
throw new InvalidHttpParameterException(INVALID_CONTRACT_TYPE, e);
}
}

private Message.Builder getBuilder(ContractType type) throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException, InstantiationException,
ContractValidateException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
String input = request.getReader().lines()
.collect(Collectors.joining(System.lineSeparator()));
Util.checkBodySize(input);
JSONObject jsonObject = JSONObject.parseObject(input);
JSONObject jsonObject = Util.parseJsonBody(input);
boolean visible = Util.getVisiblePost(input);

String ivk = jsonObject.getString("ivk");
Expand Down
104 changes: 83 additions & 21 deletions framework/src/main/java/org/tron/core/services/http/servlets/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.tron.common.utils.Commons.decodeFromBase58Check;

import com.google.common.collect.ImmutableSet;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import com.google.protobuf.GeneratedMessageV3;
Expand All @@ -12,6 +13,7 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.math.BigDecimal;
import java.nio.charset.Charset;
Expand All @@ -21,14 +23,17 @@
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.util.encoders.DecoderException;
import org.bouncycastle.util.encoders.Hex;
import org.eclipse.jetty.http.BadMessageException;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.util.MultiMap;
Expand All @@ -52,10 +57,15 @@
import org.tron.core.capsule.TransactionCapsule;
import org.tron.core.config.args.Args;
import org.tron.core.db.TransactionTrace;
import org.tron.core.exception.BadItemException;
import org.tron.core.exception.ContractExeException;
import org.tron.core.exception.ContractSizeNotEqualToOneException;
import org.tron.core.exception.ContractValidateException;
import org.tron.core.exception.InvalidHttpParameterException;
import org.tron.core.exception.ItemNotFoundException;
import org.tron.core.exception.MaintenanceUnavailableException;
import org.tron.core.exception.NonUniqueObjectException;
import org.tron.core.exception.ZksnarkException;
import org.tron.core.services.http.servlets.JsonFormat.ParseException;
import org.tron.json.JSON;
import org.tron.json.JSONArray;
Expand All @@ -76,15 +86,31 @@ public class Util {
private static final String INTERNAL_SERVER_ERROR = "internal server error";
public static final String RATE_LIMITER_ERROR_MSG = "lack of computing resources";
static final String INVALID_ADDRESS_MSG = "INVALID address";

@317787106 317787106 Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SHOULD]: clarify that this message also covers empty addresses.

Util.getAddress() uses INVALID_ADDRESS_MSG both when the address is missing or blank (StringUtils.isBlank(addressStr)) and when decoding or validation fails. Could we change the text to "Invalid or empty address" so callers can more easily recognize an omitted or empty address parameter as a possible cause?

Please also update the affected error-message assertions, including AddressQueryServletTestBase.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd keep INVALID address in this PR. Util.getAddress() already uses this one text for both a missing and an invalid address, and this PR reuses it in Util.getHexAddress() when the Base58 decoder throws. The wording also has precedent: in 4.8.2.4, getreward and getbrokerage returned errors starting with INVALID address, . If we want a separate message for a missing address, I'd rather change it in its own PR so the new text is announced on its own.

static final String UNSUPPORTED_CHARSET_MSG = "unsupported charset in Content-Type";

public static final String EVENTS_DEPRECATED_MSG =
"'events' field is deprecated and no longer supported";

private static final Set<Class<?>> BUSINESS_ERROR_TYPES = ImmutableSet.of(
ParseException.class,
ContractValidateException.class,
ContractSizeNotEqualToOneException.class,
MaintenanceUnavailableException.class,
InvalidHttpParameterException.class,
NonUniqueObjectException.class,
ItemNotFoundException.class,
BadItemException.class,
ZksnarkException.class,
ContractExeException.class,
IllegalArgumentException.class,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[DISCUSS] Exact-class IAE/ISE pass-through re-exposes server-internal messages

Allowlisting every non-blank IllegalArgumentException / IllegalStateException message re-opens part of the surface that #6954 closed, because these JDK-wide types are also thrown by internal code on HTTP-reachable paths with messages not written for callers. One concrete reachable example: CreateCommonTransactionServlet.java:36 calls ContractType.valueOf(Util.getContractType(contract)), so an unknown contract type now returns No enum constant org.tron.protos.Protocol.Transaction.Contract.ContractType.X verbatim, leaking the internal proto class name. The test changes in this PR acknowledge the wider surface: BroadcastServletTest and GetTransactionListFromPendingServletTest had to switch their mocks from IllegalStateException to RuntimeException because wallet/manager ISE messages would now pass through, and the No enum constant internal.Type.VALUE fail-closed case was removed from UtilProcessErrorTest.

This is still stricter than 4.8.2.4 (no class X : prefix, subclasses and blank messages fail closed), so the direction is fine — but the PR description does not record an audit of which internal IAE/ISE messages become visible again.

Evidence clarity: Confirmed

Suggestion: Confirm the reachable IAE/ISE throw sites were audited and note the conclusion in the PR description; for known internal-detail leaks such as the ContractType.valueOf call in CreateCommonTransactionServlet, catch the IAE at the servlet and rethrow an InvalidHttpParameterException with a fixed caller-facing text.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on the ContractType case, changed in 708f7da. The shared handler still allows non-blank messages from these exact types, but createCommonTransaction now checks contractType before calling Wallet and replaces the JDK text with fixed messages: Field 'contractType' is missing for a missing or null value, and invalid contractType: expect a ContractType name for a value that isn't a ContractType name.

IllegalStateException.class);

public static final String PERMISSION_ID = "Permission_id";
private static final String INVALID_PERMISSION_ID =
"invalid " + PERMISSION_ID + ": expect a 32-bit integer";
private static final int MAX_JSON_INTEGER_VALUE_LENGTH = 64;
private static final String INVALID_JSON_BODY = "INVALID JSON body";
private static final String INVALID_FORM_BODY = "INVALID form body";
public static final String VISIBLE = "visible";
public static final String INT64_AS_STRING_PARAM = "int64_as_string";
public static final String TRANSACTION = "transaction";
Expand Down Expand Up @@ -140,21 +166,19 @@ private static String clientMessage(Exception e) {
if (e == null) {
return INTERNAL_SERVER_ERROR;
}

Class<?> type = e.getClass();
if (type == IllegalArgumentException.class) {
return EVENTS_DEPRECATED_MSG.equals(e.getMessage())
? EVENTS_DEPRECATED_MSG : INTERNAL_SERVER_ERROR;
if (type == BadMessageException.class
&& ((BadMessageException) e).getCode() == HttpStatus.PAYLOAD_TOO_LARGE_413) {
return bodySizeTooBigMessage();
}
if (type == ParseException.class
|| type == ContractValidateException.class
|| type == ContractSizeNotEqualToOneException.class
|| type == MaintenanceUnavailableException.class
|| type == InvalidHttpParameterException.class) {
String message = e.getMessage();
return StringUtils.isBlank(message) ? INTERNAL_SERVER_ERROR : message;
if (type == UnsupportedEncodingException.class) {
return UNSUPPORTED_CHARSET_MSG;
}
String message = e.getMessage();
if (StringUtils.isBlank(message)) {
return INTERNAL_SERVER_ERROR;
}
return INTERNAL_SERVER_ERROR;
return BUSINESS_ERROR_TYPES.contains(type) ? message : INTERNAL_SERVER_ERROR;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remaining request-side errors still fall back to internal server error

The restored messages are useful, but several client-correctable parsing and validation failures still reach Util.processError() without being translated into a client-facing error.

The shared writer matches the exact runtime class, so adding IllegalArgumentException does not cover subclasses such as NumberFormatException or Jetty's Utf8Appendable.NotUtf8Exception.

Missing handling Example request/input Exception and current behavior Suggested handling
Invalid integer query parameters GET /wallet/getblockbynum?num=abc; similar cases exist for offset, limit, and other numeric parameters Long.parseLong() / Integer.parseInt() throws NumberFormatException, which is not an exact allowlisted type, so the response is {"Error":"internal server error"}. See GetBlockByNumServlet. Catch the parsing failure at the parameter boundary and return a fixed, field-specific message, such as invalid parameter [num]: expect a 64-bit integer.
Invalid hexadecimal field values POST /wallet/getaccountresource with {"address":"zz"}, or POST /wallet/broadcasthex with {"transaction":"zz"} Direct calls to ByteArray.fromHexString() can throw Bouncy Castle's DecoderException. These failures still become internal server error, including on POST paths. See BroadcastHexServlet. Translate the decoding failure into a fixed message appropriate to the field, such as Invalid or empty address or Invalid transaction encoding.
Missing/null transaction structure POST /wallet/broadcasttransaction with an empty body, {}, {"raw_data":null}, {"raw_data":{}}, or {"raw_data":{"contract":null}} packTransaction() dereferences a null jsonTransaction, rawData, or rawContractArray. The new catch (JSONException) does not catch these NullPointerException paths, so they still return internal server error. See Util.packTransaction. Check the required structure before dereferencing it and return fixed errors for an empty body, missing raw_data, or missing raw_data.contract.
Missing/null contractType POST /wallet/createCommonTransaction with {} or {"contractType":null} Util.getContractType() returns null, and ContractType.valueOf(null) throws NullPointerException. This still becomes internal server error. See CreateCommonTransactionServlet. Validate contractType before calling valueOf() and return a fixed message such as Missing contractType. Unknown enum values should also receive a fixed validation message rather than the JDK's internal enum-class detail.
Invalid form-body encoding POST /wallet/getblockbynum with Content-Type: application/x-www-form-urlencoded and body num=%FF or num=% UrlEncoded.decodeUtf8To() throws Utf8Appendable.NotUtf8Exception for invalid UTF-8 or incomplete percent encoding. Although it extends IllegalArgumentException, the exact-class allowlist excludes it, resulting in internal server error. See Util.getJsonString. Translate the form-decoding failure into a fixed message such as INVALID form body.
Invalid protobuf string encoding after admission checking POST /wallet/broadcasthex with {"transaction":"0a075a0512030a01ff"} This is valid hex containing a protobuf Any.type_url with invalid UTF-8. The admission guard scans the wire structure without validating that string's UTF-8, so Transaction.parseFrom(raw) can subsequently throw InvalidProtocolBufferException. That exception reaches the generic writer and becomes internal server error. See BroadcastHexServlet. Catch InvalidProtocolBufferException specifically around request transaction parsing and return a fixed message such as Invalid transaction encoding.

The PR description already lists numeric GET parameters and malformed hex values as follow-ups. These are existing coverage gaps rather than regressions introduced by this PR; the remaining cases should also be handled or explicitly documented as deferred.

For the implementation, please translate these failures locally into InvalidHttpParameterException with fixed client-facing messages. Broadening the shared allowlist to expose all NullPointerException, DecoderException, or InvalidProtocolBufferException messages would also expose unrelated internal failures.

Please cover the corresponding malformed, missing, and null inputs in regression tests, verifying that they receive the intended validation message before wallet processing.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the detailed list. Handled in this PR:

  • packTransaction: an empty body and a missing or null raw_data / contract now return fixed messages (016dad9).
  • createCommonTransaction: a missing or unknown contractType now returns a fixed message instead of the JDK enum text (708f7da).
  • Form bodies: form decoding failures now return INVALID form body when Jetty rejects a percent escape or an invalid UTF-8 sequence (8576605).

}

public static String printBlockList(BlockList list, boolean selfType) {
Expand Down Expand Up @@ -333,10 +357,23 @@ public static JSONObject printTransactionToJSON(Transaction transaction, boolean
*/
public static Transaction packTransaction(String strTransaction, boolean selfType)
throws ContractSizeNotEqualToOneException, ParseException {
JSONObject jsonTransaction = JSON.parseObject(strTransaction);
JSONObject rawData = jsonTransaction.getJSONObject("raw_data");
JSONObject jsonTransaction = parseJsonBody(strTransaction);
JSONObject rawData;
JSONArray rawContractArray;
try {
rawData = jsonTransaction.getJSONObject("raw_data");
if (rawData == null) {
throw new InvalidHttpParameterException("Field 'raw_data' is missing");
}
rawContractArray = rawData.getJSONArray("contract");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SHOULD] packTransaction still returns internal server error for missing raw_data or empty body (NPE path)

The new try/catch only handles JSONException. When the body is {}, {"raw_data":null}, or empty, no exception of that type is thrown: JSON.parseObject("") returns null (NPE at line 363), and getJSONObject("raw_data") returns null for a missing key (NPE at line 364 on rawData.getJSONArray("contract")). NPE is not allowlisted, so these requests still get internal server error — the exact opaque behavior this PR sets out to fix, on the most common malformed shapes for the broadcast-family endpoints that call packTransaction (broadcasttransaction, gettransactionsignweight, gettransactionapprovedlist, getshieldtransactionhash). The new testPackTransactionReportsMisshapedRawData covers wrong-type fields but not the missing-field case.

Evidence clarity: Confirmed

Suggestion: Add explicit null checks for jsonTransaction, rawData, and rawContractArray and throw InvalidHttpParameterException with a fixed message (e.g. Field 'raw_data' is missing), plus test cases for {}, {"raw_data":null}, and an empty body.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, fixed in 016dad9. packTransaction now parses the body with Util.parseJsonBody, the helper behind getVisiblePost, so an empty or null body returns INVALID JSON body. A missing or null raw_data returns Field 'raw_data' is missing, and a missing or null raw_data.contract returns Field 'contract' is missing. Errors inside the per-contract loop were already caught, so these were the remaining null dereferences in the transaction's outer structure.

if (rawContractArray == null) {
throw new InvalidHttpParameterException("Field 'contract' is missing");
}
} catch (JSONException e) {
throw new InvalidHttpParameterException(
e.getCause() == null ? e.getMessage() : INVALID_JSON_BODY, e);
}
JSONArray contracts = new JSONArray();
JSONArray rawContractArray = rawData.getJSONArray("contract");
if (rawContractArray.size() > 1) {
throw new ContractSizeNotEqualToOneException(String.format(
ActuatorConstant.CONTRACT_SIZE_NOT_EQUAL_TO_ONE, rawContractArray.size()));
Expand Down Expand Up @@ -389,14 +426,17 @@ public static Transaction packTransaction(String strTransaction, boolean selfTyp
}

@Deprecated
public static void checkBodySize(String body) throws Exception {
public static void checkBodySize(String body) {
CommonParameter parameter = Args.getInstance();
if (body.getBytes().length > parameter.getHttpMaxMessageSize()) {
throw new Exception("body size is too big, the limit is "
+ parameter.getHttpMaxMessageSize());
throw new InvalidHttpParameterException(bodySizeTooBigMessage());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SHOULD] checkBodySize: redundant throws Exception after switching to an unchecked exception

checkBodySize previously threw a checked new Exception(...), which justified throws Exception on the signature. It now throws only InvalidHttpParameterException, which is unchecked (it extends java.security.InvalidParameterException -> IllegalArgumentException), so the throws Exception clause no longer matches the implementation and misleads callers about the real failure contract.

Evidence clarity: Confirmed

Suggestion: Drop throws Exception from the signature; this is source-compatible for all existing callers since they catch Exception broadly.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in bcfcdb7.

}
}

private static String bodySizeTooBigMessage() {
return "body size is too big, the limit is " + Args.getInstance().getHttpMaxMessageSize();
}

public static boolean getVisible(final HttpServletRequest request) {
boolean visible = false;
if (StringUtil.isNotBlank(request.getParameter(VISIBLE))) {
Expand Down Expand Up @@ -427,7 +467,7 @@ public static boolean getInt64AsString(final HttpServletRequest request) {
public static boolean getVisiblePost(final String input) {
boolean visible = false;
if (StringUtil.isNotBlank(input)) {
JSONObject jsonObject = JSON.parseObject(input);
JSONObject jsonObject = parseJsonBody(input);
if (jsonObject.containsKey(VISIBLE)) {
visible = Boolean.parseBoolean(jsonObject.getString(VISIBLE));
}
Expand All @@ -436,6 +476,19 @@ public static boolean getVisiblePost(final String input) {
return visible;
}

static JSONObject parseJsonBody(final String input) {
JSONObject jsonObject;
try {
jsonObject = JSON.parseObject(input);
} catch (JSONException e) {
throw new InvalidHttpParameterException(INVALID_JSON_BODY, e);
}
if (jsonObject == null) {
throw new InvalidHttpParameterException(INVALID_JSON_BODY);
}
return jsonObject;
}

public static String getContractType(final String input) {
String contractType = null;
JSONObject jsonObject = JSON.parseObject(input);
Expand All @@ -447,7 +500,12 @@ public static String getContractType(final String input) {

public static String getHexAddress(final String address) {
if (address != null) {
byte[] addressByte = decodeFromBase58Check(address);
byte[] addressByte;
try {
addressByte = decodeFromBase58Check(address);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SHOULD] getHexAddress: decoder null-return paths still silently produce an empty string

The new catch maps IllegalArgumentException from the Base58Check decoder (invalid base58 characters) to INVALID address, but Commons.decodeFromBase58Check returns null instead of throwing for empty input, wrong length (!= 34), checksum failure, and non-0x41 prefix — and ByteArray.toHexString(null) returns "". So within the same method, an address with an illegal character now yields a clear INVALID address error, while a wrong-length or bad-checksum address (the more common client mistake) silently becomes "" with no error at all, and downstream servlets answer with empty/not-found results. This predates the PR, but the PR rewrites exactly this method for exactly this purpose, and the two failure paths now behave inconsistently. getHexAddress has 20+ query-servlet callers.

Evidence clarity: Confirmed

Suggestion: Also throw InvalidHttpParameterException(INVALID_ADDRESS_MSG) when decodeFromBase58Check returns null; if you prefer to keep this PR minimal, record it explicitly in the Follow up section of the PR description.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed that the two failure paths are inconsistent, but I'd keep the existing null-return behaviour out of this PR. When the decoder returns null, as it did in 4.8.2.4, each endpoint handles the resulting empty address with its existing logic. Throwing there would turn some responses that succeed today into errors, which is a behaviour change rather than a restored message. I've added it to Follow up.

} catch (IllegalArgumentException e) {
throw new InvalidHttpParameterException(INVALID_ADDRESS_MSG, e);
}
return ByteArray.toHexString(addressByte);
} else {
return null;
Expand Down Expand Up @@ -790,7 +848,11 @@ public static String getJsonString(String str) throws ParseException {
}
checkFormPairs(str);
MultiMap<String> params = new MultiMap<>();
UrlEncoded.decodeUtf8To(str, params);
try {
UrlEncoded.decodeUtf8To(str, params);
} catch (IllegalArgumentException e) {
throw new InvalidHttpParameterException(INVALID_FORM_BODY, e);
}
JSONObject json = new JSONObject();
for (Map.Entry<String, List<String>> entry : params.entrySet()) {
String key = entry.getKey();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

import java.io.ByteArrayInputStream;
Expand Down Expand Up @@ -409,6 +410,45 @@ public void testChunkedBodyOneByteOverLimitUsesActualSize() throws Exception {
Assert.assertTrue(response, response.contains(detail));
}

@Test
public void testChunkedOversizedBodyGetsBodySizeErrorFromRealServlet() throws Exception {
boolean originalNonBlocking = Args.getInstance().isRateLimiterApiNonBlocking();
Args.getInstance().setRateLimiterApiNonBlocking(false);

Wallet wallet = mock(Wallet.class);
GetBlockByNumServlet servlet = new GetBlockByNumServlet();
ReflectionTestUtils.setField(servlet, "wallet", wallet);
ReflectionTestUtils.setField(servlet, "container", new RateLimiterContainer());

int port = PublicMethod.chooseRandomPort();
TestHttpService service = new TestHttpService(port, HTTP_MAX_BODY_SIZE) {
@Override
protected void addServlet(ServletContextHandler context) {
context.addServlet(new ServletHolder(servlet), "/wallet/getblockbynum");
}
};
try {
service.start().get(10, TimeUnit.SECONDS);
URI uri = new URI(String.format("http://localhost:%d/wallet/getblockbynum", port));
String body = "{\"num\":0,\"_pad\":\"" + repeat('A', HTTP_MAX_BODY_SIZE) + "\"}";
InputStreamEntity chunked = new InputStreamEntity(
new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)), -1);
chunked.setContentType(ContentType.APPLICATION_JSON.getMimeType());

String response = postForBody(uri, chunked);

Assert.assertEquals(response, "body size is too big, the limit is " + HTTP_MAX_BODY_SIZE,
JSONObject.parseObject(response).getString("Error"));
verifyNoInteractions(wallet);
} finally {
try {
service.stop();
} finally {
Args.getInstance().setRateLimiterApiNonBlocking(originalNonBlocking);
}
}
}

@Test
public void testChunkedBodyCountResetBetweenRequests() throws Exception {
byte[] data = repeat('a', HTTP_MAX_BODY_SIZE).getBytes("UTF-8");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,24 @@ public void legitimatePayloadIsBroadcast() throws Exception {
verify(wallet).broadcastTransaction(tx);
}

@Test
public void malformedJsonBodyGetsInvalidJsonBody() throws Exception {
for (String body : new String[] {"{\"transaction\":", "[1]", "abc", "null", ""}) {
BroadcastHexServlet servlet = new BroadcastHexServlet();
Wallet wallet = mock(Wallet.class);
ReflectionTestUtils.setField(servlet, "wallet", wallet);
MockHttpServletRequest request =
new MockHttpServletRequest("POST", "/wallet/broadcasthex");
request.setContentType("application/json");
request.setContent(body.getBytes(StandardCharsets.UTF_8));
MockHttpServletResponse response = new MockHttpServletResponse();
servlet.doPost(request, response);
assertEquals(body, "{\"Error\":\"INVALID JSON body\"}",
response.getContentAsString().trim());
verifyNoInteractions(wallet);
}
}

private static void assertRejectedWithoutWallet(byte[] payload) throws Exception {
assertRejectedWithoutWallet(new BroadcastHexServlet(), payload);
}
Expand Down
Loading
Loading