본문 바로가기
  • Where there is a will there is a way.
개발/java

steemit java commitor 되기 1 core 살펴보기

by 소확행개발자 2018. 9. 27.

steemit 이 어제 하드포크 되었다. 

아직까진 네트워크가 불안정해서 포스팅과 거래가 잘 되지 않는다. 


overnodes 는 현재 spring 과 steemj core를 이용해서 개발중인데 하드포크 이후에 기존의 steemj 의 변경사항도 있고 기존 steemj 가 spring boot와 개발환경이 맞지 않는 부분이 있어서 이를 교정할 겸 spring boot에 알맞는 steemj core로 만드는 commitor 가 되려고 한다.


우선 steemj core에 대해서 살펴보자

test 에 SteemJ Integration Test 에서 

getAccounts function 살펴보기 

List<ExtendedAccount> accounts = steemJ.getAccounts(accountNames);

에서 

public List<ExtendedAccount> getAccounts(List<AccountName> accountNames)
throws SteemCommunicationException, SteemResponseException {
JsonRPCRequest requestObject = new JsonRPCRequest();
requestObject.setSteemApi(SteemApiType.DATABASE_API);
requestObject.setApiMethod(RequestMethods.GET_ACCOUNTS);

// The API expects an array of arrays here.
String[] innerParameters = new String[accountNames.size()];
for (int i = 0; i < accountNames.size(); i++) {
innerParameters[i] = accountNames.get(i).getName();
}

String[][] parameters = { innerParameters };

requestObject.setAdditionalParameters(parameters);
return communicationHandler.performRequest(requestObject, ExtendedAccount.class);
}

를 살펴보면


steemj 는 우선 JsonRPCRequest 와 Response 를 사용하여 request를 작성한다.

그런 다음에 communicationHandler 에서 request를 날린다.


public <T> List<T> performRequest(JsonRPCRequest requestObject, Class<T> targetClass)
throws SteemCommunicationException, SteemResponseException {
try {
Pair<URI, Boolean> endpoint = SteemJConfig.getInstance().getNextEndpointURI(numberOfConnectionTries++);
JsonRPCResponse rawJsonResponse = client.invokeAndReadResponse(requestObject, endpoint.getLeft(),
endpoint.getRight());
LOGGER.debug("Received {} ", rawJsonResponse);

if (rawJsonResponse.isError()) {
throw rawJsonResponse.handleError(requestObject.getId());
} else {
// HANDLE NORMAL RESPONSE
JavaType expectedResultType = mapper.getTypeFactory().constructCollectionType(List.class, targetClass);
return rawJsonResponse.handleResult(expectedResultType, requestObject.getId());
}
} catch (SteemCommunicationException e) {
LOGGER.warn("The connection has been closed. Switching the endpoint and reconnecting.");
LOGGER.debug("For the following reason: ", e);

return performRequest(requestObject, targetClass);
}
}


여기서 invokeAndReadResponse 부분에서 uri 를 날린다.


@Override
public JsonRPCResponse invokeAndReadResponse(JsonRPCRequest requestObject, URI endpointUri,
boolean sslVerificationDisabled) throws SteemCommunicationException {
try {
NetHttpTransport.Builder builder = new NetHttpTransport.Builder();
// Disable SSL verification if needed
if (sslVerificationDisabled && endpointUri.getScheme().equals("https")) {
builder.doNotValidateCertificate();
}

String requestPayload = requestObject.toJson();
HttpRequest httpRequest = builder.build().createRequestFactory(new HttpClientRequestInitializer())
.buildPostRequest(new GenericUrl(endpointUri),
ByteArrayContent.fromString("application/json", requestPayload));

LOGGER.debug("Sending {}.", requestPayload);

HttpResponse httpResponse = httpRequest.execute();

int status = httpResponse.getStatusCode();
String responsePayload = httpResponse.parseAsString();

if (status >= 200 && status < 300 && responsePayload != null) {
return new JsonRPCResponse(CommunicationHandler.getObjectMapper().readTree(responsePayload));
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}

} catch (GeneralSecurityException | IOException e) {
throw new SteemCommunicationException("A problem occured while processing the request.", e);
}
}



steem power 보내기 

steemj core 의 tdd 를 살펴보면


1. TransferToVestingOperationIntegrationTest 가 있다.

@BeforeClass()
public static void prepareTestClass() throws Exception {
setupIntegrationTestEnvironmentForTransactionVerificationTests(HTTP_MODE_IDENTIFIER,
STEEMNET_ENDPOINT_IDENTIFIER);

AccountName from = new AccountName("dez1337");
AccountName to = new AccountName("dez1337");

Asset steemAmount = new Asset(1L, AssetSymbolType.STEEM);

TransferToVestingOperation transferToVestingOperation = new TransferToVestingOperation(from, to, steemAmount);

ArrayList<Operation> operations = new ArrayList<>();
operations.add(transferToVestingOperation);

signedTransaction = new SignedTransaction(REF_BLOCK_NUM, REF_BLOCK_PREFIX, new TimePointSec(EXPIRATION_DATE),
operations, null);
signedTransaction.sign();
}


AccountName 선언을 보면 steem 의 data type인 account_name_type을 맞추었다.


AccountName TDD 

public class AccountNameTest {
private final String EXPECTED_BYTE_REPRESENTATION = "0764657a31333337";

/**
* Test the
* {@link eu.bittrade.libs.steemj.base.models.AccountName#toByteArray()
* toByteArray()} method.
*
* @throws Exception
* In case of a problem.
*/
@Test
public void testAccountNameToByteArray() throws Exception {
AccountName myAccount = new AccountName("dez1337");

assertThat("Expect that the accountName object has the given byte representation.",
CryptoUtils.HEX.encode(myAccount.toByteArray()), equalTo(EXPECTED_BYTE_REPRESENTATION));
}

/**
* Test the validation of the
* {@link eu.bittrade.libs.steemj.base.models.AccountName#setName(String name)
* setName(String name)} method by providing an account name which is too
* long.
*/
@Test(expected = InvalidParameterException.class)
public void testAccountNameValidationTooLong() {
new AccountName("thisaccountnameistoolong");
}

/**
* Test the validation of the
* {@link eu.bittrade.libs.steemj.base.models.AccountName#setName(String name)
* setName(String name)} method by providing an account name which is too
* short.
*/
@Test(expected = InvalidParameterException.class)
public void testAccountNameValidationTooShort() {
new AccountName("sh");
}

/**
* Test the validation of the
* {@link eu.bittrade.libs.steemj.base.models.AccountName#setName(String name)
* setName(String name)} method by providing an account name with an invalid
* start character.
*/
@Test(expected = InvalidParameterException.class)
public void testAccountNameValidationWrongStartChar() {
new AccountName("-dez1337");
}

/**
* Test the validation of the
* {@link eu.bittrade.libs.steemj.base.models.AccountName#setName(String name)
* setName(String name)} method by providing an account name with an invalid
* end character.
*/
@Test(expected = InvalidParameterException.class)
public void testAccountNameValidationWrongEndChar() {
new AccountName("dez1337-");
}

/**
* Test the validation of the
* {@link eu.bittrade.libs.steemj.base.models.AccountName#setName(String name)
* setName(String name)} method by providing valid account names.
*/
@Test
public void testAccountNameValidation() {
new AccountName("dez-1337");
new AccountName("dez");
new AccountName("dez1337-steemj");
}
}


@Category({ IntegrationTest.class })
@Test
public void verifyTransaction() throws Exception {
assertThat(steemJ.verifyAuthority(signedTransaction), equalTo(true));
}




댓글