Skip to content

Commit

Permalink
Support contract initcode (#3625)
Browse files Browse the repository at this point in the history
- Parse ContractCreateTransactionBody.initcode
- Show contract bytecode from initcode in REST api response if exists otherwise from contract bytecode file

Signed-off-by: Xin Li <xin.li@hedera.com>
  • Loading branch information
xin-hedera committed Apr 22, 2022
1 parent a6793ad commit 6dbb023
Show file tree
Hide file tree
Showing 18 changed files with 238 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
Expand All @@ -35,7 +36,7 @@
import com.hedera.mirror.common.domain.entity.EntityId;

@Data
@javax.persistence.Entity
@Entity
@NoArgsConstructor
@SuperBuilder
public class Contract extends AbstractEntity implements Aliasable {
Expand All @@ -48,6 +49,10 @@ public class Contract extends AbstractEntity implements Aliasable {
@Convert(converter = FileIdConverter.class)
private EntityId fileId;

@Column(updatable = false)
@ToString.Exclude
private byte[] initcode;

@Convert(converter = UnknownIdConverter.class)
private EntityId obtainerId;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,16 @@ private void processCreatedContractEntity(RecordItem recordItem, EntityId contra
entityListener.onContract(contract);
}

/**
* Updates the contract entities in ContractCreateResult.CreatedContractIDs list. The method should only be called
* for such contract entities in pre services 0.23 contract create transactions. Since services 0.23, the child
* contract creation is externalized into its own synthesized contract create transaction and should be processed by
* ContractCreateTransactionHandler.
*
* @param contract The contract entity
* @param recordItem The recordItem in which the contract is created
*/
private void updateContractEntityOnCreate(Contract contract, RecordItem recordItem) {
var contractCreateResult = recordItem.getRecord().getContractCreateResult();
var transactionBody = recordItem.getTransactionBody().getContractCreateInstance();

if (transactionBody.hasAutoRenewPeriod()) {
Expand All @@ -227,10 +235,6 @@ private void updateContractEntityOnCreate(Contract contract, RecordItem recordIt
contract.setFileId(EntityId.of(transactionBody.getFileID()));
}

if (contractCreateResult.hasEvmAddress()) {
contract.setEvmAddress(DomainUtils.toBytes(contractCreateResult.getEvmAddress().getValue()));
}

contract.setMemo(transactionBody.getMemo());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,7 @@ private Contract mergeContract(Contract previous, Contract current) {

current.setEvmAddress(previous.getEvmAddress());
current.setFileId(previous.getFileId());
current.setInitcode(previous.getInitcode());

if (current.getObtainerId() == null) {
current.setObtainerId(previous.getObtainerId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,19 @@ protected void doUpdateEntity(Contract contract, RecordItem recordItem) {
contract.setKey(transactionBody.getAdminKey().toByteArray());
}

if (transactionBody.hasProxyAccountID()) {
contract.setProxyAccountId(EntityId.of(transactionBody.getProxyAccountID()));
switch (transactionBody.getInitcodeSourceCase()) {
case FILEID:
contract.setFileId(EntityId.of(transactionBody.getFileID()));
break;
case INITCODE:
contract.setInitcode(DomainUtils.toBytes(transactionBody.getInitcode()));
break;
default:
break;
}

if (transactionBody.hasFileID()) {
contract.setFileId(EntityId.of(transactionBody.getFileID()));
if (transactionBody.hasProxyAccountID()) {
contract.setProxyAccountId(EntityId.of(transactionBody.getProxyAccountID()));
}

if (contractCreateResult.hasEvmAddress()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
alter table if exists contract add column if not exists initcode bytea null;
alter table if exists contract_history add column if not exists initcode bytea null;
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ create table if not exists contract
expiration_timestamp bigint null,
file_id bigint null,
id bigint not null,
initcode bytea null,
key bytea null,
memo text default '' not null,
num bigint not null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@

\copy assessed_custom_fee (amount, collector_account_id, consensus_timestamp, token_id) from assessed_custom_fee.csv csv;

\copy contract (auto_renew_period, created_timestamp, deleted, expiration_timestamp, file_id, id, key, memo, num, obtainer_id, proxy_account_id, public_key, realm, shard, timestamp_range, type, evm_address) from contract.csv csv;
\copy contract (auto_renew_period, created_timestamp, deleted, expiration_timestamp, file_id, id, key, memo, num, obtainer_id, proxy_account_id, public_key, realm, shard, timestamp_range, type, evm_address, initcode) from contract.csv csv;

\copy contract_history (auto_renew_period, created_timestamp, deleted, expiration_timestamp, file_id, id, key, memo, num, obtainer_id, proxy_account_id, public_key, realm, shard, timestamp_range, type, evm_address) from contract_history.csv csv;
\copy contract_history (auto_renew_period, created_timestamp, deleted, expiration_timestamp, file_id, id, key, memo, num, obtainer_id, proxy_account_id, public_key, realm, shard, timestamp_range, type, evm_address, initcode) from contract_history.csv csv;

\copy contract_log (bloom, consensus_timestamp, contract_id, data, index, topic0, topic1, topic2, topic3, root_contract_id) from contract_log.csv csv;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,10 @@ private Duration duration(int seconds) {
return Duration.newBuilder().setSeconds(seconds).build();
}

public BytesValue evmAddress() {
return BytesValue.of(bytes(20));
}

private FileID fileId() {
return FileID.newBuilder().setFileNum(id()).build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.data.util.Version;

import com.hedera.mirror.common.domain.contract.Contract;
Expand All @@ -69,6 +70,7 @@
import com.hedera.mirror.common.domain.contract.ContractStateChange;
import com.hedera.mirror.common.domain.entity.EntityId;
import com.hedera.mirror.common.domain.entity.EntityType;
import com.hedera.mirror.common.domain.transaction.RecordFile;
import com.hedera.mirror.common.domain.transaction.RecordItem;
import com.hedera.mirror.common.util.DomainUtils;
import com.hedera.mirror.importer.TestUtils;
Expand Down Expand Up @@ -100,9 +102,14 @@ void before() {
entityProperties.getPersist().setCryptoTransferAmounts(true);
}

@Test
void contractCreate() {
RecordItem recordItem = recordItemBuilder.contractCreate().build();
@ParameterizedTest
@ValueSource(booleans = {true, false})
void contractCreate(boolean bytecodeSourceFileId) {
var builder = recordItemBuilder.contractCreate();
if (!bytecodeSourceFileId) {
builder.transactionBody(b -> b.clearFileID().setInitcode(recordItemBuilder.bytes(1024)));
}
var recordItem = builder.build();
var record = recordItem.getRecord();
var transactionBody = recordItem.getTransactionBody().getContractCreateInstance();

Expand Down Expand Up @@ -130,6 +137,7 @@ void contractCreateWithEvmAddress() {
.addCreatedContractIDs(CONTRACT_ID)
.setEvmAddress(BytesValue.of(DomainUtils.fromBytes(evmAddress)))
))
.hapiVersion(RecordFile.HAPI_VERSION_0_23_0)
.build();
var record = recordItem.getRecord();
var transactionBody = recordItem.getTransactionBody().getContractCreateInstance();
Expand Down Expand Up @@ -762,6 +770,9 @@ private void assertContractEntity(RecordItem recordItem) {
DomainUtils.toBytes(contractCreateResult.getEvmAddress().getValue()) : null;
EntityId entityId = transaction.getEntityId();
Contract contract = getEntity(entityId);
EntityId expectedFileId = transactionBody.hasFileID() ? EntityId.of(transactionBody.getFileID()) : null;
byte[] expectedInitcode = transactionBody.getInitcode() != ByteString.EMPTY ?
DomainUtils.toBytes(transactionBody.getInitcode()) : null;

assertThat(transaction)
.isNotNull()
Expand All @@ -774,8 +785,9 @@ private void assertContractEntity(RecordItem recordItem) {
.returns(false, Contract::getDeleted)
.returns(evmAddress, Contract::getEvmAddress)
.returns(null, Contract::getExpirationTimestamp)
.returns(expectedFileId, Contract::getFileId)
.returns(entityId.getId(), Contract::getId)
.returns(EntityId.of(transactionBody.getFileID()), Contract::getFileId)
.returns(expectedInitcode, Contract::getInitcode)
.returns(adminKey, Contract::getKey)
.returns(transactionBody.getMemo(), Contract::getMemo)
.returns(createdTimestamp, Contract::getTimestampLower)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,17 @@
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Stream;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.util.Strings;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.support.TransactionTemplate;
Expand Down Expand Up @@ -172,7 +176,9 @@ void isEnabled() {
void onContract() {
// given
Contract contract1 = domainBuilder.contract().get();
Contract contract2 = domainBuilder.contract().customize(c -> c.evmAddress(null)).get();
Contract contract2 = domainBuilder.contract()
.customize(c -> c.evmAddress(null).fileId(null).initcode(domainBuilder.bytes(1024)))
.get();

// when
sqlEntityListener.onContract(contract1);
Expand All @@ -185,11 +191,14 @@ void onContract() {
assertThat(findHistory(Contract.class)).isEmpty();
}

@ValueSource(ints = {1, 2, 3})
@ParameterizedTest
void onContractHistory(int commitIndex) {
@ParameterizedTest(name = "{2} record files with {0}")
@MethodSource("provideParamsContractHistory")
void onContractHistory(String bytecodeSource, Consumer<Contract.ContractBuilder> customizer, int commitIndex) {
// given
Contract contractCreate = domainBuilder.contract().customize(c -> c.obtainerId(null)).get();
Contract contractCreate = domainBuilder.contract()
.customize(c -> c.obtainerId(null))
.customize(customizer)
.get();

Contract contractUpdate = contractCreate.toEntityId().toEntity();
contractUpdate.setAutoRenewPeriod(30L);
Expand Down Expand Up @@ -1468,4 +1477,17 @@ private TokenTransfer getTokenTransfer(long amount, long consensusTimestamp, Ent
tokenTransfer.setPayerAccountId(TRANSACTION_PAYER);
return tokenTransfer;
}

private static Stream<Arguments> provideParamsContractHistory() {
Consumer<Contract.ContractBuilder> emptyCustomizer = c -> {};
Consumer<Contract.ContractBuilder> initcodeCustomizer = c -> c.fileId(null).initcode(new byte[]{1, 2 ,3, 4});
return Stream.of(
Arguments.of("fileId", emptyCustomizer, 1),
Arguments.of("fileId", emptyCustomizer, 2),
Arguments.of("fileId", emptyCustomizer, 3),
Arguments.of("initcode", initcodeCustomizer, 1),
Arguments.of("initcode", initcodeCustomizer, 2),
Arguments.of("initcode", initcodeCustomizer, 3)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,13 @@

import static com.hedera.mirror.common.domain.entity.EntityType.CONTRACT;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
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 com.google.common.collect.Range;
import com.google.protobuf.ByteString;
import com.google.protobuf.BytesValue;
import com.google.protobuf.Descriptors;
Expand All @@ -35,6 +40,7 @@
import com.hederahashgraph.api.proto.java.TransactionReceipt;
import com.hederahashgraph.api.proto.java.TransactionRecord;
import java.util.List;
import java.util.function.Consumer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

Expand All @@ -43,6 +49,7 @@
import com.hedera.mirror.common.domain.entity.AbstractEntity;
import com.hedera.mirror.common.domain.entity.EntityId;
import com.hedera.mirror.common.domain.entity.EntityType;
import com.hedera.mirror.common.domain.transaction.Transaction;
import com.hedera.mirror.common.util.DomainUtils;
import com.hedera.mirror.importer.TestUtils;
import com.hedera.mirror.importer.parser.record.entity.EntityProperties;
Expand Down Expand Up @@ -135,4 +142,72 @@ void updateContractResultNonContractCallTransaction() {
.returns(null, ContractResult::getGasLimit)
.returns(null, ContractResult::getFunctionParameters);
}

@Test
void updateTransactionUnsuccessful() {
var recordItem = recordItemBuilder.contractCreate()
.receipt(r -> r.setStatus(ResponseCodeEnum.INSUFFICIENT_GAS))
.build();
var transaction = new Transaction();
transactionHandler.updateTransaction(transaction, recordItem);
verifyNoInteractions(entityListener);
}

@Test
void updateTransactionSuccessful() {
var recordItem = recordItemBuilder.contractCreate().build();
var contractId = EntityId.of(recordItem.getRecord().getReceipt().getContractID());
var timestamp = recordItem.getConsensusTimestamp();
var transaction = domainBuilder.transaction()
.customize(t -> t.consensusTimestamp(timestamp).entityId(contractId))
.get();
transactionHandler.updateTransaction(transaction, recordItem);
assertContract(contractId, timestamp, t -> assertThat(t)
.returns(null, Contract::getEvmAddress)
.satisfies(c -> assertThat(c.getFileId().getId()).isPositive())
.returns(null, Contract::getInitcode)
);
}

@Test
void updateTransactionSuccessfulWithEvmAddressAndInitcode() {
var recordItem = recordItemBuilder.contractCreate()
.transactionBody(b -> b.clearFileID().setInitcode(recordItemBuilder.bytes(2048)))
.record(r -> r.getContractCreateResultBuilder().setEvmAddress(recordItemBuilder.evmAddress()))
.build();
var contractId = EntityId.of(recordItem.getRecord().getReceipt().getContractID());
var timestamp = recordItem.getConsensusTimestamp();
var transaction = domainBuilder.transaction()
.customize(t -> t.consensusTimestamp(timestamp).entityId(contractId))
.get();
transactionHandler.updateTransaction(transaction, recordItem);
assertContract(contractId, timestamp, t -> assertThat(t)
.satisfies(c -> assertThat(c.getEvmAddress()).hasSize(20))
.returns(null, Contract::getFileId)
.satisfies(c -> assertThat(c.getInitcode()).hasSize(2048))
);
}

private void assertContract(EntityId contractId, long timestamp, Consumer<Contract> extraAssert) {
verify(entityListener, times(1)).onContract(assertArg(t -> assertAll(
() -> assertThat(t)
.isNotNull()
.satisfies(c -> assertThat(c.getAutoRenewPeriod()).isPositive())
.returns(timestamp, Contract::getCreatedTimestamp)
.returns(false, Contract::getDeleted)
.returns(null, Contract::getExpirationTimestamp)
.returns(contractId.getId(), Contract::getId)
.satisfies(c -> assertThat(c.getKey()).isNotEmpty())
.satisfies(c -> assertThat(c.getMemo()).isNotEmpty())
.returns(contractId.getEntityNum(), Contract::getNum)
.satisfies(c -> assertThat(c.getProxyAccountId().getId()).isPositive())
.satisfies(c -> assertThat(c.getPublicKey()).isNotEmpty())
.returns(contractId.getRealmNum(), Contract::getRealm)
.returns(contractId.getShardNum(), Contract::getShard)
.returns(CONTRACT, Contract::getType)
.returns(Range.atLeast(timestamp), Contract::getTimestampRange)
.returns(null, Contract::getObtainerId),
() -> extraAssert.accept(t)
)));
}
}

0 comments on commit 6dbb023

Please sign in to comment.