From c13d6a3e42c41fabb8a281179346a09f572cacf9 Mon Sep 17 00:00:00 2001 From: Rob Walworth Date: Mon, 9 Oct 2023 15:28:30 -0500 Subject: [PATCH 1/7] Add checksum capabilities | Update entity files Signed-off-by: Rob Walworth --- sdk/examples/NftAddRemoveAllowancesExample.cc | 17 +- sdk/main/CMakeLists.txt | 1 + .../AccountAllowanceApproveTransaction.h | 9 + .../AccountAllowanceDeleteTransaction.h | 9 + sdk/main/include/AccountBalanceQuery.h | 9 + sdk/main/include/AccountCreateTransaction.h | 9 + sdk/main/include/AccountDeleteTransaction.h | 9 + sdk/main/include/AccountId.h | 125 +++++--- sdk/main/include/AccountInfoQuery.h | 9 + sdk/main/include/AccountRecordsQuery.h | 9 + sdk/main/include/AccountStakersQuery.h | 9 + sdk/main/include/AccountUpdateTransaction.h | 9 + sdk/main/include/Client.h | 34 ++ sdk/main/include/ContractByteCodeQuery.h | 9 + sdk/main/include/ContractCallQuery.h | 9 + sdk/main/include/ContractCreateTransaction.h | 9 + sdk/main/include/ContractDeleteTransaction.h | 9 + sdk/main/include/ContractExecuteTransaction.h | 9 + sdk/main/include/ContractId.h | 170 ++++++---- sdk/main/include/ContractInfoQuery.h | 9 + sdk/main/include/ContractUpdateTransaction.h | 9 + sdk/main/include/CustomFee.h | 13 + sdk/main/include/CustomFixedFee.h | 8 + sdk/main/include/DelegateContractId.h | 40 ++- sdk/main/include/EthereumTransaction.h | 9 + sdk/main/include/FileAppendTransaction.h | 9 + sdk/main/include/FileContentsQuery.h | 9 + sdk/main/include/FileCreateTransaction.h | 9 + sdk/main/include/FileDeleteTransaction.h | 9 + sdk/main/include/FileId.h | 115 ++++--- sdk/main/include/FileInfoQuery.h | 9 + sdk/main/include/FileUpdateTransaction.h | 9 + sdk/main/include/FreezeTransaction.h | 9 + sdk/main/include/HbarAllowance.h | 57 +--- sdk/main/include/HbarTransfer.h | 57 +--- sdk/main/include/NetworkVersionInfoQuery.h | 9 + sdk/main/include/NftId.h | 41 +-- sdk/main/include/Query.h | 8 + sdk/main/include/ScheduleCreateTransaction.h | 9 + sdk/main/include/ScheduleDeleteTransaction.h | 9 + sdk/main/include/ScheduleId.h | 77 +++-- sdk/main/include/ScheduleInfoQuery.h | 9 + sdk/main/include/ScheduleSignTransaction.h | 9 + sdk/main/include/SystemDeleteTransaction.h | 9 + sdk/main/include/SystemUndeleteTransaction.h | 9 + sdk/main/include/TokenAllowance.h | 13 + sdk/main/include/TokenAssociateTransaction.h | 9 + sdk/main/include/TokenBurnTransaction.h | 9 + sdk/main/include/TokenCreateTransaction.h | 9 + sdk/main/include/TokenDeleteTransaction.h | 9 + sdk/main/include/TokenDissociateTransaction.h | 9 + .../TokenFeeScheduleUpdateTransaction.h | 9 + sdk/main/include/TokenFreezeTransaction.h | 9 + sdk/main/include/TokenGrantKycTransaction.h | 9 + sdk/main/include/TokenId.h | 111 ++++--- sdk/main/include/TokenInfoQuery.h | 9 + sdk/main/include/TokenMintTransaction.h | 9 + sdk/main/include/TokenNftAllowance.h | 10 +- sdk/main/include/TokenNftInfoQuery.h | 9 + sdk/main/include/TokenNftTransfer.h | 80 ++--- sdk/main/include/TokenPauseTransaction.h | 9 + sdk/main/include/TokenRevokeKycTransaction.h | 9 + sdk/main/include/TokenTransfer.h | 39 ++- sdk/main/include/TokenUnfreezeTransaction.h | 9 + sdk/main/include/TokenUnpauseTransaction.h | 9 + sdk/main/include/TokenUpdateTransaction.h | 9 + sdk/main/include/TokenWipeTransaction.h | 9 + sdk/main/include/TopicCreateTransaction.h | 9 + sdk/main/include/TopicDeleteTransaction.h | 9 + sdk/main/include/TopicId.h | 89 ++++-- sdk/main/include/TopicInfoQuery.h | 9 + .../include/TopicMessageSubmitTransaction.h | 9 + sdk/main/include/TopicUpdateTransaction.h | 9 + sdk/main/include/Transaction.h | 8 + sdk/main/include/TransactionReceiptQuery.h | 8 + sdk/main/include/TransactionRecordQuery.h | 8 + sdk/main/include/TransferTransaction.h | 22 +- .../include/exceptions/BadEntityException.h | 71 +++++ sdk/main/include/impl/EntityIdHelper.h | 170 ++++++++++ .../src/AccountAllowanceApproveTransaction.cc | 22 +- .../src/AccountAllowanceDeleteTransaction.cc | 14 +- sdk/main/src/AccountBalanceQuery.cc | 14 + sdk/main/src/AccountCreateTransaction.cc | 9 + sdk/main/src/AccountDeleteTransaction.cc | 14 + sdk/main/src/AccountId.cc | 198 ++++++------ sdk/main/src/AccountInfoQuery.cc | 6 + sdk/main/src/AccountRecordsQuery.cc | 6 + sdk/main/src/AccountStakersQuery.cc | 6 + sdk/main/src/AccountUpdateTransaction.cc | 11 + sdk/main/src/Client.cc | 39 +++ sdk/main/src/ContractByteCodeQuery.cc | 6 + sdk/main/src/ContractCallQuery.cc | 6 + sdk/main/src/ContractCreateTransaction.cc | 19 ++ sdk/main/src/ContractDeleteTransaction.cc | 16 + sdk/main/src/ContractExecuteTransaction.cc | 6 + sdk/main/src/ContractFunctionParameters.cc | 11 +- sdk/main/src/ContractId.cc | 193 +++++++---- sdk/main/src/ContractInfoQuery.cc | 6 + sdk/main/src/ContractUpdateTransaction.cc | 16 + sdk/main/src/CustomFee.cc | 7 + sdk/main/src/CustomFixedFee.cc | 11 + sdk/main/src/DelegateContractId.cc | 66 ++-- sdk/main/src/EthereumTransaction.cc | 9 + sdk/main/src/EvmAddress.cc | 20 +- sdk/main/src/FileAppendTransaction.cc | 6 + sdk/main/src/FileContentsQuery.cc | 6 + sdk/main/src/FileCreateTransaction.cc | 6 + sdk/main/src/FileDeleteTransaction.cc | 6 + sdk/main/src/FileId.cc | 120 +++---- sdk/main/src/FileInfoQuery.cc | 6 + sdk/main/src/FileUpdateTransaction.cc | 6 + sdk/main/src/FreezeTransaction.cc | 9 + sdk/main/src/HbarAllowance.cc | 28 +- sdk/main/src/HbarTransfer.cc | 29 +- sdk/main/src/NetworkVersionInfoQuery.cc | 6 + sdk/main/src/NftId.cc | 40 +-- sdk/main/src/Query.cc | 6 + sdk/main/src/ScheduleCreateTransaction.cc | 9 + sdk/main/src/ScheduleDeleteTransaction.cc | 9 + sdk/main/src/ScheduleId.cc | 100 +++--- sdk/main/src/ScheduleInfoQuery.cc | 6 + sdk/main/src/ScheduleSignTransaction.cc | 9 + sdk/main/src/SystemDeleteTransaction.cc | 14 + sdk/main/src/SystemUndeleteTransaction.cc | 14 + sdk/main/src/TokenAllowance.cc | 8 + sdk/main/src/TokenAssociateTransaction.cc | 12 + sdk/main/src/TokenBurnTransaction.cc | 6 + sdk/main/src/TokenCreateTransaction.cc | 18 ++ sdk/main/src/TokenDeleteTransaction.cc | 9 + sdk/main/src/TokenDissociateTransaction.cc | 12 + .../src/TokenFeeScheduleUpdateTransaction.cc | 10 + sdk/main/src/TokenFreezeTransaction.cc | 7 + sdk/main/src/TokenGrantKycTransaction.cc | 7 + sdk/main/src/TokenId.cc | 136 +++----- sdk/main/src/TokenInfoQuery.cc | 6 + sdk/main/src/TokenMintTransaction.cc | 6 + sdk/main/src/TokenNftAllowance.cc | 19 ++ sdk/main/src/TokenNftInfoQuery.cc | 6 + sdk/main/src/TokenNftTransfer.cc | 65 ++-- sdk/main/src/TokenPauseTransaction.cc | 6 + sdk/main/src/TokenRevokeKycTransaction.cc | 7 + sdk/main/src/TokenTransfer.cc | 23 +- sdk/main/src/TokenUnfreezeTransaction.cc | 7 + sdk/main/src/TokenUnpauseTransaction.cc | 6 + sdk/main/src/TokenUpdateTransaction.cc | 16 + sdk/main/src/TokenWipeTransaction.cc | 7 + sdk/main/src/TopicCreateTransaction.cc | 9 + sdk/main/src/TopicDeleteTransaction.cc | 9 + sdk/main/src/TopicId.cc | 145 +++------ sdk/main/src/TopicInfoQuery.cc | 6 + sdk/main/src/TopicMessageSubmitTransaction.cc | 6 + sdk/main/src/TopicUpdateTransaction.cc | 11 + sdk/main/src/Transaction.cc | 6 + sdk/main/src/TransactionReceiptQuery.cc | 9 + sdk/main/src/TransactionRecord.cc | 18 +- sdk/main/src/TransactionRecordQuery.cc | 9 + sdk/main/src/TransferTransaction.cc | 78 +++-- sdk/main/src/impl/EntityIdHelper.cc | 300 ++++++++++++++++++ .../TransferTransactionIntegrationTest.cc | 4 +- .../AccountAllowanceApproveTransactionTest.cc | 13 +- sdk/tests/unit/AssessedCustomFeesTest.cc | 6 +- sdk/tests/unit/ContractIdTest.cc | 148 ++------- sdk/tests/unit/ContractNonceInfoUnitTests.cc | 12 +- sdk/tests/unit/CustomFixedFeeTest.cc | 12 +- sdk/tests/unit/DelegateContractIdTest.cc | 51 ++- sdk/tests/unit/FileIdTest.cc | 105 +----- sdk/tests/unit/HbarAllowanceTest.cc | 56 +--- sdk/tests/unit/HbarTransferTest.cc | 31 +- sdk/tests/unit/NftIdTest.cc | 46 +-- sdk/tests/unit/TokenAssociationUnitTests.cc | 6 +- sdk/tests/unit/TokenIdTest.cc | 74 +---- sdk/tests/unit/TokenInfoUnitTests.cc | 6 +- sdk/tests/unit/TokenNftTransferTest.cc | 63 +--- sdk/tests/unit/TokenTransferTest.cc | 14 +- sdk/tests/unit/TransactionRecordTest.cc | 18 +- sdk/tests/unit/TransferTransactionTest.cc | 23 +- 176 files changed, 2976 insertions(+), 1752 deletions(-) create mode 100644 sdk/main/include/exceptions/BadEntityException.h create mode 100644 sdk/main/include/impl/EntityIdHelper.h create mode 100644 sdk/main/src/impl/EntityIdHelper.cc diff --git a/sdk/examples/NftAddRemoveAllowancesExample.cc b/sdk/examples/NftAddRemoveAllowancesExample.cc index fe5b1184f..61a1d0dba 100644 --- a/sdk/examples/NftAddRemoveAllowancesExample.cc +++ b/sdk/examples/NftAddRemoveAllowancesExample.cc @@ -155,8 +155,7 @@ int main(int argc, char** argv) // Give the spender an allowance of the NFTs. const NftId nft1(tokenId, serialNumbers.at(0)); const NftId nft2(tokenId, serialNumbers.at(1)); - std::cout << "Approve spender allowance for NFT serials " << nft1.getSerialNum() << " and " << nft2.getSerialNum() - << ": " + std::cout << "Approve spender allowance for NFT serials " << nft1.mSerialNum << " and " << nft2.mSerialNum << ": " << gStatusToString.at(AccountAllowanceApproveTransaction() .approveTokenNftAllowance(nft1, operatorAccountId, spenderAccountId) .approveTokenNftAllowance(nft2, operatorAccountId, spenderAccountId) @@ -167,7 +166,7 @@ int main(int argc, char** argv) // Send NFT1 to receiver account, using the spender account's allowance. A TransactionId must be generated manually // from the spender account ID in order for the transaction to be executed on behalf of the spender. - std::cout << "Transfer NFT " << nft1.getSerialNum() << " on behalf of the spender: " + std::cout << "Transfer NFT " << nft1.mSerialNum << " on behalf of the spender: " << gStatusToString.at(TransferTransaction() .addApprovedNftTransfer(nft1, operatorAccountId, receiverAccountId) .setTransactionId(TransactionId::generate(spenderAccountId)) @@ -179,7 +178,7 @@ int main(int argc, char** argv) << std::endl; // Remove the spender's allowance for NFT2. - std::cout << "Remove NFT " << nft2.getSerialNum() << " allowance from spender: " + std::cout << "Remove NFT " << nft2.mSerialNum << " allowance from spender: " << gStatusToString.at(AccountAllowanceDeleteTransaction() .deleteAllTokenNftAllowances(nft2, operatorAccountId) .execute(client) @@ -188,7 +187,7 @@ int main(int argc, char** argv) << std::endl; // Attempt to transfer NFT2 using the spender's now-deleted allowance. This should not work. - std::cout << "Transfer NFT " << nft2.getSerialNum() << " with no allowance (should return " + std::cout << "Transfer NFT " << nft2.mSerialNum << " with no allowance (should return " << gStatusToString.at(Status::SPENDER_DOES_NOT_HAVE_ALLOWANCE) << "): " << gStatusToString.at(TransferTransaction() .addApprovedNftTransfer(nft2, operatorAccountId, receiverAccountId) @@ -202,7 +201,7 @@ int main(int argc, char** argv) << std::endl; // Return NFT1 back to the treasury account. - std::cout << "Transfer NFT " << nft1.getSerialNum() << " back to the operator: " + std::cout << "Transfer NFT " << nft1.mSerialNum << " back to the operator: " << gStatusToString.at(TransferTransaction() .addNftTransfer(nft1, receiverAccountId, operatorAccountId) .freezeWith(&client) @@ -213,7 +212,7 @@ int main(int argc, char** argv) << std::endl; // Remove the allowance for NFT1 from the spender account. - std::cout << "Remove NFT " << nft1.getSerialNum() << " allowance from spender: " + std::cout << "Remove NFT " << nft1.mSerialNum << " allowance from spender: " << gStatusToString.at(AccountAllowanceDeleteTransaction() .deleteAllTokenNftAllowances(nft1, operatorAccountId) .execute(client) @@ -261,7 +260,7 @@ int main(int argc, char** argv) // Send NFT1 to receiver account, using the spender account's allowance. A TransactionId must be generated manually // from the spender account ID in order for the transaction to be executed on behalf of the spender. - std::cout << "Transfer NFT " << nft1.getSerialNum() << " on behalf of the spender: " + std::cout << "Transfer NFT " << nft1.mSerialNum << " on behalf of the spender: " << gStatusToString.at(TransferTransaction() .addApprovedNftTransfer(nft1, operatorAccountId, receiverAccountId) .setTransactionId(TransactionId::generate(spenderAccountId)) @@ -282,7 +281,7 @@ int main(int argc, char** argv) << std::endl; // Attempt to transfer NFT2 using the spender's now-deleted allowance. This should not work. - std::cout << "Transfer NFT " << nft2.getSerialNum() << " with no allowance (should return " + std::cout << "Transfer NFT " << nft2.mSerialNum << " with no allowance (should return " << gStatusToString.at(Status::SPENDER_DOES_NOT_HAVE_ALLOWANCE) << "): " << gStatusToString.at(TransferTransaction() .addApprovedNftTransfer(nft2, operatorAccountId, receiverAccountId) diff --git a/sdk/main/CMakeLists.txt b/sdk/main/CMakeLists.txt index 3fa12fce5..55ac0cfc5 100644 --- a/sdk/main/CMakeLists.txt +++ b/sdk/main/CMakeLists.txt @@ -142,6 +142,7 @@ add_library(${PROJECT_NAME} STATIC src/impl/BaseNodeAddress.cc src/impl/DerivationPathUtils.cc src/impl/DurationConverter.cc + src/impl/EntityIdHelper.cc src/impl/HederaCertificateVerifier.cc src/impl/HexConverter.cc src/impl/MirrorNetwork.cc diff --git a/sdk/main/include/AccountAllowanceApproveTransaction.h b/sdk/main/include/AccountAllowanceApproveTransaction.h index 430547473..f611ecca9 100644 --- a/sdk/main/include/AccountAllowanceApproveTransaction.h +++ b/sdk/main/include/AccountAllowanceApproveTransaction.h @@ -204,6 +204,15 @@ class AccountAllowanceApproveTransaction : public Transaction& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this AccountAllowanceApproveTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This AccountAllowanceApproveTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the AccountAllowanceApproveTransaction protobuf representation to the * Transaction protobuf object. diff --git a/sdk/main/include/AccountAllowanceDeleteTransaction.h b/sdk/main/include/AccountAllowanceDeleteTransaction.h index f86a6b46a..2f7366f94 100644 --- a/sdk/main/include/AccountAllowanceDeleteTransaction.h +++ b/sdk/main/include/AccountAllowanceDeleteTransaction.h @@ -105,6 +105,15 @@ class AccountAllowanceDeleteTransaction : public Transaction& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this AccountAllowanceDeleteTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This AccountAllowanceDeleteTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the AccountAllowanceDeleteTransaction protobuf representation to the * Transaction protobuf object. diff --git a/sdk/main/include/AccountBalanceQuery.h b/sdk/main/include/AccountBalanceQuery.h index ae036f7e4..c5946fde7 100644 --- a/sdk/main/include/AccountBalanceQuery.h +++ b/sdk/main/include/AccountBalanceQuery.h @@ -99,6 +99,15 @@ class AccountBalanceQuery : public Query const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::Response* response) const override; + + /** + * Derived from Query. Verify that all the checksums in this AccountBalanceQuery are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This AccountBalanceQuery's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Query. Build a Query protobuf object with this AccountBalanceQuery's data, with the input QueryHeader * protobuf object. diff --git a/sdk/main/include/AccountCreateTransaction.h b/sdk/main/include/AccountCreateTransaction.h index 0bdcd61f0..a33589d85 100644 --- a/sdk/main/include/AccountCreateTransaction.h +++ b/sdk/main/include/AccountCreateTransaction.h @@ -282,6 +282,15 @@ class AccountCreateTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this AccountCreateTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This AccountCreateTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the AccountCreateTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/AccountDeleteTransaction.h b/sdk/main/include/AccountDeleteTransaction.h index 60be33f70..23ada0d08 100644 --- a/sdk/main/include/AccountDeleteTransaction.h +++ b/sdk/main/include/AccountDeleteTransaction.h @@ -113,6 +113,15 @@ class AccountDeleteTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this AccountDeleteTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This AccountDeleteTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the AccountDeleteTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/AccountId.h b/sdk/main/include/AccountId.h index d3c6a0b2b..e853a4dcf 100644 --- a/sdk/main/include/AccountId.h +++ b/sdk/main/include/AccountId.h @@ -23,15 +23,23 @@ #include "EvmAddress.h" #include "PublicKey.h" +#include #include #include #include +#include +#include namespace proto { class AccountID; } +namespace Hedera +{ +class Client; +} + namespace Hedera { /** @@ -45,56 +53,51 @@ class AccountId /** * Construct with an account number. * - * @param num The desired account number. - * @throws std::invalid_argument If the account number is too big (max value is std::numeric_limits::max()). + * @param num The account number. */ - explicit AccountId(const uint64_t& num); + explicit AccountId(uint64_t num); /** - * Construct with an account alias. + * Construct with a PublicKey alias. * - * @param alias The desired public key account alias. + * @param alias The PublicKey alias. */ explicit AccountId(const std::shared_ptr& alias); /** - * Construct with an EVM address. + * Construct with an EVM address alias. * - * @param address The desired EVM address. + * @param address The EVM address alias. */ explicit AccountId(const EvmAddress& address); /** - * Construct with a shard, realm, and account number. + * Construct with a shard, realm, an account number, and optionally a checksum. * - * @param shard The desired shard number. - * @param realm The desired realm number. - * @param num The desired account number. - * @throws std::invalid_argument If any number is too big (max value is std::numeric_limits::max()). + * @param shard The shard number. + * @param realm The realm number. + * @param num The account number. + * @param checksum The checksum. */ - explicit AccountId(const uint64_t& shard, const uint64_t& realm, const uint64_t& num); + explicit AccountId(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum = ""); /** - * Construct with shard and realm numbers, and an account alias. + * Construct with shard and realm numbers, and a PublicKey alias. * - * @param shard The desired shard number. - * @param realm The desired realm number. - * @param alias The desired account alias. - * @throws std::invalid_argument If the shard or realm number is too big (max value is - * std::numeric_limits::max()). + * @param shard The shard number. + * @param realm The realm number. + * @param alias The PublicKey alias. */ - explicit AccountId(const uint64_t& shard, const uint64_t& realm, const std::shared_ptr& alias); + explicit AccountId(uint64_t shard, uint64_t realm, const std::shared_ptr& alias); /** - * Construct with shard and realm numbers, and an EVM address. + * Construct with shard and realm numbers, and an EVM address alias. * - * @param shard The desired shard number. - * @param realm The desired realm number. - * @param address The desired EVM address. - * @throws std::invalid_argument If the shard or realm number is too big (max value is - * std::numeric_limits::max()). + * @param shard The shard number. + * @param realm The realm number. + * @param address The EVM address alias. */ - explicit AccountId(const uint64_t& shard, const uint64_t& realm, const EvmAddress& address); + explicit AccountId(uint64_t shard, uint64_t realm, const EvmAddress& address); /** * Compare this AccountId to another AccountId and determine if they represent the same account. @@ -142,13 +145,39 @@ class AccountId uint64_t realm = 0ULL); /** - * Create an AccountId object from an AccountID protobuf object. + * Construct an AccountId from a Solidity address. + * + * @param address The Solidity address from which to create an AccountId, in a string. + * @return The constructed AccountId object. + * @throws std::invalid_argument If a Solidity address cannot be realized from the input string. + */ + [[nodiscard]] static AccountId fromSolidityAddress(std::string_view address); + + /** + * Construct an AccountId object from an AccountID protobuf object. * * @param proto The AccountID protobuf object from which to create an AccountId object. * @return The constructed AccountId object. */ [[nodiscard]] static AccountId fromProtobuf(const proto::AccountID& proto); + /** + * Construct an AccountId object from a representative byte array. + * + * @param bytes The byte array from which to construct an AccountId object. + * @return The constructed AccountId object. + */ + [[nodiscard]] static AccountId fromBytes(const std::vector& bytes); + + /** + * Verify the checksum of this AccountId using the input Client's network. Does nothing if this AccountId does not use + * an account number (i.e. it contains a PublicKey or EvmAddress alias). + * + * @param client The Client with which to validate this AccountId's checksum. + * @throws BadEntityException If the checksum of this AccountId is invalid. + */ + void validateChecksum(const Client& client) const; + /** * Construct an AccountID protobuf object from this AccountId object. * @@ -157,19 +186,43 @@ class AccountId [[nodiscard]] std::unique_ptr toProtobuf() const; /** - * Get a Solidity address representation of this AccountId (Long-Zero address). + * Get the Solidity address representation of this AccountId (Long-Zero address form). * - * @return A Solidity address representation of this AccountId. + * @return The Solidity address representation of this AccountId. + * @throws IllegalStateException If this AccountId contains an alias. */ [[nodiscard]] std::string toSolidityAddress() const; /** - * Get a string representation of this AccountId object with the form "..". + * Get the string representation of this AccountId object. * - * @return A string representation of this AccountId. + * @return The string representation of this AccountId. */ [[nodiscard]] std::string toString() const; + /** + * Get the string representation of this AccountId object with the checksum. + * + * @param client The Client with which to generate the checksum. + * @return The string representation of this AccountId object with the checksum. + * @throws IllegalStateException If this AccountId contains an alias. + */ + [[nodiscard]] std::string toStringWithChecksum([[maybe_unused]] const Client& client) const; + + /** + * Get a byte array representation of this AccountId object. + * + * @return A byte array representation of this AccountId object. + */ + [[nodiscard]] std::vector toBytes() const; + + /** + * Get the checksum of this AccountId. + * + * @return The checksum of this AccountId. + */ + [[nodiscard]] inline std::string getChecksum() const { return mChecksum; } + /** * The shard number. */ @@ -210,13 +263,9 @@ class AccountId private: /** - * Check if the shard, realm, or account numbers (respectively) are too big. - * - * @throws std::invalid_argument If the shard, realm, or account number (respectively) is too big. + * The checksum of this AccountId. */ - void checkShardNum() const; - void checkRealmNum() const; - void checkAccountNum() const; + mutable std::string mChecksum; }; } // namespace Hedera diff --git a/sdk/main/include/AccountInfoQuery.h b/sdk/main/include/AccountInfoQuery.h index d78ca069a..8fcf08f96 100644 --- a/sdk/main/include/AccountInfoQuery.h +++ b/sdk/main/include/AccountInfoQuery.h @@ -77,6 +77,15 @@ class AccountInfoQuery : public Query const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::Response* response) const override; + + /** + * Derived from Query. Verify that all the checksums in this AccountInfoQuery are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This AccountInfoQuery's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Query. Build a Query protobuf object with this AccountInfoQuery's data, with the input QueryHeader * protobuf object. diff --git a/sdk/main/include/AccountRecordsQuery.h b/sdk/main/include/AccountRecordsQuery.h index 42242ab79..c983c0374 100644 --- a/sdk/main/include/AccountRecordsQuery.h +++ b/sdk/main/include/AccountRecordsQuery.h @@ -78,6 +78,15 @@ class AccountRecordsQuery : public Query const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::Response* response) const override; + + /** + * Derived from Query. Verify that all the checksums in this AccountRecordsQuery are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This AccountRecordsQuery's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Query. Build a Query protobuf object with this AccountRecordsQuery's data, with the input QueryHeader * protobuf object. diff --git a/sdk/main/include/AccountStakersQuery.h b/sdk/main/include/AccountStakersQuery.h index 84574e7e8..e4b2f8784 100644 --- a/sdk/main/include/AccountStakersQuery.h +++ b/sdk/main/include/AccountStakersQuery.h @@ -74,6 +74,15 @@ class AccountStakersQuery : public Query const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::Response* response) const override; + + /** + * Derived from Query. Verify that all the checksums in this AccountStakersQuery are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This AccountStakersQuery's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Query. Build a Query protobuf object with this AccountStakersQuery's data, with the input QueryHeader * protobuf object. diff --git a/sdk/main/include/AccountUpdateTransaction.h b/sdk/main/include/AccountUpdateTransaction.h index db777b51e..b65fe950c 100644 --- a/sdk/main/include/AccountUpdateTransaction.h +++ b/sdk/main/include/AccountUpdateTransaction.h @@ -265,6 +265,15 @@ class AccountUpdateTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this AccountUpdateTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This AccountUpdateTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the AccountUpdateTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/Client.h b/sdk/main/include/Client.h index bb283a55d..79352779f 100644 --- a/sdk/main/include/Client.h +++ b/sdk/main/include/Client.h @@ -36,6 +36,7 @@ class Network; } class AccountId; class Hbar; +class LedgerId; class PrivateKey; class PublicKey; } @@ -207,6 +208,24 @@ class Client */ Client& setNetworkUpdatePeriod(const std::chrono::duration& update); + /** + * Set the automatic entity checksum validation policy. + * + * @param validate \c TRUE if this Client should validate entity checksums when submitting Executables, otherwise \c + * FALSE. + * @return A reference to this Client with the newly-set automatic entity checksum validation policy. + */ + Client& setAutoValidateChecksums(bool validate); + + /** + * Set the ID of the ledger of this Client's Network. Useful when constructing a Network which is a subset of an + * existing known network. Does nothing if the Client's Network is not yet initialized. + * + * @param ledgerId The LedgerId to set. + * @return A reference to this Client with the newly-set ledger ID. + */ + Client& setLedgerId(const LedgerId& ledgerId); + /** * Get a pointer to the Network this Client is using to communicate with consensus nodes. * @@ -299,6 +318,21 @@ class Client */ [[nodiscard]] std::chrono::duration getNetworkUpdatePeriod() const; + /** + * Is automatic entity checksum validation turned on for this Client? + * + * @return \c TRUE if automatic entity checksum validation is turned on, otherwise \c FALSE. + */ + [[nodiscard]] bool isAutoValidateChecksumsEnabled() const; + + /** + * Get the ID of the ledger on which this Client's Network is running. + * + * @returns The ID of the ledger on which this Client's Network is running. + * @throws UninitializedException If this Client does not have a Network initialized. + */ + [[nodiscard]] LedgerId getLedgerId() const; + /** * Get a pointer to the MirrorNetwork being used by this client. * diff --git a/sdk/main/include/ContractByteCodeQuery.h b/sdk/main/include/ContractByteCodeQuery.h index f52fdc4f9..c21f1e48b 100644 --- a/sdk/main/include/ContractByteCodeQuery.h +++ b/sdk/main/include/ContractByteCodeQuery.h @@ -75,6 +75,15 @@ class ContractByteCodeQuery : public Query& node, const std::chrono::system_clock::time_point& deadline, proto::Response* response) const override; + + /** + * Derived from Query. Verify that all the checksums in this ContractByteCodeQuery are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This ContractByteCodeQuery's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Query. Build a Query protobuf object with this ContractByteCodeQuery's data, with the input * QueryHeader protobuf object. diff --git a/sdk/main/include/ContractCallQuery.h b/sdk/main/include/ContractCallQuery.h index e10bd6948..78adef261 100644 --- a/sdk/main/include/ContractCallQuery.h +++ b/sdk/main/include/ContractCallQuery.h @@ -146,6 +146,15 @@ class ContractCallQuery : public Query& node, const std::chrono::system_clock::time_point& deadline, proto::Response* response) const override; + + /** + * Derived from Query. Verify that all the checksums in this ContractCallQuery are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This ContractCallQuery's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Query. Build a Query protobuf object with this ContractCallQuery's data, with the input QueryHeader * protobuf object. diff --git a/sdk/main/include/ContractCreateTransaction.h b/sdk/main/include/ContractCreateTransaction.h index bd66c7759..500f2ebdc 100644 --- a/sdk/main/include/ContractCreateTransaction.h +++ b/sdk/main/include/ContractCreateTransaction.h @@ -366,6 +366,15 @@ class ContractCreateTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this ContractCreateTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This ContractCreateTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the ContractCreateTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/ContractDeleteTransaction.h b/sdk/main/include/ContractDeleteTransaction.h index edb451435..bd59bc84c 100644 --- a/sdk/main/include/ContractDeleteTransaction.h +++ b/sdk/main/include/ContractDeleteTransaction.h @@ -138,6 +138,15 @@ class ContractDeleteTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this ContractDeleteTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This ContractDeleteTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the ContractDeleteTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/ContractExecuteTransaction.h b/sdk/main/include/ContractExecuteTransaction.h index 8f47ba236..067a81f92 100644 --- a/sdk/main/include/ContractExecuteTransaction.h +++ b/sdk/main/include/ContractExecuteTransaction.h @@ -162,6 +162,15 @@ class ContractExecuteTransaction : public Transaction& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this ContractExecuteTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This ContractExecuteTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the ContractExecuteTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/ContractId.h b/sdk/main/include/ContractId.h index 4bfebb990..7d61eac8f 100644 --- a/sdk/main/include/ContractId.h +++ b/sdk/main/include/ContractId.h @@ -23,14 +23,23 @@ #include "EvmAddress.h" #include "Key.h" +#include #include #include +#include +#include +#include namespace proto { class ContractID; } +namespace Hedera +{ +class Client; +} + namespace Hedera { /** @@ -44,38 +53,35 @@ class ContractId : public Key /** * Construct with a contract number. * - * @param num The desired contract number. - * @throws std::invalid_argument If the contract number is too big (max value is std::numeric_limits::max()). + * @param num The contract number. */ - explicit ContractId(const uint64_t& num); + explicit ContractId(uint64_t num); /** * Construct with an EVM address. * - * @param address The desired EVM address. + * @param address The EVM address. */ explicit ContractId(const EvmAddress& address); /** - * Construct with a shard, realm, and contract number. + * Construct with a shard, realm, a contract number, and optionally a checksum. * - * @param shard The desired shard number. - * @param realm The desired realm number. - * @param num The desired contract number. - * @throws std::invalid_argument If any number is too big (max value is std::numeric_limits::max()). + * @param shard The shard number. + * @param realm The realm number. + * @param num The contract number. + * @param checksum The checksum. */ - explicit ContractId(const uint64_t& shard, const uint64_t& realm, const uint64_t& num); + explicit ContractId(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum = ""); /** * Construct with shard and realm numbers, and an EVM address. * - * @param shard The desired shard number. - * @param realm The desired realm number. - * @param address The desired EVM address. - * @throws std::invalid_argument If the shard or realm number is too big (max value is - * std::numeric_limits::max()). + * @param shard The shard number. + * @param realm The realm number. + * @param address The EVM address. */ - explicit ContractId(const uint64_t& shard, const uint64_t& realm, const EvmAddress& address); + explicit ContractId(uint64_t shard, uint64_t realm, const EvmAddress& address); /** * Compare this ContractId to another ContractId and determine if they represent the same contract. @@ -86,115 +92,133 @@ class ContractId : public Key bool operator==(const ContractId& other) const; /** - * Construct an ContractId object from an ContractID protobuf object. + * Construct a ContractId object from a string of the form "..". can be the contract number + * or a stringified EVM address. * - * @param proto The ContractID protobuf object from which to create an ContractId object. + * @param id The contract ID string from which to construct. * @return The constructed ContractId object. + * @throws std::invalid_argument If the input string is malformed or the type of cannot be determined. */ - [[nodiscard]] static ContractId fromProtobuf(const proto::ContractID& id); + [[nodiscard]] static ContractId fromString(std::string_view id); /** - * Derived from Key. Create a clone of this ContractId object. + * Construct a ContractId object from a string that represents an EvmAddress and, optionally, a shard and realm + * number. * - * @return A pointer to the created clone of this ContractId. + * @param evmAddress The string that represents an EvmAddress. + * @param shard The shard number. + * @param realm The realm number. + * @return The constructed ContractId object. + * @throws std::invalid_argument If the input string is malformed. + * @throws OpenSSLException If OpenSSL is unable to convert the string to a byte array. */ - [[nodiscard]] std::unique_ptr clone() const override; + [[nodiscard]] static ContractId fromEvmAddress(std::string_view evmAddress, + uint64_t shard = 0ULL, + uint64_t realm = 0ULL); /** - * Derived from Key. Construct a Key protobuf object from this ContractId object. + * Construct a ContractId object from an EvmAddress object and, optionally, a shard and realm number. * - * @return A pointer to the created Key protobuf object filled with this ContractId object's data. + * @param evmAddress The EvmAddress from which to construct a ContractId. + * @param shard The shard number. + * @param realm The realm number. + * @return The constructed ContractId object. */ - [[nodiscard]] std::unique_ptr toProtobufKey() const override; + [[nodiscard]] static ContractId fromEvmAddress(const EvmAddress& evmAddress, + uint64_t shard = 0ULL, + uint64_t realm = 0ULL); /** - * Construct a ContractID protobuf object from this ContractId object. + * Construct a ContractId from a Solidity address. * - * @return A pointer to the created ContractID protobuf object filled with this ContractId object's data. + * @param address The Solidity address from which to create a ContractId, as a string. + * @return The constructed ContractId object. + * @throws std::invalid_argument If a Solidity address cannot be realized from the input string. */ - [[nodiscard]] std::unique_ptr toProtobuf() const; + [[nodiscard]] static ContractId fromSolidityAddress(std::string_view address); + + /** + * Construct an ContractId object from an ContractID protobuf object. + * + * @param proto The ContractID protobuf object from which to create an ContractId object. + * @return The constructed ContractId object. + */ + [[nodiscard]] static ContractId fromProtobuf(const proto::ContractID& id); /** - * Get a string representation of this ContractId object with the form "..". + * Construct a ContractId object from a representative byte array. * - * @return A string representation of this ContractId. + * @param bytes The byte array from which to construct a ContractId object. + * @return The constructed ContractId object. */ - [[nodiscard]] std::string toString() const; + [[nodiscard]] static ContractId fromBytes(const std::vector& bytes); /** - * Set the shard number. + * Derived from Key. Create a clone of this ContractId object. * - * @param num The desired shard number to set. - * @return A reference to this ContractId object with the newly-set shard number. - * @throws std::invalid_argument If the shard number is too big (max value is std::numeric_limits::max()). + * @return A pointer to the created clone of this ContractId. */ - ContractId& setShardNum(const uint64_t& num); + [[nodiscard]] std::unique_ptr clone() const override; /** - * Set the realm number. + * Derived from Key. Construct a Key protobuf object from this ContractId object. * - * @param num The realm number to set. - * @return A reference to this ContractId object with the newly-set realm number. - * @throws std::invalid_argument If the realm number is too big (max value is std::numeric_limits::max()). + * @return A pointer to the created Key protobuf object filled with this ContractId object's data. */ - ContractId& setRealmNum(const uint64_t& num); + [[nodiscard]] std::unique_ptr toProtobufKey() const override; /** - * Set the contract number. This is mutually exclusive with mEvmAddress, and will reset the value of mEvmAddress if is - * set. + * Derived from Key. Get a byte array representation of this ContractId object. * - * @param num The contract number to set. - * @return A reference to this ContractId object with the newly-set contract number. - * @throws std::invalid_argument If the contract number is too big (max value is std::numeric_limits::max()). + * @return A byte array representation of this ContractId object. */ - ContractId& setContractNum(const uint64_t& num); + [[nodiscard]] std::vector toBytes() const override; /** - * Set the contract EVM address. This is mutually exclusive with mContractNum, and will reset the value of the - * mContractNum is is set. + * Verify the checksum of this ContractId using the input Client's network. Does nothing if this ContractId does not + * use a contract number (i.e. it contains an EvmAddress). * - * @param address The EVM address to set. - * @return A reference to this ContractId object with the newly-set contract EVM address. + * @param client The Client with which to validate this ContractId's checksum. + * @throws BadEntityException If the checksum of this ContractId is invalid. */ - ContractId& setEvmAddress(const EvmAddress& address); + void validateChecksum(const Client& client) const; /** - * Get the shard number. + * Construct a ContractID protobuf object from this ContractId object. * - * @return The shard number. + * @return A pointer to the created ContractID protobuf object filled with this ContractId object's data. */ - [[nodiscard]] inline uint64_t getShardNum() const { return mShardNum; } + [[nodiscard]] std::unique_ptr toProtobuf() const; /** - * Get the realm number. + * Get the Solidity address representation of this ContractId (Long-Zero address form). * - * @return The realm number. + * @return The Solidity address representation of this ContractId. */ - [[nodiscard]] inline uint64_t getRealmNum() const { return mRealmNum; } + [[nodiscard]] std::string toSolidityAddress() const; /** - * Get the account number. + * Get the string representation of this ContractId object. * - * @return The account number. + * @return The string representation of this ContractId. */ - [[nodiscard]] inline std::optional getContractNum() const { return mContractNum; } + [[nodiscard]] std::string toString() const; /** - * Get the contract EVM address. + * Get the string representation of this ContractId object with the checksum. * - * @return The contract EVM address. + * @param client The Client with which to generate the checksum. + * @return The string representation of this ContractId object with the checksum. + * @throws IllegalStateException If this ContractId contains an alias. */ - [[nodiscard]] inline std::optional getEvmAddress() const { return mEvmAddress; } + [[nodiscard]] std::string toStringWithChecksum([[maybe_unused]] const Client& client) const; -private: /** - * Check if the shard, realm, or contract numbers (respectively) are too big. + * Get the checksum of this ContractId. * - * @throws std::invalid_argument If the shard, realm, or contract number (respectively) is too big. + * @return The checksum of this ContractId. */ - void checkShardNum() const; - void checkRealmNum() const; - void checkContractNum() const; + [[nodiscard]] inline std::string getChecksum() const { return mChecksum; } /** * The shard number. @@ -225,6 +249,12 @@ class ContractId : public Key * (Please do note that CREATE2 contracts can also be referenced by the three-part EVM address described above.) */ std::optional mEvmAddress; + +private: + /** + * The checksum of this ContractId. + */ + mutable std::string mChecksum; }; } // namespace Hedera diff --git a/sdk/main/include/ContractInfoQuery.h b/sdk/main/include/ContractInfoQuery.h index 51278c7c5..9274d690f 100644 --- a/sdk/main/include/ContractInfoQuery.h +++ b/sdk/main/include/ContractInfoQuery.h @@ -79,6 +79,15 @@ class ContractInfoQuery : public Query const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::Response* response) const override; + + /** + * Derived from Query. Verify that all the checksums in this ContractInfoQuery are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This ContractInfoQuery's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Query. Build a Query protobuf object with this ContractInfoQuery's data, with the input QueryHeader * protobuf object. diff --git a/sdk/main/include/ContractUpdateTransaction.h b/sdk/main/include/ContractUpdateTransaction.h index 0f57fe9e8..0eccb1e6f 100644 --- a/sdk/main/include/ContractUpdateTransaction.h +++ b/sdk/main/include/ContractUpdateTransaction.h @@ -276,6 +276,15 @@ class ContractUpdateTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this ContractUpdateTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This ContractUpdateTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the ContractUpdateTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/CustomFee.h b/sdk/main/include/CustomFee.h index 9db0bc8f6..510ab7754 100644 --- a/sdk/main/include/CustomFee.h +++ b/sdk/main/include/CustomFee.h @@ -29,6 +29,11 @@ namespace proto class CustomFee; } +namespace Hedera +{ +class Client; +} + namespace Hedera { /** @@ -63,6 +68,14 @@ class CustomFee */ [[nodiscard]] virtual std::unique_ptr toProtobuf() const = 0; + /** + * Verify the checksums of all the entities involved in this CustomFee. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This CustomFee's checksums are not valid. + */ + virtual void validateChecksums(const Client& client) const; + /** * Get the ID of the desired fee collector account. * diff --git a/sdk/main/include/CustomFixedFee.h b/sdk/main/include/CustomFixedFee.h index 6e6f9eae4..c594f23f5 100644 --- a/sdk/main/include/CustomFixedFee.h +++ b/sdk/main/include/CustomFixedFee.h @@ -63,6 +63,14 @@ class CustomFixedFee : public CustomFeeBase */ [[nodiscard]] std::unique_ptr toProtobuf() const override; + /** + * Derived from CustomFee. Verify the checksums of all the entities involved in this CustomFixedFee. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This CustomFixedFee's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Construct a FixedFee protobuf object from this CustomFixedFee object. * diff --git a/sdk/main/include/DelegateContractId.h b/sdk/main/include/DelegateContractId.h index 5f45caad5..b057098f9 100644 --- a/sdk/main/include/DelegateContractId.h +++ b/sdk/main/include/DelegateContractId.h @@ -22,6 +22,8 @@ #include "ContractId.h" +#include + namespace proto { class ContractID; @@ -43,20 +45,19 @@ class DelegateContractId : public ContractId /** * Construct with a contract number. * - * @param num The desired contract number. - * @throws std::invalid_argument If the contract number is too big (max value is std::numeric_limits::max()). + * @param num The contract number. */ - explicit DelegateContractId(const uint64_t& num); + explicit DelegateContractId(uint64_t num); /** - * Construct with a shard, realm, and contract number. + * Construct with a shard, realm, a contract number, and optionally a checksum. * - * @param shard The desired shard number. - * @param realm The desired realm number. - * @param num The desired contract number. - * @throws std::invalid_argument If any number is too big (max value is std::numeric_limits::max()). + * @param shard The shard number. + * @param realm The realm number. + * @param num The account number. + * @param checksum The checksum. */ - explicit DelegateContractId(const uint64_t& shard, const uint64_t& realm, const uint64_t& num); + explicit DelegateContractId(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum = ""); /** * Compare this DelegateContractId to another DelegateContractId and determine if they represent the same contract. @@ -67,13 +68,22 @@ class DelegateContractId : public ContractId [[nodiscard]] bool operator==(const DelegateContractId& other) const; /** - * Construct an DelegateContractId object from a string of the form "..". + * Construct a DelegateContractId object from a string of the form "..". * - * @param id The account ID string from which to construct. + * @param id The contract ID string from which to construct. * @return The constructed DelegateContractId object. */ [[nodiscard]] static DelegateContractId fromString(std::string_view id); + /** + * Construct a DelegateContractId from a Solidity address. + * + * @param address The Solidity address from which to create a DelegateContractId, as a string. + * @return The constructed DelegateContractId object. + * @throws std::invalid_argument If a Solidity address cannot be realized from the input string. + */ + [[nodiscard]] static DelegateContractId fromSolidityAddress(std::string_view address); + /** * Construct an DelegateContractId object from an DelegateContractId protobuf object. * @@ -82,6 +92,14 @@ class DelegateContractId : public ContractId */ [[nodiscard]] static DelegateContractId fromProtobuf(const proto::ContractID& id); + /** + * Construct a DelegateContractId object from a representative byte array. + * + * @param bytes The byte array from which to construct a DelegateContractId object. + * @return The constructed ContractId object. + */ + [[nodiscard]] static DelegateContractId fromBytes(const std::vector& bytes); + /** * Derived from Key. Create a clone of this DelegateContractId object. * diff --git a/sdk/main/include/EthereumTransaction.h b/sdk/main/include/EthereumTransaction.h index 52d1298bc..c5345c11d 100644 --- a/sdk/main/include/EthereumTransaction.h +++ b/sdk/main/include/EthereumTransaction.h @@ -134,6 +134,15 @@ class EthereumTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this EthereumTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This EthereumTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the EthereumTransaction protobuf representation to the Transaction protobuf * object. diff --git a/sdk/main/include/FileAppendTransaction.h b/sdk/main/include/FileAppendTransaction.h index 00066699c..eebb79664 100644 --- a/sdk/main/include/FileAppendTransaction.h +++ b/sdk/main/include/FileAppendTransaction.h @@ -123,6 +123,15 @@ class FileAppendTransaction : public ChunkedTransaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this FileAppendTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This FileAppendTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add this FileAppendTransaction's protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/FileContentsQuery.h b/sdk/main/include/FileContentsQuery.h index 4b4d05aa8..c15d7a3c3 100644 --- a/sdk/main/include/FileContentsQuery.h +++ b/sdk/main/include/FileContentsQuery.h @@ -78,6 +78,15 @@ class FileContentsQuery : public Query const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::Response* response) const override; + + /** + * Derived from Query. Verify that all the checksums in this FileContentsQuery are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This FileContentsQuery's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Query. Build a Query protobuf object with this FileContentsQuery's data, with the input QueryHeader * protobuf object. diff --git a/sdk/main/include/FileCreateTransaction.h b/sdk/main/include/FileCreateTransaction.h index b69ea63ea..a78d47b75 100644 --- a/sdk/main/include/FileCreateTransaction.h +++ b/sdk/main/include/FileCreateTransaction.h @@ -161,6 +161,15 @@ class FileCreateTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this FileCreateTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This FileCreateTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the FileCreateTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/FileDeleteTransaction.h b/sdk/main/include/FileDeleteTransaction.h index fd0cc28e2..ca85c2a0b 100644 --- a/sdk/main/include/FileDeleteTransaction.h +++ b/sdk/main/include/FileDeleteTransaction.h @@ -95,6 +95,15 @@ class FileDeleteTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this FileDeleteTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This FileDeleteTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the FileDeleteTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/FileId.h b/sdk/main/include/FileId.h index def9382cb..6f1b2e706 100644 --- a/sdk/main/include/FileId.h +++ b/sdk/main/include/FileId.h @@ -20,15 +20,22 @@ #ifndef HEDERA_SDK_CPP_FILE_ID_H_ #define HEDERA_SDK_CPP_FILE_ID_H_ +#include #include #include #include +#include namespace proto { class FileID; } +namespace Hedera +{ +class Client; +} + namespace Hedera { /** @@ -57,20 +64,19 @@ class FileId /** * Construct with a file number. * - * @param num The desired file number. - * @throws std::invalid_argument If the file number is too big (max value is std::numeric_limits::max()). + * @param num The file number. */ - explicit FileId(const uint64_t& num); + explicit FileId(uint64_t num); /** - * Construct with a shard, realm, and file number. + * Construct with a shard, realm, a file number, and optionally a checksum. * - * @param shard The desired shard number. - * @param realm The desired realm number. - * @param num The desired file number. - * @throws std::invalid_argument If any number is too big (max value is std::numeric_limits::max()). + * @param shard The shard number. + * @param realm The realm number. + * @param num The file number. + * @param checksum The checksum. */ - explicit FileId(const uint64_t& shard, const uint64_t& realm, const uint64_t& num); + explicit FileId(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum = ""); /** * Compare this FileId to another FileId and determine if they represent the same file. @@ -81,7 +87,7 @@ class FileId bool operator==(const FileId& other) const; /** - * Construct an FileId object from a string of the form "..". + * Construct a FileId object from a string of the form "..". * * @param id The file ID string from which to construct. * @return The constructed FileId object. @@ -90,93 +96,80 @@ class FileId [[nodiscard]] static FileId fromString(std::string_view id); /** - * Create an FileId object from an FileId protobuf object. + * Construct a FileId from a Solidity address. * - * @param proto The FileId protobuf object from which to create an FileId object. + * @param address The Solidity address from which to create a FileId, as a string. * @return The constructed FileId object. + * @throws std::invalid_argument If a Solidity address cannot be realized from the input string. */ - [[nodiscard]] static FileId fromProtobuf(const proto::FileID& proto); - - /** - * Construct an FileId protobuf object from this FileId object. - * - * @return A pointer to the created FileId protobuf object filled with this FileId object's data. - */ - [[nodiscard]] std::unique_ptr toProtobuf() const; + [[nodiscard]] static FileId fromSolidityAddress(std::string_view address); /** - * Get a string representation of this FileId object with the form "..". + * Construct a FileId from a FileId protobuf object. * - * @return A string representation of this FileId. + * @param proto The FileId protobuf object from which to create a FileId object. + * @return The constructed FileId object. */ - [[nodiscard]] std::string toString() const; + [[nodiscard]] static FileId fromProtobuf(const proto::FileID& proto); /** - * Set the shard number. + * Construct a FileId object from a representative byte array. * - * @param num The desired shard number to set. - * @return A reference to this FileId object with the newly-set shard number. - * @throws std::invalid_argument If the shard number is too big (max value is std::numeric_limits::max()). + * @param bytes The byte array from which to construct a FileId object. + * @return The constructed FileId object. */ - FileId& setShardNum(const uint64_t& num); + [[nodiscard]] static FileId fromBytes(const std::vector& bytes); /** - * Set the realm number. + * Verify the checksum of this FileId using the input Client's network. * - * @param num The realm number to set. - * @return A reference to this FileId object with the newly-set realm number. - * @throws std::invalid_argument If the realm number is too big (max value is std::numeric_limits::max()). + * @param client The Client with which to validate this FileId's checksum. + * @throws BadEntityException If the checksum of this FileId is invalid. */ - FileId& setRealmNum(const uint64_t& num); + void validateChecksum(const Client& client) const; /** - * Set the file number. + * Construct a FileID protobuf object from this FileId object. * - * @param num The file number to set. - * @return A reference to this FileId object with the newly-set file number. - * @throws std::invalid_argument If the account number is too big (max value is std::numeric_limits::max()). + * @return A pointer to the created FileId protobuf object filled with this FileId object's data. */ - FileId& setFileNum(const uint64_t& num); + [[nodiscard]] std::unique_ptr toProtobuf() const; /** - * Get the shard number. + * Get the Solidity address representation of this FileId (Long-Zero address form). * - * @return The shard number. + * @return The Solidity address representation of this FileId. */ - [[nodiscard]] inline uint64_t getShardNum() const { return mShardNum; } + [[nodiscard]] std::string toSolidityAddress() const; /** - * Get the realm number. + * Get the string representation of this FileId object. * - * @return The realm number. + * @return The string representation of this FileId. */ - [[nodiscard]] inline uint64_t getRealmNum() const { return mRealmNum; } + [[nodiscard]] std::string toString() const; /** - * Get the file number. + * Get the string representation of this FileId object with the checksum. * - * @return The file number. + * @param client The Client with which to generate the checksum. + * @return The string representation of this FileId object with the checksum. */ - [[nodiscard]] inline uint64_t getFileNum() const { return mFileNum; } + [[nodiscard]] std::string toStringWithChecksum([[maybe_unused]] const Client& client) const; -private: /** - * Parse the input string and attempt to put it into the input number. + * Get a byte array representation of this FileId object. * - * @param str The string to parse. - * @param num The number in which to put the parsed string. - * @throws std::invalid_argument If unable to parse the string and put it into the input number. + * @return A byte array representation of this FileId object. */ - static void parseNum(std::string_view str, uint64_t& num); + [[nodiscard]] std::vector toBytes() const; /** - * Check if the shard, realm, or file numbers (respectively) are too big. + * Get the checksum of this ContractId. * - * @throws std::invalid_argument If the shard, realm, or file number (respectively) is too big. + * @return The checksum of this ContractId. */ - void checkShardNum() const; - void checkRealmNum() const; - void checkFileNum() const; + [[nodiscard]] inline std::string getChecksum() const { return mChecksum; } /** * The shard number. @@ -192,6 +185,12 @@ class FileId * The file number. */ uint64_t mFileNum = 0ULL; + +private: + /** + * The checksum of this FileIds. + */ + mutable std::string mChecksum; }; } // namespace Hedera diff --git a/sdk/main/include/FileInfoQuery.h b/sdk/main/include/FileInfoQuery.h index d7b9ad033..a47b24112 100644 --- a/sdk/main/include/FileInfoQuery.h +++ b/sdk/main/include/FileInfoQuery.h @@ -76,6 +76,15 @@ class FileInfoQuery : public Query const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::Response* response) const override; + + /** + * Derived from Query. Verify that all the checksums in this FileInfoQuery are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This FileInfoQuery's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Query. Build a Query protobuf object with this FileInfoQuery's data, with the input QueryHeader * protobuf object. diff --git a/sdk/main/include/FileUpdateTransaction.h b/sdk/main/include/FileUpdateTransaction.h index ca4891e86..9f11bdbb0 100644 --- a/sdk/main/include/FileUpdateTransaction.h +++ b/sdk/main/include/FileUpdateTransaction.h @@ -176,6 +176,15 @@ class FileUpdateTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this FileUpdateTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This FileUpdateTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the FileUpdateTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/FreezeTransaction.h b/sdk/main/include/FreezeTransaction.h index 1e1607503..fc0a315f5 100644 --- a/sdk/main/include/FreezeTransaction.h +++ b/sdk/main/include/FreezeTransaction.h @@ -150,6 +150,15 @@ class FreezeTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this FreezeTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This FreezeTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the FreezeTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/HbarAllowance.h b/sdk/main/include/HbarAllowance.h index 14cc0675b..d2c28c587 100644 --- a/sdk/main/include/HbarAllowance.h +++ b/sdk/main/include/HbarAllowance.h @@ -30,6 +30,11 @@ namespace proto class CryptoAllowance; } +namespace Hedera +{ +class Client; +} + namespace Hedera { /** @@ -58,58 +63,20 @@ class HbarAllowance [[nodiscard]] static HbarAllowance fromProtobuf(const proto::CryptoAllowance& proto); /** - * Construct a CryptoAllowance protobuf object from this HbarAllowance object. - * - * @return A pointer to a constructed CryptoAllowance protobuf object filled with this HbarAllowance object's data. - */ - [[nodiscard]] std::unique_ptr toProtobuf() const; - - /** - * Set the ID of the account approving an allowance of its Hbars. - * - * @param accountId The ID of the account approving an allowance of its Hbars. - * @return A reference to this HbarAllowance object with the newly-set owner account ID. - */ - HbarAllowance& setOwnerAccountId(const AccountId& accountId); - - /** - * Set the ID of the account being allowed to spend the Hbars. + * Validate the checksums of the entity IDs in this HbarAllowance. * - * @param accountId The ID of the account being allowed to spend the Hbars. - * @return A reference to this HbarAllowance object with the newly-set spender account ID. + * @param client The Client to use to validate the checksums. + * @throws BadEntityException If the checksums are not valid. */ - HbarAllowance& setSpenderAccountId(const AccountId& accountId); + void validateChecksums(const Client& client) const; /** - * Set the amount of Hbars that are being allowed to be spent. - * - * @param amount The amount of Hbars that are being allowed to be spent. - * @return A reference to this HbarAllowance object with the newly-set amount. - */ - HbarAllowance& setAmount(const Hbar& amount); - - /** - * Set the ID of the account approving an allowance of its Hbars. - * - * @return The ID of the account approving an allowance of its Hbars. - */ - [[nodiscard]] inline AccountId getOwnerAccountId() const { return mOwnerAccountId; } - - /** - * Get the ID of the account being allowed to spend the Hbars. - * - * @return The ID of the account being allowed to spend the Hbars. - */ - [[nodiscard]] inline AccountId getSpenderAccountId() const { return mSpenderAccountId; } - - /** - * Get the amount of Hbars that are being allowed to be spent. + * Construct a CryptoAllowance protobuf object from this HbarAllowance object. * - * @return The amount of Hbars that are being allowed to be spent. + * @return A pointer to a constructed CryptoAllowance protobuf object filled with this HbarAllowance object's data. */ - [[nodiscard]] inline Hbar getAmount() const { return mAmount; } + [[nodiscard]] std::unique_ptr toProtobuf() const; -private: /** * The ID of the account approving an allowance of its Hbars. */ diff --git a/sdk/main/include/HbarTransfer.h b/sdk/main/include/HbarTransfer.h index d5dabece4..6a4971f19 100644 --- a/sdk/main/include/HbarTransfer.h +++ b/sdk/main/include/HbarTransfer.h @@ -33,6 +33,17 @@ namespace Hedera class HbarTransfer { public: + HbarTransfer() = default; + + /** + * Construct with an account ID, amount, and approval. + * + * @param accountId The ID of the account doing the transfer. + * @param amount The amount to transfer. + * @param approval \c TRUE if this is an approved allowance transfer, otherwise \c FALSE. + */ + explicit HbarTransfer(AccountId accountId, const Hbar& amount, bool approval); + /** * Construct an HbarTransfer object from an AccountAmount protobuf object. * @@ -48,52 +59,6 @@ class HbarTransfer */ [[nodiscard]] std::unique_ptr toProtobuf() const; - /** - * Set the ID of the account associated with this HbarTransfer. - * - * @param accountId The ID of the account associated with this HbarTransfer. - * @return A reference to this HbarTransfer object with the newly-set account ID. - */ - HbarTransfer& setAccountId(const AccountId& accountId); - - /** - * Set the amount of Hbar that was transferred into (positive) or out of (negative) the account. - * - * @param amount The amount transferred. - * @return A reference to this HbarTransfer object with the newly-set transfer amount. - */ - HbarTransfer& setAmount(const Hbar& amount); - - /** - * Set if this HbarTransfer is approved. - * - * @param approved \c TRUE if this HbarTransfer is approved, otherwise \c FALSE. - * @return A reference to this HbarTransfer object with the newly-set approval status. - */ - HbarTransfer& setApproved(bool approved); - - /** - * Get the ID of the account associated with this HbarTransfer. - * - * @return The account ID. - */ - [[nodiscard]] inline AccountId getAccountId() const { return mAccountId; } - - /** - * Get the amount that was or will be transferred. - * - * @return The transfer amount. - */ - [[nodiscard]] inline Hbar getAmount() const { return mAmount; } - - /** - * Determine if this HbarTransfer is approved or not. - * - * @return \c TRUE if this transfer is approved, otherwise \c FALSE - */ - [[nodiscard]] inline bool getApproval() const { return mIsApproved; } - -private: /** * The ID of the account associated with this HbarTransfer. */ diff --git a/sdk/main/include/NetworkVersionInfoQuery.h b/sdk/main/include/NetworkVersionInfoQuery.h index c010953b4..77893f31a 100644 --- a/sdk/main/include/NetworkVersionInfoQuery.h +++ b/sdk/main/include/NetworkVersionInfoQuery.h @@ -58,6 +58,15 @@ class NetworkVersionInfoQuery : public Query& node, const std::chrono::system_clock::time_point& deadline, proto::Response* response) const override; + + /** + * Derived from Query. Verify that all the checksums in this NetworkVersionInfoQuery are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This NetworkVersionInfoQuery's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Query. Build a Query protobuf object with this NetworkVersionInfoQuery's data, with the input * QueryHeader protobuf object. diff --git a/sdk/main/include/NftId.h b/sdk/main/include/NftId.h index 46a49ae9c..aaeb4cf2f 100644 --- a/sdk/main/include/NftId.h +++ b/sdk/main/include/NftId.h @@ -47,7 +47,7 @@ class NftId * @param serialNumber The serial number to set. * @throws std::invalid_argument If the serial number is too big (max value is std::numeric_limits::max()). */ - explicit NftId(const TokenId& id, const uint64_t& serialNumber); + explicit NftId(TokenId id, const uint64_t& serialNumber); /** * Compare this NftId to another NftId and determine if they represent the same token. @@ -87,45 +87,6 @@ class NftId */ [[nodiscard]] std::string toString() const; - /** - * Set the token ID. - * - * @param id The desired token ID to set. - * @return A reference to this NftId object with the newly-set TokenId. - */ - NftId& setTokenId(const TokenId& id); - - /** - * Set the serial number. - * - * @param num The desired serial number to set. - * @return A reference to this NftId object with the newly-set serial number. - * @throws std::invalid_argument If the serial number is too big (max value is std::numeric_limits::max()). - */ - NftId& setSerialNum(const uint64_t& num); - - /** - * Get the token ID. - * - * @return The token ID. - */ - [[nodiscard]] inline TokenId getTokenId() const { return mTokenId; } - - /** - * Get the serial number. - * - * @return The serial number. - */ - [[nodiscard]] inline uint64_t getSerialNum() const { return mSerialNum; } - -private: - /** - * Check if the serial number is too big. - * - * @throws std::invalid_argument If the serial number is too big (max value is std::numeric_limits::max()). - */ - void checkSerialNum() const; - /** * The ID of the non-fungible token of which this NFT is an instance. */ diff --git a/sdk/main/include/Query.h b/sdk/main/include/Query.h index 927953ca2..4b5a18841 100644 --- a/sdk/main/include/Query.h +++ b/sdk/main/include/Query.h @@ -132,6 +132,14 @@ class Query : public Executable const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this ScheduleCreateTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This ScheduleCreateTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the ScheduleCreateTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/ScheduleDeleteTransaction.h b/sdk/main/include/ScheduleDeleteTransaction.h index 962440fa1..316ea012b 100644 --- a/sdk/main/include/ScheduleDeleteTransaction.h +++ b/sdk/main/include/ScheduleDeleteTransaction.h @@ -100,6 +100,15 @@ class ScheduleDeleteTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this ScheduleDeleteTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This ScheduleDeleteTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the ScheduleDeleteTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/ScheduleId.h b/sdk/main/include/ScheduleId.h index 7bbe6a585..283db7e48 100644 --- a/sdk/main/include/ScheduleId.h +++ b/sdk/main/include/ScheduleId.h @@ -4,7 +4,7 @@ * * Copyright (C) 2020 - 2023 Hedera Hashgraph, LLC * - * Licensed under the Apache License, Version 2.0 (the "License"); + * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * @@ -21,7 +21,6 @@ #define HEDERA_SDK_CPP_SCHEDULE_ID_H_ #include -#include #include #include #include @@ -32,6 +31,11 @@ namespace proto class ScheduleID; } +namespace Hedera +{ +class Client; +} + namespace Hedera { /** @@ -45,18 +49,19 @@ class ScheduleId /** * Construct with a schedule number. * - * @param num The desired schedule number. + * @param num The schedule number. */ - explicit ScheduleId(const uint64_t& num); + explicit ScheduleId(uint64_t num); /** - * Construct with a shard, realm, and schedule number. + * Construct with a shard, realm, a schedule number, and optionally a checksum. * - * @param shard The desired shard number. - * @param realm The desired realm number. - * @param num The desired schedule number. + * @param shard The shard number. + * @param realm The realm number. + * @param num The schedule number. + * @param checksum The checksum. */ - explicit ScheduleId(const uint64_t& shard, const uint64_t& realm, const uint64_t& num); + explicit ScheduleId(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum = ""); /** * Compare this ScheduleId to another ScheduleId and determine if they represent the same schedule. @@ -70,48 +75,70 @@ class ScheduleId * Construct a ScheduleId object from a string of the form "..". * * @param id The schedule ID string from which to construct. - * @throws std::invalid_argument If the input string is malformed. * @return The constructed ScheduleId object. + * @throws std::invalid_argument If the input string is malformed. */ [[nodiscard]] static ScheduleId fromString(std::string_view id); /** - * Construct a ScheduleId object from a ScheduleId protobuf object. + * Construct a ScheduleId from a ScheduleId protobuf object. * - * @param proto The ScheduleId protobuf object from which to construct a ScheduleId object. + * @param proto The ScheduleId protobuf object from which to create a ScheduleId object. * @return The constructed ScheduleId object. */ [[nodiscard]] static ScheduleId fromProtobuf(const proto::ScheduleID& proto); /** - * Construct a ScheduleId object from a byte array. + * Construct a ScheduleId object from a representative byte array. * - * @param bytes The byte array from which to construct. + * @param bytes The byte array from which to construct a ScheduleId object. * @return The constructed ScheduleId object. - * @throws std::invalid_argument If a ScheduleId object cannot be constructed from the input byte array. */ [[nodiscard]] static ScheduleId fromBytes(const std::vector& bytes); /** - * Construct a ScheduleId protobuf object from this ScheduleId object. + * Verify the checksum of this ScheduleId using the input Client's network. + * + * @param client The Client with which to validate this ScheduleId's checksum. + * @throws BadEntityException If the checksum of this ScheduleId is invalid. + */ + void validateChecksum(const Client& client) const; + + /** + * Construct a ScheduleID protobuf object from this ScheduleId object. * * @return A pointer to the created ScheduleId protobuf object filled with this ScheduleId object's data. */ [[nodiscard]] std::unique_ptr toProtobuf() const; /** - * Get the byte representation of this ScheduleId object. + * Get the string representation of this ScheduleId object. * - * @return The byte representation of this ScheduleId. + * @return The string representation of this ScheduleId. + */ + [[nodiscard]] std::string toString() const; + + /** + * Get the string representation of this ScheduleId object with the checksum. + * + * @param client The Client with which to generate the checksum. + * @return The string representation of this ScheduleId object with the checksum. + */ + [[nodiscard]] std::string toStringWithChecksum([[maybe_unused]] const Client& client) const; + + /** + * Get a byte array representation of this ScheduleId object. + * + * @return A byte array representation of this ScheduleId object. */ [[nodiscard]] std::vector toBytes() const; /** - * Get the string representation of this ScheduleId object with the form "..". + * Get the checksum of this ContractId. * - * @return The string representation of this ScheduleId. + * @return The checksum of this ContractId. */ - [[nodiscard]] std::string toString() const; + [[nodiscard]] inline std::string getChecksum() const { return mChecksum; } /** * The shard number. @@ -124,9 +151,15 @@ class ScheduleId uint64_t mRealmNum = 0ULL; /** - * The schedule ID number. + * The schedule number. */ uint64_t mScheduleNum = 0ULL; + +private: + /** + * The checksum of this ScheduleIds. + */ + mutable std::string mChecksum; }; } // namespace Hedera diff --git a/sdk/main/include/ScheduleInfoQuery.h b/sdk/main/include/ScheduleInfoQuery.h index 9ac95f421..0d0d31f35 100644 --- a/sdk/main/include/ScheduleInfoQuery.h +++ b/sdk/main/include/ScheduleInfoQuery.h @@ -75,6 +75,15 @@ class ScheduleInfoQuery : public Query const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::Response* response) const override; + + /** + * Derived from Query. Verify that all the checksums in this ScheduleInfoQuery are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This ScheduleInfoQuery's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Query. Build a Query protobuf object with this ScheduleInfoQuery's data, with the input QueryHeader * protobuf object. diff --git a/sdk/main/include/ScheduleSignTransaction.h b/sdk/main/include/ScheduleSignTransaction.h index 3691c621a..054d1d823 100644 --- a/sdk/main/include/ScheduleSignTransaction.h +++ b/sdk/main/include/ScheduleSignTransaction.h @@ -108,6 +108,15 @@ class ScheduleSignTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this ScheduleSignTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This ScheduleSignTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the ScheduleSignTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/SystemDeleteTransaction.h b/sdk/main/include/SystemDeleteTransaction.h index 1b73b0010..1c2dc1ca2 100644 --- a/sdk/main/include/SystemDeleteTransaction.h +++ b/sdk/main/include/SystemDeleteTransaction.h @@ -136,6 +136,15 @@ class SystemDeleteTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this SystemDeleteTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This SystemDeleteTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the SystemDeleteTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/SystemUndeleteTransaction.h b/sdk/main/include/SystemUndeleteTransaction.h index 912644510..d8880cb43 100644 --- a/sdk/main/include/SystemUndeleteTransaction.h +++ b/sdk/main/include/SystemUndeleteTransaction.h @@ -116,6 +116,15 @@ class SystemUndeleteTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this SystemUndeleteTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This SystemUndeleteTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the SystemUndeleteTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TokenAllowance.h b/sdk/main/include/TokenAllowance.h index 31c8c7c45..e2e6fc30e 100644 --- a/sdk/main/include/TokenAllowance.h +++ b/sdk/main/include/TokenAllowance.h @@ -33,6 +33,11 @@ namespace proto class TokenAllowance; } +namespace Hedera +{ +class Client; +} + namespace Hedera { /** @@ -69,6 +74,14 @@ class TokenAllowance */ [[nodiscard]] static TokenAllowance fromBytes(const std::vector& bytes); + /** + * Validate the checksums of the entity IDs in this TokenAllowance. + * + * @param client The Client to use to validate the checksums. + * @throws BadEntityException If the checksums are not valid. + */ + void validateChecksums(const Client& client) const; + /** * Construct a TokenAllowance protobuf object from this TokenAllowance object. * diff --git a/sdk/main/include/TokenAssociateTransaction.h b/sdk/main/include/TokenAssociateTransaction.h index 742be8553..3023af4ec 100644 --- a/sdk/main/include/TokenAssociateTransaction.h +++ b/sdk/main/include/TokenAssociateTransaction.h @@ -134,6 +134,15 @@ class TokenAssociateTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenAssociateTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenAssociateTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenAssociateTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TokenBurnTransaction.h b/sdk/main/include/TokenBurnTransaction.h index 0df3c75a4..cc0ac4438 100644 --- a/sdk/main/include/TokenBurnTransaction.h +++ b/sdk/main/include/TokenBurnTransaction.h @@ -132,6 +132,15 @@ class TokenBurnTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenBurnTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenBurnTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenBurnTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TokenCreateTransaction.h b/sdk/main/include/TokenCreateTransaction.h index 88293de10..38f0425d7 100644 --- a/sdk/main/include/TokenCreateTransaction.h +++ b/sdk/main/include/TokenCreateTransaction.h @@ -417,6 +417,15 @@ class TokenCreateTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenCreateTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenCreateTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenCreateTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TokenDeleteTransaction.h b/sdk/main/include/TokenDeleteTransaction.h index 47be5021b..8f72c4b24 100644 --- a/sdk/main/include/TokenDeleteTransaction.h +++ b/sdk/main/include/TokenDeleteTransaction.h @@ -102,6 +102,15 @@ class TokenDeleteTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenDeleteTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenDeleteTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenDeleteTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TokenDissociateTransaction.h b/sdk/main/include/TokenDissociateTransaction.h index d5733e63e..7f6b62e5f 100644 --- a/sdk/main/include/TokenDissociateTransaction.h +++ b/sdk/main/include/TokenDissociateTransaction.h @@ -129,6 +129,15 @@ class TokenDissociateTransaction : public Transaction& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenDissociateTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenDissociateTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenDissociateTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TokenFeeScheduleUpdateTransaction.h b/sdk/main/include/TokenFeeScheduleUpdateTransaction.h index 78ae5eef8..ba47768e2 100644 --- a/sdk/main/include/TokenFeeScheduleUpdateTransaction.h +++ b/sdk/main/include/TokenFeeScheduleUpdateTransaction.h @@ -117,6 +117,15 @@ class TokenFeeScheduleUpdateTransaction : public Transaction& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenFeeScheduleUpdateTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenFeeScheduleUpdateTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenFeeScheduleUpdateTransaction protobuf representation to the * Transaction protobuf object. diff --git a/sdk/main/include/TokenFreezeTransaction.h b/sdk/main/include/TokenFreezeTransaction.h index 49b325712..1b0d11c3b 100644 --- a/sdk/main/include/TokenFreezeTransaction.h +++ b/sdk/main/include/TokenFreezeTransaction.h @@ -121,6 +121,15 @@ class TokenFreezeTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenFreezeTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenFreezeTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenFreezeTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TokenGrantKycTransaction.h b/sdk/main/include/TokenGrantKycTransaction.h index 7da1c0ee1..5c6966537 100644 --- a/sdk/main/include/TokenGrantKycTransaction.h +++ b/sdk/main/include/TokenGrantKycTransaction.h @@ -124,6 +124,15 @@ class TokenGrantKycTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenGrantKycTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenGrantKycTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenGrantKycTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TokenId.h b/sdk/main/include/TokenId.h index 91d79d3b2..a964c1a48 100644 --- a/sdk/main/include/TokenId.h +++ b/sdk/main/include/TokenId.h @@ -4,7 +4,7 @@ * * Copyright (C) 2020 - 2023 Hedera Hashgraph, LLC * - * Licensed under the Apache License, Version 2.0 (the "License"); + * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * @@ -20,15 +20,23 @@ #ifndef HEDERA_SDK_CPP_TOKEN_ID_H_ #define HEDERA_SDK_CPP_TOKEN_ID_H_ +#include #include #include #include +#include namespace proto { class TokenID; } +namespace Hedera +{ +class Client; +class NftId; +} + namespace Hedera { /** @@ -42,20 +50,19 @@ class TokenId /** * Construct with a token number. * - * @param num The desired token number. - * @throws std::invalid_argument If the token number is too big (max value is std::numeric_limits::max()). + * @param num The token number. */ - explicit TokenId(const uint64_t& num); + explicit TokenId(uint64_t num); /** - * Construct with a shard, realm, and token number. + * Construct with a shard, realm, a token number, and optionally a checksum. * - * @param shard The desired shard number. - * @param realm The desired realm number. - * @param num The desired token number. - * @throws std::invalid_argument If any number is too big (max value is std::numeric_limits::max()). + * @param shard The shard number. + * @param realm The realm number. + * @param num The token number. + * @param checksum The checksum. */ - explicit TokenId(const uint64_t& shard, const uint64_t& realm, const uint64_t& num); + explicit TokenId(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum = ""); /** * Compare this TokenId to another TokenId and determine if they represent the same token. @@ -69,89 +76,87 @@ class TokenId * Construct a TokenId object from a string of the form "..". * * @param id The token ID string from which to construct. + * @return The constructed TokenId object. * @throws std::invalid_argument If the input string is malformed. */ [[nodiscard]] static TokenId fromString(std::string_view id); /** - * Construct an TokenId object from a TokenID protobuf object. + * Construct a TokenId from a Solidity address. * - * @param proto The TokenID protobuf object from which to construct a TokenId object. + * @param address The Solidity address from which to create a TokenId, as a string. * @return The constructed TokenId object. + * @throws std::invalid_argument If a Solidity address cannot be realized from the input string. */ - [[nodiscard]] static TokenId fromProtobuf(const proto::TokenID& proto); + [[nodiscard]] static TokenId fromSolidityAddress(std::string_view address); /** - * Construct a TokenID protobuf object from this TokenId object. + * Construct a TokenId from a TokenId protobuf object. * - * @return A pointer to the created TokenID protobuf object filled with this TokenId object's data. + * @param proto The TokenId protobuf object from which to create a TokenId object. + * @return The constructed TokenId object. */ - [[nodiscard]] std::unique_ptr toProtobuf() const; + [[nodiscard]] static TokenId fromProtobuf(const proto::TokenID& proto); /** - * Get the string representation of this TokenId object with the form "..". + * Construct a TokenId object from a representative byte array. * - * @return The string representation of this TokenId. + * @param bytes The byte array from which to construct a TokenId object. + * @return The constructed TokenId object. */ - [[nodiscard]] std::string toString() const; + [[nodiscard]] static TokenId fromBytes(const std::vector& bytes); /** - * Set the shard number. + * Verify the checksum of this TokenId using the input Client's network. * - * @param num The desired shard number to set. - * @return A reference to this TokenId object with the newly-set shard number. - * @throws std::invalid_argument If the shard number is too big (max value is std::numeric_limits::max()). + * @param client The Client with which to validate this TokenId's checksum. + * @throws BadEntityException If the checksum of this TokenId is invalid. */ - TokenId& setShardNum(const uint64_t& num); + void validateChecksum(const Client& client) const; /** - * Set the realm number. + * Construct an NftId from this TokenId and a serial number. * - * @param num The realm number to set. - * @return A reference to this TokenId object with the newly-set realm number. - * @throws std::invalid_argument If the realm number is too big (max value is std::numeric_limits::max()). + * @param serial The serial number of the NftId. + * @param The constructed NftId. */ - TokenId& setRealmNum(const uint64_t& num); + [[nodiscard]] NftId nft(uint64_t serial) const; /** - * Set the token number. + * Construct a TokenID protobuf object from this TokenId object. * - * @param num The token number to set. - * @return A reference to this TokenId object with the newly-set token number. - * @throws std::invalid_argument If the account number is too big (max value is std::numeric_limits::max()). + * @return A pointer to the created TokenId protobuf object filled with this TokenId object's data. */ - TokenId& setTokenNum(const uint64_t& num); + [[nodiscard]] std::unique_ptr toProtobuf() const; /** - * Get the shard number. + * Get the string representation of this TokenId object. * - * @return The shard number. + * @return The string representation of this TokenId. */ - [[nodiscard]] inline uint64_t getShardNum() const { return mShardNum; } + [[nodiscard]] std::string toString() const; /** - * Get the realm number. + * Get the string representation of this TokenId object with the checksum. * - * @return The realm number. + * @param client The Client with which to generate the checksum. + * @return The string representation of this TokenId object with the checksum. */ - [[nodiscard]] inline uint64_t getRealmNum() const { return mRealmNum; } + [[nodiscard]] std::string toStringWithChecksum([[maybe_unused]] const Client& client) const; /** - * Get the token number. + * Get a byte array representation of this TokenId object. * - * @return The token number. + * @return A byte array representation of this TokenId object. */ - [[nodiscard]] inline uint64_t getTokenNum() const { return mTokenNum; } + [[nodiscard]] std::vector toBytes() const; -private: /** - * Check if the shard, realm, or token numbers (respectively) are too big. + * Get the checksum of this ContractId. * - * @throws std::invalid_argument If the shard, realm, or token number (respectively) is too big. + * @return The checksum of this ContractId. */ - void checkShardNum() const; - void checkRealmNum() const; - void checkTokenNum() const; + [[nodiscard]] inline std::string getChecksum() const { return mChecksum; } /** * The shard number. @@ -164,9 +169,15 @@ class TokenId uint64_t mRealmNum = 0ULL; /** - * The token ID number. + * The token number. */ uint64_t mTokenNum = 0ULL; + +private: + /** + * The checksum of this TokenIds. + */ + mutable std::string mChecksum; }; } // namespace Hedera diff --git a/sdk/main/include/TokenInfoQuery.h b/sdk/main/include/TokenInfoQuery.h index f3b8fe06b..e79d64d97 100644 --- a/sdk/main/include/TokenInfoQuery.h +++ b/sdk/main/include/TokenInfoQuery.h @@ -75,6 +75,15 @@ class TokenInfoQuery : public Query const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::Response* response) const override; + + /** + * Derived from Query. Verify that all the checksums in this TokenInfoQuery are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenInfoQuery's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Query. Build a Query protobuf object with this TokenInfoQuery's data, with the input QueryHeader * protobuf object. diff --git a/sdk/main/include/TokenMintTransaction.h b/sdk/main/include/TokenMintTransaction.h index 353720201..692b679bc 100644 --- a/sdk/main/include/TokenMintTransaction.h +++ b/sdk/main/include/TokenMintTransaction.h @@ -152,6 +152,15 @@ class TokenMintTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenMintTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenMintTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenMintTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TokenNftAllowance.h b/sdk/main/include/TokenNftAllowance.h index ad91dbc0b..0df0165b7 100644 --- a/sdk/main/include/TokenNftAllowance.h +++ b/sdk/main/include/TokenNftAllowance.h @@ -81,6 +81,14 @@ class TokenNftAllowance */ [[nodiscard]] static TokenNftAllowance fromBytes(const std::vector& bytes); + /** + * Validate the checksums of the entity IDs in this TokenNftAllowance. + * + * @param client The Client to use to validate the checksums. + * @throws BadEntityException If the checksums are not valid. + */ + void validateChecksums(const Client& client) const; + /** * Construct an NftAllowance protobuf object from this TokenNftAllowance object. * @@ -92,7 +100,7 @@ class TokenNftAllowance * Construct an NftRemoveAllowance protobuf object from this TokenNftAllowance object. * * @return A pointer to a constructed NftRemoveAllowance protobuf object filled with this TokenNftAllowance object's - * data. + * data. */ [[nodiscard]] std::unique_ptr toRemoveProtobuf() const; diff --git a/sdk/main/include/TokenNftInfoQuery.h b/sdk/main/include/TokenNftInfoQuery.h index 34503fd0f..f89e98d1e 100644 --- a/sdk/main/include/TokenNftInfoQuery.h +++ b/sdk/main/include/TokenNftInfoQuery.h @@ -80,6 +80,15 @@ class TokenNftInfoQuery : public Query const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::Response* response) const override; + + /** + * Derived from Query. Verify that all the checksums in this TokenNftInfoQuery are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenNftInfoQuery's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Query. Build a Query protobuf object with this TokenNftInfoQuery's data, with the input QueryHeader * protobuf object. diff --git a/sdk/main/include/TokenNftTransfer.h b/sdk/main/include/TokenNftTransfer.h index 67d825485..689a1757b 100644 --- a/sdk/main/include/TokenNftTransfer.h +++ b/sdk/main/include/TokenNftTransfer.h @@ -40,82 +40,42 @@ namespace Hedera class TokenNftTransfer { public: - /** - * Construct a TokenNftTransfer object from an NftTransfer protobuf object. - * - * @param proto The NftTransfer protobuf object from which to construct an TokenNftTransfer object. - * @return The constructed TokenNftTransfer object. - */ - [[nodiscard]] static TokenNftTransfer fromProtobuf(const proto::NftTransfer& proto); - - /** - * Construct an NftTransfer protobuf object from this TokenNftTransfer object. - * - * @return A pointer to a created NftTransfer protobuf object filled with this TokenNftTransfer object's data. - */ - [[nodiscard]] std::unique_ptr toProtobuf() const; + TokenNftTransfer() = default; /** - * Set the ID of the NFT. + * Construct with an nft ID, sender account ID, receiver account ID, and approval. * * @param nftId The ID of the NFT. - * @param A reference to this TokenNftTransfer object with the newly-set NFT ID. - */ - TokenNftTransfer& setNftId(const NftId& nftId); - - /** - * Set the ID of the account sending the NFT. - * - * @param accountId The ID of the account that is sending the NFT. - * @return A reference to this TokenNftTransfer object with the newly-set sender account ID. + * @param sender The ID of the account sending the NFT. + * @param receiver The ID of the account receiving the NFT. + * @param approved \c TRUE if this is an approved allowance NFT transfer, otherwise \c FALSE. */ - TokenNftTransfer& setSenderAccountId(const AccountId& accountId); + TokenNftTransfer(NftId nftId, AccountId sender, AccountId receiver, bool approved); /** - * Set the ID of the account receiving the NFT. + * Construct a TokenNftTransfer object from an NftTransfer protobuf object and a TokenId object. * - * @param accountId The ID of the account that is receiving the NFT. - * @return A reference to this TokenNftTransfer object with the newly-set receiver account ID. - */ - TokenNftTransfer& setReceiverAccountId(const AccountId& accountId); - - /** - * Set if this TokenNftTransfer is approved. - * - * @param approval \c TRUE if this is an approved transfer, otherwise \c FALSE. - * @return A reference to this TokenNftTransfer object with the newly-set approval status. - */ - TokenNftTransfer& setApproval(bool approval); - - /** - * Get the NFT ID. - * - * @return The NFT ID. - */ - [[nodiscard]] inline NftId getNftId() const { return mNftId; } - - /** - * Get the sender account ID. - * - * @return The sender account ID. + * @param proto The NftTransfer protobuf object from which to construct an TokenNftTransfer object. + * @param tokenId The ID of the token. + * @return The constructed TokenNftTransfer object. */ - [[nodiscard]] inline AccountId getSenderAccountId() const { return mSenderAccountID; } + [[nodiscard]] static TokenNftTransfer fromProtobuf(const proto::NftTransfer& proto, const TokenId& tokenId); /** - * Get the receiver account ID. + * Validate the checksums of the entities associated with this TokenNftTransfer. * - * @return The receiver account ID. + * @param client The Client to use to validate the checksums. + * @throws BadEntityException If any of the checksums are not valid. */ - [[nodiscard]] inline AccountId getReceiverAccountId() const { return mReceiverAccountID; } + void validateChecksums(const Client& client) const; /** - * Determine if this transfer is approved or not. + * Construct an NftTransfer protobuf object from this TokenNftTransfer object. * - * @return \c TRUE if this is an approved transfer, otherwise \c FALSE. + * @return A pointer to a created NftTransfer protobuf object filled with this TokenNftTransfer object's data. */ - [[nodiscard]] inline bool getApproval() const { return mIsApproval; } + [[nodiscard]] std::unique_ptr toProtobuf() const; -private: /** * The ID of the NFT. */ @@ -124,12 +84,12 @@ class TokenNftTransfer /** * The account ID of the sender. */ - AccountId mSenderAccountID; + AccountId mSenderAccountId; /** * The account ID of the receiver. */ - AccountId mReceiverAccountID; + AccountId mReceiverAccountId; /** * If \c TRUE then the transfer is expected to be an approved allowance and the senderAccountID is expected to be the diff --git a/sdk/main/include/TokenPauseTransaction.h b/sdk/main/include/TokenPauseTransaction.h index 532811f37..95bceea1c 100644 --- a/sdk/main/include/TokenPauseTransaction.h +++ b/sdk/main/include/TokenPauseTransaction.h @@ -112,6 +112,15 @@ class TokenPauseTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenPauseTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenPauseTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenPauseTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TokenRevokeKycTransaction.h b/sdk/main/include/TokenRevokeKycTransaction.h index 165a55ba8..5ffeb0e66 100644 --- a/sdk/main/include/TokenRevokeKycTransaction.h +++ b/sdk/main/include/TokenRevokeKycTransaction.h @@ -125,6 +125,15 @@ class TokenRevokeKycTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenRevokeKycTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenRevokeKycTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenRevokeKycTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TokenTransfer.h b/sdk/main/include/TokenTransfer.h index 19e87205d..893b740a3 100644 --- a/sdk/main/include/TokenTransfer.h +++ b/sdk/main/include/TokenTransfer.h @@ -29,7 +29,11 @@ namespace proto { class AccountAmount; -class TokenTransferList; +} + +namespace Hedera +{ +class Client; } namespace Hedera @@ -46,9 +50,9 @@ class TokenTransfer /** * Construct with a token ID, account ID, amount, and approval. * - * @param tokenId The ID of the token involved with this TokenTransfer. - * @param accountId The ID of the account to/from which the token is being transferred. - * @param amount The amount of the token being transferred. + * @param tokenId The ID of the token involved with this TokenTransfer. + * @param accountId The ID of the account to/from which the token is being transferred. + * @param amount The amount of the token being transferred. * @param isApproved \c TRUE if this transfer is approved, otherwise \c FALSE. */ TokenTransfer(const TokenId& tokenId, AccountId accountId, int64_t amount, bool isApproved); @@ -56,20 +60,33 @@ class TokenTransfer /** * Construct with a token ID, account ID, amount, expected decimals of the token, and approval. * - * @param tokenId The ID of the token involved with this TokenTransfer. - * @param accountId The ID of the account to/from which the token is being transferred. - * @param amount The amount of the token being transferred. + * @param tokenId The ID of the token involved with this TokenTransfer. + * @param accountId The ID of the account to/from which the token is being transferred. + * @param amount The amount of the token being transferred. * @param isApproved \c TRUE if this transfer is approved, otherwise \c FALSE. */ TokenTransfer(const TokenId& tokenId, AccountId accountId, int64_t amount, uint32_t decimals, bool isApproved); /** - * Construct a list of TokenTransfers objects from a TokenTransferList protobuf object. + * Construct a TokenTransfer object from an AccountAmount protobuf object, a TokenId object, and the number of + * expected decimals. + * + * @param proto The AccountAmount protobuf object from which to construct the TokenTransfer object. + * @param tokenId The ID of the token. + * @param decimals The number of expected decimals. + * @return The constructed TokenTransfer object. + */ + [[nodiscard]] static TokenTransfer fromProtobuf(const proto::AccountAmount& proto, + const TokenId& tokenId, + uint32_t expectedDecimals); + + /** + * Validate the checksums of the entities in this TokenTransfer. * - * @param proto The TokenTransferList protobuf object from which to construct the list of TokenTransfer objects. - * @return The list of TokenTransfer objects. + * @param client The Client to use to validate the checksums. + * @throws BadEntityException If a checksum of one of the entities is not valid. */ - [[nodiscard]] static std::vector fromProtobuf(const proto::TokenTransferList& proto); + void validateChecksums(const Client& client) const; /** * Construct an AccountAmount protobuf object from this TokenTransfer object. diff --git a/sdk/main/include/TokenUnfreezeTransaction.h b/sdk/main/include/TokenUnfreezeTransaction.h index 86e6ecf16..0c6108ef2 100644 --- a/sdk/main/include/TokenUnfreezeTransaction.h +++ b/sdk/main/include/TokenUnfreezeTransaction.h @@ -122,6 +122,15 @@ class TokenUnfreezeTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenUnfreezeTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenUnfreezeTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenUnfreezeTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TokenUnpauseTransaction.h b/sdk/main/include/TokenUnpauseTransaction.h index 9b79819c1..0129da1b3 100644 --- a/sdk/main/include/TokenUnpauseTransaction.h +++ b/sdk/main/include/TokenUnpauseTransaction.h @@ -96,6 +96,15 @@ class TokenUnpauseTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenUnpauseTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenUnpauseTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenUnpauseTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TokenUpdateTransaction.h b/sdk/main/include/TokenUpdateTransaction.h index 76c622413..c2f99693d 100644 --- a/sdk/main/include/TokenUpdateTransaction.h +++ b/sdk/main/include/TokenUpdateTransaction.h @@ -323,6 +323,15 @@ class TokenUpdateTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenUpdateTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenUpdateTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenUpdateTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TokenWipeTransaction.h b/sdk/main/include/TokenWipeTransaction.h index 80a672cf4..4e8d417fd 100644 --- a/sdk/main/include/TokenWipeTransaction.h +++ b/sdk/main/include/TokenWipeTransaction.h @@ -165,6 +165,15 @@ class TokenWipeTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TokenWipeTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TokenWipeTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TokenWipeTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TopicCreateTransaction.h b/sdk/main/include/TopicCreateTransaction.h index 4b9cf0c2a..1bb06bf5b 100644 --- a/sdk/main/include/TopicCreateTransaction.h +++ b/sdk/main/include/TopicCreateTransaction.h @@ -174,6 +174,15 @@ class TopicCreateTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TopicCreateTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TopicCreateTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TopicCreateTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TopicDeleteTransaction.h b/sdk/main/include/TopicDeleteTransaction.h index 3fc56e864..1141dc05c 100644 --- a/sdk/main/include/TopicDeleteTransaction.h +++ b/sdk/main/include/TopicDeleteTransaction.h @@ -100,6 +100,15 @@ class TopicDeleteTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TopicDeleteTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TopicDeleteTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TopicDeleteTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/TopicId.h b/sdk/main/include/TopicId.h index cf2c3c980..8d08e9204 100644 --- a/sdk/main/include/TopicId.h +++ b/sdk/main/include/TopicId.h @@ -4,7 +4,7 @@ * * Copyright (C) 2020 - 2023 Hedera Hashgraph, LLC * - * Licensed under the Apache License, Version 2.0 (the "License"); + * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * @@ -21,7 +21,6 @@ #define HEDERA_SDK_CPP_TOPIC_ID_H_ #include -#include #include #include #include @@ -32,6 +31,11 @@ namespace proto class TopicID; } +namespace Hedera +{ +class Client; +} + namespace Hedera { /** @@ -45,18 +49,19 @@ class TopicId /** * Construct with a topic number. * - * @param num The desired topic number. + * @param num The topic number. */ - explicit TopicId(const uint64_t& num); + explicit TopicId(uint64_t num); /** - * Construct with a shard, realm, and topic number. + * Construct with a shard, realm, a topic number, and optionally a checksum. * - * @param shard The desired shard number. - * @param realm The desired realm number. - * @param num The desired topic number. + * @param shard The shard number. + * @param realm The realm number. + * @param num The topic number. + * @param checksum The checksum. */ - explicit TopicId(const uint64_t& shard, const uint64_t& realm, const uint64_t& num); + explicit TopicId(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum = ""); /** * Compare this TopicId to another TopicId and determine if they represent the same topic. @@ -70,65 +75,87 @@ class TopicId * Construct a TopicId object from a string of the form "..". * * @param id The topic ID string from which to construct. - * @throws std::invalid_argument If the input string is malformed. * @return The constructed TopicId object. + * @throws std::invalid_argument If the input string is malformed. */ [[nodiscard]] static TopicId fromString(std::string_view id); /** - * Construct a TopicId object from a solidity address. + * Construct a TopicId from a Solidity address. * - * @param addr The solidity address from which to construct. - * @throws std::invalid_argument If the input address is malformed. + * @param address The Solidity address from which to create a TopicId, as a string. * @return The constructed TopicId object. + * @throws std::invalid_argument If a Solidity address cannot be realized from the input string. */ - [[nodiscard]] static TopicId fromSolidityAddress(std::string_view addr); + [[nodiscard]] static TopicId fromSolidityAddress(std::string_view address); /** - * Construct a TopicId object from a TopicId protobuf object. + * Construct a TopicId from a TopicId protobuf object. * - * @param proto The TopicId protobuf object from which to construct a TopicId object. + * @param proto The TopicId protobuf object from which to create a TopicId object. * @return The constructed TopicId object. */ [[nodiscard]] static TopicId fromProtobuf(const proto::TopicID& proto); /** - * Construct a TopicId object from a byte array. + * Construct a TopicId object from a representative byte array. * - * @param bytes The byte array from which to construct. + * @param bytes The byte array from which to construct a TopicId object. * @return The constructed TopicId object. - * @throws std::invalid_argument If a TopicId object cannot be constructed from the input byte array. */ [[nodiscard]] static TopicId fromBytes(const std::vector& bytes); /** - * Get the solidity address representation of this TopicId object. + * Verify the checksum of this TopicId using the input Client's network. * - * @return The solidity address representation, as a string. + * @param client The Client with which to validate this TopicId's checksum. + * @throws BadEntityException If the checksum of this TopicId is invalid. */ - [[nodiscard]] std::string toSolidityAddress() const; + void validateChecksum(const Client& client) const; /** - * Construct a TopicId protobuf object from this TopicId object. + * Construct a TopicID protobuf object from this TopicId object. * * @return A pointer to the created TopicId protobuf object filled with this TopicId object's data. */ [[nodiscard]] std::unique_ptr toProtobuf() const; /** - * Get the byte representation of this TopicId object. + * Get the Solidity address representation of this TopicId (Long-Zero address form). * - * @return The byte representation of this TopicId. + * @return The Solidity address representation of this TopicId. */ - [[nodiscard]] std::vector toBytes() const; + [[nodiscard]] std::string toSolidityAddress() const; /** - * Get the string representation of this TopicId object with the form "..". + * Get the string representation of this TopicId object. * * @return The string representation of this TopicId. */ [[nodiscard]] std::string toString() const; + /** + * Get the string representation of this TopicId object with the checksum. + * + * @param client The Client with which to generate the checksum. + * @return The string representation of this TopicId object with the checksum. + */ + [[nodiscard]] std::string toStringWithChecksum([[maybe_unused]] const Client& client) const; + + /** + * Get a byte array representation of this TopicId object. + * + * @return A byte array representation of this TopicId object. + */ + [[nodiscard]] std::vector toBytes() const; + + /** + * Get the checksum of this ContractId. + * + * @return The checksum of this ContractId. + */ + [[nodiscard]] inline std::string getChecksum() const { return mChecksum; } + /** * The shard number. */ @@ -140,9 +167,15 @@ class TopicId uint64_t mRealmNum = 0ULL; /** - * The topic ID number. + * The topic number. */ uint64_t mTopicNum = 0ULL; + +private: + /** + * The checksum of this TopicIds. + */ + mutable std::string mChecksum; }; } // namespace Hedera diff --git a/sdk/main/include/TopicInfoQuery.h b/sdk/main/include/TopicInfoQuery.h index fa08a76e6..a97a3acec 100644 --- a/sdk/main/include/TopicInfoQuery.h +++ b/sdk/main/include/TopicInfoQuery.h @@ -75,6 +75,15 @@ class TopicInfoQuery : public Query const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::Response* response) const override; + + /** + * Derived from Query. Verify that all the checksums in this TopicInfoQuery are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TopicInfoQuery's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Query. Build a Query protobuf object with this TopicInfoQuery's data, with the input QueryHeader * protobuf object. diff --git a/sdk/main/include/TopicMessageSubmitTransaction.h b/sdk/main/include/TopicMessageSubmitTransaction.h index a1e10d913..d5abc94c7 100644 --- a/sdk/main/include/TopicMessageSubmitTransaction.h +++ b/sdk/main/include/TopicMessageSubmitTransaction.h @@ -119,6 +119,15 @@ class TopicMessageSubmitTransaction : public ChunkedTransaction& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TopicMessageSubmitTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TopicMessageSubmitTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TopicMessageSubmitTransaction protobuf representation to the * Transaction protobuf object. diff --git a/sdk/main/include/TopicUpdateTransaction.h b/sdk/main/include/TopicUpdateTransaction.h index 14466625f..2b57d1e18 100644 --- a/sdk/main/include/TopicUpdateTransaction.h +++ b/sdk/main/include/TopicUpdateTransaction.h @@ -235,6 +235,15 @@ class TopicUpdateTransaction : public Transaction const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TopicUpdateTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TopicUpdateTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TopicUpdateTransaction protobuf representation to the Transaction * protobuf object. diff --git a/sdk/main/include/Transaction.h b/sdk/main/include/Transaction.h index 09c187598..976177aff 100644 --- a/sdk/main/include/Transaction.h +++ b/sdk/main/include/Transaction.h @@ -447,6 +447,14 @@ class Transaction */ virtual void addToBody(proto::TransactionBody& body) const = 0; + /** + * Verify that all the checksums in this Transaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This Transaction's checksums are not valid. + */ + virtual void validateChecksums(const Client& client) const = 0; + /** * Derived from Executable. Construct a TransactionResponse object from a TransactionResponse protobuf object. * diff --git a/sdk/main/include/TransactionReceiptQuery.h b/sdk/main/include/TransactionReceiptQuery.h index 91295ac14..16079604b 100644 --- a/sdk/main/include/TransactionReceiptQuery.h +++ b/sdk/main/include/TransactionReceiptQuery.h @@ -117,6 +117,14 @@ class TransactionReceiptQuery : public Query const std::shared_ptr& node, const std::chrono::system_clock::time_point& deadline, proto::TransactionResponse* response) const override; + + /** + * Derived from Transaction. Verify that all the checksums in this TransferTransaction are valid. + * + * @param client The Client that should be used to validate the checksums. + * @throws BadEntityException This TransferTransaction's checksums are not valid. + */ + void validateChecksums(const Client& client) const override; + /** * Derived from Transaction. Build and add the TransferTransaction protobuf representation to the Transaction * protobuf object. @@ -250,9 +259,11 @@ class TransferTransaction : public Transaction /** * Add an Hbar transfer to the Hbar transfers list. * - * @param transfer The Hbar transfer to add. + * @param accountId The ID of the account doing the transfer. + * @param amount The amount to transfer. + * @param approved \c TRUE if this is an approved allowance transfer, otherwise \c FALSE. */ - void doHbarTransfer(const HbarTransfer& transfer); + void doHbarTransfer(const AccountId& accountId, const Hbar& amount, bool approved); /** * Add a token transfer to the token transfers list. @@ -264,9 +275,12 @@ class TransferTransaction : public Transaction /** * Add an NFT transfer to the NFT transfers list. * - * @param transfer The NFT transfer to add. + * @param nftId The ID of the NFT. + * @param sender The ID of the account sending the NFT. + * @param receiver The ID of the account receiving the NFT. + * @param approved \c TRUE if this is an approved allowance NFT transfer, otherwise \c FALSE. */ - void doNftTransfer(const TokenNftTransfer& transfer); + void doNftTransfer(const NftId& nftId, const AccountId& sender, const AccountId& receiver, bool approved); /** * The desired Hbar balance adjustments. diff --git a/sdk/main/include/exceptions/BadEntityException.h b/sdk/main/include/exceptions/BadEntityException.h new file mode 100644 index 000000000..6527e0d99 --- /dev/null +++ b/sdk/main/include/exceptions/BadEntityException.h @@ -0,0 +1,71 @@ +/*- + * + * Hedera C++ SDK + * + * Copyright (C) 2020 - 2023 Hedera Hashgraph, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License") + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#ifndef HEDERA_SDK_CPP_BAD_ENTITY_EXCEPTION_H_ +#define HEDERA_SDK_CPP_BAD_ENTITY_EXCEPTION_H_ + +#include +#include +#include + +namespace Hedera +{ +/** + * Exception that is thrown when a key could not be realized from a given input. + */ +class BadEntityException : public std::exception +{ +public: + /** + * Construct with an entity, its expected checksum, and its calculated checksum. + * + * @param shard The shard of the entity. + * @param realm The realm of the entity. + * @param num The num of the entity. + * @param expectedChecksum The checksum against which the calculated checksum was validated. + * @param calculatedChecksum The checksum that was calculated of the input entity. + */ + explicit BadEntityException(uint64_t shard, + uint64_t realm, + uint64_t num, + std::string_view expectedChecksum, + std::string_view calculatedChecksum) + : mError(std::string("Expected checksum ") + expectedChecksum.data() + " for entity " + std::to_string(shard) + + '.' + std::to_string(realm) + '.' + std::to_string(num) + " does not match its calculated checksum " + + calculatedChecksum.data()) + { + } + + /** + * Get the descriptor message for this error. + * + * @return The descriptor message for this error. + */ + [[nodiscard]] const char* what() const noexcept override { return mError.data(); }; + +private: + /** + * Descriptive error message. + */ + std::string mError; +}; + +} // namespace Hedera + +#endif // HEDERA_SDK_CPP_BAD_ENTITY_EXCEPTION_H_ diff --git a/sdk/main/include/impl/EntityIdHelper.h b/sdk/main/include/impl/EntityIdHelper.h new file mode 100644 index 000000000..7c650daa5 --- /dev/null +++ b/sdk/main/include/impl/EntityIdHelper.h @@ -0,0 +1,170 @@ +/*- + * + * Hedera C++ SDK + * + * Copyright (C) 2020 - 2023 Hedera Hashgraph, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License") + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#ifndef HEDERA_SDK_CPP_IMPL_ENTITY_ID_HELPER_H_ +#define HEDERA_SDK_CPP_IMPL_ENTITY_ID_HELPER_H_ + +#include +#include +#include +#include + +namespace Hedera +{ +class Client; +class LedgerId; +} + +namespace Hedera::internal::EntityIdHelper +{ +/** + * The length of a Solidity address in bytes. + */ +constexpr unsigned int SOLIDITY_ADDRESS_LEN = 20; + +/** + * The length of a hex-encoded Solidity address. + */ +constexpr unsigned int SOLIDITY_ADDRESS_LEN_HEX = SOLIDITY_ADDRESS_LEN * 2; + +/** + * Create an EntityType from a Solidity address byte array. + * + * @tparam EntityType The type of entity to create. + * @param address The Solidity address byte array from which to construct the EntityType. + * @return The constructed EntityType. + * @throws std::invalid_argument If the input byte array is not a valid Solidity address. + */ +template +[[nodiscard]] EntityType fromSolidityAddress(const std::vector& address); + +/** + * Convert a string to a uint64_t. E.g. "123" will return 123. + * + * @param str The string to convert. + * @return The uint64_t contained in the string. + */ +[[nodiscard]] uint64_t getNum(std::string_view str); + +/** + * Get the shard from an entity ID. + * + * @param id The ID of the entity from which to grab the shard number. + * @return The shard number of the input entity ID. + * @throws std::invalid_argument If the shard number is unable to be realized from the input entity ID. + */ +[[nodiscard]] uint64_t getShardNum(std::string_view id); + +/** + * Get the realm from an entity ID. + * + * @param id The ID of the entity from which to grab the realm number. + * @return The realm number of the input entity ID. + * @throws std::invalid_argument If the realm number is unable to be realized from the input entity ID. + */ +[[nodiscard]] uint64_t getRealmNum(std::string_view id); + +/** + * Get the number from an entity ID. + * + * @param id The ID of the entity from which to grab the entity number. + * @return The entity number of the input entity ID. + * @throws std::invalid_argument If the entity number is unable to be realized from the input entity ID. + */ +[[nodiscard]] uint64_t getEntityNum(std::string_view id); + +/** + * Get the number from an entity ID as a string. + * + * @param id The ID of the entity from which to grab the entity number. + * @return The entity number of the input entity ID as a string. + * @throws std::invalid_argument If the entity number is unable to be realized from the input entity ID. + */ +[[nodiscard]] std::string_view getEntityNumStr(std::string_view id); + +/** + * Get the checksum from an entity ID. + * + * @param id The ID of the entity from which to grab the checksum. + * @return The checksum of the input entity ID. Returns an empty string if there is no checksum. + */ +[[nodiscard]] std::string_view getChecksum(std::string_view id); + +/** + * Generate the checksum of a Hedera address for a particular ledger. + * + * @param address The Hedera address from which to generate a checksum. + * @param ledgerId The ID for which the checksum should be generated. + */ +[[nodiscard]] std::string checksum(std::string_view address, const LedgerId& ledgerId); + +/** + * Determine if the input byte array could represent a long-zero address. + * + * @param address The byte array to determine if it could be a long-zero address. + * @return \c TRUE if the input byte array could represent a long-zero address, otherwise \c FALSE. + */ +[[nodiscard]] bool isLongZeroAddress(const std::vector& address); + +/** + * Decode a Solidity address contained in a string to a byte array. + * + * @param address The Solidity address to decode. + * @return The bytes of the Solidity address. + * @throws std::invalid_argument If a Solidity address cannot be realized from the input string. + */ +[[nodiscard]] std::vector decodeSolidityAddress(std::string_view address); + +/** + * Get the string representation of an entity, optionally with a checksum. + * + * @param shard The shard of the entity. + * @param realm The realm of the entity. + * @param num The number of the entity. + * @param checksum The checksum of the entity. + * @return The string representation of an entity. + */ +[[nodiscard]] std::string toString(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum = ""); + +/** + * Get the Solidity address of an entity. + * + * @param shard The shard of the entity. + * @param realm The realm of the entity. + * @param num The number of the entity. + * @return The Solidity address of the entity, in a string. + * @throws std::invalid_argument If the shard number is too large (value must be able to fit in 4 bytes). + */ +[[nodiscard]] std::string toSolidityAddress(uint64_t shard, uint64_t realm, uint64_t num); + +/** + * Validate the checksum of an entity. + * + * @param shard The shard of the entity. + * @param realm The realm of the entity. + * @param num The number of the entity. + * @param client The Client to use to validate the checksum. + * @param expectedChecksum The checksum to validate. + * @throws BadEntityException If the checksum of the entity doesn't match up with the expected checksum. + */ +void validate(uint64_t shard, uint64_t realm, uint64_t num, const Client& client, std::string_view expectedChecksum); + +} // namespace Hedera::internal::EntityIdHelper + +#endif // HEDERA_SDK_CPP_IMPL_ENTITY_ID_HELPER_H_ diff --git a/sdk/main/src/AccountAllowanceApproveTransaction.cc b/sdk/main/src/AccountAllowanceApproveTransaction.cc index ee404abd8..628eb9bd1 100644 --- a/sdk/main/src/AccountAllowanceApproveTransaction.cc +++ b/sdk/main/src/AccountAllowanceApproveTransaction.cc @@ -85,18 +85,18 @@ AccountAllowanceApproveTransaction& AccountAllowanceApproveTransaction::approveT // Add the serial number to the token allowance if there's already an allowance for this token ID, owner, and spender. for (TokenNftAllowance& allowance : mNftAllowances) { - if (allowance.mTokenId == nftId.getTokenId() && allowance.mOwnerAccountId == ownerAccountId && + if (allowance.mTokenId == nftId.mTokenId && allowance.mOwnerAccountId == ownerAccountId && allowance.mSpenderAccountId == spenderAccountId) { - allowance.mSerialNumbers.push_back(nftId.getSerialNum()); + allowance.mSerialNumbers.push_back(nftId.mSerialNum); return *this; } } - mNftAllowances.emplace_back(nftId.getTokenId(), + mNftAllowances.emplace_back(nftId.mTokenId, ownerAccountId, spenderAccountId, - std::vector{ nftId.getSerialNum() }, + std::vector{ nftId.mSerialNum }, std::optional(), (delegatingAccountId == AccountId()) ? std::optional() : delegatingAccountId); return *this; @@ -145,6 +145,20 @@ grpc::Status AccountAllowanceApproveTransaction::submitRequest(const proto::Tran proto::TransactionBody::DataCase::kCryptoApproveAllowance, request, deadline, response); } +//----- +void AccountAllowanceApproveTransaction::validateChecksums(const Client& client) const +{ + std::for_each(mHbarAllowances.cbegin(), + mHbarAllowances.cend(), + [&client](const HbarAllowance& allowance) { allowance.validateChecksums(client); }); + std::for_each(mTokenAllowances.cbegin(), + mTokenAllowances.cend(), + [&client](const TokenAllowance& allowance) { allowance.validateChecksums(client); }); + std::for_each(mNftAllowances.cbegin(), + mNftAllowances.cend(), + [&client](const TokenNftAllowance& allowance) { allowance.validateChecksums(client); }); +} + //----- void AccountAllowanceApproveTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/AccountAllowanceDeleteTransaction.cc b/sdk/main/src/AccountAllowanceDeleteTransaction.cc index 9f5510b1a..68b7fd241 100644 --- a/sdk/main/src/AccountAllowanceDeleteTransaction.cc +++ b/sdk/main/src/AccountAllowanceDeleteTransaction.cc @@ -54,15 +54,15 @@ AccountAllowanceDeleteTransaction& AccountAllowanceDeleteTransaction::deleteAllT // Add the serial number to the token allowance if there's already an allowance for this token ID, owner, and spender. for (TokenNftAllowance& allowance : mNftAllowanceDeletions) { - if (allowance.mTokenId == nftId.getTokenId() && allowance.mOwnerAccountId == owner) + if (allowance.mTokenId == nftId.mTokenId && allowance.mOwnerAccountId == owner) { - allowance.mSerialNumbers.push_back(nftId.getSerialNum()); + allowance.mSerialNumbers.push_back(nftId.mSerialNum); return *this; } } mNftAllowanceDeletions.emplace_back( - nftId.getTokenId(), owner, std::optional(), std::vector{ nftId.getSerialNum() }); + nftId.mTokenId, owner, std::optional(), std::vector{ nftId.mSerialNum }); return *this; } @@ -75,6 +75,14 @@ grpc::Status AccountAllowanceDeleteTransaction::submitRequest(const proto::Trans return node->submitTransaction(proto::TransactionBody::DataCase::kCryptoDeleteAllowance, request, deadline, response); } +//----- +void AccountAllowanceDeleteTransaction::validateChecksums(const Client& client) const +{ + std::for_each(mNftAllowanceDeletions.cbegin(), + mNftAllowanceDeletions.cend(), + [&client](const TokenNftAllowance& allowance) { allowance.validateChecksums(client); }); +} + //----- void AccountAllowanceDeleteTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/AccountBalanceQuery.cc b/sdk/main/src/AccountBalanceQuery.cc index 2b3b331aa..4409503aa 100644 --- a/sdk/main/src/AccountBalanceQuery.cc +++ b/sdk/main/src/AccountBalanceQuery.cc @@ -61,6 +61,20 @@ grpc::Status AccountBalanceQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kCryptogetAccountBalance, request, deadline, response); } +//----- +void AccountBalanceQuery::validateChecksums(const Client& client) const +{ + if (mAccountId.has_value()) + { + mAccountId->validateChecksum(client); + } + + if (mContractId.has_value()) + { + mContractId->validateChecksum(client); + } +} + //----- proto::Query AccountBalanceQuery::buildRequest(proto::QueryHeader* header) const { diff --git a/sdk/main/src/AccountCreateTransaction.cc b/sdk/main/src/AccountCreateTransaction.cc index b830115d0..9f8f1577c 100644 --- a/sdk/main/src/AccountCreateTransaction.cc +++ b/sdk/main/src/AccountCreateTransaction.cc @@ -167,6 +167,15 @@ grpc::Status AccountCreateTransaction::submitRequest(const proto::Transaction& r return node->submitTransaction(proto::TransactionBody::DataCase::kCryptoCreateAccount, request, deadline, response); } +//----- +void AccountCreateTransaction::validateChecksums(const Client& client) const +{ + if (mStakedAccountId.has_value()) + { + mStakedAccountId->validateChecksum(client); + } +} + //----- void AccountCreateTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/AccountDeleteTransaction.cc b/sdk/main/src/AccountDeleteTransaction.cc index 3986f2b75..fd56ab85b 100644 --- a/sdk/main/src/AccountDeleteTransaction.cc +++ b/sdk/main/src/AccountDeleteTransaction.cc @@ -69,6 +69,20 @@ grpc::Status AccountDeleteTransaction::submitRequest(const proto::Transaction& r return node->submitTransaction(proto::TransactionBody::DataCase::kCryptoDelete, request, deadline, response); } +//----- +void AccountDeleteTransaction::validateChecksums(const Client& client) const +{ + if (mDeleteAccountId.has_value()) + { + mDeleteAccountId->validateChecksum(client); + } + + if (mTransferAccountId.has_value()) + { + mTransferAccountId->validateChecksum(client); + } +} + //----- void AccountDeleteTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/AccountId.cc b/sdk/main/src/AccountId.cc index 2a64a06ac..d89e01c0d 100644 --- a/sdk/main/src/AccountId.cc +++ b/sdk/main/src/AccountId.cc @@ -18,13 +18,14 @@ * */ #include "AccountId.h" +#include "Client.h" +#include "LedgerId.h" #include "PublicKey.h" #include "exceptions/BadKeyException.h" #include "exceptions/IllegalStateException.h" -#include "impl/HexConverter.h" +#include "impl/EntityIdHelper.h" #include "impl/Utilities.h" -#include #include #include #include @@ -32,10 +33,9 @@ namespace Hedera { //----- -AccountId::AccountId(const uint64_t& num) +AccountId::AccountId(uint64_t num) : mAccountNum(num) { - checkAccountNum(); } //----- @@ -51,105 +51,94 @@ AccountId::AccountId(const EvmAddress& address) } //----- -AccountId::AccountId(const uint64_t& shard, const uint64_t& realm, const uint64_t& num) +AccountId::AccountId(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum) : mShardNum(shard) , mRealmNum(realm) , mAccountNum(num) + , mChecksum(checksum) { - checkShardNum(); - checkRealmNum(); - checkAccountNum(); } //----- -AccountId::AccountId(const uint64_t& shard, const uint64_t& realm, const std::shared_ptr& alias) +AccountId::AccountId(uint64_t shard, uint64_t realm, const std::shared_ptr& alias) : mShardNum(shard) , mRealmNum(realm) , mPublicKeyAlias(alias) { - checkShardNum(); - checkRealmNum(); } //----- -AccountId::AccountId(const uint64_t& shard, const uint64_t& realm, const EvmAddress& address) +AccountId::AccountId(uint64_t shard, uint64_t realm, const EvmAddress& address) : mShardNum(shard) , mRealmNum(realm) , mEvmAddressAlias(address) { - checkShardNum(); - checkRealmNum(); } //----- -AccountId AccountId::fromString(std::string_view id) +bool AccountId::operator==(const AccountId& other) const { - if (id.size() == 2 * EvmAddress::NUM_BYTES || id.size() == 2 * EvmAddress::NUM_BYTES + 2) - { - return fromEvmAddress(id); - } - - AccountId accountId; - - // Get the indices of the two delimiter '.' - const size_t firstDot = id.find_first_of('.'); - const size_t secondDot = id.find_last_of('.'); - - // Make sure there are at least two dots - if (firstDot == secondDot) - { - throw std::invalid_argument("Input account ID string is malformed"); - } - - // Grab the three strings - const std::string_view shardStr = id.substr(0, firstDot); - const std::string_view realmStr = id.substr(firstDot + 1, secondDot - firstDot - 1); - const std::string_view accountNumStr = id.substr(secondDot + 1, id.size() - secondDot - 1); - - // Convert the shard number - auto result = std::from_chars(shardStr.data(), shardStr.data() + shardStr.size(), accountId.mShardNum); - if (result.ec != std::errc() || result.ptr != shardStr.data() + shardStr.size()) - { - throw std::invalid_argument("Input account ID string is malformed"); - } - accountId.checkShardNum(); - - // Convert the realm number - result = std::from_chars(realmStr.data(), realmStr.data() + realmStr.size(), accountId.mRealmNum); - if (result.ec != std::errc() || result.ptr != realmStr.data() + realmStr.size()) - { - throw std::invalid_argument("Input account ID string is malformed"); - } - accountId.checkRealmNum(); + return (mShardNum == other.mShardNum) && (mRealmNum == other.mRealmNum) && + ((mAccountNum && other.mAccountNum && mAccountNum == other.mAccountNum) || + (mPublicKeyAlias && other.mPublicKeyAlias && + mPublicKeyAlias->toStringDer() == other.mPublicKeyAlias->toStringDer()) || + (mEvmAddressAlias && other.mEvmAddressAlias && + mEvmAddressAlias->toString() == other.mEvmAddressAlias->toString()) || + (!mAccountNum && !other.mAccountNum && !mPublicKeyAlias && !other.mPublicKeyAlias && !mEvmAddressAlias && + !other.mEvmAddressAlias)); +} - // Determine what the input account number is. First determine if it is an alias (stringified DER-encoded PublicKey) +//----- +AccountId AccountId::fromString(std::string_view id) +{ + // First try the input id as an EvmAddress. If not an EvmAddress, process as normal. try { - accountId.mPublicKeyAlias = PublicKey::fromStringDer(accountNumStr); - return accountId; + return fromEvmAddress(id); } - catch (const BadKeyException&) + catch (const std::invalid_argument&) { - // If not an alias, determine if it is an EVM address + // Get the shard and realm numbers. + const uint64_t shard = internal::EntityIdHelper::getShardNum(id); + const uint64_t realm = internal::EntityIdHelper::getRealmNum(id); + + // Determine what the entity ID number is. First try to see if it's just an account number. Get the entity number + // string before the try-block to verify the input ID isn't malformed. + const std::string_view entityNum = internal::EntityIdHelper::getEntityNumStr(id); + const std::string_view checksum = internal::EntityIdHelper::getChecksum(id); try { - accountId.mEvmAddressAlias = EvmAddress::fromString(accountNumStr); + return AccountId(shard, realm, internal::EntityIdHelper::getNum(entityNum), checksum); } catch (const std::invalid_argument&) { - // If not an EVM address, then treat as a normal account number - uint64_t accountNum; - result = std::from_chars(accountNumStr.data(), accountNumStr.data() + accountNumStr.size(), accountNum); - if (result.ec != std::errc() || result.ptr != accountNumStr.data() + accountNumStr.size()) + // If the entity number isn't an account number, it's an alias. Aliases cannot have checksums, so verify that + // first. + if (!checksum.empty()) + { + throw std::invalid_argument("Account ID aliases can't have checksums"); + } + + // First try the alias as a PublicKey. + try + { + return AccountId(shard, realm, PublicKey::fromStringDer(entityNum)); + } + catch (const BadKeyException&) { - throw std::invalid_argument("Input account ID string is malformed"); + // If not a PublicKey, it must be an EVM address. + try + { + return AccountId(shard, realm, EvmAddress::fromString(entityNum)); + } + catch (const std::invalid_argument&) + { + // If not an EVM address, the entity ID cannot be realized. + throw std::invalid_argument(std::string("Account number/alias cannot be realized from ") + entityNum.data()); + } } - accountId.mAccountNum = accountNum; - accountId.checkAccountNum(); } } - - return accountId; } //----- @@ -165,16 +154,17 @@ AccountId AccountId::fromEvmAddress(const EvmAddress& evmAddress, uint64_t shard } //----- -bool AccountId::operator==(const AccountId& other) const +AccountId AccountId::fromSolidityAddress(std::string_view address) { - return (mShardNum == other.mShardNum) && (mRealmNum == other.mRealmNum) && - ((mAccountNum && other.mAccountNum && mAccountNum == other.mAccountNum) || - (mPublicKeyAlias && other.mPublicKeyAlias && - mPublicKeyAlias->toStringDer() == other.mPublicKeyAlias->toStringDer()) || - (mEvmAddressAlias && other.mEvmAddressAlias && - mEvmAddressAlias->toString() == other.mEvmAddressAlias->toString()) || - (!mAccountNum && !other.mAccountNum && !mPublicKeyAlias && !other.mPublicKeyAlias && !mEvmAddressAlias && - !other.mEvmAddressAlias)); + const std::vector bytes = internal::EntityIdHelper::decodeSolidityAddress(address); + if (internal::EntityIdHelper::isLongZeroAddress(bytes)) + { + return internal::EntityIdHelper::fromSolidityAddress(bytes); + } + else + { + return fromEvmAddress(address); + } } //----- @@ -210,6 +200,23 @@ AccountId AccountId::fromProtobuf(const proto::AccountID& proto) return accountId; } +//----- +AccountId AccountId::fromBytes(const std::vector& bytes) +{ + proto::AccountID proto; + proto.ParseFromArray(bytes.data(), static_cast(bytes.size())); + return fromProtobuf(proto); +} + +//----- +void AccountId::validateChecksum(const Client& client) const +{ + if (mAccountNum.has_value() && !mChecksum.empty()) + { + internal::EntityIdHelper::validate(mShardNum, mRealmNum, mAccountNum.value(), client, mChecksum); + } +} + //----- std::unique_ptr AccountId::toProtobuf() const { @@ -236,16 +243,14 @@ std::unique_ptr AccountId::toProtobuf() const //----- std::string AccountId::toSolidityAddress() const { - // If the shard number is a value greater than 32 bits can represent, then creating a Long-Zero format is impossible. - if (mShardNum > std::numeric_limits::max()) + if (mAccountNum.has_value()) { - throw IllegalStateException("Shard number is too big. Its value must be able to fit in 32 bits."); + return internal::EntityIdHelper::toSolidityAddress(mShardNum, mRealmNum, mAccountNum.value()); + } + else + { + throw IllegalStateException("AccountId must contain an account number to generate a Solidity address"); } - - return internal::HexConverter::bytesToHex(internal::Utilities::concatenateVectors( - { internal::Utilities::removePrefix(internal::Utilities::getBytes(mShardNum), sizeof(uint64_t) - 4), - internal::Utilities::getBytes(mRealmNum), - internal::Utilities::getBytes(mAccountNum.value()) })); } //----- @@ -273,30 +278,27 @@ std::string AccountId::toString() const } //----- -void AccountId::checkShardNum() const +std::string AccountId::toStringWithChecksum(const Client& client) const { - if (mShardNum > std::numeric_limits::max()) + // Checksums are only valid for accounts not using an alias. + if (!mAccountNum.has_value()) { - throw std::invalid_argument("Input shard number is too large"); + throw IllegalStateException("Checksums can only be generated for AccountIds that have an account number"); } -} -//----- -void AccountId::checkRealmNum() const -{ - if (mRealmNum > std::numeric_limits::max()) + if (mChecksum.empty()) { - throw std::invalid_argument("Input realm number is too large"); + mChecksum = internal::EntityIdHelper::checksum( + internal::EntityIdHelper::toString(mShardNum, mRealmNum, mAccountNum.value()), client.getLedgerId()); } + + return internal::EntityIdHelper::toString(mShardNum, mRealmNum, mAccountNum.value(), mChecksum); } //----- -void AccountId::checkAccountNum() const +std::vector AccountId::toBytes() const { - if (*mAccountNum > std::numeric_limits::max()) - { - throw std::invalid_argument("Input account number is too large"); - } + return internal::Utilities::stringToByteVector(toProtobuf()->SerializeAsString()); } } // namespace Hedera diff --git a/sdk/main/src/AccountInfoQuery.cc b/sdk/main/src/AccountInfoQuery.cc index e0ae014c1..adce23546 100644 --- a/sdk/main/src/AccountInfoQuery.cc +++ b/sdk/main/src/AccountInfoQuery.cc @@ -50,6 +50,12 @@ grpc::Status AccountInfoQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kCryptoGetInfo, request, deadline, response); } +//----- +void AccountInfoQuery::validateChecksums(const Client& client) const +{ + mAccountId.validateChecksum(client); +} + //----- proto::Query AccountInfoQuery::buildRequest(proto::QueryHeader* header) const { diff --git a/sdk/main/src/AccountRecordsQuery.cc b/sdk/main/src/AccountRecordsQuery.cc index 42ce27480..144a045b3 100644 --- a/sdk/main/src/AccountRecordsQuery.cc +++ b/sdk/main/src/AccountRecordsQuery.cc @@ -50,6 +50,12 @@ grpc::Status AccountRecordsQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kCryptoGetAccountRecords, request, deadline, response); } +//----- +void AccountRecordsQuery::validateChecksums(const Client& client) const +{ + mAccountId.validateChecksum(client); +} + //----- proto::Query AccountRecordsQuery::buildRequest(proto::QueryHeader* header) const { diff --git a/sdk/main/src/AccountStakersQuery.cc b/sdk/main/src/AccountStakersQuery.cc index 960316c12..7633c72d5 100644 --- a/sdk/main/src/AccountStakersQuery.cc +++ b/sdk/main/src/AccountStakersQuery.cc @@ -59,6 +59,12 @@ grpc::Status AccountStakersQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kCryptoGetProxyStakers, request, deadline, response); } +//----- +void AccountStakersQuery::validateChecksums(const Client& client) const +{ + mAccountId.validateChecksum(client); +} + //----- proto::Query AccountStakersQuery::buildRequest(proto::QueryHeader* header) const { diff --git a/sdk/main/src/AccountUpdateTransaction.cc b/sdk/main/src/AccountUpdateTransaction.cc index 3bc7717ec..67626e412 100644 --- a/sdk/main/src/AccountUpdateTransaction.cc +++ b/sdk/main/src/AccountUpdateTransaction.cc @@ -156,6 +156,17 @@ grpc::Status AccountUpdateTransaction::submitRequest(const proto::Transaction& r return node->submitTransaction(proto::TransactionBody::DataCase::kCryptoUpdateAccount, request, deadline, response); } +//----- +void AccountUpdateTransaction::validateChecksums(const Client& client) const +{ + mAccountId.validateChecksum(client); + + if (mStakedAccountId.has_value()) + { + mStakedAccountId->validateChecksum(client); + } +} + //----- void AccountUpdateTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/Client.cc b/sdk/main/src/Client.cc index 9639c0748..36b710201 100644 --- a/sdk/main/src/Client.cc +++ b/sdk/main/src/Client.cc @@ -25,6 +25,7 @@ #include "NodeAddressBook.h" #include "PrivateKey.h" #include "PublicKey.h" +#include "exceptions/UninitializedException.h" #include "impl/BaseNodeAddress.h" #include "impl/MirrorNetwork.h" #include "impl/Network.h" @@ -83,6 +84,9 @@ struct Client::ClientImpl // The period of time to wait between network updates. std::chrono::duration mNetworkUpdatePeriod = DEFAULT_NETWORK_UPDATE_PERIOD; + // Should this Client automatically validate entity checksums? + bool mAutoValidateChecksums = false; + // Has this Client made its initial network update? This is utilized in case the user updates the network update // period before the initial update is made, as it prevents the update period from being overwritten. bool mMadeInitialNetworkUpdate = false; @@ -297,6 +301,24 @@ Client& Client::setNetworkUpdatePeriod(const std::chrono::duration& upda return *this; } +//----- +Client& Client::setAutoValidateChecksums(bool validate) +{ + mImpl->mAutoValidateChecksums = validate; + return *this; +} + +//----- +Client& Client::setLedgerId(const LedgerId& ledgerId) +{ + if (mImpl->mNetwork) + { + mImpl->mNetwork->setLedgerId(ledgerId); + } + + return *this; +} + //----- std::shared_ptr Client::getNetwork() const { @@ -372,6 +394,23 @@ std::chrono::duration Client::getNetworkUpdatePeriod() const return mImpl->mNetworkUpdatePeriod; } +//----- +bool Client::isAutoValidateChecksumsEnabled() const +{ + return mImpl->mAutoValidateChecksums; +} + +//----- +LedgerId Client::getLedgerId() const +{ + if (!mImpl->mNetwork) + { + throw UninitializedException("Client does not have a Network from which to grab the ledger ID"); + } + + return mImpl->mNetwork->getLedgerId(); +} + //----- std::shared_ptr Client::getMirrorNetwork() const { diff --git a/sdk/main/src/ContractByteCodeQuery.cc b/sdk/main/src/ContractByteCodeQuery.cc index a9d778776..087ba7d32 100644 --- a/sdk/main/src/ContractByteCodeQuery.cc +++ b/sdk/main/src/ContractByteCodeQuery.cc @@ -50,6 +50,12 @@ grpc::Status ContractByteCodeQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kContractGetBytecode, request, deadline, response); } +//----- +void ContractByteCodeQuery::validateChecksums(const Client& client) const +{ + mContractId.validateChecksum(client); +} + //----- proto::Query ContractByteCodeQuery::buildRequest(proto::QueryHeader* header) const { diff --git a/sdk/main/src/ContractCallQuery.cc b/sdk/main/src/ContractCallQuery.cc index 5ee753d95..74c2b8f6a 100644 --- a/sdk/main/src/ContractCallQuery.cc +++ b/sdk/main/src/ContractCallQuery.cc @@ -78,6 +78,12 @@ grpc::Status ContractCallQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kContractCallLocal, request, deadline, response); } +//----- +void ContractCallQuery::validateChecksums(const Client& client) const +{ + mContractId.validateChecksum(client); +} + //----- proto::Query ContractCallQuery::buildRequest(proto::QueryHeader* header) const { diff --git a/sdk/main/src/ContractCreateTransaction.cc b/sdk/main/src/ContractCreateTransaction.cc index b411f012c..9424b2d90 100644 --- a/sdk/main/src/ContractCreateTransaction.cc +++ b/sdk/main/src/ContractCreateTransaction.cc @@ -174,6 +174,25 @@ grpc::Status ContractCreateTransaction::submitRequest(const proto::Transaction& proto::TransactionBody::DataCase::kContractCreateInstance, request, deadline, response); } +//----- +void ContractCreateTransaction::validateChecksums(const Client& client) const +{ + if (mBytecodeFileId.has_value()) + { + mBytecodeFileId->validateChecksum(client); + } + + if (mAutoRenewAccountId.has_value()) + { + mAutoRenewAccountId->validateChecksum(client); + } + + if (mStakedAccountId.has_value()) + { + mStakedAccountId->validateChecksum(client); + } +} + //----- void ContractCreateTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/ContractDeleteTransaction.cc b/sdk/main/src/ContractDeleteTransaction.cc index 48d26ecbf..b345679ba 100644 --- a/sdk/main/src/ContractDeleteTransaction.cc +++ b/sdk/main/src/ContractDeleteTransaction.cc @@ -78,6 +78,22 @@ grpc::Status ContractDeleteTransaction::submitRequest(const proto::Transaction& proto::TransactionBody::DataCase::kContractDeleteInstance, request, deadline, response); } +//----- +void ContractDeleteTransaction::validateChecksums(const Client& client) const +{ + mContractId.validateChecksum(client); + + if (mTransferContractId.has_value()) + { + mTransferContractId->validateChecksum(client); + } + + if (mTransferAccountId.has_value()) + { + mTransferAccountId->validateChecksum(client); + } +} + //----- void ContractDeleteTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/ContractExecuteTransaction.cc b/sdk/main/src/ContractExecuteTransaction.cc index bec8b4a3e..14409796a 100644 --- a/sdk/main/src/ContractExecuteTransaction.cc +++ b/sdk/main/src/ContractExecuteTransaction.cc @@ -94,6 +94,12 @@ grpc::Status ContractExecuteTransaction::submitRequest(const proto::Transaction& return node->submitTransaction(proto::TransactionBody::DataCase::kContractCall, request, deadline, response); } +//----- +void ContractExecuteTransaction::validateChecksums(const Client& client) const +{ + mContractId.validateChecksum(client); +} + //----- void ContractExecuteTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/ContractFunctionParameters.cc b/sdk/main/src/ContractFunctionParameters.cc index ace6abffb..6b25fe314 100644 --- a/sdk/main/src/ContractFunctionParameters.cc +++ b/sdk/main/src/ContractFunctionParameters.cc @@ -19,6 +19,7 @@ */ #include "ContractFunctionParameters.h" #include "exceptions/OpenSSLException.h" +#include "impl/EntityIdHelper.h" #include "impl/HexConverter.h" #include "impl/Utilities.h" @@ -29,10 +30,6 @@ namespace Hedera { namespace { -// The length of a solidity address. -constexpr int SOLIDITY_ADDRESS_LEN = 20; -// The length of a hex-encoded solidity address. -constexpr int SOLIDITY_ADDRESS_LEN_HEX = SOLIDITY_ADDRESS_LEN * 2; // Padding that can substring without new allocations. const std::vector POSITIVE_PADDING(31, std::byte(0x00)); const std::vector NEGATIVE_PADDING(31, std::byte(0xFF)); @@ -237,10 +234,10 @@ template address.remove_prefix(2); } - if (address.size() != SOLIDITY_ADDRESS_LEN_HEX) + if (address.size() != internal::EntityIdHelper::SOLIDITY_ADDRESS_LEN_HEX) { - throw std::invalid_argument("Solidity addresses must be " + std::to_string(SOLIDITY_ADDRESS_LEN_HEX) + - " characters"); + throw std::invalid_argument("Solidity addresses must be " + + std::to_string(internal::EntityIdHelper::SOLIDITY_ADDRESS_LEN_HEX) + " characters"); } try diff --git a/sdk/main/src/ContractId.cc b/sdk/main/src/ContractId.cc index 6c54ecb25..916e61f34 100644 --- a/sdk/main/src/ContractId.cc +++ b/sdk/main/src/ContractId.cc @@ -18,6 +18,11 @@ * */ #include "ContractId.h" +#include "Client.h" +#include "LedgerId.h" +#include "exceptions/IllegalStateException.h" +#include "impl/EntityIdHelper.h" +#include "impl/HexConverter.h" #include "impl/Utilities.h" #include @@ -26,10 +31,9 @@ namespace Hedera { //----- -ContractId::ContractId(const uint64_t& num) +ContractId::ContractId(uint64_t num) : mContractNum(num) { - checkContractNum(); } //----- @@ -39,24 +43,20 @@ ContractId::ContractId(const EvmAddress& address) } //----- -ContractId::ContractId(const uint64_t& shard, const uint64_t& realm, const uint64_t& num) +ContractId::ContractId(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum) : mShardNum(shard) , mRealmNum(realm) , mContractNum(num) + , mChecksum(checksum) { - checkShardNum(); - checkRealmNum(); - checkContractNum(); } //----- -ContractId::ContractId(const uint64_t& shard, const uint64_t& realm, const EvmAddress& address) +ContractId::ContractId(uint64_t shard, uint64_t realm, const EvmAddress& address) : mShardNum(shard) , mRealmNum(realm) , mEvmAddress(address) { - checkShardNum(); - checkRealmNum(); } //----- @@ -68,6 +68,70 @@ bool ContractId::operator==(const ContractId& other) const (!mContractNum && !other.mContractNum && !mEvmAddress && !other.mEvmAddress)); } +//----- +ContractId ContractId::fromString(std::string_view id) +{ + // Get the shard and realm numbers. + const uint64_t shard = internal::EntityIdHelper::getShardNum(id); + const uint64_t realm = internal::EntityIdHelper::getRealmNum(id); + + // Determine what the entity ID number is. First try to see if it's just a contract number. Get the entity number + // string before the try-block to verify the input ID isn't malformed. + const std::string_view entityNum = internal::EntityIdHelper::getEntityNumStr(id); + const std::string_view checksum = internal::EntityIdHelper::getChecksum(id); + try + { + return ContractId(shard, realm, internal::EntityIdHelper::getNum(entityNum), checksum); + } + catch (const std::invalid_argument&) + { + // If the entity number isn't a contract number, it's an EvmAddress. An EvmAddress cannot have checksums, so verify + // that first. + if (!checksum.empty()) + { + throw std::invalid_argument("Contract IDs with EVM addresses can't have checksums"); + } + + // Try the entity number as an EVM address. + try + { + return ContractId(shard, realm, EvmAddress::fromString(entityNum)); + } + catch (const std::invalid_argument&) + { + // If not an EVM address, the entity ID cannot be realized. + throw std::invalid_argument(std::string("Contract number/EVM address cannot be realized from ") + + entityNum.data()); + } + } +} + +//----- +ContractId ContractId::fromEvmAddress(std::string_view evmAddress, uint64_t shard, uint64_t realm) +{ + return fromEvmAddress(EvmAddress::fromString(evmAddress), shard, realm); +} + +//----- +ContractId ContractId::fromEvmAddress(const EvmAddress& evmAddress, uint64_t shard, uint64_t realm) +{ + return ContractId(shard, realm, evmAddress); +} + +//----- +ContractId ContractId::fromSolidityAddress(std::string_view address) +{ + const std::vector bytes = internal::EntityIdHelper::decodeSolidityAddress(address); + if (internal::EntityIdHelper::isLongZeroAddress(bytes)) + { + return internal::EntityIdHelper::fromSolidityAddress(bytes); + } + else + { + return fromEvmAddress(address); + } +} + //----- ContractId ContractId::fromProtobuf(const proto::ContractID& proto) { @@ -87,6 +151,14 @@ ContractId ContractId::fromProtobuf(const proto::ContractID& proto) return contractId; } +//----- +ContractId ContractId::fromBytes(const std::vector& bytes) +{ + proto::ContractID proto; + proto.ParseFromArray(bytes.data(), static_cast(bytes.size())); + return fromProtobuf(proto); +} + //----- std::unique_ptr ContractId::clone() const { @@ -101,6 +173,21 @@ std::unique_ptr ContractId::toProtobufKey() const return proto; } +//----- +std::vector ContractId::toBytes() const +{ + return internal::Utilities::stringToByteVector(toProtobuf()->SerializeAsString()); +} + +//----- +void ContractId::validateChecksum(const Client& client) const +{ + if (mContractNum.has_value() && !mChecksum.empty()) + { + internal::EntityIdHelper::validate(mShardNum, mRealmNum, mContractNum.value(), client, mChecksum); + } +} + //----- std::unique_ptr ContractId::toProtobuf() const { @@ -108,11 +195,11 @@ std::unique_ptr ContractId::toProtobuf() const proto->set_shardnum(static_cast(mShardNum)); proto->set_realmnum(static_cast(mRealmNum)); - if (mContractNum) + if (mContractNum.has_value()) { - proto->set_contractnum(static_cast(*mContractNum)); + proto->set_contractnum(static_cast(mContractNum.value())); } - else if (mEvmAddress) + else if (mEvmAddress.has_value()) { proto->set_evm_address(internal::Utilities::byteVectorToString(mEvmAddress->toBytes())); } @@ -121,83 +208,59 @@ std::unique_ptr ContractId::toProtobuf() const } //----- -std::string ContractId::toString() const +std::string ContractId::toSolidityAddress() const { - std::string str = std::to_string(mShardNum) + '.' + std::to_string(mRealmNum) + '.'; - - if (mContractNum) + if (mEvmAddress.has_value()) { - return str + std::to_string(*mContractNum); + return internal::HexConverter::bytesToHex(mEvmAddress->toBytes()); } - else if (mEvmAddress) + else if (mContractNum.has_value()) { - return str + mEvmAddress->toString(); + return internal::EntityIdHelper::toSolidityAddress(mShardNum, mRealmNum, mContractNum.value()); } else { - // Uninitialized case - return str + '0'; + throw IllegalStateException( + "ContractId must contain a contract number of EVM address to generate a Solidity address"); } } //----- -ContractId& ContractId::setShardNum(const uint64_t& num) -{ - mShardNum = num; - checkShardNum(); - return *this; -} - -//----- -ContractId& ContractId::setRealmNum(const uint64_t& num) -{ - mRealmNum = num; - checkRealmNum(); - return *this; -} - -//----- -ContractId& ContractId::setContractNum(const uint64_t& num) -{ - mContractNum = num; - checkContractNum(); - mEvmAddress.reset(); - return *this; -} - -//----- -ContractId& ContractId::setEvmAddress(const EvmAddress& address) +std::string ContractId::toString() const { - mEvmAddress = address; - mContractNum.reset(); - return *this; -} + std::string str = std::to_string(mShardNum) + '.' + std::to_string(mRealmNum) + '.'; -//----- -void ContractId::checkShardNum() const -{ - if (mShardNum > std::numeric_limits::max()) + if (mContractNum.has_value()) { - throw std::invalid_argument("Input shard number is too large"); + return str + std::to_string(mContractNum.value()); + } + else if (mEvmAddress.has_value()) + { + return str + mEvmAddress->toString(); + } + else + { + // Uninitialized case + return str + '0'; } } //----- -void ContractId::checkRealmNum() const +std::string ContractId::toStringWithChecksum(const Client& client) const { - if (mRealmNum > std::numeric_limits::max()) + // Checksums are only valid for contracts using a contract number. + if (!mContractNum.has_value()) { - throw std::invalid_argument("Input realm number is too large"); + throw IllegalStateException("Checksums can only be generated for ContractIds that contain a contract number"); } -} -//----- -void ContractId::checkContractNum() const -{ - if (mContractNum && *mContractNum > std::numeric_limits::max()) + if (mChecksum.empty()) { - throw std::invalid_argument("Input contract number is too large"); + mChecksum = internal::EntityIdHelper::checksum( + internal::EntityIdHelper::toString(mShardNum, mRealmNum, mContractNum.value()), client.getLedgerId()); } + + return internal::EntityIdHelper::toString(mShardNum, mRealmNum, mContractNum.value(), mChecksum); } } // namespace Hedera diff --git a/sdk/main/src/ContractInfoQuery.cc b/sdk/main/src/ContractInfoQuery.cc index 0984055b1..11cf52a1c 100644 --- a/sdk/main/src/ContractInfoQuery.cc +++ b/sdk/main/src/ContractInfoQuery.cc @@ -50,6 +50,12 @@ grpc::Status ContractInfoQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kContractGetInfo, request, deadline, response); } +//----- +void ContractInfoQuery::validateChecksums(const Client& client) const +{ + mContractId.validateChecksum(client); +} + //----- proto::Query ContractInfoQuery::buildRequest(proto::QueryHeader* header) const { diff --git a/sdk/main/src/ContractUpdateTransaction.cc b/sdk/main/src/ContractUpdateTransaction.cc index 630f31c23..cfb909506 100644 --- a/sdk/main/src/ContractUpdateTransaction.cc +++ b/sdk/main/src/ContractUpdateTransaction.cc @@ -150,6 +150,22 @@ grpc::Status ContractUpdateTransaction::submitRequest(const proto::Transaction& proto::TransactionBody::DataCase::kContractUpdateInstance, request, deadline, response); } +//----- +void ContractUpdateTransaction::validateChecksums(const Client& client) const +{ + mContractId.validateChecksum(client); + + if (mAutoRenewAccountId.has_value()) + { + mAutoRenewAccountId->validateChecksum(client); + } + + if (mStakedAccountId.has_value()) + { + mStakedAccountId->validateChecksum(client); + } +} + //----- void ContractUpdateTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/CustomFee.cc b/sdk/main/src/CustomFee.cc index de437fe62..96ccc5b89 100644 --- a/sdk/main/src/CustomFee.cc +++ b/sdk/main/src/CustomFee.cc @@ -18,6 +18,7 @@ * */ #include "CustomFee.h" +#include "Client.h" #include "CustomFixedFee.h" #include "CustomFractionalFee.h" #include "CustomRoyaltyFee.h" @@ -42,6 +43,12 @@ std::unique_ptr CustomFee::fromProtobuf(const proto::CustomFee& proto } } +//----- +void CustomFee::validateChecksums(const Client& client) const +{ + mFeeCollectorAccountId.validateChecksum(client); +} + //----- std::unique_ptr CustomFee::initProtobuf() const { diff --git a/sdk/main/src/CustomFixedFee.cc b/sdk/main/src/CustomFixedFee.cc index 6840260ab..94cf165d2 100644 --- a/sdk/main/src/CustomFixedFee.cc +++ b/sdk/main/src/CustomFixedFee.cc @@ -57,6 +57,17 @@ std::unique_ptr CustomFixedFee::toProtobuf() const return fee; } +//----- +void CustomFixedFee::validateChecksums(const Client& client) const +{ + CustomFee::validateChecksums(client); + + if (mDenominatingTokenId.has_value()) + { + mDenominatingTokenId->validateChecksum(client); + } +} + //----- std::unique_ptr CustomFixedFee::toFixedFeeProtobuf() const { diff --git a/sdk/main/src/DelegateContractId.cc b/sdk/main/src/DelegateContractId.cc index b922327a2..c66d68f81 100644 --- a/sdk/main/src/DelegateContractId.cc +++ b/sdk/main/src/DelegateContractId.cc @@ -18,21 +18,21 @@ * */ #include "DelegateContractId.h" +#include "impl/EntityIdHelper.h" -#include #include namespace Hedera { //----- -DelegateContractId::DelegateContractId(const uint64_t& num) +DelegateContractId::DelegateContractId(uint64_t num) : ContractId(num) { } //----- -DelegateContractId::DelegateContractId(const uint64_t& shard, const uint64_t& realm, const uint64_t& num) - : ContractId(shard, realm, num) +DelegateContractId::DelegateContractId(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum) + : ContractId(shard, realm, num, checksum) { } @@ -45,47 +45,17 @@ bool DelegateContractId::operator==(const DelegateContractId& other) const //----- DelegateContractId DelegateContractId::fromString(std::string_view id) { - // Get the indices of the two delimiter '.' - const size_t firstDot = id.find_first_of('.'); - const size_t secondDot = id.find_last_of('.'); - - // Make sure there are at least two dots - if (firstDot == secondDot) - { - throw std::invalid_argument("Input delegate contract ID string is malformed"); - } - - uint64_t shardNum; - uint64_t realmNum; - uint64_t contractNum; - - // Grab the three strings - const std::string_view shardStr = id.substr(0, firstDot); - const std::string_view realmStr = id.substr(firstDot + 1, secondDot - firstDot - 1); - const std::string_view contractNumStr = id.substr(secondDot + 1, id.size() - secondDot - 1); - - // Convert the shard number - auto result = std::from_chars(shardStr.data(), shardStr.data() + shardStr.size(), shardNum); - if (result.ec != std::errc() || result.ptr != shardStr.data() + shardStr.size()) - { - throw std::invalid_argument("Input account ID string is malformed"); - } - - // Convert the realm number - result = std::from_chars(realmStr.data(), realmStr.data() + realmStr.size(), realmNum); - if (result.ec != std::errc() || result.ptr != realmStr.data() + realmStr.size()) - { - throw std::invalid_argument("Input account ID string is malformed"); - } - - // Convert the contract number. - result = std::from_chars(contractNumStr.data(), contractNumStr.data() + contractNumStr.size(), contractNum); - if (result.ec != std::errc() || result.ptr != contractNumStr.data() + contractNumStr.size()) - { - throw std::invalid_argument("Input account ID string is malformed"); - } + return DelegateContractId(internal::EntityIdHelper::getShardNum(id), + internal::EntityIdHelper::getRealmNum(id), + internal::EntityIdHelper::getEntityNum(id), + internal::EntityIdHelper::getChecksum(id)); +} - return DelegateContractId(shardNum, realmNum, contractNum); +//----- +DelegateContractId DelegateContractId::fromSolidityAddress(std::string_view address) +{ + return internal::EntityIdHelper::fromSolidityAddress( + internal::EntityIdHelper::decodeSolidityAddress(address)); } //----- @@ -96,6 +66,14 @@ DelegateContractId DelegateContractId::fromProtobuf(const proto::ContractID& pro static_cast(proto.contractnum())); } +//----- +DelegateContractId DelegateContractId::fromBytes(const std::vector& bytes) +{ + proto::ContractID proto; + proto.ParseFromArray(bytes.data(), static_cast(bytes.size())); + return fromProtobuf(proto); +} + //----- std::unique_ptr DelegateContractId::clone() const { diff --git a/sdk/main/src/EthereumTransaction.cc b/sdk/main/src/EthereumTransaction.cc index 7f8caf8cb..db8bbc331 100644 --- a/sdk/main/src/EthereumTransaction.cc +++ b/sdk/main/src/EthereumTransaction.cc @@ -75,6 +75,15 @@ grpc::Status EthereumTransaction::submitRequest(const proto::Transaction& reques return node->submitTransaction(proto::TransactionBody::DataCase::kEthereumTransaction, request, deadline, response); } +//----- +void EthereumTransaction::validateChecksums(const Client& client) const +{ + if (mCallDataFileId.has_value()) + { + mCallDataFileId->validateChecksum(client); + } +} + //----- void EthereumTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/EvmAddress.cc b/sdk/main/src/EvmAddress.cc index 8313cb90b..474bceb94 100644 --- a/sdk/main/src/EvmAddress.cc +++ b/sdk/main/src/EvmAddress.cc @@ -18,6 +18,7 @@ * */ #include "EvmAddress.h" +#include "exceptions/OpenSSLException.h" #include "impl/HexConverter.h" #include @@ -40,22 +41,23 @@ EvmAddress EvmAddress::fromString(std::string_view address) throw std::invalid_argument("Input EVM address string is not the correct size"); } - // Remove the prefix if it exists + // Remove the prefix if it exists. if (hasPrefix) { address.remove_prefix(prefix.size()); } - // Ensure all digits are hex digits - if (!std::all_of(address.cbegin(), address.cend(), [](unsigned char c) { return std::isxdigit(c); })) + // Decode the EVM address and return it. + try { - throw std::invalid_argument("Input EVM address is not a hex-encoded string"); + evmAddress.mEvmAddress = internal::HexConverter::hexToBytes(address); + evmAddress.checkEvmAddress(); + return evmAddress; + } + catch (const OpenSSLException&) + { + throw std::invalid_argument("Input EVM address is malformed"); } - - evmAddress.mEvmAddress = internal::HexConverter::hexToBytes(address); - evmAddress.checkEvmAddress(); - - return evmAddress; } //----- diff --git a/sdk/main/src/FileAppendTransaction.cc b/sdk/main/src/FileAppendTransaction.cc index 51958de40..b2c2aafd3 100644 --- a/sdk/main/src/FileAppendTransaction.cc +++ b/sdk/main/src/FileAppendTransaction.cc @@ -87,6 +87,12 @@ grpc::Status FileAppendTransaction::submitRequest(const proto::Transaction& requ return node->submitTransaction(proto::TransactionBody::DataCase::kFileAppend, request, deadline, response); } +//----- +void FileAppendTransaction::validateChecksums(const Client& client) const +{ + mFileId.validateChecksum(client); +} + //----- void FileAppendTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/FileContentsQuery.cc b/sdk/main/src/FileContentsQuery.cc index 4333239b9..bbb3ba29d 100644 --- a/sdk/main/src/FileContentsQuery.cc +++ b/sdk/main/src/FileContentsQuery.cc @@ -50,6 +50,12 @@ grpc::Status FileContentsQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kFileGetContents, request, deadline, response); } +//----- +void FileContentsQuery::validateChecksums(const Client& client) const +{ + mFileId.validateChecksum(client); +} + //----- proto::Query FileContentsQuery::buildRequest(proto::QueryHeader* header) const { diff --git a/sdk/main/src/FileCreateTransaction.cc b/sdk/main/src/FileCreateTransaction.cc index feb5695bf..6a31f2c7c 100644 --- a/sdk/main/src/FileCreateTransaction.cc +++ b/sdk/main/src/FileCreateTransaction.cc @@ -102,6 +102,12 @@ grpc::Status FileCreateTransaction::submitRequest(const proto::Transaction& requ return node->submitTransaction(proto::TransactionBody::DataCase::kFileCreate, request, deadline, response); } +//----- +void FileCreateTransaction::validateChecksums(const Client& client) const +{ + // No entity IDs to validate. +} + //----- void FileCreateTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/FileDeleteTransaction.cc b/sdk/main/src/FileDeleteTransaction.cc index f4682d02c..b0def2dc8 100644 --- a/sdk/main/src/FileDeleteTransaction.cc +++ b/sdk/main/src/FileDeleteTransaction.cc @@ -59,6 +59,12 @@ grpc::Status FileDeleteTransaction::submitRequest(const proto::Transaction& requ return node->submitTransaction(proto::TransactionBody::DataCase::kFileDelete, request, deadline, response); } +//----- +void FileDeleteTransaction::validateChecksums(const Client& client) const +{ + mFileId.validateChecksum(client); +} + //----- void FileDeleteTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/FileId.cc b/sdk/main/src/FileId.cc index 29f883009..db6a7df90 100644 --- a/sdk/main/src/FileId.cc +++ b/sdk/main/src/FileId.cc @@ -18,8 +18,11 @@ * */ #include "FileId.h" +#include "Client.h" +#include "LedgerId.h" +#include "impl/EntityIdHelper.h" +#include "impl/Utilities.h" -#include #include #include @@ -35,21 +38,18 @@ const FileId FileId::FEE_SCHEDULE = FileId(0ULL, 0ULL, 111ULL); const FileId FileId::EXCHANGE_RATES = FileId(0ULL, 0ULL, 112ULL); //----- -FileId::FileId(const uint64_t& num) +FileId::FileId(uint64_t num) : mFileNum(num) { - checkFileNum(); } //----- -FileId::FileId(const uint64_t& shard, const uint64_t& realm, const uint64_t& num) +FileId::FileId(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum) : mShardNum(shard) , mRealmNum(realm) , mFileNum(num) + , mChecksum(checksum) { - checkShardNum(); - checkRealmNum(); - checkFileNum(); } //----- @@ -61,31 +61,17 @@ bool FileId::operator==(const FileId& other) const //----- FileId FileId::fromString(std::string_view id) { - FileId fileId; - - // Get the indices of the two delimiter '.' - const size_t firstDot = id.find_first_of('.'); - const size_t secondDot = id.find_last_of('.'); - - // Make sure there are at least two dots - if (firstDot == secondDot) - { - throw std::invalid_argument("Input file ID string is malformed"); - } - - // Convert the shard number - parseNum(id.substr(0, firstDot), fileId.mShardNum); - fileId.checkShardNum(); - - // Convert the realm number - parseNum(id.substr(firstDot + 1, secondDot - firstDot - 1), fileId.mRealmNum); - fileId.checkRealmNum(); - - // Convert the shard number - parseNum(id.substr(secondDot + 1, id.size() - secondDot - 1), fileId.mFileNum); - fileId.checkFileNum(); + return FileId(internal::EntityIdHelper::getShardNum(id), + internal::EntityIdHelper::getRealmNum(id), + internal::EntityIdHelper::getEntityNum(id), + internal::EntityIdHelper::getChecksum(id)); +} - return fileId; +//----- +FileId FileId::fromSolidityAddress(std::string_view address) +{ + return internal::EntityIdHelper::fromSolidityAddress( + internal::EntityIdHelper::decodeSolidityAddress(address)); } //----- @@ -97,80 +83,60 @@ FileId FileId::fromProtobuf(const proto::FileID& proto) } //----- -std::unique_ptr FileId::toProtobuf() const +FileId FileId::fromBytes(const std::vector& bytes) { - auto body = std::make_unique(); - body->set_shardnum(static_cast(mShardNum)); - body->set_realmnum(static_cast(mRealmNum)); - body->set_filenum(static_cast(mFileNum)); - return body; + proto::FileID proto; + proto.ParseFromArray(bytes.data(), static_cast(bytes.size())); + return fromProtobuf(proto); } //----- -std::string FileId::toString() const +void FileId::validateChecksum(const Client& client) const { - return std::to_string(mShardNum) + '.' + std::to_string(mRealmNum) + '.' + std::to_string(mFileNum); -} - -//----- -FileId& FileId::setShardNum(const uint64_t& num) -{ - mShardNum = num; - checkShardNum(); - return *this; + if (!mChecksum.empty()) + { + internal::EntityIdHelper::validate(mShardNum, mRealmNum, mFileNum, client, mChecksum); + } } //----- -FileId& FileId::setRealmNum(const uint64_t& num) +std::unique_ptr FileId::toProtobuf() const { - mRealmNum = num; - checkRealmNum(); - return *this; + auto body = std::make_unique(); + body->set_shardnum(static_cast(mShardNum)); + body->set_realmnum(static_cast(mRealmNum)); + body->set_filenum(static_cast(mFileNum)); + return body; } //----- -FileId& FileId::setFileNum(const uint64_t& num) +std::string FileId::toSolidityAddress() const { - mFileNum = num; - checkFileNum(); - return *this; + return internal::EntityIdHelper::toSolidityAddress(mShardNum, mRealmNum, mFileNum); } //----- -void FileId::checkShardNum() const +std::string FileId::toString() const { - if (mShardNum > std::numeric_limits::max()) - { - throw std::invalid_argument("Input shard number is too large"); - } + return internal::EntityIdHelper::toString(mShardNum, mRealmNum, mFileNum); } //----- -void FileId::checkRealmNum() const +std::string FileId::toStringWithChecksum(const Client& client) const { - if (mRealmNum > std::numeric_limits::max()) + if (mChecksum.empty()) { - throw std::invalid_argument("Input realm number is too large"); + mChecksum = internal::EntityIdHelper::checksum(internal::EntityIdHelper::toString(mShardNum, mRealmNum, mFileNum), + client.getLedgerId()); } -} -//----- -void FileId::checkFileNum() const -{ - if (mFileNum > std::numeric_limits::max()) - { - throw std::invalid_argument("Input file number is too large"); - } + return internal::EntityIdHelper::toString(mShardNum, mRealmNum, mFileNum, mChecksum); } //----- -void FileId::parseNum(std::string_view str, uint64_t& num) +std::vector FileId::toBytes() const { - if (std::from_chars_result result = std::from_chars(str.data(), str.data() + str.size(), num); - result.ec != std::errc() || result.ptr != str.data() + str.size()) - { - throw std::invalid_argument("Input file ID string is malformed"); - } + return internal::Utilities::stringToByteVector(toProtobuf()->SerializeAsString()); } } // namespace Hedera diff --git a/sdk/main/src/FileInfoQuery.cc b/sdk/main/src/FileInfoQuery.cc index 81b96c0bb..0af7caaec 100644 --- a/sdk/main/src/FileInfoQuery.cc +++ b/sdk/main/src/FileInfoQuery.cc @@ -50,6 +50,12 @@ grpc::Status FileInfoQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kFileGetInfo, request, deadline, response); } +//----- +void FileInfoQuery::validateChecksums(const Client& client) const +{ + mFileId.validateChecksum(client); +} + //----- proto::Query FileInfoQuery::buildRequest(proto::QueryHeader* header) const { diff --git a/sdk/main/src/FileUpdateTransaction.cc b/sdk/main/src/FileUpdateTransaction.cc index 94d93ae77..c86541275 100644 --- a/sdk/main/src/FileUpdateTransaction.cc +++ b/sdk/main/src/FileUpdateTransaction.cc @@ -110,6 +110,12 @@ grpc::Status FileUpdateTransaction::submitRequest(const proto::Transaction& requ return node->submitTransaction(proto::TransactionBody::DataCase::kFileUpdate, request, deadline, response); } +//----- +void FileUpdateTransaction::validateChecksums(const Client& client) const +{ + mFileId.validateChecksum(client); +} + //----- void FileUpdateTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/FreezeTransaction.cc b/sdk/main/src/FreezeTransaction.cc index a35b3a0fc..81f392e4f 100644 --- a/sdk/main/src/FreezeTransaction.cc +++ b/sdk/main/src/FreezeTransaction.cc @@ -85,6 +85,15 @@ grpc::Status FreezeTransaction::submitRequest(const proto::Transaction& request, return node->submitTransaction(proto::TransactionBody::DataCase::kFreeze, request, deadline, response); } +//----- +void FreezeTransaction::validateChecksums(const Client& client) const +{ + if (mFileId.has_value()) + { + mFileId->validateChecksum(client); + } +} + //----- void FreezeTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/HbarAllowance.cc b/sdk/main/src/HbarAllowance.cc index bb72d6866..77266c03b 100644 --- a/sdk/main/src/HbarAllowance.cc +++ b/sdk/main/src/HbarAllowance.cc @@ -50,6 +50,13 @@ HbarAllowance HbarAllowance::fromProtobuf(const proto::CryptoAllowance& proto) return allowance; } +//----- +void HbarAllowance::validateChecksums(const Client& client) const +{ + mOwnerAccountId.validateChecksum(client); + mSpenderAccountId.validateChecksum(client); +} + //----- std::unique_ptr HbarAllowance::toProtobuf() const { @@ -60,25 +67,4 @@ std::unique_ptr HbarAllowance::toProtobuf() const return proto; } -//----- -HbarAllowance& HbarAllowance::setOwnerAccountId(const AccountId& accountId) -{ - mOwnerAccountId = accountId; - return *this; -} - -//----- -HbarAllowance& HbarAllowance::setSpenderAccountId(const AccountId& accountId) -{ - mSpenderAccountId = accountId; - return *this; -} - -//----- -HbarAllowance& HbarAllowance::setAmount(const Hbar& amount) -{ - mAmount = amount; - return *this; -} - } // namespace Hedera diff --git a/sdk/main/src/HbarTransfer.cc b/sdk/main/src/HbarTransfer.cc index 00632c6d7..b2736f5f8 100644 --- a/sdk/main/src/HbarTransfer.cc +++ b/sdk/main/src/HbarTransfer.cc @@ -23,6 +23,14 @@ namespace Hedera { +//----- +HbarTransfer::HbarTransfer(AccountId accountId, const Hbar& amount, bool approval) + : mAccountId(std::move(accountId)) + , mAmount(amount) + , mIsApproved(approval) +{ +} + //----- HbarTransfer HbarTransfer::fromProtobuf(const proto::AccountAmount& proto) { @@ -50,25 +58,4 @@ std::unique_ptr HbarTransfer::toProtobuf() const return proto; } -//----- -HbarTransfer& HbarTransfer::setAccountId(const AccountId& accountId) -{ - mAccountId = accountId; - return *this; -} - -//----- -HbarTransfer& HbarTransfer::setAmount(const Hbar& amount) -{ - mAmount = amount; - return *this; -} - -//----- -HbarTransfer& HbarTransfer::setApproved(bool approved) -{ - mIsApproved = approved; - return *this; -} - } // namespace Hedera diff --git a/sdk/main/src/NetworkVersionInfoQuery.cc b/sdk/main/src/NetworkVersionInfoQuery.cc index 786091bd0..84d19156b 100644 --- a/sdk/main/src/NetworkVersionInfoQuery.cc +++ b/sdk/main/src/NetworkVersionInfoQuery.cc @@ -46,6 +46,12 @@ grpc::Status NetworkVersionInfoQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kNetworkGetVersionInfo, request, deadline, response); } +//----- +void NetworkVersionInfoQuery::validateChecksums(const Client& client) const +{ + // No entity IDs to validate. +} + //----- proto::Query NetworkVersionInfoQuery::buildRequest(proto::QueryHeader* header) const { diff --git a/sdk/main/src/NftId.cc b/sdk/main/src/NftId.cc index 5d231c8a8..47900342a 100644 --- a/sdk/main/src/NftId.cc +++ b/sdk/main/src/NftId.cc @@ -25,11 +25,10 @@ namespace Hedera { //----- -NftId::NftId(const TokenId& id, const uint64_t& serialNumber) - : mTokenId(id) +NftId::NftId(TokenId id, const uint64_t& serialNumber) + : mTokenId(std::move(id)) , mSerialNum(serialNumber) { - checkSerialNum(); } //----- @@ -61,7 +60,6 @@ NftId NftId::fromString(std::string_view id) { throw std::invalid_argument("Input NFT ID string is malformed"); } - nftId.checkSerialNum(); return nftId; } @@ -69,15 +67,7 @@ NftId NftId::fromString(std::string_view id) //----- NftId NftId::fromProtobuf(const proto::NftID& proto) { - NftId nftId; - - if (proto.has_token_id()) - { - nftId.mTokenId = TokenId::fromProtobuf(proto.token_id()); - } - - nftId.mSerialNum = static_cast(proto.serial_number()); - return nftId; + return NftId(TokenId::fromProtobuf(proto.token_id()), static_cast(proto.serial_number())); } //----- @@ -95,28 +85,4 @@ std::string NftId::toString() const return mTokenId.toString() + '/' + std::to_string(mSerialNum); } -//----- -NftId& NftId::setTokenId(const TokenId& id) -{ - mTokenId = id; - return *this; -} - -//----- -NftId& NftId::setSerialNum(const uint64_t& num) -{ - mSerialNum = num; - checkSerialNum(); - return *this; -} - -//----- -void NftId::checkSerialNum() const -{ - if (mSerialNum > std::numeric_limits::max()) - { - throw std::invalid_argument("Input serial number too big"); - } -} - } // namespace Hedera \ No newline at end of file diff --git a/sdk/main/src/Query.cc b/sdk/main/src/Query.cc index 08ea9ac2c..a4251d89e 100644 --- a/sdk/main/src/Query.cc +++ b/sdk/main/src/Query.cc @@ -250,6 +250,12 @@ void Query::onExecute(const Client& client) client.getNetwork()->getNodeAccountIdsForExecute()); } + // Validate checksums if that option is enabled. + if (client.isAutoValidateChecksumsEnabled()) + { + validateChecksums(client); + } + // There's nothing else to do if this Query is free or is meant to get the cost. if (!isPaymentRequired() || mImpl->mGetCost) { diff --git a/sdk/main/src/ScheduleCreateTransaction.cc b/sdk/main/src/ScheduleCreateTransaction.cc index 663afda81..184b22379 100644 --- a/sdk/main/src/ScheduleCreateTransaction.cc +++ b/sdk/main/src/ScheduleCreateTransaction.cc @@ -220,6 +220,15 @@ grpc::Status ScheduleCreateTransaction::submitRequest(const proto::Transaction& return node->submitTransaction(proto::TransactionBody::DataCase::kScheduleCreate, request, deadline, response); } +//----- +void ScheduleCreateTransaction::validateChecksums(const Client& client) const +{ + if (mImpl->mPayerAccountId.has_value()) + { + mImpl->mPayerAccountId->validateChecksum(client); + } +} + //----- void ScheduleCreateTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/ScheduleDeleteTransaction.cc b/sdk/main/src/ScheduleDeleteTransaction.cc index 46338f360..0bdc81660 100644 --- a/sdk/main/src/ScheduleDeleteTransaction.cc +++ b/sdk/main/src/ScheduleDeleteTransaction.cc @@ -59,6 +59,15 @@ grpc::Status ScheduleDeleteTransaction::submitRequest(const proto::Transaction& return node->submitTransaction(proto::TransactionBody::DataCase::kScheduleDelete, request, deadline, response); } +//----- +void ScheduleDeleteTransaction::validateChecksums(const Client& client) const +{ + if (mScheduleId.has_value()) + { + mScheduleId->validateChecksum(client); + } +} + //----- void ScheduleDeleteTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/ScheduleId.cc b/sdk/main/src/ScheduleId.cc index 7cb794243..a185ec3f5 100644 --- a/sdk/main/src/ScheduleId.cc +++ b/sdk/main/src/ScheduleId.cc @@ -4,7 +4,7 @@ * * Copyright (C) 2020 - 2023 Hedera Hashgraph, LLC * - * Licensed under the Apache License, Version 2.0 (the "License"); + * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * @@ -18,26 +18,28 @@ * */ #include "ScheduleId.h" -#include "exceptions/IllegalStateException.h" +#include "Client.h" +#include "LedgerId.h" +#include "impl/EntityIdHelper.h" #include "impl/Utilities.h" -#include #include #include namespace Hedera { //----- -ScheduleId::ScheduleId(const uint64_t& num) +ScheduleId::ScheduleId(uint64_t num) : mScheduleNum(num) { } //----- -ScheduleId::ScheduleId(const uint64_t& shard, const uint64_t& realm, const uint64_t& num) +ScheduleId::ScheduleId(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum) : mShardNum(shard) , mRealmNum(realm) , mScheduleNum(num) + , mChecksum(checksum) { } @@ -50,45 +52,10 @@ bool ScheduleId::operator==(const ScheduleId& other) const //----- ScheduleId ScheduleId::fromString(std::string_view id) { - ScheduleId topicId; - - // Get the indices of the two delimiter '.' - const size_t firstDot = id.find_first_of('.'); - const size_t secondDot = id.find_last_of('.'); - - // Make sure there are at least two dots - if (firstDot == secondDot) - { - throw std::invalid_argument("Input topic ID string is malformed"); - } - - // Grab the three strings - const std::string_view shardStr = id.substr(0, firstDot); - const std::string_view realmStr = id.substr(firstDot + 1, secondDot - firstDot - 1); - const std::string_view topicStr = id.substr(secondDot + 1, id.size() - secondDot - 1); - - // Convert the shard number - auto result = std::from_chars(shardStr.data(), shardStr.data() + shardStr.size(), topicId.mShardNum); - if (result.ec != std::errc() || result.ptr != shardStr.data() + shardStr.size()) - { - throw std::invalid_argument("Input topic ID string is malformed"); - } - - // Convert the realm number - result = std::from_chars(realmStr.data(), realmStr.data() + realmStr.size(), topicId.mRealmNum); - if (result.ec != std::errc() || result.ptr != realmStr.data() + realmStr.size()) - { - throw std::invalid_argument("Input topic ID string is malformed"); - } - - // Convert the topic number - result = std::from_chars(topicStr.data(), topicStr.data() + topicStr.size(), topicId.mScheduleNum); - if (result.ec != std::errc() || result.ptr != topicStr.data() + topicStr.size()) - { - throw std::invalid_argument("Input topic ID string is malformed"); - } - - return topicId; + return ScheduleId(internal::EntityIdHelper::getShardNum(id), + internal::EntityIdHelper::getRealmNum(id), + internal::EntityIdHelper::getEntityNum(id), + internal::EntityIdHelper::getChecksum(id)); } //----- @@ -102,31 +69,52 @@ ScheduleId ScheduleId::fromProtobuf(const proto::ScheduleID& proto) //----- ScheduleId ScheduleId::fromBytes(const std::vector& bytes) { - proto::ScheduleID protoScheduleId; - protoScheduleId.ParseFromArray(bytes.data(), static_cast(bytes.size())); - return fromProtobuf(protoScheduleId); + proto::ScheduleID proto; + proto.ParseFromArray(bytes.data(), static_cast(bytes.size())); + return fromProtobuf(proto); } //----- -std::unique_ptr ScheduleId::toProtobuf() const +void ScheduleId::validateChecksum(const Client& client) const { - auto protoScheduleId = std::make_unique(); - protoScheduleId->set_shardnum(static_cast(mShardNum)); - protoScheduleId->set_realmnum(static_cast(mRealmNum)); - protoScheduleId->set_schedulenum(static_cast(mScheduleNum)); - return protoScheduleId; + if (!mChecksum.empty()) + { + internal::EntityIdHelper::validate(mShardNum, mRealmNum, mScheduleNum, client, mChecksum); + } } //----- -std::vector ScheduleId::toBytes() const +std::unique_ptr ScheduleId::toProtobuf() const { - return internal::Utilities::stringToByteVector(toProtobuf()->SerializeAsString()); + auto body = std::make_unique(); + body->set_shardnum(static_cast(mShardNum)); + body->set_realmnum(static_cast(mRealmNum)); + body->set_schedulenum(static_cast(mScheduleNum)); + return body; } //----- std::string ScheduleId::toString() const { - return std::to_string(mShardNum) + '.' + std::to_string(mRealmNum) + '.' + std::to_string(mScheduleNum); + return internal::EntityIdHelper::toString(mShardNum, mRealmNum, mScheduleNum); +} + +//----- +std::string ScheduleId::toStringWithChecksum(const Client& client) const +{ + if (mChecksum.empty()) + { + mChecksum = internal::EntityIdHelper::checksum( + internal::EntityIdHelper::toString(mShardNum, mRealmNum, mScheduleNum), client.getLedgerId()); + } + + return internal::EntityIdHelper::toString(mShardNum, mRealmNum, mScheduleNum, mChecksum); +} + +//----- +std::vector ScheduleId::toBytes() const +{ + return internal::Utilities::stringToByteVector(toProtobuf()->SerializeAsString()); } } // namespace Hedera diff --git a/sdk/main/src/ScheduleInfoQuery.cc b/sdk/main/src/ScheduleInfoQuery.cc index 3df0c5e11..967a30caa 100644 --- a/sdk/main/src/ScheduleInfoQuery.cc +++ b/sdk/main/src/ScheduleInfoQuery.cc @@ -50,6 +50,12 @@ grpc::Status ScheduleInfoQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kScheduleGetInfo, request, deadline, response); } +//----- +void ScheduleInfoQuery::validateChecksums(const Client& client) const +{ + mScheduleId.validateChecksum(client); +} + //----- proto::Query ScheduleInfoQuery::buildRequest(proto::QueryHeader* header) const { diff --git a/sdk/main/src/ScheduleSignTransaction.cc b/sdk/main/src/ScheduleSignTransaction.cc index b31e9b9c6..fa7514fb9 100644 --- a/sdk/main/src/ScheduleSignTransaction.cc +++ b/sdk/main/src/ScheduleSignTransaction.cc @@ -67,6 +67,15 @@ grpc::Status ScheduleSignTransaction::submitRequest(const proto::Transaction& re return node->submitTransaction(proto::TransactionBody::DataCase::kScheduleSign, request, deadline, response); } +//----- +void ScheduleSignTransaction::validateChecksums(const Client& client) const +{ + if (mScheduleId.has_value()) + { + mScheduleId->validateChecksum(client); + } +} + //----- void ScheduleSignTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/SystemDeleteTransaction.cc b/sdk/main/src/SystemDeleteTransaction.cc index 167f33d1c..75cdd160f 100644 --- a/sdk/main/src/SystemDeleteTransaction.cc +++ b/sdk/main/src/SystemDeleteTransaction.cc @@ -79,6 +79,20 @@ grpc::Status SystemDeleteTransaction::submitRequest(const proto::Transaction& re return node->submitTransaction(proto::TransactionBody::DataCase::kSystemDelete, request, deadline, response); } +//----- +void SystemDeleteTransaction::validateChecksums(const Client& client) const +{ + if (mFileId.has_value()) + { + mFileId->validateChecksum(client); + } + + if (mContractId.has_value()) + { + mContractId->validateChecksum(client); + } +} + //----- void SystemDeleteTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/SystemUndeleteTransaction.cc b/sdk/main/src/SystemUndeleteTransaction.cc index 08ed8015f..1d08ef874 100644 --- a/sdk/main/src/SystemUndeleteTransaction.cc +++ b/sdk/main/src/SystemUndeleteTransaction.cc @@ -70,6 +70,20 @@ grpc::Status SystemUndeleteTransaction::submitRequest(const proto::Transaction& return node->submitTransaction(proto::TransactionBody::DataCase::kSystemUndelete, request, deadline, response); } +//----- +void SystemUndeleteTransaction::validateChecksums(const Client& client) const +{ + if (mFileId.has_value()) + { + mFileId->validateChecksum(client); + } + + if (mContractId.has_value()) + { + mContractId->validateChecksum(client); + } +} + //----- void SystemUndeleteTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenAllowance.cc b/sdk/main/src/TokenAllowance.cc index bb8560ab7..53c4f7f4f 100644 --- a/sdk/main/src/TokenAllowance.cc +++ b/sdk/main/src/TokenAllowance.cc @@ -50,6 +50,14 @@ TokenAllowance TokenAllowance::fromBytes(const std::vector& bytes) return fromProtobuf(tokenAllowance); } +//----- +void TokenAllowance::validateChecksums(const Client& client) const +{ + mTokenId.validateChecksum(client); + mOwnerAccountId.validateChecksum(client); + mSpenderAccountId.validateChecksum(client); +} + //----- std::unique_ptr TokenAllowance::toProtobuf() const { diff --git a/sdk/main/src/TokenAssociateTransaction.cc b/sdk/main/src/TokenAssociateTransaction.cc index 8125a8e05..25b58c9c4 100644 --- a/sdk/main/src/TokenAssociateTransaction.cc +++ b/sdk/main/src/TokenAssociateTransaction.cc @@ -67,6 +67,18 @@ grpc::Status TokenAssociateTransaction::submitRequest(const proto::Transaction& return node->submitTransaction(proto::TransactionBody::DataCase::kTokenAssociate, request, deadline, response); } +//----- +void TokenAssociateTransaction::validateChecksums(const Client& client) const +{ + if (mAccountId.has_value()) + { + mAccountId->validateChecksum(client); + } + + std::for_each( + mTokenIds.cbegin(), mTokenIds.cend(), [&client](const TokenId& tokenId) { tokenId.validateChecksum(client); }); +} + //----- void TokenAssociateTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenBurnTransaction.cc b/sdk/main/src/TokenBurnTransaction.cc index 44f18ca70..647b6a9aa 100644 --- a/sdk/main/src/TokenBurnTransaction.cc +++ b/sdk/main/src/TokenBurnTransaction.cc @@ -75,6 +75,12 @@ grpc::Status TokenBurnTransaction::submitRequest(const proto::Transaction& reque return node->submitTransaction(proto::TransactionBody::DataCase::kTokenBurn, request, deadline, response); } +//----- +void TokenBurnTransaction::validateChecksums(const Client& client) const +{ + mTokenId.validateChecksum(client); +} + //----- void TokenBurnTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenCreateTransaction.cc b/sdk/main/src/TokenCreateTransaction.cc index 200f37230..f63a4712d 100644 --- a/sdk/main/src/TokenCreateTransaction.cc +++ b/sdk/main/src/TokenCreateTransaction.cc @@ -232,6 +232,24 @@ grpc::Status TokenCreateTransaction::submitRequest(const proto::Transaction& req return node->submitTransaction(proto::TransactionBody::DataCase::kTokenCreation, request, deadline, response); } +//----- +void TokenCreateTransaction::validateChecksums(const Client& client) const +{ + if (mTreasuryAccountId.has_value()) + { + mTreasuryAccountId->validateChecksum(client); + } + + if (mAutoRenewAccountId.has_value()) + { + mAutoRenewAccountId->validateChecksum(client); + } + + std::for_each(mCustomFees.cbegin(), + mCustomFees.cend(), + [&client](const std::shared_ptr& fee) { fee->validateChecksums(client); }); +} + //----- void TokenCreateTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenDeleteTransaction.cc b/sdk/main/src/TokenDeleteTransaction.cc index 443b623c6..34f25012c 100644 --- a/sdk/main/src/TokenDeleteTransaction.cc +++ b/sdk/main/src/TokenDeleteTransaction.cc @@ -59,6 +59,15 @@ grpc::Status TokenDeleteTransaction::submitRequest(const proto::Transaction& req return node->submitTransaction(proto::TransactionBody::DataCase::kTokenDeletion, request, deadline, response); } +//----- +void TokenDeleteTransaction::validateChecksums(const Client& client) const +{ + if (mTokenId.has_value()) + { + mTokenId->validateChecksum(client); + } +} + //----- void TokenDeleteTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenDissociateTransaction.cc b/sdk/main/src/TokenDissociateTransaction.cc index ba4208016..87cec6747 100644 --- a/sdk/main/src/TokenDissociateTransaction.cc +++ b/sdk/main/src/TokenDissociateTransaction.cc @@ -67,6 +67,18 @@ grpc::Status TokenDissociateTransaction::submitRequest(const proto::Transaction& return node->submitTransaction(proto::TransactionBody::DataCase::kTokenDissociate, request, deadline, response); } +//----- +void TokenDissociateTransaction::validateChecksums(const Client& client) const +{ + if (mAccountId.has_value()) + { + mAccountId->validateChecksum(client); + } + + std::for_each( + mTokenIds.cbegin(), mTokenIds.cend(), [&client](const TokenId& tokenId) { tokenId.validateChecksum(client); }); +} + //----- void TokenDissociateTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenFeeScheduleUpdateTransaction.cc b/sdk/main/src/TokenFeeScheduleUpdateTransaction.cc index a685e29e2..3600710ad 100644 --- a/sdk/main/src/TokenFeeScheduleUpdateTransaction.cc +++ b/sdk/main/src/TokenFeeScheduleUpdateTransaction.cc @@ -69,6 +69,16 @@ grpc::Status TokenFeeScheduleUpdateTransaction::submitRequest(const proto::Trans proto::TransactionBody::DataCase::kTokenFeeScheduleUpdate, request, deadline, response); } +//----- +void TokenFeeScheduleUpdateTransaction::validateChecksums(const Client& client) const +{ + mTokenId.validateChecksum(client); + + std::for_each(mCustomFees.cbegin(), + mCustomFees.cend(), + [&client](const std::shared_ptr& fee) { fee->validateChecksums(client); }); +} + //----- void TokenFeeScheduleUpdateTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenFreezeTransaction.cc b/sdk/main/src/TokenFreezeTransaction.cc index 721c4a318..edfb820bc 100644 --- a/sdk/main/src/TokenFreezeTransaction.cc +++ b/sdk/main/src/TokenFreezeTransaction.cc @@ -67,6 +67,13 @@ grpc::Status TokenFreezeTransaction::submitRequest(const proto::Transaction& req return node->submitTransaction(proto::TransactionBody::DataCase::kTokenFreeze, request, deadline, response); } +//----- +void TokenFreezeTransaction::validateChecksums(const Client& client) const +{ + mTokenId.validateChecksum(client); + mAccountId.validateChecksum(client); +} + //----- void TokenFreezeTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenGrantKycTransaction.cc b/sdk/main/src/TokenGrantKycTransaction.cc index 91a260300..7cde8f77d 100644 --- a/sdk/main/src/TokenGrantKycTransaction.cc +++ b/sdk/main/src/TokenGrantKycTransaction.cc @@ -67,6 +67,13 @@ grpc::Status TokenGrantKycTransaction::submitRequest(const proto::Transaction& r return node->submitTransaction(proto::TransactionBody::DataCase::kTokenGrantKyc, request, deadline, response); } +//----- +void TokenGrantKycTransaction::validateChecksums(const Client& client) const +{ + mTokenId.validateChecksum(client); + mAccountId.validateChecksum(client); +} + //----- void TokenGrantKycTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenId.cc b/sdk/main/src/TokenId.cc index eab671fda..8e51f09e2 100644 --- a/sdk/main/src/TokenId.cc +++ b/sdk/main/src/TokenId.cc @@ -18,29 +18,30 @@ * */ #include "TokenId.h" +#include "Client.h" +#include "LedgerId.h" +#include "NftId.h" +#include "impl/EntityIdHelper.h" +#include "impl/Utilities.h" -#include +#include #include -#include namespace Hedera { //----- -TokenId::TokenId(const uint64_t& num) +TokenId::TokenId(uint64_t num) : mTokenNum(num) { - checkTokenNum(); } //----- -TokenId::TokenId(const uint64_t& shard, const uint64_t& realm, const uint64_t& num) +TokenId::TokenId(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum) : mShardNum(shard) , mRealmNum(realm) , mTokenNum(num) + , mChecksum(checksum) { - checkShardNum(); - checkRealmNum(); - checkTokenNum(); } //----- @@ -52,125 +53,82 @@ bool TokenId::operator==(const TokenId& other) const //----- TokenId TokenId::fromString(std::string_view id) { - TokenId tokenId; - - // Get the indices of the two delimiter '.' - const size_t firstDot = id.find_first_of('.'); - const size_t secondDot = id.find_last_of('.'); - - // Make sure there are at least two dots - if (firstDot == secondDot) - { - throw std::invalid_argument("Input token ID string is malformed"); - } - - // Grab the three strings - const std::string_view shardStr = id.substr(0, firstDot); - const std::string_view realmStr = id.substr(firstDot + 1, secondDot - firstDot - 1); - const std::string_view tokenStr = id.substr(secondDot + 1, id.size() - secondDot - 1); - - // Convert the shard number - auto result = std::from_chars(shardStr.data(), shardStr.data() + shardStr.size(), tokenId.mShardNum); - if (result.ec != std::errc() || result.ptr != shardStr.data() + shardStr.size()) - { - throw std::invalid_argument("Input token ID string is malformed"); - } - tokenId.checkShardNum(); - - // Convert the realm number - result = std::from_chars(realmStr.data(), realmStr.data() + realmStr.size(), tokenId.mRealmNum); - if (result.ec != std::errc() || result.ptr != realmStr.data() + realmStr.size()) - { - throw std::invalid_argument("Input token ID string is malformed"); - } - tokenId.checkRealmNum(); - - // Convert the token number - result = std::from_chars(tokenStr.data(), tokenStr.data() + tokenStr.size(), tokenId.mTokenNum); - if (result.ec != std::errc() || result.ptr != tokenStr.data() + tokenStr.size()) - { - throw std::invalid_argument("Input token ID string is malformed"); - } - tokenId.checkTokenNum(); - - return tokenId; + return TokenId(internal::EntityIdHelper::getShardNum(id), + internal::EntityIdHelper::getRealmNum(id), + internal::EntityIdHelper::getEntityNum(id), + internal::EntityIdHelper::getChecksum(id)); } //----- -TokenId TokenId::fromProtobuf(const proto::TokenID& proto) +TokenId TokenId::fromSolidityAddress(std::string_view address) { - TokenId tokenId; - tokenId.mShardNum = static_cast(proto.shardnum()); - tokenId.mRealmNum = static_cast(proto.realmnum()); - tokenId.mTokenNum = static_cast(proto.tokennum()); - return tokenId; + return internal::EntityIdHelper::fromSolidityAddress( + internal::EntityIdHelper::decodeSolidityAddress(address)); } //----- -std::unique_ptr TokenId::toProtobuf() const +TokenId TokenId::fromProtobuf(const proto::TokenID& proto) { - auto proto = std::make_unique(); - proto->set_shardnum(static_cast(mShardNum)); - proto->set_realmnum(static_cast(mRealmNum)); - proto->set_tokennum(static_cast(mTokenNum)); - return proto; + return TokenId(static_cast(proto.shardnum()), + static_cast(proto.realmnum()), + static_cast(proto.tokennum())); } //----- -std::string TokenId::toString() const +TokenId TokenId::fromBytes(const std::vector& bytes) { - return std::to_string(mShardNum) + '.' + std::to_string(mRealmNum) + '.' + std::to_string(mTokenNum); + proto::TokenID proto; + proto.ParseFromArray(bytes.data(), static_cast(bytes.size())); + return fromProtobuf(proto); } //----- -TokenId& TokenId::setShardNum(const uint64_t& num) +void TokenId::validateChecksum(const Client& client) const { - mShardNum = num; - checkShardNum(); - return *this; + if (!mChecksum.empty()) + { + internal::EntityIdHelper::validate(mShardNum, mRealmNum, mTokenNum, client, mChecksum); + } } //----- -TokenId& TokenId::setRealmNum(const uint64_t& num) +NftId TokenId::nft(uint64_t serial) const { - mRealmNum = num; - checkRealmNum(); - return *this; + return NftId(*this, serial); } //----- -TokenId& TokenId::setTokenNum(const uint64_t& num) +std::unique_ptr TokenId::toProtobuf() const { - mTokenNum = num; - checkTokenNum(); - return *this; + auto body = std::make_unique(); + body->set_shardnum(static_cast(mShardNum)); + body->set_realmnum(static_cast(mRealmNum)); + body->set_tokennum(static_cast(mTokenNum)); + return body; } //----- -void TokenId::checkShardNum() const +std::string TokenId::toString() const { - if (mShardNum > std::numeric_limits::max()) - { - throw std::invalid_argument("Input shard number is too large"); - } + return internal::EntityIdHelper::toString(mShardNum, mRealmNum, mTokenNum); } //----- -void TokenId::checkRealmNum() const +std::string TokenId::toStringWithChecksum(const Client& client) const { - if (mRealmNum > std::numeric_limits::max()) + if (mChecksum.empty()) { - throw std::invalid_argument("Input realm number is too large"); + mChecksum = internal::EntityIdHelper::checksum(internal::EntityIdHelper::toString(mShardNum, mRealmNum, mTokenNum), + client.getLedgerId()); } + + return internal::EntityIdHelper::toString(mShardNum, mRealmNum, mTokenNum, mChecksum); } //----- -void TokenId::checkTokenNum() const +std::vector TokenId::toBytes() const { - if (mTokenNum > std::numeric_limits::max()) - { - throw std::invalid_argument("Input token number is too large"); - } + return internal::Utilities::stringToByteVector(toProtobuf()->SerializeAsString()); } } // namespace Hedera diff --git a/sdk/main/src/TokenInfoQuery.cc b/sdk/main/src/TokenInfoQuery.cc index 2be359bcb..d1805f32b 100644 --- a/sdk/main/src/TokenInfoQuery.cc +++ b/sdk/main/src/TokenInfoQuery.cc @@ -50,6 +50,12 @@ grpc::Status TokenInfoQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kTokenGetInfo, request, deadline, response); } +//----- +void TokenInfoQuery::validateChecksums(const Client& client) const +{ + mTokenId.validateChecksum(client); +} + //----- proto::Query TokenInfoQuery::buildRequest(proto::QueryHeader* header) const { diff --git a/sdk/main/src/TokenMintTransaction.cc b/sdk/main/src/TokenMintTransaction.cc index be8db9bc1..0e8c1e7c1 100644 --- a/sdk/main/src/TokenMintTransaction.cc +++ b/sdk/main/src/TokenMintTransaction.cc @@ -85,6 +85,12 @@ grpc::Status TokenMintTransaction::submitRequest(const proto::Transaction& reque return node->submitTransaction(proto::TransactionBody::DataCase::kTokenMint, request, deadline, response); } +//----- +void TokenMintTransaction::validateChecksums(const Client& client) const +{ + mTokenId.validateChecksum(client); +} + //----- void TokenMintTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenNftAllowance.cc b/sdk/main/src/TokenNftAllowance.cc index a0c849d0e..6d44704f7 100644 --- a/sdk/main/src/TokenNftAllowance.cc +++ b/sdk/main/src/TokenNftAllowance.cc @@ -87,6 +87,25 @@ TokenNftAllowance TokenNftAllowance::fromBytes(const std::vector& byt return fromProtobuf(nftAllowance); } +//----- +void TokenNftAllowance::validateChecksums(const Client& client) const +{ + if (mTokenId.has_value()) + { + mTokenId->validateChecksum(client); + } + + if (mOwnerAccountId.has_value()) + { + mOwnerAccountId->validateChecksum(client); + } + + if (mSpenderAccountId.has_value()) + { + mSpenderAccountId->validateChecksum(client); + } +} + //----- std::unique_ptr TokenNftAllowance::toProtobuf() const { diff --git a/sdk/main/src/TokenNftInfoQuery.cc b/sdk/main/src/TokenNftInfoQuery.cc index 4d4e5fa0f..ca55cba92 100644 --- a/sdk/main/src/TokenNftInfoQuery.cc +++ b/sdk/main/src/TokenNftInfoQuery.cc @@ -53,6 +53,12 @@ grpc::Status TokenNftInfoQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kTokenGetNftInfo, request, deadline, response); } +//----- +void TokenNftInfoQuery::validateChecksums(const Client& client) const +{ + mNftId.mTokenId.validateChecksum(client); +} + //----- proto::Query TokenNftInfoQuery::buildRequest(proto::QueryHeader* header) const { diff --git a/sdk/main/src/TokenNftTransfer.cc b/sdk/main/src/TokenNftTransfer.cc index ca4262d9b..38ba3fa1b 100644 --- a/sdk/main/src/TokenNftTransfer.cc +++ b/sdk/main/src/TokenNftTransfer.cc @@ -19,68 +19,45 @@ */ #include "TokenNftTransfer.h" -#include #include namespace Hedera { //----- -TokenNftTransfer TokenNftTransfer::fromProtobuf(const proto::NftTransfer& proto) +TokenNftTransfer::TokenNftTransfer(NftId nftId, AccountId sender, AccountId receiver, bool approved) + : mNftId(std::move(nftId)) + , mSenderAccountId(std::move(sender)) + , mReceiverAccountId(std::move(receiver)) + , mIsApproval(approved) { - TokenNftTransfer tokenNftTransfer; - - if (proto.has_senderaccountid()) - { - tokenNftTransfer.mSenderAccountID = AccountId::fromProtobuf(proto.senderaccountid()); - } - - if (proto.has_receiveraccountid()) - { - tokenNftTransfer.mReceiverAccountID = AccountId::fromProtobuf(proto.receiveraccountid()); - } - - tokenNftTransfer.mNftId.setSerialNum(static_cast(proto.serialnumber())); - tokenNftTransfer.mIsApproval = proto.is_approval(); - return tokenNftTransfer; } //----- -std::unique_ptr TokenNftTransfer::toProtobuf() const +TokenNftTransfer TokenNftTransfer::fromProtobuf(const proto::NftTransfer& proto, const TokenId& tokenId) { - auto proto = std::make_unique(); - proto->set_allocated_senderaccountid(mSenderAccountID.toProtobuf().release()); - proto->set_allocated_receiveraccountid(mReceiverAccountID.toProtobuf().release()); - proto->set_serialnumber(static_cast(mNftId.getSerialNum())); - proto->set_is_approval(mIsApproval); - return proto; + return TokenNftTransfer(NftId(tokenId, static_cast(proto.serialnumber())), + AccountId::fromProtobuf(proto.senderaccountid()), + AccountId::fromProtobuf(proto.receiveraccountid()), + proto.is_approval()); } //----- -TokenNftTransfer& TokenNftTransfer::setNftId(const NftId& nftId) +void TokenNftTransfer::validateChecksums(const Hedera::Client& client) const { - mNftId = nftId; - return *this; + mNftId.mTokenId.validateChecksum(client); + mSenderAccountId.validateChecksum(client); + mReceiverAccountId.validateChecksum(client); } //----- -TokenNftTransfer& TokenNftTransfer::setSenderAccountId(const AccountId& accountId) -{ - mSenderAccountID = accountId; - return *this; -} - -//----- -TokenNftTransfer& TokenNftTransfer::setReceiverAccountId(const AccountId& accountId) -{ - mReceiverAccountID = accountId; - return *this; -} - -//----- -TokenNftTransfer& TokenNftTransfer::setApproval(bool approval) +std::unique_ptr TokenNftTransfer::toProtobuf() const { - mIsApproval = approval; - return *this; + auto proto = std::make_unique(); + proto->set_allocated_senderaccountid(mSenderAccountId.toProtobuf().release()); + proto->set_allocated_receiveraccountid(mReceiverAccountId.toProtobuf().release()); + proto->set_serialnumber(static_cast(mNftId.mSerialNum)); + proto->set_is_approval(mIsApproval); + return proto; } } // namespace Hedera diff --git a/sdk/main/src/TokenPauseTransaction.cc b/sdk/main/src/TokenPauseTransaction.cc index f71c1edeb..9a638e751 100644 --- a/sdk/main/src/TokenPauseTransaction.cc +++ b/sdk/main/src/TokenPauseTransaction.cc @@ -59,6 +59,12 @@ grpc::Status TokenPauseTransaction::submitRequest(const proto::Transaction& requ return node->submitTransaction(proto::TransactionBody::DataCase::kTokenPause, request, deadline, response); } +//----- +void TokenPauseTransaction::validateChecksums(const Client& client) const +{ + mTokenId.validateChecksum(client); +} + //----- void TokenPauseTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenRevokeKycTransaction.cc b/sdk/main/src/TokenRevokeKycTransaction.cc index 813a2e0c0..c8841c2a4 100644 --- a/sdk/main/src/TokenRevokeKycTransaction.cc +++ b/sdk/main/src/TokenRevokeKycTransaction.cc @@ -67,6 +67,13 @@ grpc::Status TokenRevokeKycTransaction::submitRequest(const proto::Transaction& return node->submitTransaction(proto::TransactionBody::DataCase::kTokenRevokeKyc, request, deadline, response); } +//----- +void TokenRevokeKycTransaction::validateChecksums(const Client& client) const +{ + mTokenId.validateChecksum(client); + mAccountId.validateChecksum(client); +} + //----- void TokenRevokeKycTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenTransfer.cc b/sdk/main/src/TokenTransfer.cc index a40a79bb5..88664d06d 100644 --- a/sdk/main/src/TokenTransfer.cc +++ b/sdk/main/src/TokenTransfer.cc @@ -47,22 +47,17 @@ TokenTransfer::TokenTransfer(const TokenId& tokenId, } //----- -std::vector TokenTransfer::fromProtobuf(const proto::TokenTransferList& proto) +TokenTransfer TokenTransfer::fromProtobuf(const proto::AccountAmount& proto, const TokenId& tokenId, uint32_t decimals) { - std::vector transfers; - const TokenId tokenId = TokenId::fromProtobuf(proto.token()); - - for (int i = 0; i < proto.transfers_size(); ++i) - { - const proto::AccountAmount& amount = proto.transfers(i); - transfers.emplace_back(tokenId, - AccountId::fromProtobuf(amount.accountid()), - amount.amount(), - proto.has_expected_decimals() ? proto.expected_decimals().value() : 0U, - amount.is_approval()); - } + return TokenTransfer( + tokenId, AccountId::fromProtobuf(proto.accountid()), proto.amount(), decimals, proto.is_approval()); +} - return transfers; +//----- +void TokenTransfer::validateChecksums(const Client& client) const +{ + mTokenId.validateChecksum(client); + mAccountId.validateChecksum(client); } //----- diff --git a/sdk/main/src/TokenUnfreezeTransaction.cc b/sdk/main/src/TokenUnfreezeTransaction.cc index 04086399e..c38bc2c08 100644 --- a/sdk/main/src/TokenUnfreezeTransaction.cc +++ b/sdk/main/src/TokenUnfreezeTransaction.cc @@ -67,6 +67,13 @@ grpc::Status TokenUnfreezeTransaction::submitRequest(const proto::Transaction& r return node->submitTransaction(proto::TransactionBody::DataCase::kTokenUnfreeze, request, deadline, response); } +//----- +void TokenUnfreezeTransaction::validateChecksums(const Client& client) const +{ + mTokenId.validateChecksum(client); + mAccountId.validateChecksum(client); +} + //----- void TokenUnfreezeTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenUnpauseTransaction.cc b/sdk/main/src/TokenUnpauseTransaction.cc index 9f325de2c..7a52ec711 100644 --- a/sdk/main/src/TokenUnpauseTransaction.cc +++ b/sdk/main/src/TokenUnpauseTransaction.cc @@ -59,6 +59,12 @@ grpc::Status TokenUnpauseTransaction::submitRequest(const proto::Transaction& re return node->submitTransaction(proto::TransactionBody::DataCase::kTokenUnpause, request, deadline, response); } +//----- +void TokenUnpauseTransaction::validateChecksums(const Client& client) const +{ + mTokenId.validateChecksum(client); +} + //----- void TokenUnpauseTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenUpdateTransaction.cc b/sdk/main/src/TokenUpdateTransaction.cc index a63614821..ad6aeb88a 100644 --- a/sdk/main/src/TokenUpdateTransaction.cc +++ b/sdk/main/src/TokenUpdateTransaction.cc @@ -175,6 +175,22 @@ grpc::Status TokenUpdateTransaction::submitRequest(const proto::Transaction& req return node->submitTransaction(proto::TransactionBody::DataCase::kTokenUpdate, request, deadline, response); } +//----- +void TokenUpdateTransaction::validateChecksums(const Client& client) const +{ + mTokenId.validateChecksum(client); + + if (mTreasuryAccountId.has_value()) + { + mTreasuryAccountId->validateChecksum(client); + } + + if (mAutoRenewAccountId.has_value()) + { + mAutoRenewAccountId->validateChecksum(client); + } +} + //----- void TokenUpdateTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TokenWipeTransaction.cc b/sdk/main/src/TokenWipeTransaction.cc index fc092e9a6..662a0ba9e 100644 --- a/sdk/main/src/TokenWipeTransaction.cc +++ b/sdk/main/src/TokenWipeTransaction.cc @@ -83,6 +83,13 @@ grpc::Status TokenWipeTransaction::submitRequest(const proto::Transaction& reque return node->submitTransaction(proto::TransactionBody::DataCase::kTokenWipe, request, deadline, response); } +//----- +void TokenWipeTransaction::validateChecksums(const Client& client) const +{ + mTokenId.validateChecksum(client); + mAccountId.validateChecksum(client); +} + //----- void TokenWipeTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TopicCreateTransaction.cc b/sdk/main/src/TopicCreateTransaction.cc index 387bd2735..af3727f7f 100644 --- a/sdk/main/src/TopicCreateTransaction.cc +++ b/sdk/main/src/TopicCreateTransaction.cc @@ -92,6 +92,15 @@ grpc::Status TopicCreateTransaction::submitRequest(const proto::Transaction& req return node->submitTransaction(proto::TransactionBody::DataCase::kConsensusCreateTopic, request, deadline, response); } +//----- +void TopicCreateTransaction::validateChecksums(const Client& client) const +{ + if (mAutoRenewAccountId.has_value()) + { + mAutoRenewAccountId->validateChecksum(client); + } +} + //----- void TopicCreateTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TopicDeleteTransaction.cc b/sdk/main/src/TopicDeleteTransaction.cc index 7b281a717..e026d9305 100644 --- a/sdk/main/src/TopicDeleteTransaction.cc +++ b/sdk/main/src/TopicDeleteTransaction.cc @@ -59,6 +59,15 @@ grpc::Status TopicDeleteTransaction::submitRequest(const proto::Transaction& req return node->submitTransaction(proto::TransactionBody::DataCase::kConsensusDeleteTopic, request, deadline, response); } +//----- +void TopicDeleteTransaction::validateChecksums(const Client& client) const +{ + if (mTopicId.has_value()) + { + mTopicId->validateChecksum(client); + } +} + //----- void TopicDeleteTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TopicId.cc b/sdk/main/src/TopicId.cc index 481f07391..cf299d684 100644 --- a/sdk/main/src/TopicId.cc +++ b/sdk/main/src/TopicId.cc @@ -4,7 +4,7 @@ * * Copyright (C) 2020 - 2023 Hedera Hashgraph, LLC * - * Licensed under the Apache License, Version 2.0 (the "License"); + * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * @@ -18,28 +18,28 @@ * */ #include "TopicId.h" -#include "exceptions/IllegalStateException.h" -#include "exceptions/OpenSSLException.h" -#include "impl/HexConverter.h" +#include "Client.h" +#include "LedgerId.h" +#include "impl/EntityIdHelper.h" #include "impl/Utilities.h" -#include #include #include namespace Hedera { //----- -TopicId::TopicId(const uint64_t& num) +TopicId::TopicId(uint64_t num) : mTopicNum(num) { } //----- -TopicId::TopicId(const uint64_t& shard, const uint64_t& realm, const uint64_t& num) +TopicId::TopicId(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum) : mShardNum(shard) , mRealmNum(realm) , mTopicNum(num) + , mChecksum(checksum) { } @@ -52,79 +52,17 @@ bool TopicId::operator==(const TopicId& other) const //----- TopicId TopicId::fromString(std::string_view id) { - TopicId topicId; - - // Get the indices of the two delimiter '.' - const size_t firstDot = id.find_first_of('.'); - const size_t secondDot = id.find_last_of('.'); - - // Make sure there are at least two dots - if (firstDot == secondDot) - { - throw std::invalid_argument("Input topic ID string is malformed"); - } - - // Grab the three strings - const std::string_view shardStr = id.substr(0, firstDot); - const std::string_view realmStr = id.substr(firstDot + 1, secondDot - firstDot - 1); - const std::string_view topicStr = id.substr(secondDot + 1, id.size() - secondDot - 1); - - // Convert the shard number - auto result = std::from_chars(shardStr.data(), shardStr.data() + shardStr.size(), topicId.mShardNum); - if (result.ec != std::errc() || result.ptr != shardStr.data() + shardStr.size()) - { - throw std::invalid_argument("Input topic ID string is malformed"); - } - - // Convert the realm number - result = std::from_chars(realmStr.data(), realmStr.data() + realmStr.size(), topicId.mRealmNum); - if (result.ec != std::errc() || result.ptr != realmStr.data() + realmStr.size()) - { - throw std::invalid_argument("Input topic ID string is malformed"); - } - - // Convert the topic number - result = std::from_chars(topicStr.data(), topicStr.data() + topicStr.size(), topicId.mTopicNum); - if (result.ec != std::errc() || result.ptr != topicStr.data() + topicStr.size()) - { - throw std::invalid_argument("Input topic ID string is malformed"); - } - - return topicId; + return TopicId(internal::EntityIdHelper::getShardNum(id), + internal::EntityIdHelper::getRealmNum(id), + internal::EntityIdHelper::getEntityNum(id), + internal::EntityIdHelper::getChecksum(id)); } //----- -TopicId TopicId::fromSolidityAddress(std::string_view addr) +TopicId TopicId::fromSolidityAddress(std::string_view address) { - TopicId topicId; - - // Remove hex prefix if it exists. - if (const std::string_view prefix = "0x"; addr.substr(0, prefix.size()) == prefix) - { - addr.remove_prefix(prefix.size()); - } - - if (addr.size() != 40) - { - throw std::invalid_argument("Input string doesn't represent a solidity address"); - } - - std::vector bytes; - try - { - bytes = internal::HexConverter::hexToBytes(addr); - } - catch (const OpenSSLException&) - { - throw std::invalid_argument("Input string doesn't represent a solidity address"); - } - - // First four bytes are the shard ID, the next eight the realm ID, and the last eight are the topic ID. - topicId.mShardNum = static_cast(*internal::Utilities::toTypePtr(bytes.data())); - topicId.mRealmNum = *internal::Utilities::toTypePtr(bytes.data() + 4); - topicId.mTopicNum = *internal::Utilities::toTypePtr(bytes.data() + 12); - - return topicId; + return internal::EntityIdHelper::fromSolidityAddress( + internal::EntityIdHelper::decodeSolidityAddress(address)); } //----- @@ -138,49 +76,58 @@ TopicId TopicId::fromProtobuf(const proto::TopicID& proto) //----- TopicId TopicId::fromBytes(const std::vector& bytes) { - proto::TopicID protoTopicId; - protoTopicId.ParseFromArray(bytes.data(), static_cast(bytes.size())); - return fromProtobuf(protoTopicId); + proto::TopicID proto; + proto.ParseFromArray(bytes.data(), static_cast(bytes.size())); + return fromProtobuf(proto); } //----- -std::string TopicId::toSolidityAddress() const +void TopicId::validateChecksum(const Client& client) const { - if (mShardNum > std::numeric_limits::max()) + if (!mChecksum.empty()) { - throw IllegalStateException("Shard number requires more than 32 bits to serialize"); + internal::EntityIdHelper::validate(mShardNum, mRealmNum, mTopicNum, client, mChecksum); } - - const auto shardNumPtr = internal::Utilities::toTypePtr(&mShardNum); - const auto realmNumPtr = internal::Utilities::toTypePtr(&mRealmNum); - const auto topicNumPtr = internal::Utilities::toTypePtr(&mTopicNum); - - return internal::HexConverter::bytesToHex( - internal::Utilities::concatenateVectors({ std::vector(shardNumPtr, shardNumPtr + 4), - std::vector(realmNumPtr, realmNumPtr + 8), - std::vector(topicNumPtr, topicNumPtr + 8) })); } //----- std::unique_ptr TopicId::toProtobuf() const { - auto protoTopicId = std::make_unique(); - protoTopicId->set_shardnum(static_cast(mShardNum)); - protoTopicId->set_realmnum(static_cast(mRealmNum)); - protoTopicId->set_topicnum(static_cast(mTopicNum)); - return protoTopicId; + auto body = std::make_unique(); + body->set_shardnum(static_cast(mShardNum)); + body->set_realmnum(static_cast(mRealmNum)); + body->set_topicnum(static_cast(mTopicNum)); + return body; } //----- -std::vector TopicId::toBytes() const +std::string TopicId::toSolidityAddress() const { - return internal::Utilities::stringToByteVector(toProtobuf()->SerializeAsString()); + return internal::EntityIdHelper::toSolidityAddress(mShardNum, mRealmNum, mTopicNum); } //----- std::string TopicId::toString() const { - return std::to_string(mShardNum) + '.' + std::to_string(mRealmNum) + '.' + std::to_string(mTopicNum); + return internal::EntityIdHelper::toString(mShardNum, mRealmNum, mTopicNum); +} + +//----- +std::string TopicId::toStringWithChecksum(const Client& client) const +{ + if (mChecksum.empty()) + { + mChecksum = internal::EntityIdHelper::checksum(internal::EntityIdHelper::toString(mShardNum, mRealmNum, mTopicNum), + client.getLedgerId()); + } + + return internal::EntityIdHelper::toString(mShardNum, mRealmNum, mTopicNum, mChecksum); +} + +//----- +std::vector TopicId::toBytes() const +{ + return internal::Utilities::stringToByteVector(toProtobuf()->SerializeAsString()); } } // namespace Hedera diff --git a/sdk/main/src/TopicInfoQuery.cc b/sdk/main/src/TopicInfoQuery.cc index eb398da01..3b3e2c28d 100644 --- a/sdk/main/src/TopicInfoQuery.cc +++ b/sdk/main/src/TopicInfoQuery.cc @@ -53,6 +53,12 @@ grpc::Status TopicInfoQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kConsensusGetTopicInfo, request, deadline, response); } +//----- +void TopicInfoQuery::validateChecksums(const Client& client) const +{ + mTopicId.validateChecksum(client); +} + //----- proto::Query TopicInfoQuery::buildRequest(proto::QueryHeader* header) const { diff --git a/sdk/main/src/TopicMessageSubmitTransaction.cc b/sdk/main/src/TopicMessageSubmitTransaction.cc index ca4bd981d..87d4c509a 100644 --- a/sdk/main/src/TopicMessageSubmitTransaction.cc +++ b/sdk/main/src/TopicMessageSubmitTransaction.cc @@ -80,6 +80,12 @@ grpc::Status TopicMessageSubmitTransaction::submitRequest(const proto::Transacti proto::TransactionBody::DataCase::kConsensusSubmitMessage, request, deadline, response); } +//----- +void TopicMessageSubmitTransaction::validateChecksums(const Client& client) const +{ + mTopicId.validateChecksum(client); +} + //----- void TopicMessageSubmitTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/TopicUpdateTransaction.cc b/sdk/main/src/TopicUpdateTransaction.cc index 785e73623..a6a66eab5 100644 --- a/sdk/main/src/TopicUpdateTransaction.cc +++ b/sdk/main/src/TopicUpdateTransaction.cc @@ -142,6 +142,17 @@ grpc::Status TopicUpdateTransaction::submitRequest(const proto::Transaction& req return node->submitTransaction(proto::TransactionBody::DataCase::kConsensusUpdateTopic, request, deadline, response); } +//----- +void TopicUpdateTransaction::validateChecksums(const Client& client) const +{ + mTopicId.validateChecksum(client); + + if (mAutoRenewAccountId.has_value()) + { + mAutoRenewAccountId->validateChecksum(client); + } +} + //----- void TopicUpdateTransaction::addToBody(proto::TransactionBody& body) const { diff --git a/sdk/main/src/Transaction.cc b/sdk/main/src/Transaction.cc index 899cd63b2..6dba4fa38 100644 --- a/sdk/main/src/Transaction.cc +++ b/sdk/main/src/Transaction.cc @@ -1037,6 +1037,12 @@ void Transaction::onExecute(const Client& client) freezeWith(&client); } + // Validate checksums if that option is enabled. + if (client.isAutoValidateChecksumsEnabled()) + { + validateChecksums(client); + } + // Sign with the operator if the operator's presence, and if it's paying for the Transaction. if (client.getOperatorAccountId().has_value() && client.getOperatorAccountId().value() == mImpl->mTransactionId.getAccountId()) diff --git a/sdk/main/src/TransactionReceiptQuery.cc b/sdk/main/src/TransactionReceiptQuery.cc index 1abc95a3c..ca3171226 100644 --- a/sdk/main/src/TransactionReceiptQuery.cc +++ b/sdk/main/src/TransactionReceiptQuery.cc @@ -65,6 +65,15 @@ grpc::Status TransactionReceiptQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kTransactionGetReceipt, request, deadline, response); } +//----- +void TransactionReceiptQuery::validateChecksums(const Client& client) const +{ + if (mTransactionId.has_value()) + { + mTransactionId->getAccountId().validateChecksum(client); + } +} + //----- typename Executable::ExecutionStatus TransactionReceiptQuery::determineStatus(Status status, const Client& client, const proto::Response& response) diff --git a/sdk/main/src/TransactionRecord.cc b/sdk/main/src/TransactionRecord.cc index 3407eaed7..29ab3e485 100644 --- a/sdk/main/src/TransactionRecord.cc +++ b/sdk/main/src/TransactionRecord.cc @@ -78,22 +78,16 @@ TransactionRecord TransactionRecord::fromProtobuf(const proto::TransactionRecord const TokenId tokenId = TokenId::fromProtobuf(list.token()); // Fungible token - const std::vector fungibleTransfers = TokenTransfer::fromProtobuf(list); - transactionRecord.mTokenTransferList.insert( - transactionRecord.mTokenTransferList.cend(), fungibleTransfers.cbegin(), fungibleTransfers.cend()); + for (int j = 0; j < list.transfers_size(); ++j) + { + transactionRecord.mTokenTransferList.push_back(TokenTransfer::fromProtobuf( + list.transfers(j), tokenId, list.has_expected_decimals() ? list.expected_decimals().value() : 0U)); + } // NFT for (int j = 0; j < list.nfttransfers_size(); ++j) { - const proto::NftTransfer& nftTransfer = list.nfttransfers(j); - - TokenNftTransfer transfer; - transfer.setNftId(NftId(tokenId, static_cast(nftTransfer.serialnumber()))); - transfer.setSenderAccountId(AccountId::fromProtobuf(nftTransfer.senderaccountid())); - transfer.setReceiverAccountId(AccountId::fromProtobuf(nftTransfer.receiveraccountid())); - transfer.setApproval(nftTransfer.is_approval()); - - transactionRecord.mNftTransferList.push_back(transfer); + transactionRecord.mNftTransferList.push_back(TokenNftTransfer::fromProtobuf(list.nfttransfers(j), tokenId)); } } diff --git a/sdk/main/src/TransactionRecordQuery.cc b/sdk/main/src/TransactionRecordQuery.cc index e2fdb4344..e271f64fa 100644 --- a/sdk/main/src/TransactionRecordQuery.cc +++ b/sdk/main/src/TransactionRecordQuery.cc @@ -53,6 +53,15 @@ grpc::Status TransactionRecordQuery::submitRequest(const proto::Query& request, return node->submitQuery(proto::Query::QueryCase::kTransactionGetRecord, request, deadline, response); } +//----- +void TransactionRecordQuery::validateChecksums(const Client& client) const +{ + if (mTransactionId.has_value()) + { + mTransactionId->getAccountId().validateChecksum(client); + } +} + //----- typename Executable::ExecutionStatus TransactionRecordQuery::determineStatus(Status status, const Client& client, const proto::Response& response) diff --git a/sdk/main/src/TransferTransaction.cc b/sdk/main/src/TransferTransaction.cc index 1255f03f5..250149366 100644 --- a/sdk/main/src/TransferTransaction.cc +++ b/sdk/main/src/TransferTransaction.cc @@ -47,7 +47,7 @@ TransferTransaction& TransferTransaction::addHbarTransfer(const AccountId& accou { requireNotFrozen(); - doHbarTransfer(HbarTransfer().setAccountId(accountId).setAmount(amount).setApproved(false)); + doHbarTransfer(accountId, amount, false); return *this; } @@ -69,11 +69,7 @@ TransferTransaction& TransferTransaction::addNftTransfer(const NftId& nftId, { requireNotFrozen(); - doNftTransfer(TokenNftTransfer() - .setNftId(nftId) - .setSenderAccountId(senderAccountId) - .setReceiverAccountId(receiverAccountId) - .setApproval(false)); + doNftTransfer(nftId, senderAccountId, receiverAccountId, false); return *this; } @@ -94,7 +90,7 @@ TransferTransaction& TransferTransaction::addApprovedHbarTransfer(const AccountI { requireNotFrozen(); - doHbarTransfer(HbarTransfer().setAccountId(accountId).setAmount(amount).setApproved(true)); + doHbarTransfer(accountId, amount, true); return *this; } @@ -116,11 +112,7 @@ TransferTransaction& TransferTransaction::addApprovedNftTransfer(const NftId& nf { requireNotFrozen(); - doNftTransfer(TokenNftTransfer() - .setNftId(nftId) - .setSenderAccountId(senderAccountId) - .setReceiverAccountId(receiverAccountId) - .setApproval(true)); + doNftTransfer(nftId, senderAccountId, receiverAccountId, true); return *this; } @@ -143,7 +135,7 @@ std::unordered_map TransferTransaction::getHbarTransfers() cons for (const HbarTransfer& transfer : mHbarTransfers) { - hbarTransfers[transfer.getAccountId()] += transfer.getAmount(); + hbarTransfers[transfer.mAccountId] += transfer.mAmount; } return hbarTransfers; @@ -169,7 +161,7 @@ std::unordered_map> TransferTransaction:: for (const TokenNftTransfer& transfer : mNftTransfers) { - nftTransfers[transfer.getNftId().getTokenId()].push_back(transfer); + nftTransfers[transfer.mNftId.mTokenId].push_back(transfer); } return nftTransfers; @@ -200,6 +192,20 @@ grpc::Status TransferTransaction::submitRequest(const proto::Transaction& reques return node->submitTransaction(proto::TransactionBody::DataCase::kCryptoTransfer, request, deadline, response); } +//----- +void TransferTransaction::validateChecksums(const Client& client) const +{ + std::for_each(mHbarTransfers.cbegin(), + mHbarTransfers.cend(), + [&client](const HbarTransfer& transfer) { transfer.mAccountId.validateChecksum(client); }); + std::for_each(mTokenTransfers.cbegin(), + mTokenTransfers.cend(), + [&client](const TokenTransfer& transfer) { transfer.validateChecksums(client); }); + std::for_each(mNftTransfers.cbegin(), + mNftTransfers.cend(), + [&client](const TokenNftTransfer& transfer) { transfer.validateChecksums(client); }); +} + //----- void TransferTransaction::addToBody(proto::TransactionBody& body) const { @@ -220,11 +226,7 @@ void TransferTransaction::initFromSourceTransactionBody() for (int i = 0; i < body.transfers().accountamounts_size(); ++i) { - const proto::AccountAmount& accountAmount = body.transfers().accountamounts(i); - mHbarTransfers.push_back(HbarTransfer() - .setAccountId(AccountId::fromProtobuf(accountAmount.accountid())) - .setAmount(Hbar(accountAmount.amount(), HbarUnit::TINYBAR())) - .setApproved(accountAmount.is_approval())); + mHbarTransfers.push_back(HbarTransfer::fromProtobuf(body.transfers().accountamounts(i))); } for (int i = 0; i < body.tokentransfers_size(); ++i) @@ -238,18 +240,13 @@ void TransferTransaction::initFromSourceTransactionBody() mTokenTransfers.emplace_back(tokenId, AccountId::fromProtobuf(accountAmount.accountid()), accountAmount.amount(), - transfer.expected_decimals().value(), + transfer.has_expected_decimals() ? transfer.expected_decimals().value() : 0U, accountAmount.is_approval()); } for (int j = 0; j < transfer.nfttransfers_size(); ++j) { - const proto::NftTransfer& nftTransfer = transfer.nfttransfers(j); - mNftTransfers.push_back(TokenNftTransfer() - .setNftId(NftId(tokenId, static_cast(nftTransfer.serialnumber()))) - .setSenderAccountId(AccountId::fromProtobuf(nftTransfer.senderaccountid())) - .setReceiverAccountId(AccountId::fromProtobuf(nftTransfer.receiveraccountid())) - .setApproval(nftTransfer.is_approval())); + mNftTransfers.emplace_back(TokenNftTransfer::fromProtobuf(transfer.nfttransfers(j), tokenId)); } } } @@ -298,7 +295,7 @@ proto::CryptoTransferTransactionBody* TransferTransaction::build() const proto::TokenTransferList* list = nullptr; for (int i = 0; i < body->mutable_tokentransfers()->size(); ++i) { - if (TokenId::fromProtobuf(body->mutable_tokentransfers(i)->token()) == transfer.getNftId().getTokenId()) + if (TokenId::fromProtobuf(body->mutable_tokentransfers(i)->token()) == transfer.mNftId.mTokenId) { list = body->mutable_tokentransfers(i); } @@ -307,7 +304,7 @@ proto::CryptoTransferTransactionBody* TransferTransaction::build() const if (!list) { list = body->add_tokentransfers(); - list->set_allocated_token(transfer.getNftId().getTokenId().toProtobuf().release()); + list->set_allocated_token(transfer.mNftId.mTokenId.toProtobuf().release()); } *list->add_nfttransfers() = *transfer.toProtobuf(); @@ -317,30 +314,28 @@ proto::CryptoTransferTransactionBody* TransferTransaction::build() const } //---- -void TransferTransaction::doHbarTransfer(const HbarTransfer& transfer) +void TransferTransaction::doHbarTransfer(const AccountId& accountId, const Hbar& amount, bool approved) { // If a transfer has already been added for an account, just update the amount if the approval status is the same for (auto transferIter = mHbarTransfers.begin(); transferIter != mHbarTransfers.end(); ++transferIter) { - if (transferIter->getAccountId() == transfer.getAccountId() && - transferIter->getApproval() == transfer.getApproval()) + if (transferIter->mAccountId == accountId && transferIter->mIsApproved == approved) { - if (const auto newValue = - Hbar(transferIter->getAmount().toTinybars() + transfer.getAmount().toTinybars(), HbarUnit::TINYBAR()); + if (const auto newValue = Hbar(transferIter->mAmount.toTinybars() + amount.toTinybars(), HbarUnit::TINYBAR()); newValue.toTinybars() == 0LL) { mHbarTransfers.erase(transferIter); } else { - transferIter->setAmount(newValue); + transferIter->mAmount = newValue; } return; } } - mHbarTransfers.push_back(transfer); + mHbarTransfers.emplace_back(accountId, amount, approved); } //----- @@ -372,21 +367,22 @@ void TransferTransaction::doTokenTransfer(const TokenTransfer& transfer) } //----- -void TransferTransaction::doNftTransfer(const TokenNftTransfer& transfer) +void TransferTransaction::doNftTransfer(const NftId& nftId, + const AccountId& sender, + const AccountId& receiver, + bool approved) { for (auto transferIter = mNftTransfers.begin(); transferIter != mNftTransfers.end(); ++transferIter) { - if (transferIter->getNftId().getSerialNum() == transfer.getNftId().getSerialNum() && - transferIter->getSenderAccountId() == transfer.getReceiverAccountId() && - transferIter->getReceiverAccountId() == transfer.getSenderAccountId() && - transferIter->getApproval() == transfer.getApproval()) + if (transferIter->mNftId.mSerialNum == nftId.mSerialNum && transferIter->mSenderAccountId == receiver && + transferIter->mReceiverAccountId == sender && transferIter->mIsApproval == approved) { mNftTransfers.erase(transferIter); return; } } - mNftTransfers.push_back(transfer); + mNftTransfers.emplace_back(nftId, sender, receiver, approved); } } // namespace Hedera diff --git a/sdk/main/src/impl/EntityIdHelper.cc b/sdk/main/src/impl/EntityIdHelper.cc new file mode 100644 index 000000000..8155af720 --- /dev/null +++ b/sdk/main/src/impl/EntityIdHelper.cc @@ -0,0 +1,300 @@ +/*- + * + * Hedera C++ SDK + * + * Copyright (C) 2020 - 2023 Hedera Hashgraph, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License") + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#include "impl/EntityIdHelper.h" +#include "AccountId.h" +#include "Client.h" +#include "ContractId.h" +#include "DelegateContractId.h" +#include "FileId.h" +#include "LedgerId.h" +#include "ScheduleId.h" +#include "TokenId.h" +#include "TopicId.h" +#include "exceptions/BadEntityException.h" +#include "exceptions/OpenSSLException.h" +#include "exceptions/UninitializedException.h" +#include "impl/HexConverter.h" +#include "impl/Utilities.h" + +#include +#include +#include +#include + +namespace Hedera::internal::EntityIdHelper +{ +//----- +template +EntityType fromSolidityAddress(const std::vector& address) +{ + if (address.size() != SOLIDITY_ADDRESS_LEN) + { + throw std::invalid_argument("Input address is not a valid Solidity address. Solidity addresses should be " + + std::to_string(SOLIDITY_ADDRESS_LEN) + " bytes long"); + } + + return EntityType(static_cast(*internal::Utilities::toTypePtr(address.data())), + *internal::Utilities::toTypePtr(address.data() + 4), + *internal::Utilities::toTypePtr(address.data() + 12)); +} + +//----- +uint64_t getNum(std::string_view str) +{ + uint64_t num; + if (auto result = std::from_chars(str.data(), str.data() + str.size(), num); + result.ec != std::errc() || result.ptr != str.data() + str.size()) + { + throw std::invalid_argument("Input entity ID string is malformed"); + } + + return num; +} + +//----- +uint64_t getShardNum(std::string_view id) +{ + const size_t firstDot = id.find_first_of('.'); + + if (firstDot == std::string::npos) + { + throw std::invalid_argument("Input entity ID string is malformed"); + } + + return getNum(id.substr(0, firstDot)); +} + +//----- +uint64_t getRealmNum(std::string_view id) +{ + const size_t firstDot = id.find_first_of('.'); + const size_t lastDot = id.find_last_of('.'); + + if (firstDot == lastDot) + { + throw std::invalid_argument("Input entity ID string is malformed"); + } + + return getNum(id.substr(firstDot + 1, lastDot - firstDot - 1)); +} + +//----- +uint64_t getEntityNum(std::string_view id) +{ + return getNum(getEntityNumStr(id)); +} + +//----- +std::string_view getEntityNumStr(std::string_view id) +{ + const size_t lastDot = id.find_last_of('.'); + const size_t dash = id.find_last_of('-'); + + if (lastDot == std::string::npos) + { + throw std::invalid_argument("Input entity ID string is malformed"); + } + + // If there's no checksum (i.e. there's a dash), then just return the rest of the string from the last dot. + return id.substr(lastDot + 1, (dash == std::string::npos) ? id.size() - lastDot - 1 : dash - lastDot - 1); +} + +//----- +std::string_view getChecksum(std::string_view id) +{ + const size_t dash = id.find_last_of('-'); + return (dash == std::string::npos) ? std::string_view() : id.substr(dash + 1, id.size() - dash - 1); +} + +//----- +std::string checksum(std::string_view address, const LedgerId& ledgerId) +{ + const unsigned int weight = 31U; + const unsigned int p3 = 26 * 26 * 26; // The amount of permutations in a three-digit, base 26 string. + const unsigned int p5 = 26 * 26 * 26 * 26 * 26; // The amount of permutations in a five-digit, base 26 string. + + // Step 1: Construct an array of the digits in the address, using 10 to represent '.' + std::vector digitArray; + digitArray.reserve(address.size()); + std::for_each( + address.cbegin(), address.cend(), [&digitArray](char c) { digitArray.push_back(c == '.' ? 10U : c - '0'); }); + + // Step 2: Construct a byte array containing the ledger ID, followed by six zero bytes. + const std::vector ledgerIdArray = Utilities::concatenateVectors({ + ledgerId.toBytes(), + {std::byte(0x0), std::byte(0x0), std::byte(0x0), std::byte(0x0), std::byte(0x0), std::byte(0x0)} + }); + + // Step 3: Get the weighted sum of all the digits, modded by p3. Also get the sums of the digits in the array of + // digits, separating by even and odd indices. Finishing by modding 11. + unsigned int evenIndexSum = 0U; + unsigned int oddIndexSum = 0U; + unsigned int digitArrayWeightedSum = 0U; + for (unsigned int i = 0U; i < digitArray.size(); ++i) + { + digitArrayWeightedSum = digitArrayWeightedSum * weight + digitArray.at(i); + if (i % 2U == 0U) + { + evenIndexSum += digitArray.at(i); + } + else + { + oddIndexSum += digitArray.at(i); + } + } + + evenIndexSum %= 11U; + oddIndexSum %= 11U; + digitArrayWeightedSum %= p3; + + // Step 4: Get the weighted sum of all bytes in the ledger ID bytes, modded by p5. + unsigned int ledgerIdWeightedSum = 0U; + std::for_each(ledgerIdArray.cbegin(), + ledgerIdArray.cend(), + [&ledgerIdWeightedSum](std::byte byte) + { ledgerIdWeightedSum = ledgerIdWeightedSum * weight + std::to_integer(byte); }); + ledgerIdWeightedSum %= p5; + + // Step 5: Calculate the checksum, as a number. + unsigned int checksum = ((((((address.size() % 5U) * 11U + evenIndexSum) * 11U + oddIndexSum) * p3 + + digitArrayWeightedSum + ledgerIdWeightedSum) % + p5) * + 1'000'003U) % + p5; + + // Step 6: Write the checksum in base 26, using a-z as the digits. There should only be five characters. + std::string checksumStr; + for (int i = 0; i < 5; ++i) + { + checksumStr.push_back(static_cast('a' + checksum % 26U)); + checksum /= 26U; + } + + // Step 7: Reverse the checksum string since it was constructed from the least significant digit. + std::reverse(checksumStr.begin(), checksumStr.end()); + + return checksumStr; +} + +//----- +bool isLongZeroAddress(const std::vector& address) +{ + // The address is a possible long-zero address if the first 12 bytes are zeros. + for (int i = 0; i < 12; ++i) + { + if (address.at(i) != std::byte(0x0)) + { + return false; + } + } + + return true; +} + +//----- +std::vector decodeSolidityAddress(std::string_view address) +{ + // Make sure the size of the address is correct. + const std::string_view prefix = "0x"; + const bool hasPrefix = address.substr(0, prefix.size()) == prefix; + if ((hasPrefix && address.size() != SOLIDITY_ADDRESS_LEN_HEX + prefix.size()) || + (!hasPrefix && address.size() != SOLIDITY_ADDRESS_LEN_HEX)) + { + throw std::invalid_argument("Input Solidity address is not the correct size, it must be " + + std::to_string(SOLIDITY_ADDRESS_LEN_HEX) + " hex characters"); + } + + // Remove the prefix if it exists. + if (hasPrefix) + { + address.remove_prefix(prefix.size()); + } + + try + { + return internal::HexConverter::hexToBytes(address); + } + catch (const OpenSSLException&) + { + throw std::invalid_argument(std::string("Input Solidity address ") + address.data() + " is not valid hex"); + } +} + +//----- +std::string toString(uint64_t shard, uint64_t realm, uint64_t num, std::string_view checksum) +{ + std::string str = std::to_string(shard) + '.' + std::to_string(realm) + '.' + std::to_string(num); + if (!checksum.empty()) + { + str += '-'; + str += checksum; + } + + return str; +} + +//----- +std::string toSolidityAddress(uint64_t shard, uint64_t realm, uint64_t num) +{ + // If the shard number is a value greater than 32 bits can represent, then creating a Long-Zero format is impossible. + if (shard > static_cast(std::numeric_limits::max())) + { + throw std::invalid_argument("Shard number is too big. Its value must be able to fit in 32 bits."); + } + + return internal::HexConverter::bytesToHex(internal::Utilities::concatenateVectors( + { internal::Utilities::removePrefix(internal::Utilities::getBytes(shard), sizeof(uint64_t) - 4), + internal::Utilities::getBytes(realm), + internal::Utilities::getBytes(num) })); +} + +//----- +void validate(uint64_t shard, uint64_t realm, uint64_t num, const Client& client, std::string_view expectedChecksum) +{ + // Make sure the Client's network is initialized. + if (!client.getNetwork()) + { + throw UninitializedException("Client has no network with which to validate checksum"); + } + + // Calculate the checksum of the input entity. + const std::string calculatedChecksum = + checksum(std::to_string(shard) + '.' + std::to_string(realm) + '.' + std::to_string(num), client.getLedgerId()); + + if (calculatedChecksum != expectedChecksum) + { + throw BadEntityException(shard, realm, num, expectedChecksum, calculatedChecksum); + } +} + +/** + * Explicit template instantiations. + */ +// clang-format off +template AccountId fromSolidityAddress (const std::vector&); +template ContractId fromSolidityAddress (const std::vector&); +template DelegateContractId fromSolidityAddress (const std::vector&); +template FileId fromSolidityAddress (const std::vector&); +template ScheduleId fromSolidityAddress (const std::vector&); +template TokenId fromSolidityAddress (const std::vector&); +template TopicId fromSolidityAddress (const std::vector&); +// clang-format on + +} // namespace Hedera::internal::EntityIdHelper diff --git a/sdk/tests/integration/TransferTransactionIntegrationTest.cc b/sdk/tests/integration/TransferTransactionIntegrationTest.cc index 0eb9108c7..a53ab4b8d 100644 --- a/sdk/tests/integration/TransferTransactionIntegrationTest.cc +++ b/sdk/tests/integration/TransferTransactionIntegrationTest.cc @@ -34,8 +34,6 @@ #include "TransactionResponse.h" #include "TransferTransaction.h" #include "impl/HexConverter.h" -#include "impl/TimestampConverter.h" -#include "impl/Utilities.h" #include #include @@ -184,7 +182,7 @@ TEST_F(TransferTransactionIntegrationTest, CanSpendHbarAllowance) bool transferFound = false; for (const auto& transfer : txRecord.mHbarTransferList) { - if (transfer.getAccountId() == allowerId && transfer.getAmount() == amount.negated()) + if (transfer.mAccountId == allowerId && transfer.mAmount == amount.negated()) { transferFound = true; break; diff --git a/sdk/tests/unit/AccountAllowanceApproveTransactionTest.cc b/sdk/tests/unit/AccountAllowanceApproveTransactionTest.cc index 898089633..3f396f971 100644 --- a/sdk/tests/unit/AccountAllowanceApproveTransactionTest.cc +++ b/sdk/tests/unit/AccountAllowanceApproveTransactionTest.cc @@ -106,10 +106,9 @@ TEST_F(AccountAllowanceApproveTransactionTest, ConstructAccountAllowanceApproveT // Then ASSERT_EQ(accountAllowanceApproveTransaction.getHbarApprovals().size(), 1); - EXPECT_EQ(accountAllowanceApproveTransaction.getHbarApprovals().at(0).getOwnerAccountId(), getTestOwnerAccountId()); - EXPECT_EQ(accountAllowanceApproveTransaction.getHbarApprovals().at(0).getSpenderAccountId(), - getTestSpenderAccountId()); - EXPECT_EQ(accountAllowanceApproveTransaction.getHbarApprovals().at(0).getAmount(), getTestAmountHbar()); + EXPECT_EQ(accountAllowanceApproveTransaction.getHbarApprovals().at(0).mOwnerAccountId, getTestOwnerAccountId()); + EXPECT_EQ(accountAllowanceApproveTransaction.getHbarApprovals().at(0).mSpenderAccountId, getTestSpenderAccountId()); + EXPECT_EQ(accountAllowanceApproveTransaction.getHbarApprovals().at(0).mAmount, getTestAmountHbar()); ASSERT_EQ(accountAllowanceApproveTransaction.getTokenApprovals().size(), 1); EXPECT_EQ(accountAllowanceApproveTransaction.getTokenApprovals().at(0).mTokenId, getTestTokenId()); @@ -140,9 +139,9 @@ TEST_F(AccountAllowanceApproveTransactionTest, ApproveHbarAllowance) // Then ASSERT_EQ(transaction.getHbarApprovals().size(), 1); - EXPECT_EQ(transaction.getHbarApprovals().at(0).getOwnerAccountId(), getTestOwnerAccountId()); - EXPECT_EQ(transaction.getHbarApprovals().at(0).getSpenderAccountId(), getTestSpenderAccountId()); - EXPECT_EQ(transaction.getHbarApprovals().at(0).getAmount(), getTestAmountHbar()); + EXPECT_EQ(transaction.getHbarApprovals().at(0).mOwnerAccountId, getTestOwnerAccountId()); + EXPECT_EQ(transaction.getHbarApprovals().at(0).mSpenderAccountId, getTestSpenderAccountId()); + EXPECT_EQ(transaction.getHbarApprovals().at(0).mAmount, getTestAmountHbar()); } //----- diff --git a/sdk/tests/unit/AssessedCustomFeesTest.cc b/sdk/tests/unit/AssessedCustomFeesTest.cc index 49ff39aed..4131fff37 100644 --- a/sdk/tests/unit/AssessedCustomFeesTest.cc +++ b/sdk/tests/unit/AssessedCustomFeesTest.cc @@ -86,9 +86,9 @@ TEST_F(AssessedCustomFeeTest, ToProtobuf) // Then EXPECT_EQ(protoAssessedCustomFee->amount(), getTestAmount()); ASSERT_TRUE(protoAssessedCustomFee->has_token_id()); - EXPECT_EQ(protoAssessedCustomFee->token_id().shardnum(), getTestTokenId().getShardNum()); - EXPECT_EQ(protoAssessedCustomFee->token_id().realmnum(), getTestTokenId().getRealmNum()); - EXPECT_EQ(protoAssessedCustomFee->token_id().tokennum(), getTestTokenId().getTokenNum()); + EXPECT_EQ(protoAssessedCustomFee->token_id().shardnum(), getTestTokenId().mShardNum); + EXPECT_EQ(protoAssessedCustomFee->token_id().realmnum(), getTestTokenId().mRealmNum); + EXPECT_EQ(protoAssessedCustomFee->token_id().tokennum(), getTestTokenId().mTokenNum); ASSERT_TRUE(protoAssessedCustomFee->has_fee_collector_account_id()); EXPECT_EQ(protoAssessedCustomFee->fee_collector_account_id().shardnum(), getTestFeeCollectorAccountId().mShardNum); EXPECT_EQ(protoAssessedCustomFee->fee_collector_account_id().realmnum(), getTestFeeCollectorAccountId().mRealmNum); diff --git a/sdk/tests/unit/ContractIdTest.cc b/sdk/tests/unit/ContractIdTest.cc index 9746a7c26..59d206612 100644 --- a/sdk/tests/unit/ContractIdTest.cc +++ b/sdk/tests/unit/ContractIdTest.cc @@ -43,19 +43,6 @@ class ContractIdTest : public ::testing::Test const EvmAddress mEvmAddress = EvmAddress::fromString("0x0123456789abcdef0123456789abcdef01234567"); }; -//----- -TEST_F(ContractIdTest, DefaultConstructContractId) -{ - // Given / When - const ContractId contractId; - - // Then - EXPECT_EQ(contractId.getShardNum(), 0ULL); - EXPECT_EQ(contractId.getRealmNum(), 0ULL); - EXPECT_FALSE(contractId.getContractNum().has_value()); - EXPECT_FALSE(contractId.getEvmAddress().has_value()); -} - //----- TEST_F(ContractIdTest, ConstructWithContractNum) { @@ -63,11 +50,11 @@ TEST_F(ContractIdTest, ConstructWithContractNum) const ContractId contractId(getTestContractNum()); // Then - EXPECT_EQ(contractId.getShardNum(), 0ULL); - EXPECT_EQ(contractId.getRealmNum(), 0ULL); - ASSERT_TRUE(contractId.getContractNum().has_value()); - EXPECT_EQ(contractId.getContractNum(), getTestContractNum()); - EXPECT_FALSE(contractId.getEvmAddress().has_value()); + EXPECT_EQ(contractId.mShardNum, 0ULL); + EXPECT_EQ(contractId.mRealmNum, 0ULL); + ASSERT_TRUE(contractId.mContractNum.has_value()); + EXPECT_EQ(contractId.mContractNum, getTestContractNum()); + EXPECT_FALSE(contractId.mEvmAddress.has_value()); } //----- @@ -84,11 +71,11 @@ TEST_F(ContractIdTest, ConstructWithEvmAddress) const ContractId contractId(getTestEvmAddress()); // Then - EXPECT_EQ(contractId.getShardNum(), 0ULL); - EXPECT_EQ(contractId.getRealmNum(), 0ULL); - EXPECT_FALSE(contractId.getContractNum().has_value()); - ASSERT_TRUE(contractId.getEvmAddress().has_value()); - EXPECT_EQ(contractId.getEvmAddress()->toBytes(), getTestEvmAddress().toBytes()); + EXPECT_EQ(contractId.mShardNum, 0ULL); + EXPECT_EQ(contractId.mRealmNum, 0ULL); + EXPECT_FALSE(contractId.mContractNum.has_value()); + ASSERT_TRUE(contractId.mEvmAddress.has_value()); + EXPECT_EQ(contractId.mEvmAddress->toBytes(), getTestEvmAddress().toBytes()); } //----- @@ -98,11 +85,11 @@ TEST_F(ContractIdTest, ConstructWithShardRealmContractNum) const ContractId contractId(getTestShardNum(), getTestRealmNum(), getTestContractNum()); // Then - EXPECT_EQ(contractId.getShardNum(), getTestShardNum()); - EXPECT_EQ(contractId.getRealmNum(), getTestRealmNum()); - ASSERT_TRUE(contractId.getContractNum().has_value()); - EXPECT_EQ(contractId.getContractNum(), getTestContractNum()); - EXPECT_FALSE(contractId.getEvmAddress().has_value()); + EXPECT_EQ(contractId.mShardNum, getTestShardNum()); + EXPECT_EQ(contractId.mRealmNum, getTestRealmNum()); + ASSERT_TRUE(contractId.mContractNum.has_value()); + EXPECT_EQ(contractId.mContractNum, getTestContractNum()); + EXPECT_FALSE(contractId.mEvmAddress.has_value()); } //----- @@ -124,11 +111,11 @@ TEST_F(ContractIdTest, ConstructWithShardRealmEvmAddress) const ContractId contractId(getTestShardNum(), getTestRealmNum(), getTestEvmAddress()); // Then - EXPECT_EQ(contractId.getShardNum(), getTestShardNum()); - EXPECT_EQ(contractId.getRealmNum(), getTestRealmNum()); - EXPECT_FALSE(contractId.getContractNum().has_value()); - ASSERT_TRUE(contractId.getEvmAddress().has_value()); - EXPECT_EQ(contractId.getEvmAddress()->toBytes(), getTestEvmAddress().toBytes()); + EXPECT_EQ(contractId.mShardNum, getTestShardNum()); + EXPECT_EQ(contractId.mRealmNum, getTestRealmNum()); + EXPECT_FALSE(contractId.mContractNum.has_value()); + ASSERT_TRUE(contractId.mEvmAddress.has_value()); + EXPECT_EQ(contractId.mEvmAddress->toBytes(), getTestEvmAddress().toBytes()); } //----- @@ -176,17 +163,17 @@ TEST_F(ContractIdTest, FromProtobuf) const ContractId contractIdEvmAddress = ContractId::fromProtobuf(protoContractIdEvmAddress); // Then - EXPECT_EQ(contractIdContractNum.getShardNum(), getTestShardNum()); - EXPECT_EQ(contractIdContractNum.getRealmNum(), getTestRealmNum()); - ASSERT_TRUE(contractIdContractNum.getContractNum().has_value()); - EXPECT_EQ(contractIdContractNum.getContractNum(), getTestContractNum()); - EXPECT_FALSE(contractIdContractNum.getEvmAddress().has_value()); - - EXPECT_EQ(contractIdEvmAddress.getShardNum(), getTestShardNum()); - EXPECT_EQ(contractIdEvmAddress.getRealmNum(), getTestRealmNum()); - EXPECT_FALSE(contractIdEvmAddress.getContractNum().has_value()); - ASSERT_TRUE(contractIdEvmAddress.getEvmAddress().has_value()); - EXPECT_EQ(contractIdEvmAddress.getEvmAddress()->toBytes(), getTestEvmAddress().toBytes()); + EXPECT_EQ(contractIdContractNum.mShardNum, getTestShardNum()); + EXPECT_EQ(contractIdContractNum.mRealmNum, getTestRealmNum()); + ASSERT_TRUE(contractIdContractNum.mContractNum.has_value()); + EXPECT_EQ(contractIdContractNum.mContractNum, getTestContractNum()); + EXPECT_FALSE(contractIdContractNum.mEvmAddress.has_value()); + + EXPECT_EQ(contractIdEvmAddress.mShardNum, getTestShardNum()); + EXPECT_EQ(contractIdEvmAddress.mRealmNum, getTestRealmNum()); + EXPECT_FALSE(contractIdEvmAddress.mContractNum.has_value()); + ASSERT_TRUE(contractIdEvmAddress.mEvmAddress.has_value()); + EXPECT_EQ(contractIdEvmAddress.mEvmAddress->toBytes(), getTestEvmAddress().toBytes()); } //----- @@ -284,76 +271,3 @@ TEST_F(ContractIdTest, ToString) std::to_string(getTestShardNum()) + '.' + std::to_string(getTestRealmNum()) + '.' + getTestEvmAddress().toString()); } - -//----- -TEST_F(ContractIdTest, GetSetShardNum) -{ - // Given - ContractId contractId; - - // When - EXPECT_THROW(contractId.setShardNum(getTestNumTooBig()), std::invalid_argument); - contractId.setShardNum(getTestShardNum()); - - // Then - EXPECT_EQ(contractId.getShardNum(), getTestShardNum()); -} - -//----- -TEST_F(ContractIdTest, GetSetRealmNum) -{ - // Given - ContractId contractId; - - // When - EXPECT_THROW(contractId.setRealmNum(getTestNumTooBig()), std::invalid_argument); - contractId.setRealmNum(getTestRealmNum()); - - // Then - EXPECT_EQ(contractId.getRealmNum(), getTestRealmNum()); -} - -//----- -TEST_F(ContractIdTest, GetSetContractNum) -{ - // Given - ContractId contractId; - - // When - EXPECT_THROW(contractId.setContractNum(getTestNumTooBig()), std::invalid_argument); - contractId.setContractNum(getTestContractNum()); - - // Then - ASSERT_TRUE(contractId.getContractNum().has_value()); - EXPECT_EQ(contractId.getContractNum(), getTestContractNum()); -} - -//----- -TEST_F(ContractIdTest, GetSetEvmAddress) -{ - // Given - ContractId contractId; - - // When - contractId.setEvmAddress(getTestEvmAddress()); - - // Then - ASSERT_TRUE(contractId.getEvmAddress().has_value()); - EXPECT_EQ(contractId.getEvmAddress()->toBytes(), getTestEvmAddress().toBytes()); -} - -//----- -TEST_F(ContractIdTest, ResetMutuallyExclusiveIds) -{ - // Given - ContractId contractIdContractNum(getTestContractNum()); - ContractId contractIdEvmAddress(getTestEvmAddress()); - - // When - contractIdContractNum.setEvmAddress(getTestEvmAddress()); - contractIdEvmAddress.setContractNum(getTestContractNum()); - - // Then - EXPECT_FALSE(contractIdContractNum.getContractNum().has_value()); - EXPECT_FALSE(contractIdEvmAddress.getEvmAddress().has_value()); -} diff --git a/sdk/tests/unit/ContractNonceInfoUnitTests.cc b/sdk/tests/unit/ContractNonceInfoUnitTests.cc index 306c86c7f..3ddcd9dc6 100644 --- a/sdk/tests/unit/ContractNonceInfoUnitTests.cc +++ b/sdk/tests/unit/ContractNonceInfoUnitTests.cc @@ -66,12 +66,12 @@ TEST_F(ContractNonceInfoTest, ToProtobuf) // Then EXPECT_EQ(protoContractNonceInfo.get()->contract_id().shardnum(), - static_cast(getTestContractId().getShardNum())); + static_cast(getTestContractId().mShardNum)); EXPECT_EQ(protoContractNonceInfo.get()->contract_id().realmnum(), - static_cast(getTestContractId().getRealmNum())); + static_cast(getTestContractId().mRealmNum)); ASSERT_EQ(protoContractNonceInfo.get()->contract_id().contract_case(), proto::ContractID::ContractCase::kContractNum); EXPECT_EQ(protoContractNonceInfo.get()->contract_id().contractnum(), - static_cast(getTestContractId().getContractNum().value())); + static_cast(getTestContractId().mContractNum.value())); EXPECT_EQ(protoContractNonceInfo.get()->nonce(), getTestNonce()); } @@ -101,8 +101,8 @@ TEST_F(ContractNonceInfoTest, FromBytes) ContractNonceInfo::fromBytes(internal::Utilities::stringToByteVector(protoContractNonceInfo.SerializeAsString())); // Then - EXPECT_EQ(contractNonceInfo.mContractId.getShardNum(), getTestContractId().getShardNum()); - EXPECT_EQ(contractNonceInfo.mContractId.getRealmNum(), getTestContractId().getRealmNum()); - EXPECT_EQ(contractNonceInfo.mContractId.getContractNum(), getTestContractId().getContractNum()); + EXPECT_EQ(contractNonceInfo.mContractId.mShardNum, getTestContractId().mShardNum); + EXPECT_EQ(contractNonceInfo.mContractId.mRealmNum, getTestContractId().mRealmNum); + EXPECT_EQ(contractNonceInfo.mContractId.mContractNum, getTestContractId().mContractNum); EXPECT_EQ(contractNonceInfo.mNonce, getTestNonce()); } diff --git a/sdk/tests/unit/CustomFixedFeeTest.cc b/sdk/tests/unit/CustomFixedFeeTest.cc index 54d5bc3e9..b8a2d342c 100644 --- a/sdk/tests/unit/CustomFixedFeeTest.cc +++ b/sdk/tests/unit/CustomFixedFeeTest.cc @@ -94,9 +94,9 @@ TEST_F(CustomFixedFeeTest, ToProtobuf) ASSERT_EQ(protoCustomFee->fee_case(), proto::CustomFee::FeeCase::kFixedFee); EXPECT_EQ(protoCustomFee->fixed_fee().amount(), getTestAmount()); - EXPECT_EQ(protoCustomFee->fixed_fee().denominating_token_id().shardnum(), getTestTokenId().getShardNum()); - EXPECT_EQ(protoCustomFee->fixed_fee().denominating_token_id().realmnum(), getTestTokenId().getRealmNum()); - EXPECT_EQ(protoCustomFee->fixed_fee().denominating_token_id().tokennum(), getTestTokenId().getTokenNum()); + EXPECT_EQ(protoCustomFee->fixed_fee().denominating_token_id().shardnum(), getTestTokenId().mShardNum); + EXPECT_EQ(protoCustomFee->fixed_fee().denominating_token_id().realmnum(), getTestTokenId().mRealmNum); + EXPECT_EQ(protoCustomFee->fixed_fee().denominating_token_id().tokennum(), getTestTokenId().mTokenNum); } //----- @@ -112,9 +112,9 @@ TEST_F(CustomFixedFeeTest, ToFixedFeeProtobuf) // Then EXPECT_EQ(protoFixedFee->amount(), getTestAmount()); - EXPECT_EQ(protoFixedFee->denominating_token_id().shardnum(), getTestTokenId().getShardNum()); - EXPECT_EQ(protoFixedFee->denominating_token_id().realmnum(), getTestTokenId().getRealmNum()); - EXPECT_EQ(protoFixedFee->denominating_token_id().tokennum(), getTestTokenId().getTokenNum()); + EXPECT_EQ(protoFixedFee->denominating_token_id().shardnum(), getTestTokenId().mShardNum); + EXPECT_EQ(protoFixedFee->denominating_token_id().realmnum(), getTestTokenId().mRealmNum); + EXPECT_EQ(protoFixedFee->denominating_token_id().tokennum(), getTestTokenId().mTokenNum); } //----- diff --git a/sdk/tests/unit/DelegateContractIdTest.cc b/sdk/tests/unit/DelegateContractIdTest.cc index 3a313e630..1e53e2e69 100644 --- a/sdk/tests/unit/DelegateContractIdTest.cc +++ b/sdk/tests/unit/DelegateContractIdTest.cc @@ -41,19 +41,6 @@ class DelegateContractIdTest : public ::testing::Test const uint64_t mNumTooBig = static_cast(std::numeric_limits::max()) + 1ULL; }; -//----- -TEST_F(DelegateContractIdTest, DefaultConstructDelegateContractId) -{ - // Given / When - const DelegateContractId delegateContractId; - - // Then - EXPECT_EQ(delegateContractId.getShardNum(), 0ULL); - EXPECT_EQ(delegateContractId.getRealmNum(), 0ULL); - EXPECT_FALSE(delegateContractId.getContractNum().has_value()); - EXPECT_FALSE(delegateContractId.getEvmAddress().has_value()); -} - //----- TEST_F(DelegateContractIdTest, ConstructWithContractNum) { @@ -61,11 +48,11 @@ TEST_F(DelegateContractIdTest, ConstructWithContractNum) const DelegateContractId delegateContractId(getTestContractNum()); // Then - EXPECT_EQ(delegateContractId.getShardNum(), 0ULL); - EXPECT_EQ(delegateContractId.getRealmNum(), 0ULL); - ASSERT_TRUE(delegateContractId.getContractNum().has_value()); - EXPECT_EQ(delegateContractId.getContractNum(), getTestContractNum()); - EXPECT_FALSE(delegateContractId.getEvmAddress().has_value()); + EXPECT_EQ(delegateContractId.mShardNum, 0ULL); + EXPECT_EQ(delegateContractId.mRealmNum, 0ULL); + ASSERT_TRUE(delegateContractId.mContractNum.has_value()); + EXPECT_EQ(delegateContractId.mContractNum, getTestContractNum()); + EXPECT_FALSE(delegateContractId.mEvmAddress.has_value()); } //----- @@ -82,11 +69,11 @@ TEST_F(DelegateContractIdTest, ConstructWithShardRealmContractNum) const DelegateContractId delegateContractId(getTestShardNum(), getTestRealmNum(), getTestContractNum()); // Then - EXPECT_EQ(delegateContractId.getShardNum(), getTestShardNum()); - EXPECT_EQ(delegateContractId.getRealmNum(), getTestRealmNum()); - ASSERT_TRUE(delegateContractId.getContractNum().has_value()); - EXPECT_EQ(delegateContractId.getContractNum(), getTestContractNum()); - EXPECT_FALSE(delegateContractId.getEvmAddress().has_value()); + EXPECT_EQ(delegateContractId.mShardNum, getTestShardNum()); + EXPECT_EQ(delegateContractId.mRealmNum, getTestRealmNum()); + ASSERT_TRUE(delegateContractId.mContractNum.has_value()); + EXPECT_EQ(delegateContractId.mContractNum, getTestContractNum()); + EXPECT_FALSE(delegateContractId.mEvmAddress.has_value()); } //----- @@ -126,10 +113,10 @@ TEST_F(DelegateContractIdTest, FromCorrectlyFormedString) std::to_string(getTestContractNum()))); // Then - EXPECT_EQ(delegateContractId.getShardNum(), getTestShardNum()); - EXPECT_EQ(delegateContractId.getRealmNum(), getTestRealmNum()); - ASSERT_TRUE(delegateContractId.getContractNum().has_value()); - EXPECT_EQ(delegateContractId.getContractNum(), getTestContractNum()); + EXPECT_EQ(delegateContractId.mShardNum, getTestShardNum()); + EXPECT_EQ(delegateContractId.mRealmNum, getTestRealmNum()); + ASSERT_TRUE(delegateContractId.mContractNum.has_value()); + EXPECT_EQ(delegateContractId.mContractNum, getTestContractNum()); } //----- @@ -213,11 +200,11 @@ TEST_F(DelegateContractIdTest, FromProtobuf) const DelegateContractId delegateContractId = DelegateContractId::fromProtobuf(protoContractId); // Then - EXPECT_EQ(delegateContractId.getShardNum(), getTestShardNum()); - EXPECT_EQ(delegateContractId.getRealmNum(), getTestRealmNum()); - ASSERT_TRUE(delegateContractId.getContractNum().has_value()); - EXPECT_EQ(delegateContractId.getContractNum(), getTestContractNum()); - EXPECT_FALSE(delegateContractId.getEvmAddress().has_value()); + EXPECT_EQ(delegateContractId.mShardNum, getTestShardNum()); + EXPECT_EQ(delegateContractId.mRealmNum, getTestRealmNum()); + ASSERT_TRUE(delegateContractId.mContractNum.has_value()); + EXPECT_EQ(delegateContractId.mContractNum, getTestContractNum()); + EXPECT_FALSE(delegateContractId.mEvmAddress.has_value()); } //----- diff --git a/sdk/tests/unit/FileIdTest.cc b/sdk/tests/unit/FileIdTest.cc index 9dcef4a67..c797f8bf6 100644 --- a/sdk/tests/unit/FileIdTest.cc +++ b/sdk/tests/unit/FileIdTest.cc @@ -41,18 +41,6 @@ class FileIdTest : public ::testing::Test const uint64_t mNumTooBig = static_cast(std::numeric_limits::max()) + 1ULL; }; -//----- -TEST_F(FileIdTest, DefaultConstructFileId) -{ - // Given / When - const FileId fileId; - - // Then - EXPECT_EQ(fileId.getShardNum(), 0ULL); - EXPECT_EQ(fileId.getRealmNum(), 0ULL); - EXPECT_EQ(fileId.getFileNum(), 0ULL); -} - //----- TEST_F(FileIdTest, ConstructWithFileNum) { @@ -60,9 +48,9 @@ TEST_F(FileIdTest, ConstructWithFileNum) const FileId fileId(getTestFileNum()); // Then - EXPECT_EQ(fileId.getShardNum(), 0ULL); - EXPECT_EQ(fileId.getRealmNum(), 0ULL); - EXPECT_EQ(fileId.getFileNum(), getTestFileNum()); + EXPECT_EQ(fileId.mShardNum, 0ULL); + EXPECT_EQ(fileId.mRealmNum, 0ULL); + EXPECT_EQ(fileId.mFileNum, getTestFileNum()); } //----- @@ -79,9 +67,9 @@ TEST_F(FileIdTest, ConstructWithShardRealmFileNum) const FileId fileId(getTestShardNum(), getTestRealmNum(), getTestFileNum()); // Then - EXPECT_EQ(fileId.getShardNum(), getTestShardNum()); - EXPECT_EQ(fileId.getRealmNum(), getTestRealmNum()); - EXPECT_EQ(fileId.getFileNum(), getTestFileNum()); + EXPECT_EQ(fileId.mShardNum, getTestShardNum()); + EXPECT_EQ(fileId.mRealmNum, getTestRealmNum()); + EXPECT_EQ(fileId.mFileNum, getTestFileNum()); } //----- @@ -120,9 +108,9 @@ TEST_F(FileIdTest, FromString) '.' + std::to_string(getTestFileNum()))); // Then - EXPECT_EQ(fileId.getShardNum(), getTestShardNum()); - EXPECT_EQ(fileId.getRealmNum(), getTestRealmNum()); - EXPECT_EQ(fileId.getFileNum(), getTestFileNum()); + EXPECT_EQ(fileId.mShardNum, getTestShardNum()); + EXPECT_EQ(fileId.mRealmNum, getTestRealmNum()); + EXPECT_EQ(fileId.mFileNum, getTestFileNum()); } //----- @@ -191,9 +179,9 @@ TEST_F(FileIdTest, FromProtobuf) const FileId fileId = FileId::fromProtobuf(protoFileId); // Then - EXPECT_EQ(fileId.getShardNum(), getTestShardNum()); - EXPECT_EQ(fileId.getRealmNum(), getTestRealmNum()); - EXPECT_EQ(fileId.getFileNum(), getTestFileNum()); + EXPECT_EQ(fileId.mShardNum, getTestShardNum()); + EXPECT_EQ(fileId.mRealmNum, getTestRealmNum()); + EXPECT_EQ(fileId.mFileNum, getTestFileNum()); } //----- @@ -231,72 +219,3 @@ TEST_F(FileIdTest, ToString) std::to_string(getTestShardNum()) + '.' + std::to_string(getTestRealmNum()) + '.' + std::to_string(getTestFileNum())); } - -//----- -TEST_F(FileIdTest, SetGetShardNum) -{ - // Given - FileId fileId; - - // When - fileId.setShardNum(getTestShardNum()); - - // Then - EXPECT_EQ(fileId.getShardNum(), getTestShardNum()); -} - -//----- -TEST_F(FileIdTest, SetGetShardNumTooBig) -{ - // Given - FileId fileId; - - // When / Then - EXPECT_THROW(fileId.setShardNum(getTestNumTooBig()), std::invalid_argument); -} - -//----- -TEST_F(FileIdTest, SetGetRealmNum) -{ - // Given - FileId fileId; - - // When - fileId.setRealmNum(getTestRealmNum()); - - // Then - EXPECT_EQ(fileId.getRealmNum(), getTestRealmNum()); -} - -//----- -TEST_F(FileIdTest, SetGetRealmNumTooBig) -{ - // Given - FileId fileId; - - // When / Then - EXPECT_THROW(fileId.setRealmNum(getTestNumTooBig()), std::invalid_argument); -} - -//----- -TEST_F(FileIdTest, SetGetFileNum) -{ - // Given - FileId fileId; - - // When - fileId.setFileNum(getTestFileNum()); - - // Then - EXPECT_EQ(fileId.getFileNum(), getTestFileNum()); -} - -//----- -TEST_F(FileIdTest, SetGetFileNumTooBig) -{ - // Given - FileId fileId; - - // When / Then - EXPECT_THROW(fileId.setFileNum(getTestNumTooBig()), std::invalid_argument); -} diff --git a/sdk/tests/unit/HbarAllowanceTest.cc b/sdk/tests/unit/HbarAllowanceTest.cc index 2658e0812..9949b69db 100644 --- a/sdk/tests/unit/HbarAllowanceTest.cc +++ b/sdk/tests/unit/HbarAllowanceTest.cc @@ -46,48 +46,9 @@ TEST_F(HbarAllowanceTest, ConstructWithOwnerSpenderAmount) const HbarAllowance hbarAllowance(getTestOwnerAccountId(), getTestSpenderAccountId(), getTestAmount()); // Then - EXPECT_EQ(hbarAllowance.getOwnerAccountId(), getTestOwnerAccountId()); - EXPECT_EQ(hbarAllowance.getSpenderAccountId(), getTestSpenderAccountId()); - EXPECT_EQ(hbarAllowance.getAmount(), getTestAmount()); -} - -//----- -TEST_F(HbarAllowanceTest, GetSetOwnerAccountId) -{ - // Given - HbarAllowance hbarAllowance; - - // When - hbarAllowance.setOwnerAccountId(getTestOwnerAccountId()); - - // Then - EXPECT_EQ(hbarAllowance.getOwnerAccountId(), getTestOwnerAccountId()); -} - -//----- -TEST_F(HbarAllowanceTest, GetSetSpenderAccountId) -{ - // Given - HbarAllowance hbarAllowance; - - // When - hbarAllowance.setSpenderAccountId(getTestSpenderAccountId()); - - // Then - EXPECT_EQ(hbarAllowance.getSpenderAccountId(), getTestSpenderAccountId()); -} - -//----- -TEST_F(HbarAllowanceTest, GetSetAmount) -{ - // Given - HbarAllowance hbarAllowance; - - // When - hbarAllowance.setAmount(getTestAmount()); - - // Then - EXPECT_EQ(hbarAllowance.getAmount(), getTestAmount()); + EXPECT_EQ(hbarAllowance.mOwnerAccountId, getTestOwnerAccountId()); + EXPECT_EQ(hbarAllowance.mSpenderAccountId, getTestSpenderAccountId()); + EXPECT_EQ(hbarAllowance.mAmount, getTestAmount()); } //----- @@ -103,19 +64,16 @@ TEST_F(HbarAllowanceTest, FromProtobuf) const HbarAllowance hbarAllowance = HbarAllowance::fromProtobuf(cryptoAllowance); // Then - EXPECT_EQ(hbarAllowance.getOwnerAccountId(), getTestOwnerAccountId()); - EXPECT_EQ(hbarAllowance.getSpenderAccountId(), getTestSpenderAccountId()); - EXPECT_EQ(hbarAllowance.getAmount(), getTestAmount()); + EXPECT_EQ(hbarAllowance.mOwnerAccountId, getTestOwnerAccountId()); + EXPECT_EQ(hbarAllowance.mSpenderAccountId, getTestSpenderAccountId()); + EXPECT_EQ(hbarAllowance.mAmount, getTestAmount()); } //----- TEST_F(HbarAllowanceTest, ToProtobuf) { // Given - HbarAllowance hbarAllowance; - hbarAllowance.setOwnerAccountId(getTestOwnerAccountId()); - hbarAllowance.setSpenderAccountId(getTestSpenderAccountId()); - hbarAllowance.setAmount(getTestAmount()); + const HbarAllowance hbarAllowance(getTestOwnerAccountId(), getTestSpenderAccountId(), getTestAmount()); // When const std::unique_ptr cryptoAllowance = hbarAllowance.toProtobuf(); diff --git a/sdk/tests/unit/HbarTransferTest.cc b/sdk/tests/unit/HbarTransferTest.cc index 13b9bbf45..ca384ffe8 100644 --- a/sdk/tests/unit/HbarTransferTest.cc +++ b/sdk/tests/unit/HbarTransferTest.cc @@ -41,21 +41,14 @@ class HbarTransferTest : public ::testing::Test TEST_F(HbarTransferTest, SerializeTransferToProtobuf) { // Given - const AccountId testAccountId = getTestAccountId(); - const int64_t testAmount = getTestAmount(); - const auto testHbarAmount = Hbar(testAmount, HbarUnit::TINYBAR()); - - HbarTransfer testTransfer; - testTransfer.setAccountId(testAccountId); - testTransfer.setAmount(testHbarAmount); - testTransfer.setApproved(false); + const HbarTransfer testTransfer(getTestAccountId(), Hbar(getTestAmount(), HbarUnit::TINYBAR()), false); // When const auto protoAccountAmountPtr = std::unique_ptr(testTransfer.toProtobuf()); // Then - EXPECT_EQ(protoAccountAmountPtr->accountid().accountnum(), testAccountId.mAccountNum); - EXPECT_EQ(protoAccountAmountPtr->amount(), testAmount); + EXPECT_EQ(protoAccountAmountPtr->accountid().accountnum(), getTestAccountId().mAccountNum); + EXPECT_EQ(protoAccountAmountPtr->amount(), getTestAmount()); EXPECT_FALSE(protoAccountAmountPtr->is_approval()); } @@ -74,9 +67,9 @@ TEST_F(HbarTransferTest, DeserializeTransferFromProtobuf) const HbarTransfer transfer = HbarTransfer::fromProtobuf(testProtoAccountAmount); // Then - EXPECT_EQ(transfer.getAccountId(), testAccountId); - EXPECT_EQ(transfer.getAmount().toTinybars(), testAmount); - EXPECT_TRUE(transfer.getApproval()); + EXPECT_EQ(transfer.mAccountId, testAccountId); + EXPECT_EQ(transfer.mAmount.toTinybars(), testAmount); + EXPECT_TRUE(transfer.mIsApproved); } // Tests serialization & deserialization of Hedera::HbarTransfer -> proto::AccountAmount -> Hedera::HbarTransfer. @@ -91,16 +84,16 @@ TEST_F(HbarTransferTest, ProtoTransfer) protoAccountAmount.set_is_approval(true); HbarTransfer transfer = HbarTransfer::fromProtobuf(protoAccountAmount); - EXPECT_EQ(transfer.getAccountId(), accountId); - EXPECT_EQ(transfer.getAmount().toTinybars(), amount); - EXPECT_TRUE(transfer.getApproval()); + EXPECT_EQ(transfer.mAccountId, accountId); + EXPECT_EQ(transfer.mAmount.toTinybars(), amount); + EXPECT_TRUE(transfer.mIsApproved); accountId.mAccountNum = 15ULL; amount = 15LL; - transfer.setAccountId(accountId); - transfer.setAmount(Hbar(amount, HbarUnit::TINYBAR())); - transfer.setApproved(false); + transfer.mAccountId = accountId; + transfer.mAmount = Hbar(amount, HbarUnit::TINYBAR()); + transfer.mIsApproved = false; const auto protoAccountAmountPtr = std::unique_ptr(transfer.toProtobuf()); EXPECT_EQ(protoAccountAmountPtr->accountid().accountnum(), accountId.mAccountNum); diff --git a/sdk/tests/unit/NftIdTest.cc b/sdk/tests/unit/NftIdTest.cc index 4ccef1a29..39cee3426 100644 --- a/sdk/tests/unit/NftIdTest.cc +++ b/sdk/tests/unit/NftIdTest.cc @@ -38,20 +38,12 @@ class NftIdTest : public ::testing::Test const uint64_t mNumTooBig = static_cast(std::numeric_limits::max()) + 1ULL; }; -//----- -TEST_F(NftIdTest, DefaultConstructNftId) -{ - const NftId nftId; - EXPECT_EQ(nftId.getTokenId(), TokenId()); - EXPECT_EQ(nftId.getSerialNum(), 0ULL); -} - //----- TEST_F(NftIdTest, ConstructWithTokenIdSerialNum) { const NftId nftId(getTestTokenId(), getTestSerialNum()); - EXPECT_EQ(nftId.getTokenId(), getTestTokenId()); - EXPECT_EQ(nftId.getSerialNum(), getTestSerialNum()); + EXPECT_EQ(nftId.mTokenId, getTestTokenId()); + EXPECT_EQ(nftId.mSerialNum, getTestSerialNum()); EXPECT_THROW(NftId(getTestTokenId(), getTestNumTooBig()), std::invalid_argument); } @@ -72,8 +64,8 @@ TEST_F(NftIdTest, ConstructFromString) NftId nftId; EXPECT_NO_THROW(nftId = NftId::fromString(testTokenIdStr + '/' + testSerialNumSr)); - EXPECT_EQ(nftId.getTokenId(), getTestTokenId()); - EXPECT_EQ(nftId.getSerialNum(), getTestSerialNum()); + EXPECT_EQ(nftId.mTokenId, getTestTokenId()); + EXPECT_EQ(nftId.mSerialNum, getTestSerialNum()); EXPECT_THROW(nftId = NftId::fromString(testTokenIdStr + testSerialNumSr), std::invalid_argument); EXPECT_THROW(nftId = NftId::fromString('/' + testTokenIdStr + testSerialNumSr), std::invalid_argument); @@ -92,9 +84,7 @@ TEST_F(NftIdTest, ConstructFromString) //----- TEST_F(NftIdTest, ProtobufNftId) { - NftId nftId; - nftId.setTokenId(getTestTokenId()); - nftId.setSerialNum(getTestSerialNum()); + NftId nftId(getTestTokenId(), getTestSerialNum()); // Serialize token ID and serial number std::unique_ptr protoNftID = nftId.toProtobuf(); @@ -106,8 +96,8 @@ TEST_F(NftIdTest, ProtobufNftId) // Deserialize token ID and serial number nftId = NftId::fromProtobuf(*protoNftID); - EXPECT_EQ(nftId.getTokenId(), getTestTokenId()); - EXPECT_EQ(nftId.getSerialNum(), getTestSerialNum() - 1ULL); + EXPECT_EQ(nftId.mTokenId, getTestTokenId()); + EXPECT_EQ(nftId.mSerialNum, getTestSerialNum() - 1ULL); } //----- @@ -116,25 +106,7 @@ TEST_F(NftIdTest, ToString) NftId nftId; EXPECT_EQ(nftId.toString(), "0.0.0/0"); - nftId.setTokenId(getTestTokenId()); - nftId.setSerialNum(getTestSerialNum()); + nftId.mTokenId = getTestTokenId(); + nftId.mSerialNum = getTestSerialNum(); EXPECT_EQ(nftId.toString(), getTestTokenId().toString() + '/' + std::to_string(getTestSerialNum())); } - -//----- -TEST_F(NftIdTest, SetGetTokenId) -{ - NftId nftId; - nftId.setTokenId(getTestTokenId()); - EXPECT_EQ(nftId.getTokenId(), getTestTokenId()); -} - -//----- -TEST_F(NftIdTest, SetGetSerialNum) -{ - NftId nftId; - nftId.setSerialNum(getTestSerialNum()); - - EXPECT_EQ(nftId.getSerialNum(), getTestSerialNum()); - EXPECT_THROW(nftId.setSerialNum(getTestNumTooBig()), std::invalid_argument); -} diff --git a/sdk/tests/unit/TokenAssociationUnitTests.cc b/sdk/tests/unit/TokenAssociationUnitTests.cc index 2c12d28e2..eef61439b 100644 --- a/sdk/tests/unit/TokenAssociationUnitTests.cc +++ b/sdk/tests/unit/TokenAssociationUnitTests.cc @@ -69,9 +69,9 @@ TEST_F(TokenAssociationTest, ToProtobuf) EXPECT_EQ(protoTokenAssociation->account_id().realmnum(), getTestAccountId().mRealmNum); EXPECT_EQ(protoTokenAssociation->account_id().accountnum(), getTestAccountId().mAccountNum); ASSERT_TRUE(protoTokenAssociation->has_token_id()); - EXPECT_EQ(protoTokenAssociation->token_id().shardnum(), getTestTokenId().getShardNum()); - EXPECT_EQ(protoTokenAssociation->token_id().realmnum(), getTestTokenId().getRealmNum()); - EXPECT_EQ(protoTokenAssociation->token_id().tokennum(), getTestTokenId().getTokenNum()); + EXPECT_EQ(protoTokenAssociation->token_id().shardnum(), getTestTokenId().mShardNum); + EXPECT_EQ(protoTokenAssociation->token_id().realmnum(), getTestTokenId().mRealmNum); + EXPECT_EQ(protoTokenAssociation->token_id().tokennum(), getTestTokenId().mTokenNum); } //----- diff --git a/sdk/tests/unit/TokenIdTest.cc b/sdk/tests/unit/TokenIdTest.cc index 829ec178f..a2155b2c1 100644 --- a/sdk/tests/unit/TokenIdTest.cc +++ b/sdk/tests/unit/TokenIdTest.cc @@ -40,22 +40,13 @@ class TokenIdTest : public ::testing::Test const uint64_t mNumTooBig = static_cast(std::numeric_limits::max()) + 1ULL; }; -//----- -TEST_F(TokenIdTest, DefaultConstructTokenId) -{ - const TokenId tokenId; - EXPECT_EQ(tokenId.getShardNum(), 0ULL); - EXPECT_EQ(tokenId.getRealmNum(), 0ULL); - EXPECT_EQ(tokenId.getTokenNum(), 0ULL); -} - //----- TEST_F(TokenIdTest, ConstructWithTokenNum) { const TokenId tokenId(getTestTokenNum()); - EXPECT_EQ(tokenId.getShardNum(), 0ULL); - EXPECT_EQ(tokenId.getRealmNum(), 0ULL); - EXPECT_EQ(tokenId.getTokenNum(), getTestTokenNum()); + EXPECT_EQ(tokenId.mShardNum, 0ULL); + EXPECT_EQ(tokenId.mRealmNum, 0ULL); + EXPECT_EQ(tokenId.mTokenNum, getTestTokenNum()); EXPECT_THROW(TokenId{ getTestNumTooBig() }, std::invalid_argument); } @@ -64,9 +55,9 @@ TEST_F(TokenIdTest, ConstructWithTokenNum) TEST_F(TokenIdTest, ConstructWithShardRealmTokenNum) { const TokenId tokenId(getTestShardNum(), getTestRealmNum(), getTestTokenNum()); - EXPECT_EQ(tokenId.getShardNum(), getTestShardNum()); - EXPECT_EQ(tokenId.getRealmNum(), getTestRealmNum()); - EXPECT_EQ(tokenId.getTokenNum(), getTestTokenNum()); + EXPECT_EQ(tokenId.mShardNum, getTestShardNum()); + EXPECT_EQ(tokenId.mRealmNum, getTestRealmNum()); + EXPECT_EQ(tokenId.mTokenNum, getTestTokenNum()); EXPECT_THROW((TokenId{ getTestNumTooBig(), getTestRealmNum(), getTestTokenNum() }), std::invalid_argument); EXPECT_THROW((TokenId{ getTestShardNum(), getTestNumTooBig(), getTestTokenNum() }), std::invalid_argument); @@ -92,9 +83,9 @@ TEST_F(TokenIdTest, ConstructFromString) TokenId tokenId; EXPECT_NO_THROW(tokenId = TokenId::fromString(testShardNumStr + '.' + testRealmNumStr + '.' + testTokenNumStr)); - EXPECT_EQ(tokenId.getShardNum(), getTestShardNum()); - EXPECT_EQ(tokenId.getRealmNum(), getTestRealmNum()); - EXPECT_EQ(tokenId.getTokenNum(), getTestTokenNum()); + EXPECT_EQ(tokenId.mShardNum, getTestShardNum()); + EXPECT_EQ(tokenId.mRealmNum, getTestRealmNum()); + EXPECT_EQ(tokenId.mTokenNum, getTestTokenNum()); EXPECT_THROW(tokenId = TokenId::fromString(testShardNumStr + testRealmNumStr + testTokenNumStr), std::invalid_argument); @@ -140,10 +131,7 @@ TEST_F(TokenIdTest, ConstructFromString) //----- TEST_F(TokenIdTest, ProtobufTokenId) { - TokenId tokenId; - tokenId.setShardNum(getTestShardNum()); - tokenId.setRealmNum(getTestRealmNum()); - tokenId.setTokenNum(getTestTokenNum()); + TokenId tokenId(getTestShardNum(), getTestRealmNum(), getTestTokenNum()); // Serialize shard, realm, token number std::unique_ptr protoTokenId = tokenId.toProtobuf(); @@ -163,9 +151,9 @@ TEST_F(TokenIdTest, ProtobufTokenId) // Deserialize shard, realm, token number tokenId = TokenId::fromProtobuf(*protoTokenId); - EXPECT_EQ(tokenId.getShardNum(), newShard); - EXPECT_EQ(tokenId.getRealmNum(), newRealm); - EXPECT_EQ(tokenId.getTokenNum(), newToken); + EXPECT_EQ(tokenId.mShardNum, newShard); + EXPECT_EQ(tokenId.mRealmNum, newRealm); + EXPECT_EQ(tokenId.mTokenNum, newToken); } //----- @@ -174,40 +162,10 @@ TEST_F(TokenIdTest, ToString) TokenId tokenId; EXPECT_EQ(tokenId.toString(), "0.0.0"); - tokenId.setShardNum(getTestShardNum()); - tokenId.setRealmNum(getTestRealmNum()); - tokenId.setTokenNum(getTestTokenNum()); + tokenId.mShardNum = getTestShardNum(); + tokenId.mRealmNum = getTestRealmNum(); + tokenId.mTokenNum = getTestTokenNum(); EXPECT_EQ(tokenId.toString(), std::to_string(getTestShardNum()) + '.' + std::to_string(getTestRealmNum()) + '.' + std::to_string(getTestTokenNum())); } - -//----- -TEST_F(TokenIdTest, SetGetShardNum) -{ - TokenId tokenId; - tokenId.setShardNum(getTestShardNum()); - - EXPECT_EQ(tokenId.getShardNum(), getTestShardNum()); - EXPECT_THROW(tokenId.setShardNum(getTestNumTooBig()), std::invalid_argument); -} - -//----- -TEST_F(TokenIdTest, SetGetRealmNum) -{ - TokenId tokenId; - tokenId.setRealmNum(getTestRealmNum()); - - EXPECT_EQ(tokenId.getRealmNum(), getTestRealmNum()); - EXPECT_THROW(tokenId.setRealmNum(getTestNumTooBig()), std::invalid_argument); -} - -//----- -TEST_F(TokenIdTest, SetGetAccountNum) -{ - TokenId tokenId; - tokenId.setTokenNum(getTestTokenNum()); - - EXPECT_EQ(tokenId.getTokenNum(), getTestTokenNum()); - EXPECT_THROW(tokenId.setTokenNum(getTestNumTooBig()), std::invalid_argument); -} diff --git a/sdk/tests/unit/TokenInfoUnitTests.cc b/sdk/tests/unit/TokenInfoUnitTests.cc index 73432fded..4dc2e7ad0 100644 --- a/sdk/tests/unit/TokenInfoUnitTests.cc +++ b/sdk/tests/unit/TokenInfoUnitTests.cc @@ -337,9 +337,9 @@ TEST_F(TokenInfoTest, ToProtobuf) const std::unique_ptr protoTokenInfo = tokenInfo.toProtobuf(); // Then - EXPECT_EQ(protoTokenInfo->tokenid().shardnum(), getTestTokenId().getShardNum()); - EXPECT_EQ(protoTokenInfo->tokenid().realmnum(), getTestTokenId().getRealmNum()); - EXPECT_EQ(protoTokenInfo->tokenid().tokennum(), getTestTokenId().getTokenNum()); + EXPECT_EQ(protoTokenInfo->tokenid().shardnum(), getTestTokenId().mShardNum); + EXPECT_EQ(protoTokenInfo->tokenid().realmnum(), getTestTokenId().mRealmNum); + EXPECT_EQ(protoTokenInfo->tokenid().tokennum(), getTestTokenId().mTokenNum); EXPECT_EQ(protoTokenInfo->name(), getTestTokenName()); EXPECT_EQ(protoTokenInfo->symbol(), getTestTokenSymbol()); EXPECT_EQ(protoTokenInfo->decimals(), getTestDecimals()); diff --git a/sdk/tests/unit/TokenNftTransferTest.cc b/sdk/tests/unit/TokenNftTransferTest.cc index 6e865d941..4eac6dc09 100644 --- a/sdk/tests/unit/TokenNftTransferTest.cc +++ b/sdk/tests/unit/TokenNftTransferTest.cc @@ -40,71 +40,26 @@ class TokenNftTransferTest : public ::testing::Test const bool mIsApproval = true; }; -//----- -TEST_F(TokenNftTransferTest, DefaultConstruction) -{ - TokenNftTransfer tokenNftTransfer; - EXPECT_EQ(tokenNftTransfer.getNftId(), NftId()); - EXPECT_EQ(tokenNftTransfer.getSenderAccountId(), AccountId()); - EXPECT_EQ(tokenNftTransfer.getReceiverAccountId(), AccountId()); - EXPECT_FALSE(tokenNftTransfer.getApproval()); -} - -//----- -TEST_F(TokenNftTransferTest, SetGetNftId) -{ - TokenNftTransfer tokenNftTransfer; - tokenNftTransfer.setNftId(getTestNftId()); - EXPECT_EQ(tokenNftTransfer.getNftId(), getTestNftId()); -} - -//----- -TEST_F(TokenNftTransferTest, SetGetSenderAccountId) -{ - TokenNftTransfer tokenNftTransfer; - tokenNftTransfer.setSenderAccountId(getTestSenderAccountId()); - EXPECT_EQ(tokenNftTransfer.getSenderAccountId(), getTestSenderAccountId()); -} - -//----- -TEST_F(TokenNftTransferTest, SetGetReceiverAccountId) -{ - TokenNftTransfer tokenNftTransfer; - tokenNftTransfer.setReceiverAccountId(getTestReceiverAccountId()); - EXPECT_EQ(tokenNftTransfer.getReceiverAccountId(), getTestReceiverAccountId()); -} - -//----- -TEST_F(TokenNftTransferTest, SetGetApproval) -{ - TokenNftTransfer tokenNftTransfer; - tokenNftTransfer.setApproval(getTestIsApproval()); - EXPECT_EQ(tokenNftTransfer.getApproval(), getTestIsApproval()); -} - //----- TEST_F(TokenNftTransferTest, ProtobufTokenNftTransfer) { - TokenNftTransfer tokenNftTransfer; - tokenNftTransfer.setNftId(getTestNftId()); - tokenNftTransfer.setSenderAccountId(getTestSenderAccountId()); - tokenNftTransfer.setReceiverAccountId(getTestReceiverAccountId()); - tokenNftTransfer.setApproval(getTestIsApproval()); + TokenNftTransfer tokenNftTransfer( + getTestNftId(), getTestSenderAccountId(), getTestReceiverAccountId(), getTestIsApproval()); std::unique_ptr protoNftTransfer = tokenNftTransfer.toProtobuf(); EXPECT_EQ(protoNftTransfer->senderaccountid().accountnum(), getTestSenderAccountId().mAccountNum); EXPECT_EQ(protoNftTransfer->receiveraccountid().accountnum(), getTestReceiverAccountId().mAccountNum); - EXPECT_EQ(protoNftTransfer->serialnumber(), getTestNftId().getSerialNum()); + EXPECT_EQ(protoNftTransfer->serialnumber(), getTestNftId().mSerialNum); EXPECT_EQ(protoNftTransfer->is_approval(), getTestIsApproval()); protoNftTransfer->set_allocated_senderaccountid(getTestReceiverAccountId().toProtobuf().release()); protoNftTransfer->set_allocated_receiveraccountid(getTestSenderAccountId().toProtobuf().release()); - protoNftTransfer->set_serialnumber(static_cast(getTestNftId().getSerialNum()) - 1LL); + protoNftTransfer->set_serialnumber(static_cast(getTestNftId().mSerialNum) - 1LL); protoNftTransfer->set_is_approval(!getTestIsApproval()); - tokenNftTransfer = TokenNftTransfer::fromProtobuf(*protoNftTransfer); - EXPECT_EQ(tokenNftTransfer.getNftId().getSerialNum(), getTestNftId().getSerialNum() - 1ULL); - EXPECT_EQ(tokenNftTransfer.getSenderAccountId(), getTestReceiverAccountId()); - EXPECT_EQ(tokenNftTransfer.getReceiverAccountId(), getTestSenderAccountId()); - EXPECT_EQ(tokenNftTransfer.getApproval(), !getTestIsApproval()); + tokenNftTransfer = TokenNftTransfer::fromProtobuf(*protoNftTransfer, getTestNftId().mTokenId); + EXPECT_EQ(tokenNftTransfer.mNftId.mSerialNum, getTestNftId().mSerialNum - 1ULL); + EXPECT_EQ(tokenNftTransfer.mSenderAccountId, getTestReceiverAccountId()); + EXPECT_EQ(tokenNftTransfer.mReceiverAccountId, getTestSenderAccountId()); + EXPECT_EQ(tokenNftTransfer.mIsApproval, !getTestIsApproval()); } diff --git a/sdk/tests/unit/TokenTransferTest.cc b/sdk/tests/unit/TokenTransferTest.cc index 26d756788..bc66ec27f 100644 --- a/sdk/tests/unit/TokenTransferTest.cc +++ b/sdk/tests/unit/TokenTransferTest.cc @@ -104,15 +104,15 @@ TEST_F(TokenTransferTest, FromProtobuf) tokenTransferList.set_allocated_expected_decimals(decimalPtr.release()); // When - const std::vector tokenTransfers = TokenTransfer::fromProtobuf(tokenTransferList); + const TokenTransfer tokenTransfer = + TokenTransfer::fromProtobuf(*amount, getTestTokenId(), tokenTransferList.expected_decimals().value()); // Then - ASSERT_EQ(tokenTransfers.size(), 1); - EXPECT_EQ(tokenTransfers.at(0).mTokenId, getTestTokenId()); - EXPECT_EQ(tokenTransfers.at(0).mAccountId, getTestAccountId()); - EXPECT_EQ(tokenTransfers.at(0).mAmount, getTestAmount()); - EXPECT_EQ(tokenTransfers.at(0).mExpectedDecimals, getTestExpectedDecimals()); - EXPECT_EQ(tokenTransfers.at(0).mIsApproval, getTestIsApproval()); + EXPECT_EQ(tokenTransfer.mTokenId, getTestTokenId()); + EXPECT_EQ(tokenTransfer.mAccountId, getTestAccountId()); + EXPECT_EQ(tokenTransfer.mAmount, getTestAmount()); + EXPECT_EQ(tokenTransfer.mExpectedDecimals, getTestExpectedDecimals()); + EXPECT_EQ(tokenTransfer.mIsApproval, getTestIsApproval()); } //----- diff --git a/sdk/tests/unit/TransactionRecordTest.cc b/sdk/tests/unit/TransactionRecordTest.cc index 18c70db12..dc3fae904 100644 --- a/sdk/tests/unit/TransactionRecordTest.cc +++ b/sdk/tests/unit/TransactionRecordTest.cc @@ -88,10 +88,10 @@ TEST_F(TransactionRecordTest, FromProtobuf) aa->set_amount(-amount); list = protoTransactionRecord.add_tokentransferlists(); - list->set_allocated_token(nftId.getTokenId().toProtobuf().release()); + list->set_allocated_token(nftId.mTokenId.toProtobuf().release()); proto::NftTransfer* nft = list->add_nfttransfers(); - nft->set_serialnumber(static_cast(nftId.getSerialNum())); + nft->set_serialnumber(static_cast(nftId.mSerialNum)); nft->set_allocated_senderaccountid(accountIdFrom.toProtobuf().release()); nft->set_allocated_receiveraccountid(accountIdTo.toProtobuf().release()); @@ -134,10 +134,10 @@ TEST_F(TransactionRecordTest, FromProtobuf) EXPECT_EQ(txRecord.mContractFunctionResult->mContractCallResult, contractCallResult); ASSERT_EQ(txRecord.mHbarTransferList.size(), 2); - EXPECT_EQ(txRecord.mHbarTransferList.at(0).getAccountId(), accountIdFrom); - EXPECT_EQ(txRecord.mHbarTransferList.at(0).getAmount().toTinybars(), -amount); - EXPECT_EQ(txRecord.mHbarTransferList.at(1).getAccountId(), accountIdTo); - EXPECT_EQ(txRecord.mHbarTransferList.at(1).getAmount().toTinybars(), amount); + EXPECT_EQ(txRecord.mHbarTransferList.at(0).mAccountId, accountIdFrom); + EXPECT_EQ(txRecord.mHbarTransferList.at(0).mAmount.toTinybars(), -amount); + EXPECT_EQ(txRecord.mHbarTransferList.at(1).mAccountId, accountIdTo); + EXPECT_EQ(txRecord.mHbarTransferList.at(1).mAmount.toTinybars(), amount); ASSERT_EQ(txRecord.mTokenTransferList.size(), 2); EXPECT_EQ(txRecord.mTokenTransferList.at(0).mTokenId, tokenId); @@ -148,9 +148,9 @@ TEST_F(TransactionRecordTest, FromProtobuf) EXPECT_EQ(txRecord.mTokenTransferList.at(1).mAmount, -amount); ASSERT_EQ(txRecord.mNftTransferList.size(), 1); - EXPECT_EQ(txRecord.mNftTransferList.at(0).getNftId(), nftId); - EXPECT_EQ(txRecord.mNftTransferList.at(0).getSenderAccountId(), accountIdFrom); - EXPECT_EQ(txRecord.mNftTransferList.at(0).getReceiverAccountId(), accountIdTo); + EXPECT_EQ(txRecord.mNftTransferList.at(0).mNftId, nftId); + EXPECT_EQ(txRecord.mNftTransferList.at(0).mSenderAccountId, accountIdFrom); + EXPECT_EQ(txRecord.mNftTransferList.at(0).mReceiverAccountId, accountIdTo); EXPECT_EQ(txRecord.mScheduleRef, scheduleId); diff --git a/sdk/tests/unit/TransferTransactionTest.cc b/sdk/tests/unit/TransferTransactionTest.cc index 411a058d1..1948b96fc 100644 --- a/sdk/tests/unit/TransferTransactionTest.cc +++ b/sdk/tests/unit/TransferTransactionTest.cc @@ -85,12 +85,12 @@ TEST_F(TransferTransactionTest, ConstructTransferTransactionFromTransactionBodyP amount->set_is_approval(getTestApproval()); list = body->add_tokentransfers(); - list->set_allocated_token(getTestNftId().getTokenId().toProtobuf().release()); + list->set_allocated_token(getTestNftId().mTokenId.toProtobuf().release()); proto::NftTransfer* nft = list->add_nfttransfers(); nft->set_allocated_senderaccountid(getTestAccountId1().toProtobuf().release()); nft->set_allocated_receiveraccountid(getTestAccountId2().toProtobuf().release()); - nft->set_serialnumber(static_cast(getTestNftId().getSerialNum())); + nft->set_serialnumber(static_cast(getTestNftId().mSerialNum)); nft->set_is_approval(getTestApproval()); proto::TransactionBody txBody; @@ -116,12 +116,12 @@ TEST_F(TransferTransactionTest, ConstructTransferTransactionFromTransactionBodyP EXPECT_EQ(tokenTransfers.cbegin()->second.cbegin()->second, getTestAmount().toTinybars()); ASSERT_EQ(nftTransfers.size(), 1); - EXPECT_EQ(nftTransfers.cbegin()->first, getTestNftId().getTokenId()); + EXPECT_EQ(nftTransfers.cbegin()->first, getTestNftId().mTokenId); EXPECT_EQ(nftTransfers.cbegin()->second.size(), 1); - EXPECT_EQ(nftTransfers.cbegin()->second.cbegin()->getNftId(), getTestNftId()); - EXPECT_EQ(nftTransfers.cbegin()->second.cbegin()->getSenderAccountId(), getTestAccountId1()); - EXPECT_EQ(nftTransfers.cbegin()->second.cbegin()->getReceiverAccountId(), getTestAccountId2()); - EXPECT_EQ(nftTransfers.cbegin()->second.cbegin()->getApproval(), getTestApproval()); + EXPECT_EQ(nftTransfers.cbegin()->second.cbegin()->mNftId, getTestNftId()); + EXPECT_EQ(nftTransfers.cbegin()->second.cbegin()->mSenderAccountId, getTestAccountId1()); + EXPECT_EQ(nftTransfers.cbegin()->second.cbegin()->mReceiverAccountId, getTestAccountId2()); + EXPECT_EQ(nftTransfers.cbegin()->second.cbegin()->mIsApproval, getTestApproval()); } //----- @@ -222,12 +222,11 @@ TEST_F(TransferTransactionTest, AddNftTransfer) EXPECT_NO_THROW(transaction.addNftTransfer(getTestNftId(), getTestAccountId1(), getTestAccountId2())); // Then - ASSERT_NO_THROW(transaction.getNftTransfers().empty()); + ASSERT_FALSE(transaction.getNftTransfers().empty()); EXPECT_EQ(transaction.getNftTransfers().cbegin()->first, getTestTokenId()); - EXPECT_EQ(transaction.getNftTransfers().cbegin()->second.cbegin()->getSenderAccountId(), getTestAccountId1()); - EXPECT_EQ(transaction.getNftTransfers().cbegin()->second.cbegin()->getReceiverAccountId(), getTestAccountId2()); - EXPECT_EQ(transaction.getNftTransfers().cbegin()->second.cbegin()->getNftId().getSerialNum(), - getTestNftId().getSerialNum()); + EXPECT_EQ(transaction.getNftTransfers().cbegin()->second.cbegin()->mSenderAccountId, getTestAccountId1()); + EXPECT_EQ(transaction.getNftTransfers().cbegin()->second.cbegin()->mReceiverAccountId, getTestAccountId2()); + EXPECT_EQ(transaction.getNftTransfers().cbegin()->second.cbegin()->mNftId.mSerialNum, getTestNftId().mSerialNum); } //----- From 10d5f2b03759299950bf196e0826f27a0c357102 Mon Sep 17 00:00:00 2001 From: Rob Walworth Date: Mon, 9 Oct 2023 16:08:05 -0500 Subject: [PATCH 2/7] Get tests passing Signed-off-by: Rob Walworth --- sdk/tests/unit/AccountIdTest.cc | 60 ++++++++---------------- sdk/tests/unit/ContractIdTest.cc | 33 ------------- sdk/tests/unit/DelegateContractIdTest.cc | 32 ------------- sdk/tests/unit/FileIdTest.cc | 26 ---------- sdk/tests/unit/NftIdTest.cc | 10 ++-- sdk/tests/unit/TokenIdTest.cc | 22 +++------ sdk/tests/unit/TopicIdUnitTests.cc | 20 -------- 7 files changed, 30 insertions(+), 173 deletions(-) diff --git a/sdk/tests/unit/AccountIdTest.cc b/sdk/tests/unit/AccountIdTest.cc index 4242a0daa..0f16f622d 100644 --- a/sdk/tests/unit/AccountIdTest.cc +++ b/sdk/tests/unit/AccountIdTest.cc @@ -24,7 +24,6 @@ #include "impl/Utilities.h" #include -#include #include using namespace Hedera; @@ -35,7 +34,6 @@ class AccountIdTest : public ::testing::Test [[nodiscard]] inline const uint64_t& getTestShardNum() const { return mShardNum; } [[nodiscard]] inline const uint64_t& getTestRealmNum() const { return mRealmNum; } [[nodiscard]] inline const uint64_t& getTestAccountNum() const { return mAccountNum; } - [[nodiscard]] inline const uint64_t& getTestNumTooBig() const { return mNumTooBig; } [[nodiscard]] inline const std::shared_ptr& getTestEd25519Alias() const { return mEd25519Alias; } [[nodiscard]] inline const std::shared_ptr& getTestEcdsaSecp256k1Alias() const { @@ -47,42 +45,35 @@ class AccountIdTest : public ::testing::Test const uint64_t mShardNum = 8ULL; const uint64_t mRealmNum = 90ULL; const uint64_t mAccountNum = 1000ULL; - const uint64_t mNumTooBig = static_cast(std::numeric_limits::max()) + 1ULL; const std::shared_ptr mEd25519Alias = ED25519PrivateKey::generatePrivateKey()->getPublicKey(); const std::shared_ptr mEcdsaSecp256k1Alias = ECDSAsecp256k1PrivateKey::generatePrivateKey()->getPublicKey(); const EvmAddress mEvmAddressAlias = EvmAddress::fromString("0x0123456789abcdef0123456789abcdef01234567"); }; -//----- -TEST_F(AccountIdTest, DefaultConstructAccountId) -{ - const AccountId accountId; - EXPECT_EQ(accountId.mShardNum, 0ULL); - EXPECT_EQ(accountId.mRealmNum, 0ULL); - EXPECT_FALSE(accountId.mAccountNum.has_value()); - EXPECT_EQ(accountId.mPublicKeyAlias, nullptr); - EXPECT_FALSE(accountId.mEvmAddressAlias.has_value()); -} - //----- TEST_F(AccountIdTest, ConstructWithAccountNum) { + // Given / When const AccountId accountId(getTestAccountNum()); + + // Then EXPECT_EQ(accountId.mShardNum, 0ULL); EXPECT_EQ(accountId.mRealmNum, 0ULL); EXPECT_TRUE(accountId.mAccountNum.has_value()); EXPECT_EQ(*accountId.mAccountNum, getTestAccountNum()); EXPECT_EQ(accountId.mPublicKeyAlias, nullptr); EXPECT_FALSE(accountId.mEvmAddressAlias.has_value()); - - EXPECT_THROW(AccountId{ getTestNumTooBig() }, std::invalid_argument); } //----- TEST_F(AccountIdTest, ConstructWithAccountAlias) { + // Given / When const AccountId ed25519AliasAccountId(getTestEd25519Alias()); + const AccountId ecdsaAliasAccountId(getTestEcdsaSecp256k1Alias()); + + // Then EXPECT_EQ(ed25519AliasAccountId.mShardNum, 0ULL); EXPECT_EQ(ed25519AliasAccountId.mRealmNum, 0ULL); EXPECT_FALSE(ed25519AliasAccountId.mAccountNum.has_value()); @@ -90,7 +81,6 @@ TEST_F(AccountIdTest, ConstructWithAccountAlias) EXPECT_EQ(ed25519AliasAccountId.mPublicKeyAlias->toStringDer(), getTestEd25519Alias()->toStringDer()); EXPECT_FALSE(ed25519AliasAccountId.mEvmAddressAlias.has_value()); - const AccountId ecdsaAliasAccountId(getTestEcdsaSecp256k1Alias()); EXPECT_EQ(ecdsaAliasAccountId.mShardNum, 0ULL); EXPECT_EQ(ecdsaAliasAccountId.mRealmNum, 0ULL); EXPECT_FALSE(ecdsaAliasAccountId.mAccountNum.has_value()); @@ -102,7 +92,10 @@ TEST_F(AccountIdTest, ConstructWithAccountAlias) //----- TEST_F(AccountIdTest, ConstructWithEvmAddress) { + // Given / When const AccountId accountId(getTestEvmAddressAlias()); + + // Then EXPECT_EQ(accountId.mShardNum, 0ULL); EXPECT_EQ(accountId.mRealmNum, 0ULL); EXPECT_FALSE(accountId.mAccountNum.has_value()); @@ -114,23 +107,26 @@ TEST_F(AccountIdTest, ConstructWithEvmAddress) //----- TEST_F(AccountIdTest, ConstructWithShardRealmAccountNum) { + // Given / When const AccountId accountId(getTestShardNum(), getTestRealmNum(), getTestAccountNum()); + + // Then EXPECT_EQ(accountId.mShardNum, getTestShardNum()); EXPECT_EQ(accountId.mRealmNum, getTestRealmNum()); EXPECT_TRUE(accountId.mAccountNum.has_value()); EXPECT_EQ(*accountId.mAccountNum, getTestAccountNum()); EXPECT_EQ(accountId.mPublicKeyAlias, nullptr); EXPECT_FALSE(accountId.mEvmAddressAlias.has_value()); - - EXPECT_THROW((AccountId{ getTestNumTooBig(), getTestRealmNum(), getTestAccountNum() }), std::invalid_argument); - EXPECT_THROW((AccountId{ getTestShardNum(), getTestNumTooBig(), getTestAccountNum() }), std::invalid_argument); - EXPECT_THROW((AccountId{ getTestShardNum(), getTestRealmNum(), getTestNumTooBig() }), std::invalid_argument); } //----- TEST_F(AccountIdTest, ConstructWithShardRealmAccountAlias) { + // Given / When const AccountId ed25519AliasAccountId(getTestShardNum(), getTestRealmNum(), getTestEd25519Alias()); + const AccountId ecdsaAliasAccountId(getTestShardNum(), getTestRealmNum(), getTestEcdsaSecp256k1Alias()); + + // Then EXPECT_EQ(ed25519AliasAccountId.mShardNum, getTestShardNum()); EXPECT_EQ(ed25519AliasAccountId.mRealmNum, getTestRealmNum()); EXPECT_FALSE(ed25519AliasAccountId.mAccountNum.has_value()); @@ -138,36 +134,27 @@ TEST_F(AccountIdTest, ConstructWithShardRealmAccountAlias) EXPECT_EQ(ed25519AliasAccountId.mPublicKeyAlias->toStringDer(), getTestEd25519Alias()->toStringDer()); EXPECT_FALSE(ed25519AliasAccountId.mEvmAddressAlias.has_value()); - EXPECT_THROW((AccountId{ getTestNumTooBig(), getTestRealmNum(), getTestEd25519Alias() }), std::invalid_argument); - EXPECT_THROW((AccountId{ getTestShardNum(), getTestNumTooBig(), getTestEd25519Alias() }), std::invalid_argument); - - const AccountId ecdsaAliasAccountId(getTestShardNum(), getTestRealmNum(), getTestEcdsaSecp256k1Alias()); EXPECT_EQ(ecdsaAliasAccountId.mShardNum, getTestShardNum()); EXPECT_EQ(ecdsaAliasAccountId.mRealmNum, getTestRealmNum()); EXPECT_FALSE(ecdsaAliasAccountId.mAccountNum.has_value()); EXPECT_NE(ecdsaAliasAccountId.mPublicKeyAlias, nullptr); EXPECT_EQ(ecdsaAliasAccountId.mPublicKeyAlias->toStringDer(), getTestEcdsaSecp256k1Alias()->toStringDer()); EXPECT_FALSE(ecdsaAliasAccountId.mEvmAddressAlias.has_value()); - - EXPECT_THROW((AccountId{ getTestNumTooBig(), getTestRealmNum(), getTestEcdsaSecp256k1Alias() }), - std::invalid_argument); - EXPECT_THROW((AccountId{ getTestShardNum(), getTestNumTooBig(), getTestEcdsaSecp256k1Alias() }), - std::invalid_argument); } //----- TEST_F(AccountIdTest, ConstructWithShardRealmEvmAddress) { + // Given / When const AccountId accountId(getTestShardNum(), getTestRealmNum(), getTestEvmAddressAlias()); + + // Then EXPECT_EQ(accountId.mShardNum, getTestShardNum()); EXPECT_EQ(accountId.mRealmNum, getTestRealmNum()); EXPECT_FALSE(accountId.mAccountNum.has_value()); EXPECT_EQ(accountId.mPublicKeyAlias, nullptr); EXPECT_TRUE(accountId.mEvmAddressAlias.has_value()); EXPECT_EQ(accountId.mEvmAddressAlias->toString(), getTestEvmAddressAlias().toString()); - - EXPECT_THROW((AccountId{ getTestNumTooBig(), getTestRealmNum(), getTestAccountNum() }), std::invalid_argument); - EXPECT_THROW((AccountId{ getTestShardNum(), getTestNumTooBig(), getTestAccountNum() }), std::invalid_argument); } //----- @@ -219,7 +206,6 @@ TEST_F(AccountIdTest, ConstructFromString) const std::string testShardNumStr = std::to_string(getTestShardNum()); const std::string testRealmNumStr = std::to_string(getTestRealmNum()); const std::string testAccountNumStr = std::to_string(getTestAccountNum()); - const std::string testNumTooBigStr = std::to_string(getTestNumTooBig()); AccountId accountId; EXPECT_NO_THROW(accountId = AccountId::fromString(testShardNumStr + '.' + testRealmNumStr + '.' + testAccountNumStr)); @@ -261,12 +247,6 @@ TEST_F(AccountIdTest, ConstructFromString) EXPECT_THROW(accountId = AccountId::fromString("abc"), std::invalid_argument); EXPECT_THROW(accountId = AccountId::fromString("o.o.e"), std::invalid_argument); EXPECT_THROW(accountId = AccountId::fromString("0.0.1!"), std::invalid_argument); - EXPECT_THROW(accountId = AccountId::fromString(testNumTooBigStr + '.' + testRealmNumStr + '.' + testAccountNumStr), - std::invalid_argument); - EXPECT_THROW(accountId = AccountId::fromString(testShardNumStr + '.' + testNumTooBigStr + '.' + testAccountNumStr), - std::invalid_argument); - EXPECT_THROW(accountId = AccountId::fromString(testShardNumStr + '.' + testRealmNumStr + '.' + testNumTooBigStr), - std::invalid_argument); const std::string ed25519AliasStr = getTestEd25519Alias()->toStringDer(); EXPECT_NO_THROW(accountId = AccountId::fromString(testShardNumStr + '.' + testRealmNumStr + '.' + ed25519AliasStr)); diff --git a/sdk/tests/unit/ContractIdTest.cc b/sdk/tests/unit/ContractIdTest.cc index 59d206612..f0be3390f 100644 --- a/sdk/tests/unit/ContractIdTest.cc +++ b/sdk/tests/unit/ContractIdTest.cc @@ -21,7 +21,6 @@ #include "impl/Utilities.h" #include -#include #include using namespace Hedera; @@ -32,14 +31,12 @@ class ContractIdTest : public ::testing::Test [[nodiscard]] inline const uint64_t& getTestShardNum() const { return mShardNum; } [[nodiscard]] inline const uint64_t& getTestRealmNum() const { return mRealmNum; } [[nodiscard]] inline const uint64_t& getTestContractNum() const { return mContractNum; } - [[nodiscard]] inline const uint64_t& getTestNumTooBig() const { return mNumTooBig; } [[nodiscard]] inline const EvmAddress& getTestEvmAddress() const { return mEvmAddress; } private: const uint64_t mShardNum = 1ULL; const uint64_t mRealmNum = 2ULL; const uint64_t mContractNum = 3ULL; - const uint64_t mNumTooBig = static_cast(std::numeric_limits::max()) + 1ULL; const EvmAddress mEvmAddress = EvmAddress::fromString("0x0123456789abcdef0123456789abcdef01234567"); }; @@ -56,14 +53,6 @@ TEST_F(ContractIdTest, ConstructWithContractNum) EXPECT_EQ(contractId.mContractNum, getTestContractNum()); EXPECT_FALSE(contractId.mEvmAddress.has_value()); } - -//----- -TEST_F(ContractIdTest, ConstructWithContractNumTooBig) -{ - // Given / When / Then - EXPECT_THROW(const ContractId contractId(getTestNumTooBig()), std::invalid_argument); -} - //----- TEST_F(ContractIdTest, ConstructWithEvmAddress) { @@ -92,18 +81,6 @@ TEST_F(ContractIdTest, ConstructWithShardRealmContractNum) EXPECT_FALSE(contractId.mEvmAddress.has_value()); } -//----- -TEST_F(ContractIdTest, ConstructWithShardRealmContractNumTooBig) -{ - // Given / When / Then - EXPECT_THROW(const ContractId contractId(getTestNumTooBig(), getTestRealmNum(), getTestContractNum()), - std::invalid_argument); - EXPECT_THROW(const ContractId contractId(getTestShardNum(), getTestNumTooBig(), getTestContractNum()), - std::invalid_argument); - EXPECT_THROW(const ContractId contractId(getTestShardNum(), getTestRealmNum(), getTestNumTooBig()), - std::invalid_argument); -} - //----- TEST_F(ContractIdTest, ConstructWithShardRealmEvmAddress) { @@ -118,16 +95,6 @@ TEST_F(ContractIdTest, ConstructWithShardRealmEvmAddress) EXPECT_EQ(contractId.mEvmAddress->toBytes(), getTestEvmAddress().toBytes()); } -//----- -TEST_F(ContractIdTest, ConstructWithShardRealmEvmAddressTooBig) -{ - // Given / When / Then - EXPECT_THROW(const ContractId contractId(getTestNumTooBig(), getTestRealmNum(), getTestEvmAddress()), - std::invalid_argument); - EXPECT_THROW(const ContractId contractId(getTestShardNum(), getTestNumTooBig(), getTestEvmAddress()), - std::invalid_argument); -} - //----- TEST_F(ContractIdTest, CompareContractIds) { diff --git a/sdk/tests/unit/DelegateContractIdTest.cc b/sdk/tests/unit/DelegateContractIdTest.cc index 1e53e2e69..8a395dbf0 100644 --- a/sdk/tests/unit/DelegateContractIdTest.cc +++ b/sdk/tests/unit/DelegateContractIdTest.cc @@ -21,7 +21,6 @@ #include "impl/Utilities.h" #include -#include #include using namespace Hedera; @@ -32,13 +31,11 @@ class DelegateContractIdTest : public ::testing::Test [[nodiscard]] inline const uint64_t& getTestShardNum() const { return mShardNum; } [[nodiscard]] inline const uint64_t& getTestRealmNum() const { return mRealmNum; } [[nodiscard]] inline const uint64_t& getTestContractNum() const { return mContractNum; } - [[nodiscard]] inline const uint64_t& getTestNumTooBig() const { return mNumTooBig; } private: const uint64_t mShardNum = 1ULL; const uint64_t mRealmNum = 2ULL; const uint64_t mContractNum = 3ULL; - const uint64_t mNumTooBig = static_cast(std::numeric_limits::max()) + 1ULL; }; //----- @@ -55,13 +52,6 @@ TEST_F(DelegateContractIdTest, ConstructWithContractNum) EXPECT_FALSE(delegateContractId.mEvmAddress.has_value()); } -//----- -TEST_F(DelegateContractIdTest, ConstructWithContractNumTooBig) -{ - // Given / When / Then - EXPECT_THROW(const DelegateContractId delegateContractId(getTestNumTooBig()), std::invalid_argument); -} - //----- TEST_F(DelegateContractIdTest, ConstructWithShardRealmContractNum) { @@ -76,18 +66,6 @@ TEST_F(DelegateContractIdTest, ConstructWithShardRealmContractNum) EXPECT_FALSE(delegateContractId.mEvmAddress.has_value()); } -//----- -TEST_F(DelegateContractIdTest, ConstructWithShardRealmContractNumTooBig) -{ - // Given / When / Then - EXPECT_THROW(const DelegateContractId delegateContractId(getTestNumTooBig(), getTestRealmNum(), getTestContractNum()), - std::invalid_argument); - EXPECT_THROW(const DelegateContractId delegateContractId(getTestShardNum(), getTestNumTooBig(), getTestContractNum()), - std::invalid_argument); - EXPECT_THROW(const DelegateContractId delegateContractId(getTestShardNum(), getTestRealmNum(), getTestNumTooBig()), - std::invalid_argument); -} - //----- TEST_F(DelegateContractIdTest, CompareDelegateContractIds) { @@ -126,7 +104,6 @@ TEST_F(DelegateContractIdTest, FromMalformedString) const std::string testShardNumStr = std::to_string(getTestShardNum()); const std::string testRealmNumStr = std::to_string(getTestRealmNum()); const std::string testContractNumStr = std::to_string(getTestContractNum()); - const std::string testNumTooBigStr = std::to_string(getTestNumTooBig()); DelegateContractId delegateContractId; // When / Then @@ -176,15 +153,6 @@ TEST_F(DelegateContractIdTest, FromMalformedString) EXPECT_THROW(delegateContractId = DelegateContractId::fromString("abc"), std::invalid_argument); EXPECT_THROW(delegateContractId = DelegateContractId::fromString("o.o.e"), std::invalid_argument); EXPECT_THROW(delegateContractId = DelegateContractId::fromString("0.0.1!"), std::invalid_argument); - EXPECT_THROW(delegateContractId = - DelegateContractId::fromString(testNumTooBigStr + '.' + testRealmNumStr + '.' + testContractNumStr), - std::invalid_argument); - EXPECT_THROW(delegateContractId = - DelegateContractId::fromString(testShardNumStr + '.' + testNumTooBigStr + '.' + testContractNumStr), - std::invalid_argument); - EXPECT_THROW(delegateContractId = - DelegateContractId::fromString(testShardNumStr + '.' + testRealmNumStr + '.' + testNumTooBigStr), - std::invalid_argument); } //----- diff --git a/sdk/tests/unit/FileIdTest.cc b/sdk/tests/unit/FileIdTest.cc index c797f8bf6..7ce0a4052 100644 --- a/sdk/tests/unit/FileIdTest.cc +++ b/sdk/tests/unit/FileIdTest.cc @@ -20,7 +20,6 @@ #include "FileId.h" #include -#include #include #include @@ -32,13 +31,11 @@ class FileIdTest : public ::testing::Test [[nodiscard]] inline const uint64_t& getTestShardNum() const { return mShardNum; } [[nodiscard]] inline const uint64_t& getTestRealmNum() const { return mRealmNum; } [[nodiscard]] inline const uint64_t& getTestFileNum() const { return mFileNum; } - [[nodiscard]] inline const uint64_t& getTestNumTooBig() const { return mNumTooBig; } private: const uint64_t mShardNum = 1ULL; const uint64_t mRealmNum = 20ULL; const uint64_t mFileNum = 300ULL; - const uint64_t mNumTooBig = static_cast(std::numeric_limits::max()) + 1ULL; }; //----- @@ -53,13 +50,6 @@ TEST_F(FileIdTest, ConstructWithFileNum) EXPECT_EQ(fileId.mFileNum, getTestFileNum()); } -//----- -TEST_F(FileIdTest, ConstructWithFileNumTooBig) -{ - // Given / When / Then - EXPECT_THROW(const FileId fileId(getTestNumTooBig()), std::invalid_argument); -} - //----- TEST_F(FileIdTest, ConstructWithShardRealmFileNum) { @@ -72,15 +62,6 @@ TEST_F(FileIdTest, ConstructWithShardRealmFileNum) EXPECT_EQ(fileId.mFileNum, getTestFileNum()); } -//----- -TEST_F(FileIdTest, ConstructWithShardRealmFileNumTooBig) -{ - // Given / When / Then - EXPECT_THROW(const FileId fileId(getTestNumTooBig(), getTestRealmNum(), getTestFileNum()), std::invalid_argument); - EXPECT_THROW(const FileId fileId(getTestShardNum(), getTestNumTooBig(), getTestFileNum()), std::invalid_argument); - EXPECT_THROW(const FileId fileId(getTestShardNum(), getTestRealmNum(), getTestNumTooBig()), std::invalid_argument); -} - //----- TEST_F(FileIdTest, CompareFileIds) { @@ -121,7 +102,6 @@ TEST_F(FileIdTest, FromBadString) const std::string testShardNumStr = std::to_string(getTestShardNum()); const std::string testRealmNumStr = std::to_string(getTestRealmNum()); const std::string testFileNumStr = std::to_string(getTestFileNum()); - const std::string testNumTooBigStr = std::to_string(getTestNumTooBig()); const std::string fileIdStrNoDots = testShardNumStr + testRealmNumStr + testFileNumStr; const std::string fileIdOneDotBefore = '.' + fileIdStrNoDots; @@ -140,9 +120,6 @@ TEST_F(FileIdTest, FromBadString) '.' + testShardNumStr + '.' + testRealmNumStr + '.' + testFileNumStr + '.'; const std::string fileIdRandomAlphaChars = "this is a bad file id"; const std::string fileIdWithDotsAndAlphaChars = "ab.cd.ef"; - const std::string fileIdShardNumTooBig = testNumTooBigStr + '.' + testRealmNumStr + '.' + testFileNumStr; - const std::string fileIdRealmNumTooBig = testShardNumStr + '.' + testNumTooBigStr + '.' + testFileNumStr; - const std::string fileIdFileNumTooBig = testShardNumStr + '.' + testRealmNumStr + '.' + testNumTooBigStr; // When / Then EXPECT_THROW(fileId = FileId::fromString(fileIdStrNoDots), std::invalid_argument); @@ -161,9 +138,6 @@ TEST_F(FileIdTest, FromBadString) EXPECT_THROW(fileId = FileId::fromString(fileIdDotsBetweenAllParts), std::invalid_argument); EXPECT_THROW(fileId = FileId::fromString(fileIdRandomAlphaChars), std::invalid_argument); EXPECT_THROW(fileId = FileId::fromString(fileIdWithDotsAndAlphaChars), std::invalid_argument); - EXPECT_THROW(fileId = FileId::fromString(fileIdShardNumTooBig), std::invalid_argument); - EXPECT_THROW(fileId = FileId::fromString(fileIdRealmNumTooBig), std::invalid_argument); - EXPECT_THROW(fileId = FileId::fromString(fileIdFileNumTooBig), std::invalid_argument); } //----- diff --git a/sdk/tests/unit/NftIdTest.cc b/sdk/tests/unit/NftIdTest.cc index 39cee3426..35e6ed5dd 100644 --- a/sdk/tests/unit/NftIdTest.cc +++ b/sdk/tests/unit/NftIdTest.cc @@ -30,22 +30,21 @@ class NftIdTest : public ::testing::Test protected: [[nodiscard]] inline const TokenId& getTestTokenId() const { return mTokenId; } [[nodiscard]] inline const uint64_t& getTestSerialNum() const { return mSerialNum; } - [[nodiscard]] inline const uint64_t& getTestNumTooBig() const { return mNumTooBig; } private: const TokenId mTokenId = TokenId(10ULL, 200ULL, 3000ULL); const uint64_t mSerialNum = 40000ULL; - const uint64_t mNumTooBig = static_cast(std::numeric_limits::max()) + 1ULL; }; //----- TEST_F(NftIdTest, ConstructWithTokenIdSerialNum) { + // Given / When const NftId nftId(getTestTokenId(), getTestSerialNum()); + + // Then EXPECT_EQ(nftId.mTokenId, getTestTokenId()); EXPECT_EQ(nftId.mSerialNum, getTestSerialNum()); - - EXPECT_THROW(NftId(getTestTokenId(), getTestNumTooBig()), std::invalid_argument); } //----- @@ -58,9 +57,9 @@ TEST_F(NftIdTest, CompareNftIds) //----- TEST_F(NftIdTest, ConstructFromString) { + // Given const std::string testTokenIdStr = getTestTokenId().toString(); const std::string testSerialNumSr = std::to_string(getTestSerialNum()); - const std::string testNumTooBigStr = std::to_string(getTestNumTooBig()); NftId nftId; EXPECT_NO_THROW(nftId = NftId::fromString(testTokenIdStr + '/' + testSerialNumSr)); @@ -78,7 +77,6 @@ TEST_F(NftIdTest, ConstructFromString) EXPECT_THROW(nftId = NftId::fromString(testTokenIdStr + "/abc"), std::invalid_argument); EXPECT_THROW(nftId = NftId::fromString(testTokenIdStr + "/o.o.e"), std::invalid_argument); EXPECT_THROW(nftId = NftId::fromString(testTokenIdStr + "/0001!"), std::invalid_argument); - EXPECT_THROW(nftId = NftId::fromString(testTokenIdStr + '/' + testNumTooBigStr), std::invalid_argument); } //----- diff --git a/sdk/tests/unit/TokenIdTest.cc b/sdk/tests/unit/TokenIdTest.cc index a2155b2c1..11eb170f2 100644 --- a/sdk/tests/unit/TokenIdTest.cc +++ b/sdk/tests/unit/TokenIdTest.cc @@ -20,7 +20,6 @@ #include "TokenId.h" #include -#include #include using namespace Hedera; @@ -31,37 +30,35 @@ class TokenIdTest : public ::testing::Test [[nodiscard]] inline const uint64_t& getTestShardNum() const { return mShardNum; } [[nodiscard]] inline const uint64_t& getTestRealmNum() const { return mRealmNum; } [[nodiscard]] inline const uint64_t& getTestTokenNum() const { return mTokenNum; } - [[nodiscard]] inline const uint64_t& getTestNumTooBig() const { return mNumTooBig; } private: const uint64_t mShardNum = 8ULL; const uint64_t mRealmNum = 90ULL; const uint64_t mTokenNum = 1000ULL; - const uint64_t mNumTooBig = static_cast(std::numeric_limits::max()) + 1ULL; }; //----- TEST_F(TokenIdTest, ConstructWithTokenNum) { + // Given / When const TokenId tokenId(getTestTokenNum()); + + // Then EXPECT_EQ(tokenId.mShardNum, 0ULL); EXPECT_EQ(tokenId.mRealmNum, 0ULL); EXPECT_EQ(tokenId.mTokenNum, getTestTokenNum()); - - EXPECT_THROW(TokenId{ getTestNumTooBig() }, std::invalid_argument); } //----- TEST_F(TokenIdTest, ConstructWithShardRealmTokenNum) { + // Given / When const TokenId tokenId(getTestShardNum(), getTestRealmNum(), getTestTokenNum()); + + // Then EXPECT_EQ(tokenId.mShardNum, getTestShardNum()); EXPECT_EQ(tokenId.mRealmNum, getTestRealmNum()); EXPECT_EQ(tokenId.mTokenNum, getTestTokenNum()); - - EXPECT_THROW((TokenId{ getTestNumTooBig(), getTestRealmNum(), getTestTokenNum() }), std::invalid_argument); - EXPECT_THROW((TokenId{ getTestShardNum(), getTestNumTooBig(), getTestTokenNum() }), std::invalid_argument); - EXPECT_THROW((TokenId{ getTestShardNum(), getTestRealmNum(), getTestNumTooBig() }), std::invalid_argument); } //----- @@ -79,7 +76,6 @@ TEST_F(TokenIdTest, ConstructFromString) const std::string testShardNumStr = std::to_string(getTestShardNum()); const std::string testRealmNumStr = std::to_string(getTestRealmNum()); const std::string testTokenNumStr = std::to_string(getTestTokenNum()); - const std::string testNumTooBigStr = std::to_string(getTestNumTooBig()); TokenId tokenId; EXPECT_NO_THROW(tokenId = TokenId::fromString(testShardNumStr + '.' + testRealmNumStr + '.' + testTokenNumStr)); @@ -120,12 +116,6 @@ TEST_F(TokenIdTest, ConstructFromString) EXPECT_THROW(tokenId = TokenId::fromString("abc"), std::invalid_argument); EXPECT_THROW(tokenId = TokenId::fromString("o.o.e"), std::invalid_argument); EXPECT_THROW(tokenId = TokenId::fromString("0.0.1!"), std::invalid_argument); - EXPECT_THROW(tokenId = TokenId::fromString(testNumTooBigStr + '.' + testRealmNumStr + '.' + testTokenNumStr), - std::invalid_argument); - EXPECT_THROW(tokenId = TokenId::fromString(testShardNumStr + '.' + testNumTooBigStr + '.' + testTokenNumStr), - std::invalid_argument); - EXPECT_THROW(tokenId = TokenId::fromString(testShardNumStr + '.' + testRealmNumStr + '.' + testNumTooBigStr), - std::invalid_argument); } //----- diff --git a/sdk/tests/unit/TopicIdUnitTests.cc b/sdk/tests/unit/TopicIdUnitTests.cc index 67f84c705..0de5aa0e5 100644 --- a/sdk/tests/unit/TopicIdUnitTests.cc +++ b/sdk/tests/unit/TopicIdUnitTests.cc @@ -206,26 +206,6 @@ TEST_F(TopicIdTest, FromBytes) EXPECT_EQ(topicId.mTopicNum, getTestTopicNum()); } -//----- -TEST_F(TopicIdTest, ToSolidityAddress) -{ - // Given - const std::string solidityAddress = "0123456789ABCDEF0123456789ABCDEF01234567"; - const TopicId topicId = TopicId::fromSolidityAddress(solidityAddress); - - TopicId topicIdShardTooBig = topicId; - topicIdShardTooBig.mShardNum = static_cast(std::numeric_limits::max()) + 1ULL; - - // When - std::string newSolidityAddress; - EXPECT_NO_THROW(newSolidityAddress = topicId.toSolidityAddress()); - - EXPECT_THROW(newSolidityAddress = topicIdShardTooBig.toSolidityAddress(), IllegalStateException); - - // Then - EXPECT_EQ(newSolidityAddress, solidityAddress); -} - //----- TEST_F(TopicIdTest, ToProtobuf) { From ded74b3b622b3e48bddb387c48ad57921becc69f Mon Sep 17 00:00:00 2001 From: Rob Walworth Date: Tue, 10 Oct 2023 12:41:43 -0500 Subject: [PATCH 3/7] Add ValidateChecksumExample Signed-off-by: Rob Walworth --- sdk/examples/CMakeLists.txt | 4 + sdk/examples/ValidateChecksumExample.cc | 183 ++++++++++++++++++ ...tityException.h => BadEntityIdException.h} | 18 +- sdk/main/src/impl/EntityIdHelper.cc | 7 +- 4 files changed, 199 insertions(+), 13 deletions(-) create mode 100644 sdk/examples/ValidateChecksumExample.cc rename sdk/main/include/exceptions/{BadEntityException.h => BadEntityIdException.h} (79%) diff --git a/sdk/examples/CMakeLists.txt b/sdk/examples/CMakeLists.txt index aecaca32b..2c61bcb13 100644 --- a/sdk/examples/CMakeLists.txt +++ b/sdk/examples/CMakeLists.txt @@ -28,6 +28,7 @@ set(STAKING_EXAMPLE_NAME ${PROJECT_NAME}-staking-example) set(TRANSFER_CRYPTO_EXAMPLE_NAME ${PROJECT_NAME}-transfer-crypto-example) set(TRANSFER_TOKENS_EXAMPLE_NAME ${PROJECT_NAME}-transfer-tokens-example) set(UPDATE_ACCOUNT_PUBLIC_KEY_EXAMPLE_NAME ${PROJECT_NAME}-update-account-public-key-example) +set(VALIDATE_CHECKSUM_EXAMPLE_NAME ${PROJECT_NAME}-validate-checksum-example) add_executable(${ACCOUNT_ALIAS_EXAMPLE_NAME} AccountAliasExample.cc) add_executable(${ACCOUNT_ALLOWANCE_EXAMPLE_NAME} AccountAllowanceExample.cc) @@ -59,6 +60,7 @@ add_executable(${STAKING_EXAMPLE_NAME} StakingExample.cc) add_executable(${TRANSFER_CRYPTO_EXAMPLE_NAME} TransferCryptoExample.cc) add_executable(${TRANSFER_TOKENS_EXAMPLE_NAME} TransferTokensExample.cc) add_executable(${UPDATE_ACCOUNT_PUBLIC_KEY_EXAMPLE_NAME} UpdateAccountPublicKeyExample.cc) +add_executable(${VALIDATE_CHECKSUM_EXAMPLE_NAME} ValidateChecksumExample.cc) file(COPY ${PROJECT_SOURCE_DIR}/addressbook/mainnet.pb DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_BUILD_TYPE}) @@ -108,6 +110,7 @@ target_link_libraries(${STAKING_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) target_link_libraries(${TRANSFER_CRYPTO_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) target_link_libraries(${TRANSFER_TOKENS_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) target_link_libraries(${UPDATE_ACCOUNT_PUBLIC_KEY_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) +target_link_libraries(${VALIDATE_CHECKSUM_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_BUILD_TYPE} DESTINATION examples FILES_MATCHING PATTERN *) @@ -142,4 +145,5 @@ install(TARGETS ${TRANSFER_CRYPTO_EXAMPLE_NAME} ${TRANSFER_TOKENS_EXAMPLE_NAME} ${UPDATE_ACCOUNT_PUBLIC_KEY_EXAMPLE_NAME} + ${VALIDATE_CHECKSUM_EXAMPLE_NAME} RUNTIME DESTINATION examples) diff --git a/sdk/examples/ValidateChecksumExample.cc b/sdk/examples/ValidateChecksumExample.cc new file mode 100644 index 000000000..459666eb8 --- /dev/null +++ b/sdk/examples/ValidateChecksumExample.cc @@ -0,0 +1,183 @@ +/*- + * + * Hedera C++ SDK + * + * Copyright (C) 2020 - 2023 Hedera Hashgraph, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License") + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#include "AccountBalance.h" +#include "AccountBalanceQuery.h" +#include "AccountId.h" +#include "Client.h" +#include "ED25519PrivateKey.h" +#include "exceptions/BadEntityIdException.h" + +#include +#include +#include + +using namespace Hedera; + +int main(int argc, char** argv) +{ + if (argc < 3) + { + std::cout << "Please input account ID and private key" << std::endl; + return 1; + } + + // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions + // will be paid for by this account and be signed by this key. + Client client = Client::forTestnet(); + const AccountId operatorAccountId = AccountId::fromString(argv[1]); + const std::shared_ptr operatorPrivateKey = ED25519PrivateKey::fromString(argv[2]); + client.setOperator(operatorAccountId, operatorPrivateKey.get()); + + /* + * Entity IDs, such as TokenId and AccountId, can be constructed from strings. For example, the + * AccountId::fromString(inputString) static method will attempt to parse the input string and construct the expected + * AccountId object, and will throw a std::invalid_argument if the string is incorrectly formatted. + * + * From here on, we'll talk about methods on AccountId, but equivalent methods exist on every entity ID type. + * + * fromString() expects the input to look something like this: "1.2.3-asdfg". Here, 1 is the shard, 2 is the realm, 3 + * is the number, and "asdfg" is the checksum. + * + * The checksum can be used to ensure that an entity ID was input correctly. For example, if the string being parsed + * is from a config file, or from user input, it could contain typos. + * + * You can use accountId.getChecksum() to get the checksum of an AccountId object that was constructed using + * fromString(). This will be the checksum from the input string. fromString() will merely parse the string and + * create an AccountId object with the expected shard, realm, num, and checksum values. fromString() will NOT verify + * that the AccountId maps to a valid account on the Hedera network, and it will not verify the checksum. + * + * To verify a checksum, call accountId.validateChecksum(client). If the checksum is invalid, validateChecksum() will + * throw a BadEntityIdException, otherwise it will return normally. + * + * The validity of a checksum depends on the network to which the client is connected (EG mainnet or testnet or + * previewnet). For example, a checksum that is valid for a particular shard/realm/num on mainnet will be INVALID for + * the same shard/realm/num on testnet. + * + * As far as fromString() is concerned, the checksum is optional. If you use fromString() to generate an AccountId + * from a string that does not include a checksum, such as "1.2.3", fromString() will work, but a call to the + * getChecksum() method on the resulting AccountId object will return an empty string. + * + * Generally speaking, AccountId objects can come from three places: + * 1) AccountId::fromString(str) + * 2) AccountId(shard, realm, num) + * 3) From the result of a query + * + * In the first case, the AccountId object will have a checksum (getChecksum() will not return null) if the input + * string included a checksum, and it will not have a checksum if the string did not include a checksum. + * + * In the second and third cases, the AccountId object will not have a checksum. + * + * If you call accountId.validateChecksum(client) and accountId has no checksum to validate, validateChecksum() will + * silently pass, and will not throw an exception. + * + * accountId.toString() will stringify the account ID with no checksum, accountId.toStringWithChecksum(client) will + * stringify the account ID with the correct checksum for that shard/realm/num on the client's network. + */ + std::cout << "Manual checksum validation" << std::endl << "--------------------------" << std::endl; + while (true) + { + try + { + // Get an account ID from user input. + std::string inputId; + std::cout << "Enter an account ID with a checksum: "; + std::cin >> inputId; + + const AccountId accountId = AccountId::fromString(inputId); + + std::cout << "Account ID without checksum: " << accountId.toString() << std::endl; + std::cout << "Account ID with checksum: " << accountId.toStringWithChecksum(client) << std::endl; + + if (accountId.getChecksum().empty()) + { + std::cout << "You must enter a checksum" << std::endl; + continue; + } + else + { + std::cout << "The checksum entered was " << accountId.getChecksum() << std::endl; + } + + // Validate the checksum. + accountId.validateChecksum(client); + + break; + } + catch (const std::invalid_argument& invalidArgument) + { + std::cout << invalidArgument.what() << std::endl; + } + catch (const BadEntityIdException& badEntityIdException) + { + std::cout << badEntityIdException.what() << std::endl; + } + } + + /* + * It is also possible to perform automatic checksum validation. + * + * Automatic checksum validation is disabled by default, but it can be enabled with + * client.setAutoValidateChecksums(true). You can check whether automatic checksum validation is enabled with + * client.isAutoValidateChecksumsEnabled(). + * + * When this feature is enabled, the execute() method of a transaction or query will automatically check the validity + * of checksums on any IDs in the transaction or query. It will throw an BadEntityIdException if an invalid checksum + * is encountered. + */ + client.setAutoValidateChecksums(true); + + std::cout << std::endl + << "Automatic checksum validation" << std::endl + << "-----------------------------" << std::endl; + while (true) + { + try + { + // Get an account ID from user input. + std::string inputId; + std::cout << "Enter an account ID with a checksum: "; + std::cin >> inputId; + + const AccountId accountId = AccountId::fromString(inputId); + + if (accountId.getChecksum().empty()) + { + std::cout << "You must enter a checksum" << std::endl; + continue; + } + + // Get the account's balance. + std::cout << "Balance of account: " + << AccountBalanceQuery().setAccountId(accountId).execute(client).getBalance().toTinybars() << std::endl; + + break; + } + catch (const std::invalid_argument& invalidArgument) + { + std::cout << invalidArgument.what() << std::endl; + } + catch (const BadEntityIdException& badEntityIdException) + { + std::cout << badEntityIdException.what() << std::endl; + } + } + + return 0; +} diff --git a/sdk/main/include/exceptions/BadEntityException.h b/sdk/main/include/exceptions/BadEntityIdException.h similarity index 79% rename from sdk/main/include/exceptions/BadEntityException.h rename to sdk/main/include/exceptions/BadEntityIdException.h index 6527e0d99..7f2fba460 100644 --- a/sdk/main/include/exceptions/BadEntityException.h +++ b/sdk/main/include/exceptions/BadEntityIdException.h @@ -17,8 +17,8 @@ * limitations under the License. * */ -#ifndef HEDERA_SDK_CPP_BAD_ENTITY_EXCEPTION_H_ -#define HEDERA_SDK_CPP_BAD_ENTITY_EXCEPTION_H_ +#ifndef HEDERA_SDK_CPP_BAD_ENTITY_ID_EXCEPTION_H_ +#define HEDERA_SDK_CPP_BAD_ENTITY_ID_EXCEPTION_H_ #include #include @@ -29,7 +29,7 @@ namespace Hedera /** * Exception that is thrown when a key could not be realized from a given input. */ -class BadEntityException : public std::exception +class BadEntityIdException : public std::exception { public: /** @@ -41,11 +41,11 @@ class BadEntityException : public std::exception * @param expectedChecksum The checksum against which the calculated checksum was validated. * @param calculatedChecksum The checksum that was calculated of the input entity. */ - explicit BadEntityException(uint64_t shard, - uint64_t realm, - uint64_t num, - std::string_view expectedChecksum, - std::string_view calculatedChecksum) + explicit BadEntityIdException(uint64_t shard, + uint64_t realm, + uint64_t num, + std::string_view expectedChecksum, + std::string_view calculatedChecksum) : mError(std::string("Expected checksum ") + expectedChecksum.data() + " for entity " + std::to_string(shard) + '.' + std::to_string(realm) + '.' + std::to_string(num) + " does not match its calculated checksum " + calculatedChecksum.data()) @@ -68,4 +68,4 @@ class BadEntityException : public std::exception } // namespace Hedera -#endif // HEDERA_SDK_CPP_BAD_ENTITY_EXCEPTION_H_ +#endif // HEDERA_SDK_CPP_BAD_ENTITY_ID_EXCEPTION_H_ diff --git a/sdk/main/src/impl/EntityIdHelper.cc b/sdk/main/src/impl/EntityIdHelper.cc index 8155af720..efcb2cf86 100644 --- a/sdk/main/src/impl/EntityIdHelper.cc +++ b/sdk/main/src/impl/EntityIdHelper.cc @@ -27,7 +27,7 @@ #include "ScheduleId.h" #include "TokenId.h" #include "TopicId.h" -#include "exceptions/BadEntityException.h" +#include "exceptions/BadEntityIdException.h" #include "exceptions/OpenSSLException.h" #include "exceptions/UninitializedException.h" #include "impl/HexConverter.h" @@ -149,7 +149,7 @@ std::string checksum(std::string_view address, const LedgerId& ledgerId) unsigned int digitArrayWeightedSum = 0U; for (unsigned int i = 0U; i < digitArray.size(); ++i) { - digitArrayWeightedSum = digitArrayWeightedSum * weight + digitArray.at(i); + digitArrayWeightedSum = (digitArrayWeightedSum * weight + digitArray.at(i)) % p3; if (i % 2U == 0U) { evenIndexSum += digitArray.at(i); @@ -162,7 +162,6 @@ std::string checksum(std::string_view address, const LedgerId& ledgerId) evenIndexSum %= 11U; oddIndexSum %= 11U; - digitArrayWeightedSum %= p3; // Step 4: Get the weighted sum of all bytes in the ledger ID bytes, modded by p5. unsigned int ledgerIdWeightedSum = 0U; @@ -280,7 +279,7 @@ void validate(uint64_t shard, uint64_t realm, uint64_t num, const Client& client if (calculatedChecksum != expectedChecksum) { - throw BadEntityException(shard, realm, num, expectedChecksum, calculatedChecksum); + throw BadEntityIdException(shard, realm, num, expectedChecksum, calculatedChecksum); } } From 92e97f6b67d37d0375d1b2aeb48aef01d7d00ab4 Mon Sep 17 00:00:00 2001 From: Rob Walworth Date: Tue, 10 Oct 2023 15:37:38 -0500 Subject: [PATCH 4/7] Get rid of ValuePtr | Replace Key* instances with std::shared_ptr Signed-off-by: Rob Walworth --- sdk/examples/AccountAliasExample.cc | 2 +- sdk/examples/AccountAllowanceExample.cc | 32 ++--- sdk/examples/AccountCreateWithHtsExample.cc | 2 +- ...CreateAccountTransferTransactionExample.cc | 2 +- sdk/examples/ConsensusPubSubChunkedExample.cc | 6 +- sdk/examples/ConsensusPubSubExample.cc | 2 +- sdk/examples/ContractNoncesExample.cc | 8 +- sdk/examples/CreateAccountExample.cc | 8 +- sdk/examples/CreateSimpleContractExample.cc | 8 +- sdk/examples/CreateStatefulContractExample.cc | 6 +- sdk/examples/CustomFeesExample.cc | 22 ++-- sdk/examples/DeleteAccountExample.cc | 8 +- sdk/examples/DeleteFileExample.cc | 4 +- sdk/examples/ExemptCustomFeesExample.cc | 22 ++-- sdk/examples/FileAppendChunkedExample.cc | 4 +- sdk/examples/GetFileContentsExample.cc | 4 +- sdk/examples/NftAddRemoveAllowancesExample.cc | 24 ++-- sdk/examples/ScheduleExample.cc | 14 +- .../ScheduleIdenticalTransactionExample.cc | 19 +-- .../ScheduleMultiSigTransactionExample.cc | 18 +-- ...duleTransactionMultiSigThresholdExample.cc | 20 +-- sdk/examples/ScheduleTransferExample.cc | 10 +- sdk/examples/StakingExample.cc | 4 +- sdk/examples/TransferCryptoExample.cc | 3 +- sdk/examples/TransferTokensExample.cc | 26 ++-- sdk/examples/UpdateAccountPublicKeyExample.cc | 16 +-- sdk/main/include/AccountCreateTransaction.h | 7 +- sdk/main/include/AccountInfo.h | 2 +- sdk/main/include/AccountUpdateTransaction.h | 7 +- sdk/main/include/Client.h | 5 +- sdk/main/include/ContractCreateFlow.h | 13 +- sdk/main/include/ContractCreateTransaction.h | 7 +- sdk/main/include/ContractInfo.h | 3 +- sdk/main/include/ContractUpdateTransaction.h | 7 +- sdk/main/include/FileCreateTransaction.h | 2 +- sdk/main/include/FileUpdateTransaction.h | 2 +- sdk/main/include/Key.h | 9 -- sdk/main/include/KeyList.h | 7 +- sdk/main/include/PrivateKey.h | 11 +- sdk/main/include/PublicKey.h | 17 ++- sdk/main/include/Transaction.h | 15 ++- sdk/main/include/impl/ValuePtr.h | 121 ------------------ sdk/main/src/AccountCreateTransaction.cc | 6 +- sdk/main/src/AccountInfo.cc | 3 +- sdk/main/src/AccountUpdateTransaction.cc | 6 +- sdk/main/src/Client.cc | 8 +- sdk/main/src/ContractCreateFlow.cc | 20 ++- sdk/main/src/ContractCreateTransaction.cc | 6 +- sdk/main/src/ContractInfo.cc | 2 +- sdk/main/src/ContractUpdateTransaction.cc | 6 +- sdk/main/src/ED25519PrivateKey.cc | 1 + sdk/main/src/FileCreateTransaction.cc | 2 +- sdk/main/src/FileUpdateTransaction.cc | 2 +- sdk/main/src/KeyList.cc | 16 +-- sdk/main/src/PrivateKey.cc | 41 +++++- sdk/main/src/PublicKey.cc | 41 +++++- sdk/main/src/Transaction.cc | 59 ++++++--- ...wanceApproveTransactionIntegrationTests.cc | 26 ++-- ...AccountCreateTransactionIntegrationTest.cc | 85 ++++++------ ...AccountDeleteTransactionIntegrationTest.cc | 12 +- .../AccountInfoQueryIntegrationTests.cc | 12 +- .../AccountRecordsQueryIntegrationTests.cc | 8 +- ...AccountUpdateTransactionIntegrationTest.cc | 45 ++++--- sdk/tests/integration/BaseIntegrationTest.cc | 2 +- .../integration/ClientIntegrationTest.cc | 4 +- .../ContractBytecodeQueryIntegrationTests.cc | 4 +- .../ContractCallQueryIntegrationTests.cc | 16 +-- .../ContractCreateFlowIntegrationTest.cc | 21 ++- ...ntractCreateTransactionIntegrationTests.cc | 15 +-- ...ntractDeleteTransactionIntegrationTests.cc | 3 +- ...tractExecuteTransactionIntegrationTests.cc | 13 +- .../ContractInfoQueryIntegrationTests.cc | 6 +- .../ContractNonceInfoIntegrationTest.cc | 4 +- ...ntractUpdateTransactionIntegrationTests.cc | 15 +-- .../FileAppendTransactionIntegrationTests.cc | 4 +- .../FileContentsQueryIntegrationTest.cc | 4 +- .../FileCreateTransactionIntegrationTests.cc | 4 +- .../FileDeleteTransactionIntegrationTests.cc | 2 +- .../FileInfoQueryIntegrationTests.cc | 3 +- .../FileUpdateTransactionIntegrationTests.cc | 12 +- .../FreezeTransactionIntegrationTest.cc | 4 +- ...heduleCreateTransactionIntegrationTests.cc | 37 +++--- ...heduleDeleteTransactionIntegrationTests.cc | 6 +- .../ScheduleInfoQueryIntegrationTests.cc | 4 +- ...ScheduleSignTransactionIntegrationTests.cc | 17 ++- ...SystemDeleteTransactionIntegrationTests.cc | 7 +- ...stemUndeleteTransactionIntegrationTests.cc | 2 +- ...kenAssociateTransactionIntegrationTests.cc | 16 +-- .../TokenBurnTransactionIntegrationTests.cc | 8 +- .../TokenCreateTransactionIntegrationTests.cc | 4 +- .../TokenDeleteTransactionIntegrationTests.cc | 4 +- ...enDissociateTransactionIntegrationTests.cc | 32 ++--- .../TokenFreezeTransactionIntegrationTests.cc | 20 +-- ...okenGrantKycTransactionIntegrationTests.cc | 20 +-- .../TokenInfoQueryIntegrationTests.cc | 4 +- .../TokenPauseTransactionIntegrationTests.cc | 8 +- ...kenRevokeKycTransactionIntegrationTests.cc | 20 +-- ...okenUnfreezeTransactionIntegrationTests.cc | 20 +-- ...TokenUnpauseTransactionIntegrationTests.cc | 6 +- .../TokenWipeTransactionIntegrationTests.cc | 25 ++-- .../TopicUpdateTransactionIntegrationTests.cc | 4 +- .../integration/TransactionIntegrationTest.cc | 2 +- .../TransactionReceiptIntegrationTest.cc | 8 +- .../TransactionReceiptQueryIntegrationTest.cc | 10 +- .../TransactionRecordIntegrationTest.cc | 12 +- .../TransactionRecordQueryIntegrationTest.cc | 10 +- .../TransferTransactionIntegrationTest.cc | 29 ++--- .../unit/AccountCreateTransactionTest.cc | 5 +- .../unit/AccountUpdateTransactionTest.cc | 4 +- sdk/tests/unit/ClientTest.cc | 16 +-- sdk/tests/unit/ContractCreateFlowTest.cc | 4 +- .../unit/ContractCreateTransactionTest.cc | 4 +- .../unit/ContractUpdateTransactionTest.cc | 4 +- sdk/tests/unit/EthereumFlowTest.cc | 2 +- sdk/tests/unit/FileCreateTransactionTest.cc | 18 +-- sdk/tests/unit/FileInfoTest.cc | 6 +- sdk/tests/unit/FileUpdateTransactionTest.cc | 18 +-- sdk/tests/unit/KeyListTest.cc | 26 ++-- sdk/tests/unit/ScheduleInfoUnitTests.cc | 15 +-- sdk/tests/unit/TransferTransactionTest.cc | 2 +- 120 files changed, 724 insertions(+), 807 deletions(-) delete mode 100644 sdk/main/include/impl/ValuePtr.h diff --git a/sdk/examples/AccountAliasExample.cc b/sdk/examples/AccountAliasExample.cc index 107c0b74f..3a9880414 100644 --- a/sdk/examples/AccountAliasExample.cc +++ b/sdk/examples/AccountAliasExample.cc @@ -45,7 +45,7 @@ int main(int argc, char** argv) // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); const AccountId operatorAccountId = AccountId::fromString(argv[1]); - client.setOperator(operatorAccountId, ED25519PrivateKey::fromString(argv[2]).get()); + client.setOperator(operatorAccountId, ED25519PrivateKey::fromString(argv[2])); /* * Hedera supports a form of auto account creation. diff --git a/sdk/examples/AccountAllowanceExample.cc b/sdk/examples/AccountAllowanceExample.cc index f05e6d56a..09561e7ad 100644 --- a/sdk/examples/AccountAllowanceExample.cc +++ b/sdk/examples/AccountAllowanceExample.cc @@ -47,12 +47,12 @@ int main(int argc, char** argv) // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); const AccountId operatorAccountId = AccountId::fromString(argv[1]); - client.setOperator(operatorAccountId, ED25519PrivateKey::fromString(argv[2]).get()); + client.setOperator(operatorAccountId, ED25519PrivateKey::fromString(argv[2])); // Generate ECDSAsecp256k1 key combinations for Alice, Bob, and Charlie. - const std::unique_ptr alicePrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); - const std::unique_ptr bobPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); - const std::unique_ptr charliePrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr alicePrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr bobPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr charliePrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); std::cout << "Generated Alice private key: " << alicePrivateKey->toStringRaw() << std::endl; std::cout << "Generated Bob private key: " << bobPrivateKey->toStringRaw() << std::endl; @@ -65,7 +65,7 @@ int main(int argc, char** argv) // Generate accounts for Alice, Bob, and Charlie, giving each 5 Hbar. const AccountId aliceAccountId = AccountCreateTransaction() - .setKey(alicePublicKey.get()) + .setKey(alicePublicKey) .setInitialBalance(Hbar(5LL)) .execute(client) .getReceipt(client) @@ -75,7 +75,7 @@ int main(int argc, char** argv) << HbarUnit::TINYBAR().getSymbol() << std::endl; const AccountId bobAccountId = AccountCreateTransaction() - .setKey(bobPublicKey.get()) + .setKey(bobPublicKey) .setInitialBalance(Hbar(5LL)) .execute(client) .getReceipt(client) @@ -85,7 +85,7 @@ int main(int argc, char** argv) << HbarUnit::TINYBAR().getSymbol() << std::endl; const AccountId charlieAccountId = AccountCreateTransaction() - .setKey(charliePublicKey.get()) + .setKey(charliePublicKey) .setInitialBalance(Hbar(5LL)) .execute(client) .getReceipt(client) @@ -99,7 +99,7 @@ int main(int argc, char** argv) TransactionReceipt txReceipt = AccountAllowanceApproveTransaction() .approveHbarAllowance(aliceAccountId, bobAccountId, Hbar(2LL)) .freezeWith(&client) - .sign(alicePrivateKey.get()) + .sign(alicePrivateKey) .execute(client) .getReceipt(client); std::cout << "Alice 2 Hbar allowance approval transaction status: " << gStatusToString.at(txReceipt.mStatus) @@ -114,7 +114,7 @@ int main(int argc, char** argv) // The allowance spender must pay the fee for the transaction. .setTransactionId(TransactionId::generate(bobAccountId)) .freezeWith(&client) - .sign(bobPrivateKey.get()) + .sign(bobPrivateKey) .execute(client) .getReceipt(client); std::cout << "Transfer of 1 Hbar from Alice to Charlie, using Bob's allowance: " @@ -131,7 +131,7 @@ int main(int argc, char** argv) .addHbarTransfer(charlieAccountId, Hbar(2LL)) .setTransactionId(TransactionId::generate(bobAccountId)) .freezeWith(&client) - .sign(bobPrivateKey.get()) + .sign(bobPrivateKey) .execute(client) .getReceipt(client); std::cout << "Transfer of 2 Hbar from Alice to Charlie, using Bob's allowance: " @@ -148,7 +148,7 @@ int main(int argc, char** argv) txReceipt = AccountAllowanceApproveTransaction() .approveHbarAllowance(aliceAccountId, bobAccountId, Hbar(3LL)) .freezeWith(&client) - .sign(alicePrivateKey.get()) + .sign(alicePrivateKey) .execute(client) .getReceipt(client); std::cout << "Alice 3 Hbar allowance approval transaction status: " << gStatusToString.at(txReceipt.mStatus) @@ -163,7 +163,7 @@ int main(int argc, char** argv) .addHbarTransfer(charlieAccountId, Hbar(2LL)) .setTransactionId(TransactionId::generate(bobAccountId)) .freezeWith(&client) - .sign(bobPrivateKey.get()) + .sign(bobPrivateKey) .execute(client) .getReceipt(client); std::cout << "Transfer of 2 Hbar from Alice to Charlie, using Bob's allowance: " @@ -185,7 +185,7 @@ int main(int argc, char** argv) txReceipt = AccountAllowanceApproveTransaction() .approveHbarAllowance(aliceAccountId, bobAccountId, Hbar(0LL)) .freezeWith(&client) - .sign(alicePrivateKey.get()) + .sign(alicePrivateKey) .execute(client) .getReceipt(client); std::cout << "Alice allowance deletion for Bob: " << gStatusToString.at(txReceipt.mStatus) << std::endl << std::endl; @@ -195,7 +195,7 @@ int main(int argc, char** argv) .setDeleteAccountId(aliceAccountId) .setTransferAccountId(operatorAccountId) .freezeWith(&client) - .sign(alicePrivateKey.get()) + .sign(alicePrivateKey) .execute(client) .getReceipt(client); std::cout << "Alice account deletion: " << gStatusToString.at(txReceipt.mStatus) << std::endl; @@ -204,7 +204,7 @@ int main(int argc, char** argv) .setDeleteAccountId(bobAccountId) .setTransferAccountId(operatorAccountId) .freezeWith(&client) - .sign(bobPrivateKey.get()) + .sign(bobPrivateKey) .execute(client) .getReceipt(client); std::cout << "Bob account deletion: " << gStatusToString.at(txReceipt.mStatus) << std::endl; @@ -213,7 +213,7 @@ int main(int argc, char** argv) .setDeleteAccountId(charlieAccountId) .setTransferAccountId(operatorAccountId) .freezeWith(&client) - .sign(charliePrivateKey.get()) + .sign(charliePrivateKey) .execute(client) .getReceipt(client); std::cout << "Charlie account deletion: " << gStatusToString.at(txReceipt.mStatus) << std::endl; diff --git a/sdk/examples/AccountCreateWithHtsExample.cc b/sdk/examples/AccountCreateWithHtsExample.cc index cbf66a09b..2236daa5c 100644 --- a/sdk/examples/AccountCreateWithHtsExample.cc +++ b/sdk/examples/AccountCreateWithHtsExample.cc @@ -51,7 +51,7 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(operatorAccountId, operatorPrivateKey.get()); + client.setOperator(operatorAccountId, operatorPrivateKey); // IPFS content identifiers for the NFT metadata const std::vector> CIDs = { diff --git a/sdk/examples/AutoCreateAccountTransferTransactionExample.cc b/sdk/examples/AutoCreateAccountTransferTransactionExample.cc index 9655bc96b..1e460d97c 100644 --- a/sdk/examples/AutoCreateAccountTransferTransactionExample.cc +++ b/sdk/examples/AutoCreateAccountTransferTransactionExample.cc @@ -80,7 +80,7 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(operatorAccountId, operatorPrivateKey.get()); + client.setOperator(operatorAccountId, operatorPrivateKey); /** * Step 1: Create an ECSDA private key. diff --git a/sdk/examples/ConsensusPubSubChunkedExample.cc b/sdk/examples/ConsensusPubSubChunkedExample.cc index bce68dd3c..576b782a9 100644 --- a/sdk/examples/ConsensusPubSubChunkedExample.cc +++ b/sdk/examples/ConsensusPubSubChunkedExample.cc @@ -51,7 +51,7 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(operatorAccountId, operatorPrivateKey.get()); + client.setOperator(operatorAccountId, operatorPrivateKey); // Generate a submit key for the topic. const std::shared_ptr submitKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); @@ -249,7 +249,7 @@ int main(int argc, char** argv) .setMaxChunks(15U) .setMessage(bigContents) .freezeWith(&client) - .sign(operatorPrivateKey.get()); + .sign(operatorPrivateKey); // "Send" the message to be signed again "elsewhere" by the submit key. std::vector txBytes = topicMessageSubmitTransaction.toBytes(); @@ -259,7 +259,7 @@ int main(int argc, char** argv) topicMessageSubmitTransaction = *deserializedTx.getTransaction(); // Sign the message with the submit key. - topicMessageSubmitTransaction.sign(submitKey.get()); + topicMessageSubmitTransaction.sign(submitKey); // Submit the transaction const std::vector txResponses = topicMessageSubmitTransaction.executeAll(client); diff --git a/sdk/examples/ConsensusPubSubExample.cc b/sdk/examples/ConsensusPubSubExample.cc index 37c834aec..161a4b49d 100644 --- a/sdk/examples/ConsensusPubSubExample.cc +++ b/sdk/examples/ConsensusPubSubExample.cc @@ -46,7 +46,7 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2]).get()); + client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2])); const TopicId topicId = TopicCreateTransaction().execute(client).getReceipt(client).mTopicId.value(); diff --git a/sdk/examples/ContractNoncesExample.cc b/sdk/examples/ContractNoncesExample.cc index 24190aae1..96447a79a 100644 --- a/sdk/examples/ContractNoncesExample.cc +++ b/sdk/examples/ContractNoncesExample.cc @@ -54,9 +54,9 @@ int main(int argc, char** argv) // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); const AccountId operatorId = AccountId::fromString(argv[1]); - std::unique_ptr operatorKey = ED25519PrivateKey::fromString(argv[2]); + const std::shared_ptr operatorKey = ED25519PrivateKey::fromString(argv[2]); const std::shared_ptr operatorPublicKey = operatorKey->getPublicKey(); - client.setOperator(operatorId, operatorKey.get()); + client.setOperator(operatorId, operatorKey); // Contract's bytecode as hex const std::string mBytecodeHexWithContractNonceInfo = @@ -69,7 +69,7 @@ int main(int argc, char** argv) // Create the contract's bytecode file TransactionReceipt txReceipt = FileCreateTransaction() - .setKeys({ operatorPublicKey.get() }) + .setKeys({ operatorPublicKey }) .setContents(internal::Utilities::stringToByteVector(mBytecodeHexWithContractNonceInfo)) .setMaxTransactionFee(Hbar(2LL)) .execute(client) @@ -87,7 +87,7 @@ int main(int argc, char** argv) // Create the actual contract TransactionResponse contractCreateTxResponse = ContractCreateTransaction() - .setAdminKey(operatorPublicKey.get()) + .setAdminKey(operatorPublicKey) .setGas(100000ULL) .setBytecodeFileId(newFileId) .setMemo("[e2e::ContractADeploysContractBInConstructor]") diff --git a/sdk/examples/CreateAccountExample.cc b/sdk/examples/CreateAccountExample.cc index 9afb95838..0fdf72d3a 100644 --- a/sdk/examples/CreateAccountExample.cc +++ b/sdk/examples/CreateAccountExample.cc @@ -39,7 +39,7 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2]).get()); + client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2])); // Generate a ED25519 private, public key pair const std::unique_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); @@ -49,10 +49,8 @@ int main(int argc, char** argv) std::cout << "Generated public key: " << publicKey->toStringRaw() << std::endl; // Create a new account with an initial balance of 1000 tinybars. The only required field here is the key. - TransactionResponse txResp = AccountCreateTransaction() - .setKey(publicKey.get()) - .setInitialBalance(Hbar(1000ULL, HbarUnit::TINYBAR())) - .execute(client); + TransactionResponse txResp = + AccountCreateTransaction().setKey(publicKey).setInitialBalance(Hbar(1000ULL, HbarUnit::TINYBAR())).execute(client); // Get the receipt when it becomes available TransactionReceipt txReceipt = txResp.getReceipt(client); diff --git a/sdk/examples/CreateSimpleContractExample.cc b/sdk/examples/CreateSimpleContractExample.cc index ec8da06e0..983c4d4eb 100644 --- a/sdk/examples/CreateSimpleContractExample.cc +++ b/sdk/examples/CreateSimpleContractExample.cc @@ -51,9 +51,9 @@ int main(int argc, char** argv) // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); const AccountId operatorId = AccountId::fromString(argv[1]); - std::unique_ptr operatorKey = ED25519PrivateKey::fromString(argv[2]); + const std::shared_ptr operatorKey = ED25519PrivateKey::fromString(argv[2]); const std::shared_ptr operatorPublicKey = operatorKey->getPublicKey(); - client.setOperator(operatorId, operatorKey.get()); + client.setOperator(operatorId, operatorKey); // Get the contract's bytecode const std::vector byteCode = internal::Utilities::stringToByteVector( @@ -62,7 +62,7 @@ int main(int argc, char** argv) // Create the contract's bytecode file TransactionReceipt txReceipt = FileCreateTransaction() - .setKeys({ operatorPublicKey.get() }) + .setKeys({ operatorPublicKey }) .setContents(byteCode) .setMaxTransactionFee(Hbar(2LL)) .execute(client) @@ -82,7 +82,7 @@ int main(int argc, char** argv) txReceipt = ContractCreateTransaction() .setGas(500000ULL) .setBytecodeFileId(fileId) - .setAdminKey(operatorPublicKey.get()) + .setAdminKey(operatorPublicKey) .setMaxTransactionFee(Hbar(16LL)) .execute(client) .getReceipt(client); diff --git a/sdk/examples/CreateStatefulContractExample.cc b/sdk/examples/CreateStatefulContractExample.cc index 47fea97db..bbe35c108 100644 --- a/sdk/examples/CreateStatefulContractExample.cc +++ b/sdk/examples/CreateStatefulContractExample.cc @@ -52,9 +52,9 @@ int main(int argc, char** argv) // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); const AccountId operatorId = AccountId::fromString(argv[1]); - std::unique_ptr operatorKey = ED25519PrivateKey::fromString(argv[2]); + const std::shared_ptr operatorKey = ED25519PrivateKey::fromString(argv[2]); const std::shared_ptr operatorPublicKey = operatorKey->getPublicKey(); - client.setOperator(operatorId, operatorKey.get()); + client.setOperator(operatorId, operatorKey); // Get the contract's bytecode const std::vector byteCode = internal::Utilities::stringToByteVector( @@ -63,7 +63,7 @@ int main(int argc, char** argv) // Create the contract's bytecode file TransactionReceipt txReceipt = FileCreateTransaction() - .setKeys({ operatorPublicKey.get() }) + .setKeys({ operatorPublicKey }) .setContents(byteCode) .setMaxTransactionFee(Hbar(2LL)) .execute(client) diff --git a/sdk/examples/CustomFeesExample.cc b/sdk/examples/CustomFeesExample.cc index 80f838a27..1c942e67c 100644 --- a/sdk/examples/CustomFeesExample.cc +++ b/sdk/examples/CustomFeesExample.cc @@ -56,13 +56,13 @@ int main(int argc, char** argv) const std::shared_ptr operatorPrivateKey = ED25519PrivateKey::fromString(argv[2]); Client client = Client::forTestnet(); - client.setOperator(operatorAccountId, operatorPrivateKey.get()); + client.setOperator(operatorAccountId, operatorPrivateKey); // Create three accounts, Alice, Bob, and Charlie. Alice will be the treasury for our example token. Fees only apply // in transactions not involving the treasury, so we need two other accounts. const std::shared_ptr aliceKey = ED25519PrivateKey::generatePrivateKey(); const AccountId aliceAccountId = AccountCreateTransaction() - .setKey(aliceKey.get()) + .setKey(aliceKey) .setInitialBalance(Hbar(10LL)) .execute(client) .getReceipt(client) @@ -71,7 +71,7 @@ int main(int argc, char** argv) const std::shared_ptr bobKey = ED25519PrivateKey::generatePrivateKey(); const AccountId bobAccountId = AccountCreateTransaction() - .setKey(bobKey.get()) + .setKey(bobKey) .setInitialBalance(Hbar(10LL)) .execute(client) .getReceipt(client) @@ -80,7 +80,7 @@ int main(int argc, char** argv) const std::shared_ptr charlieKey = ED25519PrivateKey::generatePrivateKey(); const AccountId charlieAccountId = AccountCreateTransaction() - .setKey(charlieKey.get()) + .setKey(charlieKey) .setInitialBalance(Hbar(10LL)) .execute(client) .getReceipt(client) @@ -112,7 +112,7 @@ int main(int argc, char** argv) .setCustomFees(customHbarFeeList) .setInitialSupply(100ULL) .freezeWith(&client) - .sign(aliceKey.get()) + .sign(aliceKey) .execute(client) .getReceipt(client) .mTokenId.value(); @@ -124,7 +124,7 @@ int main(int argc, char** argv) .setAccountId(bobAccountId) .setTokenIds({ tokenId }) .freezeWith(&client) - .sign(bobKey.get()) + .sign(bobKey) .execute(client) .getReceipt(client) .mStatus) @@ -135,7 +135,7 @@ int main(int argc, char** argv) .setAccountId(charlieAccountId) .setTokenIds({ tokenId }) .freezeWith(&client) - .sign(charlieKey.get()) + .sign(charlieKey) .execute(client) .getReceipt(client) .mStatus) @@ -147,7 +147,7 @@ int main(int argc, char** argv) .addTokenTransfer(tokenId, bobAccountId, 100LL) .addTokenTransfer(tokenId, aliceAccountId, -100LL) .freezeWith(&client) - .sign(aliceKey.get()) + .sign(aliceKey) .execute(client) .getReceipt(client) .mStatus) @@ -164,7 +164,7 @@ int main(int argc, char** argv) .addTokenTransfer(tokenId, bobAccountId, -20LL) .addTokenTransfer(tokenId, charlieAccountId, 20LL) .freezeWith(&client) - .sign(bobKey.get()) + .sign(bobKey) .execute(client) .getRecord(client); std::cout << gStatusToString.at(txRecord.mReceipt->mStatus) << std::endl; @@ -211,7 +211,7 @@ int main(int argc, char** argv) .setTokenId(tokenId) .setCustomFees(fractionalFeeList) .freezeWith(&client) - .sign(aliceKey.get()) + .sign(aliceKey) .execute(client) .getReceipt(client) .mStatus) @@ -223,7 +223,7 @@ int main(int argc, char** argv) .addTokenTransfer(tokenId, bobAccountId, -20LL) .addTokenTransfer(tokenId, charlieAccountId, 20LL) .freezeWith(&client) - .sign(bobKey.get()) + .sign(bobKey) .execute(client) .getRecord(client); std::cout << gStatusToString.at(txRecord.mReceipt->mStatus) << std::endl; diff --git a/sdk/examples/DeleteAccountExample.cc b/sdk/examples/DeleteAccountExample.cc index 0d4890a32..9411e4893 100644 --- a/sdk/examples/DeleteAccountExample.cc +++ b/sdk/examples/DeleteAccountExample.cc @@ -42,10 +42,10 @@ int main(int argc, char** argv) // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); const AccountId operatorAccountId = AccountId::fromString(argv[1]); - client.setOperator(operatorAccountId, ED25519PrivateKey::fromString(argv[2]).get()); + client.setOperator(operatorAccountId, ED25519PrivateKey::fromString(argv[2])); // Generate a ED25519 private, public key pair - const std::unique_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); const std::shared_ptr publicKey = privateKey->getPublicKey(); std::cout << "Generated private key: " << privateKey->toStringRaw() << std::endl; @@ -53,7 +53,7 @@ int main(int argc, char** argv) // Create a new account with an initial balance of 2 Hbars. The only required field here is the key. TransactionResponse txResp = - AccountCreateTransaction().setKey(publicKey.get()).setInitialBalance(Hbar(2LL)).execute(client); + AccountCreateTransaction().setKey(publicKey).setInitialBalance(Hbar(2LL)).execute(client); // Get the receipt when it becomes available TransactionReceipt txReceipt = txResp.getReceipt(client); @@ -66,7 +66,7 @@ int main(int argc, char** argv) .setDeleteAccountId(newAccountId) .setTransferAccountId(operatorAccountId) .freezeWith(&client) - .sign(privateKey.get()) + .sign(privateKey) .execute(client) .getReceipt(client); diff --git a/sdk/examples/DeleteFileExample.cc b/sdk/examples/DeleteFileExample.cc index 86be0af4f..75c37e157 100644 --- a/sdk/examples/DeleteFileExample.cc +++ b/sdk/examples/DeleteFileExample.cc @@ -42,11 +42,11 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2]).get()); + client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2])); // Create a new file. const FileId fileId = FileCreateTransaction() - .setKeys({ client.getOperatorPublicKey().get() }) + .setKeys({ client.getOperatorPublicKey() }) .setContents(internal::Utilities::stringToByteVector("Hedera Hashgraph is great!")) .execute(client) .getReceipt(client) diff --git a/sdk/examples/ExemptCustomFeesExample.cc b/sdk/examples/ExemptCustomFeesExample.cc index 47a42241e..3c9fe0da5 100644 --- a/sdk/examples/ExemptCustomFeesExample.cc +++ b/sdk/examples/ExemptCustomFeesExample.cc @@ -58,7 +58,7 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2]).get()); + client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2])); /** * Step 1: Create accounts A, B, and C. @@ -66,9 +66,9 @@ int main(int argc, char** argv) const std::shared_ptr firstAccountPrivateKey = ED25519PrivateKey::generatePrivateKey(); const AccountId firstAccountId = AccountCreateTransaction() .setInitialBalance(Hbar(10LL)) - .setKey(firstAccountPrivateKey.get()) + .setKey(firstAccountPrivateKey) .freezeWith(&client) - .sign(firstAccountPrivateKey.get()) + .sign(firstAccountPrivateKey) .execute(client) .getReceipt(client) .mAccountId.value(); @@ -77,9 +77,9 @@ int main(int argc, char** argv) const std::shared_ptr secondAccountPrivateKey = ED25519PrivateKey::generatePrivateKey(); const AccountId secondAccountId = AccountCreateTransaction() .setInitialBalance(Hbar(10LL)) - .setKey(secondAccountPrivateKey.get()) + .setKey(secondAccountPrivateKey) .freezeWith(&client) - .sign(secondAccountPrivateKey.get()) + .sign(secondAccountPrivateKey) .execute(client) .getReceipt(client) .mAccountId.value(); @@ -88,9 +88,9 @@ int main(int argc, char** argv) const std::shared_ptr thirdAccountPrivateKey = ED25519PrivateKey::generatePrivateKey(); const AccountId thirdAccountId = AccountCreateTransaction() .setInitialBalance(Hbar(10LL)) - .setKey(thirdAccountPrivateKey.get()) + .setKey(thirdAccountPrivateKey) .freezeWith(&client) - .sign(thirdAccountPrivateKey.get()) + .sign(thirdAccountPrivateKey) .execute(client) .getReceipt(client) .mAccountId.value(); @@ -130,9 +130,9 @@ int main(int argc, char** argv) .setDenominator(10LL) .setAllCollectorsAreExempt(true)) }) .freezeWith(&client) - .sign(firstAccountPrivateKey.get()) - .sign(secondAccountPrivateKey.get()) - .sign(thirdAccountPrivateKey.get()) + .sign(firstAccountPrivateKey) + .sign(secondAccountPrivateKey) + .sign(thirdAccountPrivateKey) .execute(client) .getReceipt(client) .mTokenId.value(); @@ -156,7 +156,7 @@ int main(int argc, char** argv) .addTokenTransfer(createdTokenId, secondAccountId, -10000LL) .addTokenTransfer(createdTokenId, firstAccountId, 10000LL) .freezeWith(&client) - .sign(secondAccountPrivateKey.get()) + .sign(secondAccountPrivateKey) .execute(client) .getRecord(client); std::cout << gStatusToString.at(txRecord.mReceipt->mStatus) << std::endl; diff --git a/sdk/examples/FileAppendChunkedExample.cc b/sdk/examples/FileAppendChunkedExample.cc index 79d86081a..4b78f5052 100644 --- a/sdk/examples/FileAppendChunkedExample.cc +++ b/sdk/examples/FileAppendChunkedExample.cc @@ -46,11 +46,11 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2]).get()); + client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2])); // Create a new file. const FileId fileId = FileCreateTransaction() - .setKeys({ client.getOperatorPublicKey().get() }) + .setKeys({ client.getOperatorPublicKey() }) .setContents(internal::Utilities::stringToByteVector("Hedera Hashgraph is great!")) .execute(client) .getReceipt(client) diff --git a/sdk/examples/GetFileContentsExample.cc b/sdk/examples/GetFileContentsExample.cc index 84d1ac619..48b358362 100644 --- a/sdk/examples/GetFileContentsExample.cc +++ b/sdk/examples/GetFileContentsExample.cc @@ -41,14 +41,14 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2]).get()); + client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2])); // Content to be stored in the file const std::vector contents = internal::Utilities::stringToByteVector("Hedera is great!"); // Create a new file with the contents FileId fileId = FileCreateTransaction() - .setKeys({ client.getOperatorPublicKey().get() }) + .setKeys({ client.getOperatorPublicKey() }) .setContents(contents) .execute(client) .getReceipt(client) diff --git a/sdk/examples/NftAddRemoveAllowancesExample.cc b/sdk/examples/NftAddRemoveAllowancesExample.cc index fe5b1184f..e2acf0f1b 100644 --- a/sdk/examples/NftAddRemoveAllowancesExample.cc +++ b/sdk/examples/NftAddRemoveAllowancesExample.cc @@ -68,7 +68,7 @@ int main(int argc, char** argv) const std::shared_ptr operatorPrivateKey = ED25519PrivateKey::fromString(argv[2]); Client client = Client::forTestnet(); - client.setOperator(operatorAccountId, operatorPrivateKey.get()); + client.setOperator(operatorAccountId, operatorPrivateKey); // The CIDs for the NFTs. const std::vector CIDs = { "QmNPCiNA3Dsu3K5FxDPMG5Q3fZRwVTg14EXA92uqEeSRXn", @@ -106,7 +106,7 @@ int main(int argc, char** argv) // Create a spender account to spend the NFTs. const std::shared_ptr spenderKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const AccountId spenderAccountId = AccountCreateTransaction() - .setKey(spenderKey.get()) + .setKey(spenderKey) .setInitialBalance(Hbar(2LL)) .execute(client) .getReceipt(client) @@ -116,7 +116,7 @@ int main(int argc, char** argv) // Create a receiver account to receive the NFTs. const std::shared_ptr receiverKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const AccountId receiverAccountId = AccountCreateTransaction() - .setKey(receiverKey.get()) + .setKey(receiverKey) .setInitialBalance(Hbar(2LL)) .execute(client) .getReceipt(client) @@ -129,7 +129,7 @@ int main(int argc, char** argv) .setAccountId(spenderAccountId) .setTokenIds({ tokenId }) .freezeWith(&client) - .sign(spenderKey.get()) + .sign(spenderKey) .execute(client) .getReceipt(client) .mStatus) @@ -141,7 +141,7 @@ int main(int argc, char** argv) .setAccountId(receiverAccountId) .setTokenIds({ tokenId }) .freezeWith(&client) - .sign(receiverKey.get()) + .sign(receiverKey) .execute(client) .getReceipt(client) .mStatus) @@ -172,7 +172,7 @@ int main(int argc, char** argv) .addApprovedNftTransfer(nft1, operatorAccountId, receiverAccountId) .setTransactionId(TransactionId::generate(spenderAccountId)) .freezeWith(&client) - .sign(spenderKey.get()) + .sign(spenderKey) .execute(client) .getReceipt(client) .mStatus) @@ -194,7 +194,7 @@ int main(int argc, char** argv) .addApprovedNftTransfer(nft2, operatorAccountId, receiverAccountId) .setTransactionId(TransactionId::generate(spenderAccountId)) .freezeWith(&client) - .sign(spenderKey.get()) + .sign(spenderKey) .execute(client) .setValidateStatus(false) .getReceipt(client) @@ -206,7 +206,7 @@ int main(int argc, char** argv) << gStatusToString.at(TransferTransaction() .addNftTransfer(nft1, receiverAccountId, operatorAccountId) .freezeWith(&client) - .sign(receiverKey.get()) + .sign(receiverKey) .execute(client) .getReceipt(client) .mStatus) @@ -229,7 +229,7 @@ int main(int argc, char** argv) // Create a delegate spender account. const std::shared_ptr delegateSpenderKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const AccountId delegateSpenderAccountId = AccountCreateTransaction() - .setKey(delegateSpenderKey.get()) + .setKey(delegateSpenderKey) .setInitialBalance(Hbar(2LL)) .execute(client) .getReceipt(client) @@ -253,7 +253,7 @@ int main(int argc, char** argv) AccountAllowanceApproveTransaction() .approveTokenNftAllowance(nft3, operatorAccountId, delegateSpenderAccountId, spenderAccountId) .freezeWith(&client) - .sign(spenderKey.get()) + .sign(spenderKey) .execute(client) .getReceipt(client) .mStatus) @@ -266,7 +266,7 @@ int main(int argc, char** argv) .addApprovedNftTransfer(nft1, operatorAccountId, receiverAccountId) .setTransactionId(TransactionId::generate(spenderAccountId)) .freezeWith(&client) - .sign(spenderKey.get()) + .sign(spenderKey) .execute(client) .getReceipt(client) .mStatus) @@ -288,7 +288,7 @@ int main(int argc, char** argv) .addApprovedNftTransfer(nft2, operatorAccountId, receiverAccountId) .setTransactionId(TransactionId::generate(spenderAccountId)) .freezeWith(&client) - .sign(spenderKey.get()) + .sign(spenderKey) .execute(client) .setValidateStatus(false) .getReceipt(client) diff --git a/sdk/examples/ScheduleExample.cc b/sdk/examples/ScheduleExample.cc index 869feba2b..7c3e34c1d 100644 --- a/sdk/examples/ScheduleExample.cc +++ b/sdk/examples/ScheduleExample.cc @@ -53,18 +53,18 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(operatorAccountId, operatorPrivateKey.get()); + client.setOperator(operatorAccountId, operatorPrivateKey); std::cout << "Generate two keys for an account.." << std::endl; const std::shared_ptr key1 = ED25519PrivateKey::generatePrivateKey(); const std::shared_ptr key2 = ED25519PrivateKey::generatePrivateKey(); std::cout << "Private keys generated: \n -" << key1->toStringRaw() << "\n -" << key2->toStringRaw() << std::endl; - const KeyList keyList = KeyList::of({ key1.get(), key2.get() }); + const auto keyList = std::make_shared(KeyList::of({ key1, key2 })); std::cout << "Generate account.. " << std::endl; const AccountId accountId = AccountCreateTransaction() - .setKey(&keyList) + .setKey(keyList) .setInitialBalance(Hbar(10LL)) .execute(client) .getReceipt(client) @@ -87,8 +87,8 @@ int main(int argc, char** argv) << gStatusToString.at(ScheduleSignTransaction() .setScheduleId(scheduleId) .freezeWith(&client) - .sign(key1.get()) - .sign(key2.get()) + .sign(key1) + .sign(key2) .execute(client) .getReceipt(client) .mStatus) @@ -104,8 +104,8 @@ int main(int argc, char** argv) .setDeleteAccountId(accountId) .setTransferAccountId(operatorAccountId) .freezeWith(&client) - .sign(key1.get()) - .sign(key2.get()) + .sign(key1) + .sign(key2) .execute(client) .getReceipt(client) .mStatus) diff --git a/sdk/examples/ScheduleIdenticalTransactionExample.cc b/sdk/examples/ScheduleIdenticalTransactionExample.cc index 2e676053f..8c477da26 100644 --- a/sdk/examples/ScheduleIdenticalTransactionExample.cc +++ b/sdk/examples/ScheduleIdenticalTransactionExample.cc @@ -48,7 +48,7 @@ int main(int argc, char** argv) // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); const AccountId operatorAccountId = AccountId::fromString(argv[1]); - client.setOperator(operatorAccountId, ED25519PrivateKey::fromString(argv[2]).get()); + client.setOperator(operatorAccountId, ED25519PrivateKey::fromString(argv[2])); // Create three clients, each having a different account and private key. std::array clients; @@ -63,7 +63,7 @@ int main(int argc, char** argv) std::cout << "Generated private key " << i + 1 << ": " << privateKeys.at(i)->toStringRaw() << std::endl; accountIds[i] = AccountCreateTransaction() - .setKey(privateKeys.at(i).get()) + .setKey(privateKeys.at(i)) .setInitialBalance(Hbar(1LL)) .execute(client) .getReceipt(client) @@ -71,17 +71,18 @@ int main(int argc, char** argv) std::cout << "Generated account " << i + 1 << ": " << accountIds.at(i).toString() << std::endl; clients[i] = Client::forTestnet(); - clients.at(i).setOperator(accountIds.at(i), privateKeys.at(i).get()); + clients.at(i).setOperator(accountIds.at(i), privateKeys.at(i)); std::cout << "Generated client " << i + 1 << std::endl; } // Create another account that will contain all three keys. - const KeyList keyList = KeyList::of({ privateKeys.at(0).get(), privateKeys.at(1).get(), privateKeys.at(2).get() }); + const auto keyList = + std::make_shared(KeyList::of({ privateKeys.at(0), privateKeys.at(1), privateKeys.at(2) })); // Create another sender account. std::cout << "Generate a sender account" << std::endl; const AccountId senderAccountId = AccountCreateTransaction() - .setKey(&keyList) + .setKey(keyList) .setInitialBalance(Hbar(10LL)) .execute(client) .getReceipt(client) @@ -147,7 +148,7 @@ int main(int argc, char** argv) .setDeleteAccountId(accountIds.at(i)) .setTransferAccountId(operatorAccountId) .freezeWith(&client) - .sign(privateKeys.at(i).get()) + .sign(privateKeys.at(i)) .execute(client) .getReceipt(client) .mStatus) @@ -159,9 +160,9 @@ int main(int argc, char** argv) .setDeleteAccountId(senderAccountId) .setTransferAccountId(operatorAccountId) .freezeWith(&client) - .sign(privateKeys.at(0).get()) - .sign(privateKeys.at(1).get()) - .sign(privateKeys.at(2).get()) + .sign(privateKeys.at(0)) + .sign(privateKeys.at(1)) + .sign(privateKeys.at(2)) .execute(client) .getReceipt(client) .mStatus) diff --git a/sdk/examples/ScheduleMultiSigTransactionExample.cc b/sdk/examples/ScheduleMultiSigTransactionExample.cc index a21088a13..35f9607e1 100644 --- a/sdk/examples/ScheduleMultiSigTransactionExample.cc +++ b/sdk/examples/ScheduleMultiSigTransactionExample.cc @@ -49,7 +49,7 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(operatorAccountId, operatorPrivateKey.get()); + client.setOperator(operatorAccountId, operatorPrivateKey); // Create an account with a Keylist of three keys. const std::shared_ptr key1 = ED25519PrivateKey::generatePrivateKey(); @@ -62,12 +62,12 @@ int main(int argc, char** argv) std::cout << "Generated key: " << key3->toStringRaw() << std::endl; // Put the three generated keys in a keylist. - const KeyList keyList = KeyList::of({ key1.get(), key2.get(), key3.get() }); + const auto keyList = std::make_shared(KeyList::of({ key1, key2, key3 })); // Create an account with the three keys. std::cout << "Creating account with generated keys: "; TransactionReceipt txReceipt = - AccountCreateTransaction().setKey(&keyList).setInitialBalance(Hbar(10LL)).execute(client).getReceipt(client); + AccountCreateTransaction().setKey(keyList).setInitialBalance(Hbar(10LL)).execute(client).getReceipt(client); std::cout << gStatusToString.at(txReceipt.mStatus) << std::endl; // Schedule a transfer out of the created account with 2/3 needed signatures. @@ -79,8 +79,8 @@ int main(int argc, char** argv) .setPayerAccountId(operatorAccountId) .setAdminKey(operatorPrivateKey) .freezeWith(&client) - .sign(key1.get()) - .sign(key2.get()) + .sign(key1) + .sign(key2) .execute(client) .getReceipt(client) .mScheduleId.value(); @@ -112,7 +112,7 @@ int main(int argc, char** argv) << gStatusToString.at(ScheduleSignTransaction() .setScheduleId(scheduleId) .freezeWith(&client) - .sign(key3.get()) + .sign(key3) .execute(client) .getReceipt(client) .mStatus) @@ -135,9 +135,9 @@ int main(int argc, char** argv) .setDeleteAccountId(accountId) .setTransferAccountId(operatorAccountId) .freezeWith(&client) - .sign(key1.get()) - .sign(key2.get()) - .sign(key3.get()) + .sign(key1) + .sign(key2) + .sign(key3) .execute(client) .getReceipt(client) .mStatus) diff --git a/sdk/examples/ScheduleTransactionMultiSigThresholdExample.cc b/sdk/examples/ScheduleTransactionMultiSigThresholdExample.cc index 49bfc6b60..da64816e9 100644 --- a/sdk/examples/ScheduleTransactionMultiSigThresholdExample.cc +++ b/sdk/examples/ScheduleTransactionMultiSigThresholdExample.cc @@ -49,7 +49,7 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(operatorAccountId, operatorPrivateKey.get()); + client.setOperator(operatorAccountId, operatorPrivateKey); // Create an account with a Keylist of four keys. std::cout << "Generating key list of four keys with a threshold of three.." << std::endl; @@ -59,13 +59,13 @@ int main(int argc, char** argv) ED25519PrivateKey::generatePrivateKey() }; // Put the four generated keys in a keylist and set the threshold so that only 3 out of 4 keys need to sign. - KeyList keyList = KeyList::of({ keys.at(0).get(), keys.at(1).get(), keys.at(2).get(), keys.at(3).get() }); - keyList.setThreshold(3); + auto keyList = std::make_shared(KeyList::of({ keys.at(0), keys.at(1), keys.at(2), keys.at(3) })); + keyList->setThreshold(3); // Create an account with the four keys. std::cout << "Creating account with generated keys: "; TransactionReceipt txReceipt = - AccountCreateTransaction().setKey(&keyList).setInitialBalance(Hbar(10LL)).execute(client).getReceipt(client); + AccountCreateTransaction().setKey(keyList).setInitialBalance(Hbar(10LL)).execute(client).getReceipt(client); std::cout << gStatusToString.at(txReceipt.mStatus) << std::endl; // Schedule a transfer out of the created account with only one signature. @@ -78,7 +78,7 @@ int main(int argc, char** argv) .setPayerAccountId(operatorAccountId) .setAdminKey(operatorPrivateKey) .freezeWith(&client) - .sign(keys.at(0).get()) + .sign(keys.at(0)) .execute(client) .getReceipt(client) .mScheduleId.value(); @@ -100,7 +100,7 @@ int main(int argc, char** argv) << gStatusToString.at(ScheduleSignTransaction() .setScheduleId(scheduleId) .freezeWith(&client) - .sign(keys.at(i).get()) + .sign(keys.at(i)) .execute(client) .getReceipt(client) .mStatus) @@ -113,10 +113,10 @@ int main(int argc, char** argv) .setDeleteAccountId(accountId) .setTransferAccountId(operatorAccountId) .freezeWith(&client) - .sign(keys.at(0).get()) - .sign(keys.at(1).get()) - .sign(keys.at(2).get()) - .sign(keys.at(3).get()) + .sign(keys.at(0)) + .sign(keys.at(1)) + .sign(keys.at(2)) + .sign(keys.at(3)) .execute(client) .getReceipt(client) .mStatus) diff --git a/sdk/examples/ScheduleTransferExample.cc b/sdk/examples/ScheduleTransferExample.cc index 76a52d83a..c3ec0ae21 100644 --- a/sdk/examples/ScheduleTransferExample.cc +++ b/sdk/examples/ScheduleTransferExample.cc @@ -53,7 +53,7 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(operatorAccountId, operatorPrivateKey.get()); + client.setOperator(operatorAccountId, operatorPrivateKey); // A scheduled transaction is a transaction that has been proposed by an account, but which requires more signatures // before it will actually execute on the Hedera network. @@ -77,11 +77,11 @@ int main(int argc, char** argv) std::cout << "Generate account.. " << std::endl; const std::shared_ptr accountPrivateKey = ED25519PrivateKey::generatePrivateKey(); const AccountId accountId = AccountCreateTransaction() - .setKey(accountPrivateKey.get()) + .setKey(accountPrivateKey) .setInitialBalance(Hbar(10LL)) .setReceiverSignatureRequired(true) .freezeWith(&client) - .sign(accountPrivateKey.get()) + .sign(accountPrivateKey) .execute(client) .getReceipt(client) .mAccountId.value(); @@ -133,7 +133,7 @@ int main(int argc, char** argv) << gStatusToString.at(ScheduleSignTransaction() .setScheduleId(scheduleId) .freezeWith(&client) - .sign(accountPrivateKey.get()) + .sign(accountPrivateKey) .execute(client) .getReceipt(client) .mStatus) @@ -158,7 +158,7 @@ int main(int argc, char** argv) .setDeleteAccountId(accountId) .setTransferAccountId(operatorAccountId) .freezeWith(&client) - .sign(accountPrivateKey.get()) + .sign(accountPrivateKey) .execute(client) .getReceipt(client) .mStatus) diff --git a/sdk/examples/StakingExample.cc b/sdk/examples/StakingExample.cc index 0dacaa885..ed8658a4f 100644 --- a/sdk/examples/StakingExample.cc +++ b/sdk/examples/StakingExample.cc @@ -41,7 +41,7 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2]).get()); + client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2])); // Generate a ED25519 private, public key pair const std::unique_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); @@ -52,7 +52,7 @@ int main(int argc, char** argv) // Create an account and stake to account ID 0.0.3. const AccountId newAccountId = *AccountCreateTransaction() - .setKey(publicKey.get()) + .setKey(publicKey) .setInitialBalance(Hbar(1LL)) .setStakedAccountId(AccountId(3ULL)) .execute(client) diff --git a/sdk/examples/TransferCryptoExample.cc b/sdk/examples/TransferCryptoExample.cc index ec95012fc..abaf926a1 100644 --- a/sdk/examples/TransferCryptoExample.cc +++ b/sdk/examples/TransferCryptoExample.cc @@ -24,7 +24,6 @@ #include "ED25519PrivateKey.h" #include "Hbar.h" #include "TransactionRecord.h" -#include "TransactionRecordQuery.h" #include "TransactionResponse.h" #include "TransferTransaction.h" @@ -44,7 +43,7 @@ int main(int argc, char** argv) // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); const AccountId operatorId = AccountId::fromString(argv[1]); - client.setOperator(operatorId, ED25519PrivateKey::fromString(argv[2]).get()); + client.setOperator(operatorId, ED25519PrivateKey::fromString(argv[2])); const auto recipientId = AccountId(3ULL); const Hbar amount(10000ULL, HbarUnit::TINYBAR()); diff --git a/sdk/examples/TransferTokensExample.cc b/sdk/examples/TransferTokensExample.cc index f4a057899..bc9f3de64 100644 --- a/sdk/examples/TransferTokensExample.cc +++ b/sdk/examples/TransferTokensExample.cc @@ -51,14 +51,14 @@ int main(int argc, char** argv) const std::shared_ptr operatorKey = ED25519PrivateKey::fromString(argv[2]); Client client = Client::forTestnet(); - client.setOperator(operatorAccountId, operatorKey.get()); + client.setOperator(operatorAccountId, operatorKey); // Generate two accounts. - const std::unique_ptr privateKey1 = ED25519PrivateKey::generatePrivateKey(); - const std::unique_ptr privateKey2 = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr privateKey1 = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr privateKey2 = ED25519PrivateKey::generatePrivateKey(); const AccountId accountId1 = AccountCreateTransaction() - .setKey(privateKey1.get()) + .setKey(privateKey1) .setInitialBalance(Hbar(1LL)) .execute(client) .getReceipt(client) @@ -66,7 +66,7 @@ int main(int argc, char** argv) std::cout << "Generated account with account ID " << accountId1.toString() << std::endl; const AccountId accountId2 = AccountCreateTransaction() - .setKey(privateKey2.get()) + .setKey(privateKey2) .setInitialBalance(Hbar(1LL)) .execute(client) .getReceipt(client) @@ -93,7 +93,7 @@ int main(int argc, char** argv) .setAccountId(accountId1) .setTokenIds({ tokenId }) .freezeWith(&client) - .sign(privateKey1.get()) + .sign(privateKey1) .execute(client) .getReceipt(client) .mStatus) @@ -104,7 +104,7 @@ int main(int argc, char** argv) .setAccountId(accountId2) .setTokenIds({ tokenId }) .freezeWith(&client) - .sign(privateKey2.get()) + .sign(privateKey2) .execute(client) .getReceipt(client) .mStatus) @@ -116,7 +116,7 @@ int main(int argc, char** argv) .setAccountId(accountId1) .setTokenId(tokenId) .freezeWith(&client) - .sign(privateKey1.get()) + .sign(privateKey1) .execute(client) .getReceipt(client) .mStatus) @@ -127,7 +127,7 @@ int main(int argc, char** argv) .setAccountId(accountId2) .setTokenId(tokenId) .freezeWith(&client) - .sign(privateKey2.get()) + .sign(privateKey2) .execute(client) .getReceipt(client) .mStatus) @@ -149,7 +149,7 @@ int main(int argc, char** argv) .addTokenTransfer(tokenId, accountId1, -10LL) .addTokenTransfer(tokenId, accountId2, 10LL) .freezeWith(&client) - .sign(privateKey1.get()) + .sign(privateKey1) .execute(client) .getReceipt(client) .mStatus) @@ -161,7 +161,7 @@ int main(int argc, char** argv) .addTokenTransfer(tokenId, accountId1, 10LL) .addTokenTransfer(tokenId, accountId2, -10LL) .freezeWith(&client) - .sign(privateKey2.get()) + .sign(privateKey2) .execute(client) .getReceipt(client) .mStatus) @@ -188,7 +188,7 @@ int main(int argc, char** argv) .setTransferAccountId(operatorAccountId) .setDeleteAccountId(accountId1) .freezeWith(&client) - .sign(privateKey1.get()) + .sign(privateKey1) .execute(client) .getReceipt(client) .mStatus) @@ -198,7 +198,7 @@ int main(int argc, char** argv) .setTransferAccountId(operatorAccountId) .setDeleteAccountId(accountId2) .freezeWith(&client) - .sign(privateKey2.get()) + .sign(privateKey2) .execute(client) .getReceipt(client) .mStatus) diff --git a/sdk/examples/UpdateAccountPublicKeyExample.cc b/sdk/examples/UpdateAccountPublicKeyExample.cc index 0e311a758..8ffe80236 100644 --- a/sdk/examples/UpdateAccountPublicKeyExample.cc +++ b/sdk/examples/UpdateAccountPublicKeyExample.cc @@ -44,17 +44,15 @@ int main(int argc, char** argv) // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions // will be paid for by this account and be signed by this key. Client client = Client::forTestnet(); - client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2]).get()); + client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2])); // Generate an ECDSAsecp256k1 public key to use for the new account const std::shared_ptr privateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const std::shared_ptr publicKey = privateKey->getPublicKey(); // Create a new account with an initial balance of 1000 tinybars. The only required field here is the key. - TransactionResponse txResp = AccountCreateTransaction() - .setKey(publicKey.get()) - .setInitialBalance(Hbar(1000ULL, HbarUnit::TINYBAR())) - .execute(client); + TransactionResponse txResp = + AccountCreateTransaction().setKey(publicKey).setInitialBalance(Hbar(1000ULL, HbarUnit::TINYBAR())).execute(client); // Get the receipt when it becomes available TransactionReceipt txReceipt = txResp.getReceipt(client); @@ -64,17 +62,17 @@ int main(int argc, char** argv) << publicKey->toStringDer() << std::endl; // Generate a new ED25519PrivateKey public key with which to update the account. - const std::unique_ptr newPrivateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr newPrivateKey = ED25519PrivateKey::generatePrivateKey(); const std::shared_ptr newPublicKey = newPrivateKey->getPublicKey(); // Update the account std::cout << "Updating account to use new public key: " << newPublicKey->toStringDer() << std::endl; txResp = AccountUpdateTransaction() .setAccountId(newAccountId) - .setKey(newPublicKey.get()) + .setKey(newPublicKey) .freezeWith(&client) - .sign(privateKey.get()) - .sign(newPrivateKey.get()) + .sign(privateKey) + .sign(newPrivateKey) .execute(client); txReceipt = txResp.getReceipt(client); diff --git a/sdk/main/include/AccountCreateTransaction.h b/sdk/main/include/AccountCreateTransaction.h index 0bdcd61f0..497f641b7 100644 --- a/sdk/main/include/AccountCreateTransaction.h +++ b/sdk/main/include/AccountCreateTransaction.h @@ -26,7 +26,6 @@ #include "Hbar.h" #include "Key.h" #include "Transaction.h" -#include "impl/ValuePtr.h" #include #include @@ -100,7 +99,7 @@ class AccountCreateTransaction : public Transaction * @return A reference to this AccountCreateTransaction object with the newly-set key. * @throws IllegalStateException If this AccountCreateTransaction is frozen. */ - AccountCreateTransaction& setKey(const Key* key); + AccountCreateTransaction& setKey(const std::shared_ptr& key); /** * Set the initial amount to transfer into the new account from the paying account. @@ -197,7 +196,7 @@ class AccountCreateTransaction : public Transaction * * @return A pointer to the key to be used for the new account. Nullptr if the key has not yet been set. */ - [[nodiscard]] inline const Key* getKey() const { return mKey.get(); } + [[nodiscard]] inline std::shared_ptr getKey() const { return mKey; } /** * Get the initial balance to be transferred into the new account upon creation (from the paying account). @@ -307,7 +306,7 @@ class AccountCreateTransaction : public Transaction * The key that must sign each transfer out of the account. If mReceiverSignatureRequired is \c TRUE, then it must * also sign any transfer into the account. */ - ValuePtr mKey; + std::shared_ptr mKey = nullptr; /** * The initial amount to transfer into the new account. diff --git a/sdk/main/include/AccountInfo.h b/sdk/main/include/AccountInfo.h index 877661421..a06c1aca6 100644 --- a/sdk/main/include/AccountInfo.h +++ b/sdk/main/include/AccountInfo.h @@ -79,7 +79,7 @@ class AccountInfo * The key for the account, which must sign in order to transfer out, or to modify the account in any way other than * extending its expiration date. */ - ValuePtr mKey; + std::shared_ptr mKey = nullptr; /** * The current balance of the queried account. diff --git a/sdk/main/include/AccountUpdateTransaction.h b/sdk/main/include/AccountUpdateTransaction.h index db777b51e..15ba06f93 100644 --- a/sdk/main/include/AccountUpdateTransaction.h +++ b/sdk/main/include/AccountUpdateTransaction.h @@ -23,7 +23,6 @@ #include "AccountId.h" #include "PublicKey.h" #include "Transaction.h" -#include "impl/ValuePtr.h" #include #include @@ -84,7 +83,7 @@ class AccountUpdateTransaction : public Transaction * @return A reference to this AccountUpdateTransaction object with the newly-set key. * @throws IllegalStateException If this AccountUpdateTransaction is frozen. */ - AccountUpdateTransaction& setKey(const Key* key); + AccountUpdateTransaction& setKey(const std::shared_ptr& key); /** * Set a new transfer receiver signature policy for the account. @@ -178,7 +177,7 @@ class AccountUpdateTransaction : public Transaction * * @return A pointer to the new public key to be used for the account. Nullptr if the key has not yet been set. */ - [[nodiscard]] inline const Key* getKey() const { return mKey.get(); } + [[nodiscard]] inline std::shared_ptr getKey() const { return mKey; } /** * Get the new Hbar transfer receiver signature policy to be used by the account. @@ -295,7 +294,7 @@ class AccountUpdateTransaction : public Transaction * The new key to use to sign each transfer out of the account. If mReceiverSignatureRequired is \c TRUE, then it must * also sign any transfer into the account. */ - ValuePtr mKey; + std::shared_ptr mKey = nullptr; /** * If \c TRUE, the account will have to sign any transaction being deposited into it (in addition to all withdrawals). diff --git a/sdk/main/include/Client.h b/sdk/main/include/Client.h index bb283a55d..0786447c5 100644 --- a/sdk/main/include/Client.h +++ b/sdk/main/include/Client.h @@ -107,11 +107,10 @@ class Client * key is used to sign all transactions executed by this Client. * * @param accountId The account ID of the operator. - * @param privateKey Pointer to the private key of the operator. This transfers ownership of the pointed-to PrivateKey - * to this Client. + * @param privateKey Pointer to the private key of the operator. * @return A reference to this Client object with the newly-set operator account ID and private key. */ - Client& setOperator(const AccountId& accountId, const PrivateKey* privateKey); + Client& setOperator(const AccountId& accountId, const std::shared_ptr& privateKey); /** * Initiate an orderly close of communications with the network with which this Client was configured to diff --git a/sdk/main/include/ContractCreateFlow.h b/sdk/main/include/ContractCreateFlow.h index b049e9139..4e5474b56 100644 --- a/sdk/main/include/ContractCreateFlow.h +++ b/sdk/main/include/ContractCreateFlow.h @@ -25,7 +25,6 @@ #include "Hbar.h" #include "Key.h" #include "TransactionResponse.h" -#include "impl/ValuePtr.h" #include #include @@ -98,7 +97,7 @@ class ContractCreateFlow * @param key The admin key for the new smart contract instance. * @return A reference to this ContractCreateFlow object with the newly-set admin key. */ - ContractCreateFlow& setAdminKey(const Key* key); + ContractCreateFlow& setAdminKey(const std::shared_ptr& key); /** * Set the amount of gas required to run the constructor of the new smart contract instance. @@ -226,7 +225,7 @@ class ContractCreateFlow * @param key The PrivateKey with which to sign the ContractCreateTransaction. * @return A reference to this ContractCreateFlow object with the newly-set signing PrivateKey. */ - ContractCreateFlow& sign(const PrivateKey* key); + ContractCreateFlow& sign(const std::shared_ptr& key); /** * Set the PublicKey and signer function with which the ContractCreateTransaction will be signed. @@ -260,7 +259,7 @@ class ContractCreateFlow * @return A pointer to the admin key for the new smart contract instance. Return nullptr if the admin key has not yet * been set. */ - [[nodiscard]] inline const Key* getAdminKey() const { return mAdminKey.get(); } + [[nodiscard]] inline std::shared_ptr getAdminKey() const { return mAdminKey; } /** * Get the amount of gas required to run the constructor of the new smart contract instance. @@ -369,7 +368,7 @@ class ContractCreateFlow /** * The admin key for the new smart contract instance. */ - ValuePtr mAdminKey; + std::shared_ptr mAdminKey = nullptr; /** * The amount of gas required to run the constructor of the new smart contract instance. @@ -428,12 +427,12 @@ class ContractCreateFlow /** * The PrivateKey with which to sign the ContractCreateTransaction. */ - ValuePtr mPrivateKey; + std::shared_ptr mPrivateKey = nullptr; /** * The PublicKey associated with the signer function to sign the ContractCreateTransaction. */ - std::shared_ptr mPublicKey; + std::shared_ptr mPublicKey = nullptr; /** * The signer function to use to sign the ContractCreateTransaction. diff --git a/sdk/main/include/ContractCreateTransaction.h b/sdk/main/include/ContractCreateTransaction.h index bd66c7759..f113298fd 100644 --- a/sdk/main/include/ContractCreateTransaction.h +++ b/sdk/main/include/ContractCreateTransaction.h @@ -25,7 +25,6 @@ #include "Hbar.h" #include "Key.h" #include "Transaction.h" -#include "impl/ValuePtr.h" #include #include @@ -147,7 +146,7 @@ class ContractCreateTransaction : public Transaction * @return A reference to this ContractCreateTransaction object with the newly-set admin key. * @throws IllegalStateException If this ContractCreateTransaction is frozen. */ - ContractCreateTransaction& setAdminKey(const Key* key); + ContractCreateTransaction& setAdminKey(const std::shared_ptr& key); /** * Set the amount of gas required to run the constructor of the new smart contract instance. @@ -270,7 +269,7 @@ class ContractCreateTransaction : public Transaction * @return A pointer to the admin key for the new smart contract instance. Return nullptr if the admin key has not yet * been set. */ - [[nodiscard]] inline const Key* getAdminKey() const { return mAdminKey.get(); } + [[nodiscard]] inline std::shared_ptr getAdminKey() const { return mAdminKey; } /** * Get the amount of gas required to run the constructor of the new smart contract instance. @@ -400,7 +399,7 @@ class ContractCreateTransaction : public Transaction /** * The admin key for the new smart contract instance. */ - ValuePtr mAdminKey; + std::shared_ptr mAdminKey = nullptr; /** * The amount of gas required to run the constructor of the new smart contract instance. diff --git a/sdk/main/include/ContractInfo.h b/sdk/main/include/ContractInfo.h index e916f608a..5243f0a6c 100644 --- a/sdk/main/include/ContractInfo.h +++ b/sdk/main/include/ContractInfo.h @@ -26,7 +26,6 @@ #include "Key.h" #include "LedgerId.h" #include "StakingInfo.h" -#include "impl/ValuePtr.h" #include #include @@ -75,7 +74,7 @@ class ContractInfo /** * Pointer to the admin key that can be used to modify the state of the contract. */ - ValuePtr mAdminKey; + std::shared_ptr mAdminKey = nullptr; /** * The expiration time of the queried contract and its account. diff --git a/sdk/main/include/ContractUpdateTransaction.h b/sdk/main/include/ContractUpdateTransaction.h index 0f57fe9e8..8536825fe 100644 --- a/sdk/main/include/ContractUpdateTransaction.h +++ b/sdk/main/include/ContractUpdateTransaction.h @@ -24,7 +24,6 @@ #include "ContractId.h" #include "Key.h" #include "Transaction.h" -#include "impl/ValuePtr.h" #include #include @@ -101,7 +100,7 @@ class ContractUpdateTransaction : public Transaction * @return A reference to this ContractUpdateTransaction object with the newly-set admin key. * @throws IllegalStateException If this ContractUpdateTransaction is frozen. */ - ContractUpdateTransaction& setAdminKey(const Key* adminKey); + ContractUpdateTransaction& setAdminKey(const std::shared_ptr& adminKey); /** * Set a new auto renew period for the contract. @@ -195,7 +194,7 @@ class ContractUpdateTransaction : public Transaction * @return A pointer to the new admin key to be used for the contract. Returns nullptr if the key has not yet been * set. */ - [[nodiscard]] inline const Key* getAdminKey() const { return mAdminKey.get(); } + [[nodiscard]] inline std::shared_ptr getAdminKey() const { return mAdminKey; } /** * Get the new auto renew period for the contract. @@ -310,7 +309,7 @@ class ContractUpdateTransaction : public Transaction /** * The new admin key to be used for the contract. */ - ValuePtr mAdminKey; + std::shared_ptr mAdminKey = nullptr; /** * The new auto renew period for the contract. diff --git a/sdk/main/include/FileCreateTransaction.h b/sdk/main/include/FileCreateTransaction.h index b69ea63ea..4d473fdf2 100644 --- a/sdk/main/include/FileCreateTransaction.h +++ b/sdk/main/include/FileCreateTransaction.h @@ -91,7 +91,7 @@ class FileCreateTransaction : public Transaction * @return A reference to this FileCreateTransaction object with the newly-set keys. * @throws IllegalStateException If this FileCreateTransaction is frozen. */ - FileCreateTransaction& setKeys(const std::vector& keys); + FileCreateTransaction& setKeys(const std::vector>& keys); FileCreateTransaction& setKeys(const KeyList& keys); /** diff --git a/sdk/main/include/FileUpdateTransaction.h b/sdk/main/include/FileUpdateTransaction.h index ca4891e86..fcd22e26f 100644 --- a/sdk/main/include/FileUpdateTransaction.h +++ b/sdk/main/include/FileUpdateTransaction.h @@ -96,7 +96,7 @@ class FileUpdateTransaction : public Transaction * @return A reference to this FileUpdateTransaction object with the newly-set keys. * @throws IllegalStateException If this FileUpdateTransaction is frozen. */ - FileUpdateTransaction& setKeys(const std::vector& keys); + FileUpdateTransaction& setKeys(const std::vector>& keys); FileUpdateTransaction& setKeys(const KeyList& keys); /** diff --git a/sdk/main/include/Key.h b/sdk/main/include/Key.h index 75f836b24..767cc8586 100644 --- a/sdk/main/include/Key.h +++ b/sdk/main/include/Key.h @@ -81,15 +81,6 @@ class Key Key& operator=(Key&&) = default; }; -/** - * Helper struct that handles proper copying of Key classes. - */ -struct KeyCloner -{ - Key* operator()(const Key& key) const { return key.clone().release(); } - Key* operator()(const Key* key) const { return key ? key->clone().release() : nullptr; } -}; - } // namespace Hedera #endif // HEDERA_SDK_CPP_KEY_H_ diff --git a/sdk/main/include/KeyList.h b/sdk/main/include/KeyList.h index 4bb056686..e167836d0 100644 --- a/sdk/main/include/KeyList.h +++ b/sdk/main/include/KeyList.h @@ -21,7 +21,6 @@ #define HEDERA_SDK_CPP_KEYLIST_H_ #include "Key.h" -#include "impl/ValuePtr.h" #include #include @@ -63,7 +62,7 @@ class KeyList : public Key * @param keys The list of Keys to add to this KeyList. * @return The created KeyList object. */ - [[nodiscard]] static KeyList of(const std::vector& keys); + [[nodiscard]] static KeyList of(const std::vector>& keys); /** * Construct a Keylist object with a threshold. @@ -137,7 +136,7 @@ class KeyList : public Key * * @param key The key to add to this KeyList. */ - void push_back(const Key* key); + void push_back(const std::shared_ptr& key); /** * Remove a key from this KeyList. Does nothing if the input key is not a part of this KeyList. @@ -155,7 +154,7 @@ class KeyList : public Key /** * The list of Keys that all must sign transactions. */ - std::vector> mKeys; + std::vector> mKeys; /** * The threshold number of keys that must sign a transaction. -1 means all keys must sign. diff --git a/sdk/main/include/PrivateKey.h b/sdk/main/include/PrivateKey.h index 0e73cb810..2fe0ce68b 100644 --- a/sdk/main/include/PrivateKey.h +++ b/sdk/main/include/PrivateKey.h @@ -21,7 +21,6 @@ #define HEDERA_SDK_CPP_PRIVATE_KEY_H_ #include "Key.h" -#include "impl/ValuePtr.h" #include #include @@ -118,10 +117,10 @@ class PrivateKey : public Key /** * Prevent public copying and moving to prevent slicing. Use the 'clone()' virtual method instead. */ - PrivateKey(const PrivateKey&) = default; - PrivateKey& operator=(const PrivateKey&) = default; - PrivateKey(PrivateKey&&) noexcept = default; - PrivateKey& operator=(PrivateKey&&) noexcept = default; + PrivateKey(const PrivateKey&); + PrivateKey& operator=(const PrivateKey&); + PrivateKey(PrivateKey&&) noexcept; + PrivateKey& operator=(PrivateKey&&) noexcept; /** * Construct from a wrapped OpenSSL key object and optionally a chain code. @@ -146,7 +145,7 @@ class PrivateKey : public Key * Implementation object used to hide implementation details and internal headers. */ struct PrivateKeyImpl; - ValuePtr mImpl; + std::unique_ptr mImpl; }; } // namespace Hedera diff --git a/sdk/main/include/PublicKey.h b/sdk/main/include/PublicKey.h index 294980d92..be3bb689a 100644 --- a/sdk/main/include/PublicKey.h +++ b/sdk/main/include/PublicKey.h @@ -21,7 +21,6 @@ #define HEDERA_SDK_CPP_PUBLIC_KEY_H_ #include "Key.h" -#include "impl/ValuePtr.h" #include #include @@ -34,13 +33,13 @@ class Key; class SignaturePair; } -namespace Hedera::internal::OpenSSLUtils +namespace Hedera +{ +namespace internal::OpenSSLUtils { class EVP_PKEY; } -namespace Hedera -{ class AccountId; } @@ -158,10 +157,10 @@ class PublicKey /** * Prevent public copying and moving to prevent slicing. Use the 'clone()' virtual method instead. */ - PublicKey(const PublicKey&) = default; - PublicKey& operator=(const PublicKey&) = default; - PublicKey(PublicKey&&) noexcept = default; - PublicKey& operator=(PublicKey&&) noexcept = default; + PublicKey(const PublicKey&); + PublicKey& operator=(const PublicKey&); + PublicKey(PublicKey&&) noexcept; + PublicKey& operator=(PublicKey&&) noexcept; /** * Construct with a wrapped OpenSSL key object. @@ -189,7 +188,7 @@ class PublicKey * Implementation object used to hide implementation details and internal headers. */ struct PublicKeyImpl; - ValuePtr mImpl; + std::unique_ptr mImpl; }; } // namespace Hedera diff --git a/sdk/main/include/Transaction.h b/sdk/main/include/Transaction.h index 09c187598..dc65738e1 100644 --- a/sdk/main/include/Transaction.h +++ b/sdk/main/include/Transaction.h @@ -112,7 +112,7 @@ class Transaction * @return A reference to this derived Transaction object with the signature. * @throws IllegalStateException If this Transaction object is not frozen. */ - SdkRequestType& sign(const PrivateKey* key); + SdkRequestType& sign(const std::shared_ptr& key); /** * Sign this Transaction with a given PublicKey and a signing callback. Signing a Transaction with a key that has @@ -504,6 +504,19 @@ class Transaction */ [[nodiscard]] bool keyAlreadySigned(const std::shared_ptr& publicKey) const; + /** + * Add a PublicKey and a signer function to this Transaction, and optionally the PrivateKey from which the signer + * function was generated. + * + * @param publicKey The PublicKey to add. + * @param signer The singer function to add. + * @param privateKey The PrivateKey to add. + * @return A reference to this derived Transaction object with the newly-set "signature(s)". + */ + SdkRequestType& signInternal(const std::shared_ptr& publicKey, + const std::function(const std::vector&)>& signer, + const std::shared_ptr& privateKey = nullptr); + /** * Implementation object used to hide implementation details and internal headers. */ diff --git a/sdk/main/include/impl/ValuePtr.h b/sdk/main/include/impl/ValuePtr.h deleted file mode 100644 index 2d7036a0e..000000000 --- a/sdk/main/include/impl/ValuePtr.h +++ /dev/null @@ -1,121 +0,0 @@ -/*- - * - * Hedera C++ SDK - * - * Copyright (C) 2020 - 2023 Hedera Hashgraph, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License") - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -#ifndef HEDERA_SDK_CPP_VALUE_PTR_H_ -#define HEDERA_SDK_CPP_VALUE_PTR_H_ - -#include - -namespace Hedera -{ -template -struct DefaultCloner; -} - -namespace Hedera -{ -/** - * Helper class used to give value semantics to pointers (notably abstract base classes). - * - * @tparam T The type of value. - * @tparam Cloner The cloner function type. - * @tparam Deleter The deleter function type. - */ -template, class Deleter = std::default_delete> -class ValuePtr -{ -public: - ValuePtr() = default; - ~ValuePtr() = default; - - ValuePtr(const ValuePtr& other) - : mPtr(other.mCloner(other.mPtr.get()), other.mPtr.get_deleter()) - , mCloner(other.mCloner) - { - } - - ValuePtr& operator=(const ValuePtr& other) - { - if (this != &other) - { - mPtr = { other.mCloner(other.mPtr.get()), other.mPtr.get_deleter() }; - mCloner = other.mCloner; - } - - return *this; - } - - ValuePtr(ValuePtr&&) noexcept = default; - ValuePtr& operator=(ValuePtr&&) noexcept = default; - - explicit ValuePtr(const T& val) - : mPtr(Cloner()(val), Deleter()) - { - } - - explicit ValuePtr(T&& val) - : mPtr(Cloner()(std::move(val)), Deleter()) - { - } - - explicit ValuePtr(T* val) - : mPtr(val, Deleter()) - { - } - - T* release() { return mPtr.release(); } - - T* get() noexcept { return mPtr.get(); } - Cloner& getCloner() noexcept { return mCloner; } - Deleter& getDeleter() noexcept { return mPtr.get_deleter(); } - T& operator*() { return *mPtr.get(); } - T* operator->() { return mPtr.get(); } - - const T* get() const noexcept { return mPtr.get(); } - const Cloner& getCloner() const noexcept { return mCloner; }; - const Deleter& getDeleter() const noexcept { return mPtr.get_deleter(); } - const T& operator*() const { return *mPtr.get(); } - const T* operator->() const { return mPtr.get(); } - - [[nodiscard]] explicit operator bool() const noexcept { return mPtr != nullptr; } - -private: - /** - * Underlying std::unique_ptr that contains the value. - */ - std::unique_ptr mPtr = { nullptr, Deleter() }; - - /** - * The cloner function to use to clone this ValuePtr. - */ - Cloner mCloner; -}; - -template -struct DefaultCloner -{ - DefaultCloner() = default; - T* operator()(const T& val) const { return new T(val); } - T* operator()(T&& val) const { return new T(std::move(val)); } - T* operator()(const T* val) const { return new T(*val); } -}; - -} // namespace Hedera - -#endif // HEDERA_SDK_CPP_VALUE_PTR_H_ diff --git a/sdk/main/src/AccountCreateTransaction.cc b/sdk/main/src/AccountCreateTransaction.cc index b830115d0..17317a9c1 100644 --- a/sdk/main/src/AccountCreateTransaction.cc +++ b/sdk/main/src/AccountCreateTransaction.cc @@ -56,11 +56,11 @@ AccountCreateTransaction::AccountCreateTransaction( } //----- -AccountCreateTransaction& AccountCreateTransaction::setKey(const Key* key) +AccountCreateTransaction& AccountCreateTransaction::setKey(const std::shared_ptr& key) { requireNotFrozen(); - mKey = ValuePtr(key->clone().release()); + mKey = key; return *this; } @@ -187,7 +187,7 @@ void AccountCreateTransaction::initFromSourceTransactionBody() if (body.has_key()) { - mKey = ValuePtr(Key::fromProtobuf(body.key()).release()); + mKey = Key::fromProtobuf(body.key()); } mInitialBalance = Hbar(static_cast(body.initialbalance()), HbarUnit::TINYBAR()); diff --git a/sdk/main/src/AccountInfo.cc b/sdk/main/src/AccountInfo.cc index c9cebd615..94aea8f60 100644 --- a/sdk/main/src/AccountInfo.cc +++ b/sdk/main/src/AccountInfo.cc @@ -18,7 +18,6 @@ * */ #include "AccountInfo.h" -#include "exceptions/BadKeyException.h" #include "impl/DurationConverter.h" #include "impl/TimestampConverter.h" #include "impl/Utilities.h" @@ -43,7 +42,7 @@ AccountInfo AccountInfo::fromProtobuf(const proto::CryptoGetInfoResponse_Account if (proto.has_key()) { - accountInfo.mKey = ValuePtr(Key::fromProtobuf(proto.key()).release()); + accountInfo.mKey = Key::fromProtobuf(proto.key()); } accountInfo.mBalance = Hbar(static_cast(proto.balance()), HbarUnit::TINYBAR()); diff --git a/sdk/main/src/AccountUpdateTransaction.cc b/sdk/main/src/AccountUpdateTransaction.cc index 3bc7717ec..264461b0e 100644 --- a/sdk/main/src/AccountUpdateTransaction.cc +++ b/sdk/main/src/AccountUpdateTransaction.cc @@ -53,11 +53,11 @@ AccountUpdateTransaction& AccountUpdateTransaction::setAccountId(const AccountId } //----- -AccountUpdateTransaction& AccountUpdateTransaction::setKey(const Key* key) +AccountUpdateTransaction& AccountUpdateTransaction::setKey(const std::shared_ptr& key) { requireNotFrozen(); - mKey = ValuePtr(key->clone().release()); + mKey = key; return *this; } @@ -181,7 +181,7 @@ void AccountUpdateTransaction::initFromSourceTransactionBody() if (body.has_key()) { - mKey = ValuePtr(Key::fromProtobuf(body.key()).release()); + mKey = Key::fromProtobuf(body.key()); } if (body.has_receiversigrequiredwrapper()) diff --git a/sdk/main/src/Client.cc b/sdk/main/src/Client.cc index 9639c0748..4f86ac870 100644 --- a/sdk/main/src/Client.cc +++ b/sdk/main/src/Client.cc @@ -29,7 +29,6 @@ #include "impl/MirrorNetwork.h" #include "impl/Network.h" #include "impl/TLSBehavior.h" -#include "impl/ValuePtr.h" #include #include @@ -53,7 +52,7 @@ struct Client::ClientImpl std::optional mOperatorAccountId; // Pointer to the private key this Client should use to sign transactions. - ValuePtr mOperatorPrivateKey; + std::shared_ptr mOperatorPrivateKey = nullptr; // The maximum fee this Client is willing to pay for transactions. std::optional mMaxTransactionFee; @@ -185,11 +184,10 @@ Client& Client::setMirrorNetwork(const std::vector& network) } //----- -Client& Client::setOperator(const AccountId& accountId, const PrivateKey* privateKey) +Client& Client::setOperator(const AccountId& accountId, const std::shared_ptr& privateKey) { mImpl->mOperatorAccountId = accountId; - mImpl->mOperatorPrivateKey = - ValuePtr(dynamic_cast(privateKey->clone().release())); + mImpl->mOperatorPrivateKey = privateKey; return *this; } diff --git a/sdk/main/src/ContractCreateFlow.cc b/sdk/main/src/ContractCreateFlow.cc index db94e1e1e..25aef0c38 100644 --- a/sdk/main/src/ContractCreateFlow.cc +++ b/sdk/main/src/ContractCreateFlow.cc @@ -30,8 +30,6 @@ #include "exceptions/UninitializedException.h" #include "impl/Utilities.h" -#include - namespace Hedera { //----- @@ -53,7 +51,7 @@ TransactionResponse ContractCreateFlow::execute(const Client& client, const std: // Create the file. FileCreateTransaction fileCreateTransaction = - FileCreateTransaction().setKeys({ client.getOperatorPublicKey().get() }).setContents(mBytecode); + FileCreateTransaction().setKeys({ client.getOperatorPublicKey() }).setContents(mBytecode); if (!mNodeAccountIds.empty()) { @@ -89,7 +87,7 @@ TransactionResponse ContractCreateFlow::execute(const Client& client, const std: if (mAdminKey) { - contractCreateTransaction.setAdminKey(mAdminKey.get()); + contractCreateTransaction.setAdminKey(mAdminKey); } if (mAutoRenewAccountId.has_value()) @@ -123,7 +121,7 @@ TransactionResponse ContractCreateFlow::execute(const Client& client, const std: if (mPrivateKey) { - contractCreateTransaction.sign(mPrivateKey.get()); + contractCreateTransaction.sign(mPrivateKey); } else if (mPublicKey && mSigner.has_value()) { @@ -157,9 +155,9 @@ ContractCreateFlow& ContractCreateFlow::setBytecode(std::string_view byteCode) } //----- -ContractCreateFlow& ContractCreateFlow::setAdminKey(const Key* key) +ContractCreateFlow& ContractCreateFlow::setAdminKey(const std::shared_ptr& key) { - mAdminKey = ValuePtr(key->clone().release()); + mAdminKey = key; return *this; } @@ -264,9 +262,9 @@ ContractCreateFlow& ContractCreateFlow::freezeWith(const Client& client) } //----- -ContractCreateFlow& ContractCreateFlow::sign(const PrivateKey* key) +ContractCreateFlow& ContractCreateFlow::sign(const std::shared_ptr& key) { - mPrivateKey = ValuePtr(dynamic_cast(key->clone().release())); + mPrivateKey = key; mPublicKey = nullptr; mSigner.reset(); return *this; @@ -277,7 +275,7 @@ ContractCreateFlow& ContractCreateFlow::signWith( const std::shared_ptr& key, const std::function(const std::vector&)>& signer) { - mPrivateKey = ValuePtr(); + mPrivateKey = nullptr; mPublicKey = key; mSigner = signer; return *this; @@ -291,7 +289,7 @@ ContractCreateFlow& ContractCreateFlow::signWithOperator(const Client& client) throw UninitializedException("Client operator has not yet been set"); } - mPrivateKey = ValuePtr(); + mPrivateKey = nullptr; mPublicKey = client.getOperatorPublicKey(); mSigner = client.getOperatorSigner(); return *this; diff --git a/sdk/main/src/ContractCreateTransaction.cc b/sdk/main/src/ContractCreateTransaction.cc index b411f012c..e31753b32 100644 --- a/sdk/main/src/ContractCreateTransaction.cc +++ b/sdk/main/src/ContractCreateTransaction.cc @@ -73,10 +73,10 @@ ContractCreateTransaction& ContractCreateTransaction::setBytecode(const std::vec } //----- -ContractCreateTransaction& ContractCreateTransaction::setAdminKey(const Key* key) +ContractCreateTransaction& ContractCreateTransaction::setAdminKey(const std::shared_ptr& key) { requireNotFrozen(); - mAdminKey = ValuePtr(key->clone().release()); + mAdminKey = key; return *this; } @@ -204,7 +204,7 @@ void ContractCreateTransaction::initFromSourceTransactionBody() if (body.has_adminkey()) { - mAdminKey = ValuePtr(Key::fromProtobuf(body.adminkey()).release()); + mAdminKey = Key::fromProtobuf(body.adminkey()); } mGas = static_cast(body.gas()); diff --git a/sdk/main/src/ContractInfo.cc b/sdk/main/src/ContractInfo.cc index c6323d19c..df825dad3 100644 --- a/sdk/main/src/ContractInfo.cc +++ b/sdk/main/src/ContractInfo.cc @@ -45,7 +45,7 @@ ContractInfo ContractInfo::fromProtobuf(const proto::ContractGetInfoResponse_Con if (proto.has_adminkey()) { - contractInfo.mAdminKey = ValuePtr(Key::fromProtobuf(proto.adminkey()).release()); + contractInfo.mAdminKey = Key::fromProtobuf(proto.adminkey()); } if (proto.has_expirationtime()) diff --git a/sdk/main/src/ContractUpdateTransaction.cc b/sdk/main/src/ContractUpdateTransaction.cc index 630f31c23..342612c82 100644 --- a/sdk/main/src/ContractUpdateTransaction.cc +++ b/sdk/main/src/ContractUpdateTransaction.cc @@ -62,10 +62,10 @@ ContractUpdateTransaction& ContractUpdateTransaction::setExpirationTime( } //----- -ContractUpdateTransaction& ContractUpdateTransaction::setAdminKey(const Key* adminKey) +ContractUpdateTransaction& ContractUpdateTransaction::setAdminKey(const std::shared_ptr& adminKey) { requireNotFrozen(); - mAdminKey = ValuePtr(adminKey->clone().release()); + mAdminKey = adminKey; return *this; } @@ -180,7 +180,7 @@ void ContractUpdateTransaction::initFromSourceTransactionBody() if (body.has_adminkey()) { - mAdminKey = ValuePtr(Key::fromProtobuf(body.adminkey()).release()); + mAdminKey = Key::fromProtobuf(body.adminkey()); } if (body.has_autorenewperiod()) diff --git a/sdk/main/src/ED25519PrivateKey.cc b/sdk/main/src/ED25519PrivateKey.cc index 8d0c777d8..90dcf466f 100644 --- a/sdk/main/src/ED25519PrivateKey.cc +++ b/sdk/main/src/ED25519PrivateKey.cc @@ -27,6 +27,7 @@ #include "impl/PrivateKeyImpl.h" #include "impl/Utilities.h" #include "impl/openssl_utils/EVP_MD_CTX.h" +#include "impl/openssl_utils/EVP_PKEY.h" #include "impl/openssl_utils/EVP_PKEY_CTX.h" #include "impl/openssl_utils/OpenSSLUtils.h" diff --git a/sdk/main/src/FileCreateTransaction.cc b/sdk/main/src/FileCreateTransaction.cc index feb5695bf..7057bd348 100644 --- a/sdk/main/src/FileCreateTransaction.cc +++ b/sdk/main/src/FileCreateTransaction.cc @@ -62,7 +62,7 @@ FileCreateTransaction& FileCreateTransaction::setExpirationTime( } //----- -FileCreateTransaction& FileCreateTransaction::setKeys(const std::vector& keys) +FileCreateTransaction& FileCreateTransaction::setKeys(const std::vector>& keys) { requireNotFrozen(); mKeys = KeyList::of(keys); diff --git a/sdk/main/src/FileUpdateTransaction.cc b/sdk/main/src/FileUpdateTransaction.cc index 94d93ae77..c88b39159 100644 --- a/sdk/main/src/FileUpdateTransaction.cc +++ b/sdk/main/src/FileUpdateTransaction.cc @@ -62,7 +62,7 @@ FileUpdateTransaction& FileUpdateTransaction::setExpirationTime( } //----- -FileUpdateTransaction& FileUpdateTransaction::setKeys(const std::vector& keys) +FileUpdateTransaction& FileUpdateTransaction::setKeys(const std::vector>& keys) { requireNotFrozen(); mKeys = KeyList::of(keys); diff --git a/sdk/main/src/KeyList.cc b/sdk/main/src/KeyList.cc index 0e432ebf9..df754a37e 100644 --- a/sdk/main/src/KeyList.cc +++ b/sdk/main/src/KeyList.cc @@ -18,7 +18,6 @@ * */ #include "KeyList.h" -#include "impl/ValuePtr.h" #include #include @@ -41,13 +40,10 @@ KeyList KeyList::fromProtobuf(const proto::KeyList& proto, int threshold) } //----- -KeyList KeyList::of(const std::vector& keys) +KeyList KeyList::of(const std::vector>& keys) { KeyList keyList; - std::transform(keys.cbegin(), - keys.cend(), - std::back_inserter(keyList.mKeys), - [](const Key* key) { return ValuePtr(KeyCloner()(key)); }); + keyList.mKeys = keys; return keyList; } @@ -112,13 +108,13 @@ bool KeyList::contains(const Key* key) const const std::vector keyBytes = key->toBytes(); return std::any_of(mKeys.cbegin(), mKeys.cend(), - [&keyBytes](const ValuePtr& listKey) { return listKey->toBytes() == keyBytes; }); + [&keyBytes](const std::shared_ptr& listKey) { return listKey->toBytes() == keyBytes; }); } //----- -void KeyList::push_back(const Key* key) +void KeyList::push_back(const std::shared_ptr& key) { - mKeys.emplace_back(key->clone().release()); + mKeys.push_back(key); } //----- @@ -128,7 +124,7 @@ void KeyList::remove(const Key* key) const auto eraseIter = std::remove_if(mKeys.begin(), mKeys.end(), - [&keyBytes](const ValuePtr& listKey) { return listKey->toBytes() == keyBytes; }); + [&keyBytes](const std::shared_ptr& listKey) { return listKey->toBytes() == keyBytes; }); // Erasing an element pointed to by an iterator that equals end() is undefined, so this check is necessary. if (eraseIter != mKeys.end()) diff --git a/sdk/main/src/PrivateKey.cc b/sdk/main/src/PrivateKey.cc index b2cba065d..ec25dc4ad 100644 --- a/sdk/main/src/PrivateKey.cc +++ b/sdk/main/src/PrivateKey.cc @@ -44,9 +44,48 @@ std::shared_ptr PrivateKey::getPublicKey() const return mImpl->mPublicKey; } +//----- +PrivateKey::PrivateKey(const PrivateKey& other) + : mImpl(std::make_unique(*other.mImpl)) +{ +} + +//----- +PrivateKey& PrivateKey::operator=(const PrivateKey& other) +{ + if (this != &other) + { + mImpl = std::make_unique(*other.mImpl); + } + + return *this; +} + +//----- +PrivateKey::PrivateKey(PrivateKey&& other) noexcept + : mImpl(std::move(other.mImpl)) +{ + // Leave the moved-from PrivateKey in a valid state. + other.mImpl = std::make_unique(); +} + +//----- +PrivateKey& PrivateKey::operator=(PrivateKey&& other) noexcept +{ + if (this != &other) + { + mImpl = std::move(other.mImpl); + + // Leave the moved-from PrivateKey in a valid state. + other.mImpl = std::make_unique(); + } + + return *this; +} + //----- PrivateKey::PrivateKey(internal::OpenSSLUtils::EVP_PKEY&& key, std::vector chainCode) - : mImpl(PrivateKeyImpl()) + : mImpl(std::make_unique()) { mImpl->mKey = std::move(key); mImpl->mChainCode = std::move(chainCode); diff --git a/sdk/main/src/PublicKey.cc b/sdk/main/src/PublicKey.cc index c029bd376..b380ab4c1 100644 --- a/sdk/main/src/PublicKey.cc +++ b/sdk/main/src/PublicKey.cc @@ -106,9 +106,48 @@ AccountId PublicKey::toAccountId(uint64_t shard, uint64_t realm) const return AccountId(shard, realm, getShared()); } +//----- +PublicKey::PublicKey(const PublicKey& other) + : mImpl(std::make_unique(*other.mImpl)) +{ +} + +//----- +PublicKey& PublicKey::operator=(const PublicKey& other) +{ + if (this != &other) + { + mImpl = std::make_unique(*other.mImpl); + } + + return *this; +} + +//----- +PublicKey::PublicKey(PublicKey&& other) noexcept + : mImpl(std::move(other.mImpl)) +{ + // Leave the moved-from PublicKey in a valid state. + other.mImpl = std::make_unique(); +} + +//----- +PublicKey& PublicKey::operator=(PublicKey&& other) noexcept +{ + if (this != &other) + { + mImpl = std::move(other.mImpl); + + // Leave the moved-from PublicKey in a valid state. + other.mImpl = std::make_unique(); + } + + return *this; +} + //----- PublicKey::PublicKey(internal::OpenSSLUtils::EVP_PKEY&& key) - : mImpl(PublicKeyImpl()) + : mImpl(std::make_unique()) { mImpl->mKey = std::move(key); } diff --git a/sdk/main/src/Transaction.cc b/sdk/main/src/Transaction.cc index 899cd63b2..dd5e9cc20 100644 --- a/sdk/main/src/Transaction.cc +++ b/sdk/main/src/Transaction.cc @@ -108,6 +108,11 @@ struct Transaction::TransactionImpl std::unordered_map, std::function(const std::vector&)>> mSignatories; + // Keep a map of PublicKeys to their associated PrivateKeys. If the Transaction is signed with a PrivateKey, the + // Transaction must make sure the PrivateKey does not go out of scope, otherwise it will crash when trying to generate + // a signature. + std::unordered_map, std::shared_ptr> mPrivateKeys; + // Is this Transaction frozen? bool mIsFrozen = false; @@ -298,9 +303,10 @@ std::vector Transaction::toBytes() const //----- template -SdkRequestType& Transaction::sign(const PrivateKey* key) +SdkRequestType& Transaction::sign(const std::shared_ptr& key) { - return signWith(key->getPublicKey(), [key](const std::vector& vec) { return key->sign(vec); }); + return signInternal( + key->getPublicKey(), [key](const std::vector& vec) { return key->sign(vec); }, key); } //----- @@ -309,20 +315,7 @@ SdkRequestType& Transaction::signWith( const std::shared_ptr& key, const std::function(const std::vector&)>& signer) { - if (!isFrozen()) - { - throw IllegalStateException("Transaction must be frozen in order to sign"); - } - - if (!keyAlreadySigned(key)) - { - // Adding a signature will require all Transaction protobuf objects to be regenerated. - mImpl->mTransactions.clear(); - mImpl->mTransactions.resize(mImpl->mSignedTransactions.size()); - mImpl->mSignatories[key] = signer; - } - - return static_cast(*this); + return signInternal(key, signer); } //----- @@ -336,7 +329,7 @@ SdkRequestType& Transaction::signWithOperator(const Client& clie freezeWith(&client); - return signWith(client.getOperatorPublicKey(), client.getOperatorSigner()); + return signInternal(client.getOperatorPublicKey(), client.getOperatorSigner()); } //----- @@ -363,6 +356,7 @@ SdkRequestType& Transaction::addSignature(const std::shared_ptr< mImpl->mTransactions.clear(); mImpl->mTransactions.resize(mImpl->mSignedTransactions.size()); mImpl->mSignatories.emplace(publicKey, std::function(const std::vector&)>()); + mImpl->mPrivateKeys.emplace(publicKey, nullptr); // Add the signature to the SignedTransaction protobuf object. Since there's only one node account ID, there's only // one SignedTransaction protobuf object in the vector. @@ -728,9 +722,10 @@ Transaction::Transaction( const proto::SignedTransaction& signedTx = mImpl->mSignedTransactions.back(); for (int i = 0; i < signedTx.sigmap().sigpair_size(); ++i) { - mImpl->mSignatories.emplace( - PublicKey::fromBytes(internal::Utilities::stringToByteVector(signedTx.sigmap().sigpair(i).pubkeyprefix())), - std::function(const std::vector&)>()); + const std::shared_ptr publicKey = + PublicKey::fromBytes(internal::Utilities::stringToByteVector(signedTx.sigmap().sigpair(i).pubkeyprefix())); + mImpl->mSignatories.emplace(publicKey, std::function(const std::vector&)>()); + mImpl->mPrivateKeys.emplace(publicKey, nullptr); } } } @@ -1085,6 +1080,30 @@ bool Transaction::keyAlreadySigned(const std::shared_ptrtoBytesDer() == publicKeyBytes; }); } +//----- +template +SdkRequestType& Transaction::signInternal( + const std::shared_ptr& publicKey, + const std::function(const std::vector&)>& signer, + const std::shared_ptr& privateKey) +{ + if (!isFrozen()) + { + throw IllegalStateException("Transaction must be frozen in order to sign"); + } + + if (!keyAlreadySigned(publicKey)) + { + // Adding a signature will require all Transaction protobuf objects to be regenerated. + mImpl->mTransactions.clear(); + mImpl->mTransactions.resize(mImpl->mSignedTransactions.size()); + mImpl->mSignatories.emplace(publicKey, signer); + mImpl->mPrivateKeys.emplace(publicKey, privateKey); + } + + return static_cast(*this); +} + /** * Explicit template instantiations. */ diff --git a/sdk/tests/integration/AccountAllowanceApproveTransactionIntegrationTests.cc b/sdk/tests/integration/AccountAllowanceApproveTransactionIntegrationTests.cc index 5f36ed284..0d124f9da 100644 --- a/sdk/tests/integration/AccountAllowanceApproveTransactionIntegrationTests.cc +++ b/sdk/tests/integration/AccountAllowanceApproveTransactionIntegrationTests.cc @@ -44,18 +44,18 @@ TEST_F(AccountAllowanceApproveTransactionIntegrationTest, ExecuteAccountAllowanc { // Given const Hbar amount(5LL); - const std::unique_ptr allowerKey = ED25519PrivateKey::generatePrivateKey(); - const std::unique_ptr alloweeKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr allowerKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr alloweeKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); AccountId allowerAccountId; AccountId alloweeAccountId; ASSERT_NO_THROW(allowerAccountId = AccountCreateTransaction() - .setKey(allowerKey->getPublicKey().get()) + .setKey(allowerKey->getPublicKey()) .setInitialBalance(amount) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); ASSERT_NO_THROW(alloweeAccountId = AccountCreateTransaction() - .setKey(alloweeKey->getPublicKey().get()) + .setKey(alloweeKey->getPublicKey()) .setInitialBalance(amount) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -66,7 +66,7 @@ TEST_F(AccountAllowanceApproveTransactionIntegrationTest, ExecuteAccountAllowanc EXPECT_NO_THROW(txResponse = AccountAllowanceApproveTransaction() .approveHbarAllowance(allowerAccountId, alloweeAccountId, amount) .freezeWith(&getTestClient()) - .sign(allowerKey.get()) + .sign(allowerKey) .execute(getTestClient())); // Then @@ -77,13 +77,13 @@ TEST_F(AccountAllowanceApproveTransactionIntegrationTest, ExecuteAccountAllowanc .setDeleteAccountId(allowerAccountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(allowerKey.get()) + .sign(allowerKey) .execute(getTestClient())); ASSERT_NO_THROW(AccountDeleteTransaction() .setDeleteAccountId(alloweeAccountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(alloweeKey.get()) + .sign(alloweeKey) .execute(getTestClient())); } @@ -92,18 +92,18 @@ TEST_F(AccountAllowanceApproveTransactionIntegrationTest, CannotAllowAllowanceWi { // Given const Hbar amount(5LL); - const std::unique_ptr allowerKey = ED25519PrivateKey::generatePrivateKey(); - const std::unique_ptr alloweeKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr allowerKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr alloweeKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); AccountId allowerAccountId; AccountId alloweeAccountId; ASSERT_NO_THROW(allowerAccountId = AccountCreateTransaction() - .setKey(allowerKey->getPublicKey().get()) + .setKey(allowerKey->getPublicKey()) .setInitialBalance(amount) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); ASSERT_NO_THROW(alloweeAccountId = AccountCreateTransaction() - .setKey(alloweeKey->getPublicKey().get()) + .setKey(alloweeKey->getPublicKey()) .setInitialBalance(amount) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -121,12 +121,12 @@ TEST_F(AccountAllowanceApproveTransactionIntegrationTest, CannotAllowAllowanceWi .setDeleteAccountId(allowerAccountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(allowerKey.get()) + .sign(allowerKey) .execute(getTestClient())); ASSERT_NO_THROW(AccountDeleteTransaction() .setDeleteAccountId(alloweeAccountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(alloweeKey.get()) + .sign(alloweeKey) .execute(getTestClient())); } diff --git a/sdk/tests/integration/AccountCreateTransactionIntegrationTest.cc b/sdk/tests/integration/AccountCreateTransactionIntegrationTest.cc index 7183b8e67..e485648e4 100644 --- a/sdk/tests/integration/AccountCreateTransactionIntegrationTest.cc +++ b/sdk/tests/integration/AccountCreateTransactionIntegrationTest.cc @@ -51,7 +51,7 @@ class AccountCreateTransactionIntegrationTest : public BaseIntegrationTest TEST_F(AccountCreateTransactionIntegrationTest, ExecuteAccountCreateTransaction) { // Given - const std::unique_ptr testPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr testPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const std::shared_ptr testPublicKey = std::dynamic_pointer_cast(testPrivateKey->getPublicKey()); const EvmAddress testEvmAddress = testPublicKey->toEvmAddress(); @@ -63,7 +63,7 @@ TEST_F(AccountCreateTransactionIntegrationTest, ExecuteAccountCreateTransaction) // When TransactionResponse txResponse; EXPECT_NO_THROW(txResponse = AccountCreateTransaction() - .setKey(testPublicKey.get()) + .setKey(testPublicKey) .setInitialBalance(testInitialBalance) .setReceiverSignatureRequired(true) .setAutoRenewPeriod(testAutoRenewPeriod) @@ -72,7 +72,7 @@ TEST_F(AccountCreateTransactionIntegrationTest, ExecuteAccountCreateTransaction) .setDeclineStakingReward(true) .setAlias(testEvmAddress) .freezeWith(&getTestClient()) - .sign(testPrivateKey.get()) + .sign(testPrivateKey) .execute(getTestClient())); // Then @@ -96,7 +96,7 @@ TEST_F(AccountCreateTransactionIntegrationTest, ExecuteAccountCreateTransaction) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(testPrivateKey.get()) + .sign(testPrivateKey) .execute(getTestClient())); } @@ -104,7 +104,7 @@ TEST_F(AccountCreateTransactionIntegrationTest, ExecuteAccountCreateTransaction) TEST_F(AccountCreateTransactionIntegrationTest, MutuallyExclusiveStakingIds) { // Given - const std::unique_ptr testPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr testPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const std::shared_ptr testPublicKey = std::dynamic_pointer_cast(testPrivateKey->getPublicKey()); const AccountId operatorAccountId(2ULL); @@ -115,12 +115,12 @@ TEST_F(AccountCreateTransactionIntegrationTest, MutuallyExclusiveStakingIds) TransactionResponse txResponseStakedNodeId; EXPECT_NO_THROW(txResponseStakedAccountId = AccountCreateTransaction() - .setKey(testPublicKey.get()) + .setKey(testPublicKey) .setStakedAccountId(operatorAccountId) .freezeWith(&getTestClient()) .execute(getTestClient())); EXPECT_NO_THROW(txResponseStakedNodeId = AccountCreateTransaction() - .setKey(testPublicKey.get()) + .setKey(testPublicKey) .setStakedNodeId(nodeId) .freezeWith(&getTestClient()) .execute(getTestClient())); @@ -151,13 +151,13 @@ TEST_F(AccountCreateTransactionIntegrationTest, MutuallyExclusiveStakingIds) .setDeleteAccountId(accountIdStakedAccountId) .setTransferAccountId(operatorAccountId) .freezeWith(&getTestClient()) - .sign(testPrivateKey.get()) + .sign(testPrivateKey) .execute(getTestClient())); ASSERT_NO_THROW(AccountDeleteTransaction() .setDeleteAccountId(accountIdStakedNodeId) .setTransferAccountId(operatorAccountId) .freezeWith(&getTestClient()) - .sign(testPrivateKey.get()) + .sign(testPrivateKey) .execute(getTestClient())); } @@ -165,12 +165,11 @@ TEST_F(AccountCreateTransactionIntegrationTest, MutuallyExclusiveStakingIds) TEST_F(AccountCreateTransactionIntegrationTest, NoInitialBalance) { // Given - const std::unique_ptr testKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr testKey = ED25519PrivateKey::generatePrivateKey(); // When TransactionResponse txResponse; - EXPECT_NO_THROW(txResponse = - AccountCreateTransaction().setKey(testKey->getPublicKey().get()).execute(getTestClient())); + EXPECT_NO_THROW(txResponse = AccountCreateTransaction().setKey(testKey->getPublicKey()).execute(getTestClient())); // Then AccountId accountId; @@ -190,7 +189,7 @@ TEST_F(AccountCreateTransactionIntegrationTest, NoInitialBalance) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(testKey.get()) + .sign(testKey) .execute(getTestClient())); } @@ -198,22 +197,22 @@ TEST_F(AccountCreateTransactionIntegrationTest, NoInitialBalance) TEST_F(AccountCreateTransactionIntegrationTest, AliasFromAdminKey) { // Given - const std::unique_ptr adminPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr adminPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const std::shared_ptr adminPublicKey = std::dynamic_pointer_cast(adminPrivateKey->getPublicKey()); const EvmAddress evmAddress = adminPublicKey->toEvmAddress(); AccountId adminAccountId; ASSERT_NO_THROW(adminAccountId = AccountCreateTransaction() - .setKey(adminPublicKey.get()) + .setKey(adminPublicKey) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); // When TransactionResponse txResponse; - EXPECT_NO_THROW( - txResponse = AccountCreateTransaction().setKey(adminPublicKey.get()).setAlias(evmAddress).execute(getTestClient())); + EXPECT_NO_THROW(txResponse = + AccountCreateTransaction().setKey(adminPublicKey).setAlias(evmAddress).execute(getTestClient())); // Then AccountId accountId; @@ -230,13 +229,13 @@ TEST_F(AccountCreateTransactionIntegrationTest, AliasFromAdminKey) .setDeleteAccountId(adminAccountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(adminPrivateKey.get()) + .sign(adminPrivateKey) .execute(getTestClient())); ASSERT_NO_THROW(AccountDeleteTransaction() .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(adminPrivateKey.get()) + .sign(adminPrivateKey) .execute(getTestClient())); } @@ -244,14 +243,14 @@ TEST_F(AccountCreateTransactionIntegrationTest, AliasFromAdminKey) TEST_F(AccountCreateTransactionIntegrationTest, AliasFromAdminKeyWithReceiverSigRequired) { // Given - const std::unique_ptr adminKeyPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr adminKeyPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const std::shared_ptr adminKeyPublicKey = std::dynamic_pointer_cast(adminKeyPrivateKey->getPublicKey()); const EvmAddress evmAddress = adminKeyPublicKey->toEvmAddress(); AccountId adminAccountId; ASSERT_NO_THROW(adminAccountId = AccountCreateTransaction() - .setKey(adminKeyPublicKey.get()) + .setKey(adminKeyPublicKey) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); @@ -260,10 +259,10 @@ TEST_F(AccountCreateTransactionIntegrationTest, AliasFromAdminKeyWithReceiverSig TransactionResponse txResponse; EXPECT_NO_THROW(txResponse = AccountCreateTransaction() .setReceiverSignatureRequired(true) - .setKey(adminKeyPublicKey.get()) + .setKey(adminKeyPublicKey) .setAlias(evmAddress) .freezeWith(&getTestClient()) - .sign(adminKeyPrivateKey.get()) + .sign(adminKeyPrivateKey) .execute(getTestClient())); // Then @@ -281,13 +280,13 @@ TEST_F(AccountCreateTransactionIntegrationTest, AliasFromAdminKeyWithReceiverSig .setDeleteAccountId(adminAccountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(adminKeyPrivateKey.get()) + .sign(adminKeyPrivateKey) .execute(getTestClient())); ASSERT_NO_THROW(AccountDeleteTransaction() .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(adminKeyPrivateKey.get()) + .sign(adminKeyPrivateKey) .execute(getTestClient())); } @@ -295,14 +294,14 @@ TEST_F(AccountCreateTransactionIntegrationTest, AliasFromAdminKeyWithReceiverSig TEST_F(AccountCreateTransactionIntegrationTest, CannotCreateAliasFromAdminKeyWithReceiverSigRequiredWithoutSignature) { // Given - const std::unique_ptr adminKeyPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr adminKeyPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const std::shared_ptr adminKeyPublicKey = std::dynamic_pointer_cast(adminKeyPrivateKey->getPublicKey()); const EvmAddress evmAddress = adminKeyPublicKey->toEvmAddress(); AccountId adminAccountId; ASSERT_NO_THROW(adminAccountId = AccountCreateTransaction() - .setKey(adminKeyPublicKey.get()) + .setKey(adminKeyPublicKey) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); @@ -310,7 +309,7 @@ TEST_F(AccountCreateTransactionIntegrationTest, CannotCreateAliasFromAdminKeyWit // When EXPECT_THROW(const TransactionReceipt txReceipt = AccountCreateTransaction() .setReceiverSignatureRequired(true) - .setKey(adminKeyPublicKey.get()) + .setKey(adminKeyPublicKey) .setAlias(evmAddress) .execute(getTestClient()) .getReceipt(getTestClient()), @@ -321,7 +320,7 @@ TEST_F(AccountCreateTransactionIntegrationTest, CannotCreateAliasFromAdminKeyWit .setDeleteAccountId(adminAccountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(adminKeyPrivateKey.get()) + .sign(adminKeyPrivateKey) .execute(getTestClient())); } @@ -329,15 +328,15 @@ TEST_F(AccountCreateTransactionIntegrationTest, CannotCreateAliasFromAdminKeyWit TEST_F(AccountCreateTransactionIntegrationTest, AliasDifferentFromAdminKeyWithReceiverSigRequired) { // Given - const std::unique_ptr adminPrivateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr adminPrivateKey = ED25519PrivateKey::generatePrivateKey(); AccountId adminAccountId; ASSERT_NO_THROW(adminAccountId = AccountCreateTransaction() - .setKey(adminPrivateKey->getPublicKey().get()) + .setKey(adminPrivateKey->getPublicKey()) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); - const std::unique_ptr aliasPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr aliasPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const EvmAddress alias = std::dynamic_pointer_cast(aliasPrivateKey->getPublicKey())->toEvmAddress(); @@ -345,11 +344,11 @@ TEST_F(AccountCreateTransactionIntegrationTest, AliasDifferentFromAdminKeyWithRe TransactionResponse txResponse; EXPECT_NO_THROW(txResponse = AccountCreateTransaction() .setReceiverSignatureRequired(true) - .setKey(adminPrivateKey->getPublicKey().get()) + .setKey(adminPrivateKey->getPublicKey()) .setAlias(alias) .freezeWith(&getTestClient()) - .sign(adminPrivateKey.get()) - .sign(aliasPrivateKey.get()) + .sign(adminPrivateKey) + .sign(aliasPrivateKey) .execute(getTestClient())); // Then @@ -367,13 +366,13 @@ TEST_F(AccountCreateTransactionIntegrationTest, AliasDifferentFromAdminKeyWithRe .setDeleteAccountId(adminAccountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(adminPrivateKey.get()) + .sign(adminPrivateKey) .execute(getTestClient())); ASSERT_NO_THROW(AccountDeleteTransaction() .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(adminPrivateKey.get()) + .sign(adminPrivateKey) .execute(getTestClient())); } @@ -382,25 +381,25 @@ TEST_F(AccountCreateTransactionIntegrationTest, CannotCreateWithAliasDifferentFromAdminKeyWithReceiverSigRequiredWithoutSignature) { // Given - const std::unique_ptr adminPrivateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr adminPrivateKey = ED25519PrivateKey::generatePrivateKey(); AccountId adminAccountId; ASSERT_NO_THROW(adminAccountId = AccountCreateTransaction() - .setKey(adminPrivateKey->getPublicKey().get()) + .setKey(adminPrivateKey->getPublicKey()) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); - const std::unique_ptr aliasPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr aliasPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const EvmAddress alias = std::dynamic_pointer_cast(aliasPrivateKey->getPublicKey())->toEvmAddress(); // When EXPECT_THROW(const TransactionReceipt txReceipt = AccountCreateTransaction() .setReceiverSignatureRequired(true) - .setKey(adminPrivateKey->getPublicKey().get()) + .setKey(adminPrivateKey->getPublicKey()) .setAlias(alias) .freezeWith(&getTestClient()) - .sign(aliasPrivateKey.get()) + .sign(aliasPrivateKey) .execute(getTestClient()) .getReceipt(getTestClient()), ReceiptStatusException); // INVALID_SIGNATURE @@ -410,6 +409,6 @@ TEST_F(AccountCreateTransactionIntegrationTest, .setDeleteAccountId(adminAccountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(adminPrivateKey.get()) + .sign(adminPrivateKey) .execute(getTestClient())); } diff --git a/sdk/tests/integration/AccountDeleteTransactionIntegrationTest.cc b/sdk/tests/integration/AccountDeleteTransactionIntegrationTest.cc index fabad3a4e..81da90e78 100644 --- a/sdk/tests/integration/AccountDeleteTransactionIntegrationTest.cc +++ b/sdk/tests/integration/AccountDeleteTransactionIntegrationTest.cc @@ -42,10 +42,10 @@ class AccountDeleteTransactionIntegrationTest : public BaseIntegrationTest TEST_F(AccountDeleteTransactionIntegrationTest, ExecuteAccountDeleteTransaction) { // Given - const std::unique_ptr key = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr key = ED25519PrivateKey::generatePrivateKey(); AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(key->getPublicKey().get()) + .setKey(key->getPublicKey()) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); @@ -56,7 +56,7 @@ TEST_F(AccountDeleteTransactionIntegrationTest, ExecuteAccountDeleteTransaction) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(key.get()) + .sign(key) .execute(getTestClient())); // Then @@ -76,10 +76,10 @@ TEST_F(AccountDeleteTransactionIntegrationTest, CannotDeleteInvalidAccountId) TEST_F(AccountDeleteTransactionIntegrationTest, CannotDeleteAccountWithoutSignature) { // Given - const std::unique_ptr key = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr key = ED25519PrivateKey::generatePrivateKey(); AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(key->getPublicKey().get()) + .setKey(key->getPublicKey()) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); @@ -98,6 +98,6 @@ TEST_F(AccountDeleteTransactionIntegrationTest, CannotDeleteAccountWithoutSignat .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(key.get()) + .sign(key) .execute(getTestClient())); } diff --git a/sdk/tests/integration/AccountInfoQueryIntegrationTests.cc b/sdk/tests/integration/AccountInfoQueryIntegrationTests.cc index fbce0eee4..70c380464 100644 --- a/sdk/tests/integration/AccountInfoQueryIntegrationTests.cc +++ b/sdk/tests/integration/AccountInfoQueryIntegrationTests.cc @@ -43,11 +43,11 @@ class AccountInfoQueryIntegrationTest : public BaseIntegrationTest TEST_F(AccountInfoQueryIntegrationTest, ExecuteAccountInfoQuery) { // Given - const std::unique_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); const Hbar balance(2LL); AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(privateKey->getPublicKey().get()) + .setKey(privateKey->getPublicKey()) .setInitialBalance(balance) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -70,7 +70,7 @@ TEST_F(AccountInfoQueryIntegrationTest, ExecuteAccountInfoQuery) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(privateKey.get()) + .sign(privateKey) .execute(getTestClient())); } @@ -85,10 +85,10 @@ TEST_F(AccountInfoQueryIntegrationTest, NoAccountId) TEST_F(AccountInfoQueryIntegrationTest, CannotQueryDeletedAccount) { // Given - const std::unique_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(privateKey->getPublicKey().get()) + .setKey(privateKey->getPublicKey()) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); @@ -96,7 +96,7 @@ TEST_F(AccountInfoQueryIntegrationTest, CannotQueryDeletedAccount) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(privateKey.get()) + .sign(privateKey) .execute(getTestClient()) .getReceipt(getTestClient())); diff --git a/sdk/tests/integration/AccountRecordsQueryIntegrationTests.cc b/sdk/tests/integration/AccountRecordsQueryIntegrationTests.cc index 29150c083..a0196291f 100644 --- a/sdk/tests/integration/AccountRecordsQueryIntegrationTests.cc +++ b/sdk/tests/integration/AccountRecordsQueryIntegrationTests.cc @@ -45,12 +45,12 @@ class AccountRecordsQueryIntegrationTest : public BaseIntegrationTest TEST_F(AccountRecordsQueryIntegrationTest, ExecuteAccountRecordsQuery) { // Given - const std::unique_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); const AccountId operatorAccountId(2ULL); const Hbar amount(1LL); AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(privateKey->getPublicKey().get()) + .setKey(privateKey->getPublicKey()) .setInitialBalance(amount) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -64,7 +64,7 @@ TEST_F(AccountRecordsQueryIntegrationTest, ExecuteAccountRecordsQuery) .addHbarTransfer(operatorAccountId, amount) .addHbarTransfer(accountId, amount.negated()) .freezeWith(&getTestClient()) - .sign(privateKey.get()) + .sign(privateKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -80,7 +80,7 @@ TEST_F(AccountRecordsQueryIntegrationTest, ExecuteAccountRecordsQuery) .setDeleteAccountId(accountId) .setTransferAccountId(operatorAccountId) .freezeWith(&getTestClient()) - .sign(privateKey.get()) + .sign(privateKey) .execute(getTestClient())); } diff --git a/sdk/tests/integration/AccountUpdateTransactionIntegrationTest.cc b/sdk/tests/integration/AccountUpdateTransactionIntegrationTest.cc index a710a9765..8bfab0639 100644 --- a/sdk/tests/integration/AccountUpdateTransactionIntegrationTest.cc +++ b/sdk/tests/integration/AccountUpdateTransactionIntegrationTest.cc @@ -45,9 +45,8 @@ class AccountUpdateTransactionIntegrationTest : public BaseIntegrationTest TEST_F(AccountUpdateTransactionIntegrationTest, ExecuteAccountUpdateTransaction) { // Given - const std::unique_ptr initialPrivateKey = ED25519PrivateKey::generatePrivateKey(); - - const std::unique_ptr newPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr initialPrivateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr newPrivateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const bool newReceiverSignatureRequired = true; const std::chrono::duration newAutoRenewPeriod = std::chrono::seconds(8000000); const std::chrono::system_clock::time_point newExpirationTime = @@ -59,7 +58,7 @@ TEST_F(AccountUpdateTransactionIntegrationTest, ExecuteAccountUpdateTransaction) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(initialPrivateKey->getPublicKey().get()) + .setKey(initialPrivateKey->getPublicKey()) .setAutoRenewPeriod(std::chrono::seconds(2592000)) .setAccountMemo("test account memo") .setMaxAutomaticTokenAssociations(10U) @@ -72,7 +71,7 @@ TEST_F(AccountUpdateTransactionIntegrationTest, ExecuteAccountUpdateTransaction) TransactionResponse txResponse; EXPECT_NO_THROW(txResponse = AccountUpdateTransaction() .setAccountId(accountId) - .setKey(newPrivateKey->getPublicKey().get()) + .setKey(newPrivateKey->getPublicKey()) .setReceiverSignatureRequired(newReceiverSignatureRequired) .setAutoRenewPeriod(newAutoRenewPeriod) .setExpirationTime(newExpirationTime) @@ -81,8 +80,8 @@ TEST_F(AccountUpdateTransactionIntegrationTest, ExecuteAccountUpdateTransaction) .setStakedNodeId(newStakedNodeId) .setDeclineStakingReward(newDeclineStakingRewards) .freezeWith(&getTestClient()) - .sign(initialPrivateKey.get()) - .sign(newPrivateKey.get()) + .sign(initialPrivateKey) + .sign(newPrivateKey) .execute(getTestClient())); // Then @@ -108,7 +107,7 @@ TEST_F(AccountUpdateTransactionIntegrationTest, ExecuteAccountUpdateTransaction) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(newPrivateKey.get()) + .sign(newPrivateKey) .execute(getTestClient())); } @@ -116,11 +115,11 @@ TEST_F(AccountUpdateTransactionIntegrationTest, ExecuteAccountUpdateTransaction) TEST_F(AccountUpdateTransactionIntegrationTest, CannotUpdateAccountWithoutSignature) { // Given - const std::unique_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(privateKey->getPublicKey().get()) + .setKey(privateKey->getPublicKey()) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); @@ -136,7 +135,7 @@ TEST_F(AccountUpdateTransactionIntegrationTest, CannotUpdateAccountWithoutSignat .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(privateKey.get()) + .sign(privateKey) .execute(getTestClient())); } @@ -144,11 +143,11 @@ TEST_F(AccountUpdateTransactionIntegrationTest, CannotUpdateAccountWithoutSignat TEST_F(AccountUpdateTransactionIntegrationTest, CannotUpdateAccountWithoutAccountId) { // Given - const std::unique_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(privateKey->getPublicKey().get()) + .setKey(privateKey->getPublicKey()) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); @@ -156,7 +155,7 @@ TEST_F(AccountUpdateTransactionIntegrationTest, CannotUpdateAccountWithoutAccoun // When / Then EXPECT_THROW(const TransactionReceipt txReceipt = AccountUpdateTransaction() .freezeWith(&getTestClient()) - .sign(privateKey.get()) + .sign(privateKey) .execute(getTestClient()) .getReceipt(getTestClient()), ReceiptStatusException); // ACCOUNT_ID_DOES_NOT_EXIST @@ -166,7 +165,7 @@ TEST_F(AccountUpdateTransactionIntegrationTest, CannotUpdateAccountWithoutAccoun .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(privateKey.get()) + .sign(privateKey) .execute(getTestClient())); } @@ -174,10 +173,10 @@ TEST_F(AccountUpdateTransactionIntegrationTest, CannotUpdateAccountWithoutAccoun TEST_F(AccountUpdateTransactionIntegrationTest, ExecuteWithOnlyAccountId) { // Given - const std::unique_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(privateKey->getPublicKey().get()) + .setKey(privateKey->getPublicKey()) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); @@ -186,7 +185,7 @@ TEST_F(AccountUpdateTransactionIntegrationTest, ExecuteWithOnlyAccountId) EXPECT_NO_THROW(const TransactionReceipt txReceipt = AccountUpdateTransaction() .setAccountId(accountId) .freezeWith(&getTestClient()) - .sign(privateKey.get()) + .sign(privateKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -195,7 +194,7 @@ TEST_F(AccountUpdateTransactionIntegrationTest, ExecuteWithOnlyAccountId) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(privateKey.get()) + .sign(privateKey) .execute(getTestClient())); } @@ -203,12 +202,12 @@ TEST_F(AccountUpdateTransactionIntegrationTest, ExecuteWithOnlyAccountId) TEST_F(AccountUpdateTransactionIntegrationTest, InvalidAutoRenewPeriod) { // Given - const std::unique_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr privateKey = ED25519PrivateKey::generatePrivateKey(); const std::chrono::duration invalidAutoRenewPeriod = std::chrono::seconds(777600000); AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(privateKey->getPublicKey().get()) + .setKey(privateKey->getPublicKey()) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); @@ -218,7 +217,7 @@ TEST_F(AccountUpdateTransactionIntegrationTest, InvalidAutoRenewPeriod) .setAccountId(accountId) .setAutoRenewPeriod(invalidAutoRenewPeriod) .freezeWith(&getTestClient()) - .sign(privateKey.get()) + .sign(privateKey) .execute(getTestClient()), PrecheckStatusException); // AUTORENEW_DURATION_NOT_IN_RANGE @@ -227,6 +226,6 @@ TEST_F(AccountUpdateTransactionIntegrationTest, InvalidAutoRenewPeriod) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(privateKey.get()) + .sign(privateKey) .execute(getTestClient())); } diff --git a/sdk/tests/integration/BaseIntegrationTest.cc b/sdk/tests/integration/BaseIntegrationTest.cc index 23ba333d2..b442cd4e0 100644 --- a/sdk/tests/integration/BaseIntegrationTest.cc +++ b/sdk/tests/integration/BaseIntegrationTest.cc @@ -75,7 +75,7 @@ void BaseIntegrationTest::SetUp() testInputFile.close(); mClient = Client::forNetwork(networkAccountsMap); - mClient.setOperator(operatorAccountId, ED25519PrivateKey::fromString(operatorAccountPrivateKey).get()); + mClient.setOperator(operatorAccountId, ED25519PrivateKey::fromString(operatorAccountPrivateKey)); mClient.setMirrorNetwork({ "127.0.0.1:5600" }); mClient.setNetworkUpdatePeriod(std::chrono::hours(24)); diff --git a/sdk/tests/integration/ClientIntegrationTest.cc b/sdk/tests/integration/ClientIntegrationTest.cc index 4112822b3..3ba53c441 100644 --- a/sdk/tests/integration/ClientIntegrationTest.cc +++ b/sdk/tests/integration/ClientIntegrationTest.cc @@ -110,10 +110,10 @@ TEST_F(ClientIntegrationTest, ConnectToLocalNode) // When Client client = Client::forNetwork(networkMap); - client.setOperator(operatorAccountId, ED25519PrivateKey::fromString(operatorAccountPrivateKey).get()); + client.setOperator(operatorAccountId, ED25519PrivateKey::fromString(operatorAccountPrivateKey)); TransactionResponse txResp = - AccountCreateTransaction().setKey(testPublicKey.get()).setInitialBalance(testInitialHbarBalance).execute(client); + AccountCreateTransaction().setKey(testPublicKey).setInitialBalance(testInitialHbarBalance).execute(client); const AccountId newAccountId = txResp.getReceipt(client).mAccountId.value(); diff --git a/sdk/tests/integration/ContractBytecodeQueryIntegrationTests.cc b/sdk/tests/integration/ContractBytecodeQueryIntegrationTests.cc index 7b8d29ec5..63b1415ec 100644 --- a/sdk/tests/integration/ContractBytecodeQueryIntegrationTests.cc +++ b/sdk/tests/integration/ContractBytecodeQueryIntegrationTests.cc @@ -51,7 +51,7 @@ TEST_F(ContractBytecodeQueryIntegrationTest, ExecuteContractBytecodeQuery) "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137"); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -59,7 +59,7 @@ TEST_F(ContractBytecodeQueryIntegrationTest, ExecuteContractBytecodeQuery) ContractId contractId; ASSERT_NO_THROW(contractId = ContractCreateTransaction() - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.").toBytes()) .setBytecodeFileId(fileId) diff --git a/sdk/tests/integration/ContractCallQueryIntegrationTests.cc b/sdk/tests/integration/ContractCallQueryIntegrationTests.cc index a1b33d493..7fb8fe4a6 100644 --- a/sdk/tests/integration/ContractCallQueryIntegrationTests.cc +++ b/sdk/tests/integration/ContractCallQueryIntegrationTests.cc @@ -52,7 +52,7 @@ TEST_F(ContractCallQueryIntegrationTest, ExecuteContractCallQuery) "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137"); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -60,7 +60,7 @@ TEST_F(ContractCallQueryIntegrationTest, ExecuteContractCallQuery) ContractId contractId; ASSERT_NO_THROW(contractId = ContractCreateTransaction() - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.").toBytes()) .setBytecodeFileId(fileId) @@ -97,7 +97,7 @@ TEST_F(ContractCallQueryIntegrationTest, CannotCallContractFunctionWhenContractF "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137"); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -105,7 +105,7 @@ TEST_F(ContractCallQueryIntegrationTest, CannotCallContractFunctionWhenContractF ContractId contractId; ASSERT_NO_THROW(contractId = ContractCreateTransaction() - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.").toBytes()) .setBytecodeFileId(fileId) @@ -136,7 +136,7 @@ TEST_F(ContractCallQueryIntegrationTest, CannotCallContractFunctionWhenGasIsNotS "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137"); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -144,7 +144,7 @@ TEST_F(ContractCallQueryIntegrationTest, CannotCallContractFunctionWhenGasIsNotS ContractId contractId; ASSERT_NO_THROW(contractId = ContractCreateTransaction() - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.").toBytes()) .setBytecodeFileId(fileId) @@ -175,7 +175,7 @@ TEST_F(ContractCallQueryIntegrationTest, CannotCallContractFunctionWhenContractI "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137"); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -183,7 +183,7 @@ TEST_F(ContractCallQueryIntegrationTest, CannotCallContractFunctionWhenContractI ContractId contractId; ASSERT_NO_THROW(contractId = ContractCreateTransaction() - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.").toBytes()) .setBytecodeFileId(fileId) diff --git a/sdk/tests/integration/ContractCreateFlowIntegrationTest.cc b/sdk/tests/integration/ContractCreateFlowIntegrationTest.cc index 44445c5a2..1735f7f4e 100644 --- a/sdk/tests/integration/ContractCreateFlowIntegrationTest.cc +++ b/sdk/tests/integration/ContractCreateFlowIntegrationTest.cc @@ -18,7 +18,6 @@ * */ #include "BaseIntegrationTest.h" -#include "Client.h" #include "ContractCreateFlow.h" #include "ContractDeleteTransaction.h" #include "ContractFunctionParameters.h" @@ -46,7 +45,7 @@ TEST_F(ContractCreateFlowIntegrationTest, ExecuteContractCreateFlow) TransactionResponse txResponse; ASSERT_NO_THROW(txResponse = ContractCreateFlow() .setBytecode(getTestSmartContractBytecode()) - .setAdminKey(getTestClient().getOperatorPublicKey().get()) + .setAdminKey(getTestClient().getOperatorPublicKey()) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.")) .execute(getTestClient())); @@ -71,13 +70,13 @@ TEST_F(ContractCreateFlowIntegrationTest, ExecuteContractCreateFlow) TEST_F(ContractCreateFlowIntegrationTest, CannotCreateContractWithFlowWithoutSigning) { // Given - const std::unique_ptr adminKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr adminKey = ED25519PrivateKey::generatePrivateKey(); // When / Then EXPECT_THROW(const TransactionResponse txResponse = ContractCreateFlow() .setBytecode(getTestSmartContractBytecode()) - .setAdminKey(adminKey.get()) + .setAdminKey(adminKey) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.")) .execute(getTestClient()), @@ -88,17 +87,17 @@ TEST_F(ContractCreateFlowIntegrationTest, CannotCreateContractWithFlowWithoutSig TEST_F(ContractCreateFlowIntegrationTest, ExecuteContractCreateFlowWithPrivateKey) { // Given - const std::unique_ptr adminKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr adminKey = ED25519PrivateKey::generatePrivateKey(); // When TransactionResponse txResponse; EXPECT_NO_THROW(txResponse = ContractCreateFlow() .setBytecode(getTestSmartContractBytecode()) - .setAdminKey(adminKey.get()) + .setAdminKey(adminKey) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.")) .freezeWith(getTestClient()) - .sign(adminKey.get()) + .sign(adminKey) .execute(getTestClient())); // Then @@ -114,7 +113,7 @@ TEST_F(ContractCreateFlowIntegrationTest, ExecuteContractCreateFlowWithPrivateKe .setContractId(contractId) .setTransferAccountId(getTestClient().getOperatorAccountId().value()) .freezeWith(&getTestClient()) - .sign(adminKey.get()) + .sign(adminKey) .execute(getTestClient()) .getReceipt(getTestClient())); } @@ -123,14 +122,14 @@ TEST_F(ContractCreateFlowIntegrationTest, ExecuteContractCreateFlowWithPrivateKe TEST_F(ContractCreateFlowIntegrationTest, ExecuteContractCreateFlowWithPublicKeyAndTransactionSigner) { // Given - const std::unique_ptr adminKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr adminKey = ED25519PrivateKey::generatePrivateKey(); // When TransactionResponse txResponse; EXPECT_NO_THROW(txResponse = ContractCreateFlow() .setBytecode(getTestSmartContractBytecode()) - .setAdminKey(adminKey.get()) + .setAdminKey(adminKey) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.")) .freezeWith(getTestClient()) @@ -151,7 +150,7 @@ TEST_F(ContractCreateFlowIntegrationTest, ExecuteContractCreateFlowWithPublicKey .setContractId(contractId) .setTransferAccountId(getTestClient().getOperatorAccountId().value()) .freezeWith(&getTestClient()) - .sign(adminKey.get()) + .sign(adminKey) .execute(getTestClient()) .getReceipt(getTestClient())); } \ No newline at end of file diff --git a/sdk/tests/integration/ContractCreateTransactionIntegrationTests.cc b/sdk/tests/integration/ContractCreateTransactionIntegrationTests.cc index 1b6c66592..cc0d4c96a 100644 --- a/sdk/tests/integration/ContractCreateTransactionIntegrationTests.cc +++ b/sdk/tests/integration/ContractCreateTransactionIntegrationTests.cc @@ -19,7 +19,6 @@ */ #include "AccountId.h" #include "BaseIntegrationTest.h" -#include "Client.h" #include "ContractCreateTransaction.h" #include "ContractDeleteTransaction.h" #include "ContractFunctionParameters.h" @@ -55,7 +54,7 @@ TEST_F(ContractCreateTransactionIntegrationTest, ExecuteContractCreateTransactio const std::chrono::duration autoRenewPeriod = std::chrono::hours(2016); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -66,7 +65,7 @@ TEST_F(ContractCreateTransactionIntegrationTest, ExecuteContractCreateTransactio EXPECT_NO_THROW(contractId = ContractCreateTransaction() .setBytecodeFileId(fileId) - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setGas(100000ULL) .setAutoRenewPeriod(autoRenewPeriod) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.").toBytes()) @@ -109,7 +108,7 @@ TEST_F(ContractCreateTransactionIntegrationTest, CreateContractWithNoAdminKey) const std::chrono::duration autoRenewPeriod = std::chrono::hours(2016); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -154,7 +153,7 @@ TEST_F(ContractCreateTransactionIntegrationTest, CannotCreateContractWithNoGas) "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137"); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -163,7 +162,7 @@ TEST_F(ContractCreateTransactionIntegrationTest, CannotCreateContractWithNoGas) // When / Then EXPECT_THROW(const TransactionReceipt txReceipt = ContractCreateTransaction() - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.").toBytes()) .setBytecodeFileId(fileId) .setMemo("[e2e::ContractCreateTransaction]") @@ -184,7 +183,7 @@ TEST_F(ContractCreateTransactionIntegrationTest, CannotCreateContractWithNoConst "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137"); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -192,7 +191,7 @@ TEST_F(ContractCreateTransactionIntegrationTest, CannotCreateContractWithNoConst // When / Then EXPECT_THROW(const TransactionReceipt txReceipt = ContractCreateTransaction() - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setGas(100000ULL) .setBytecodeFileId(fileId) .setMemo("[e2e::ContractCreateTransaction]") diff --git a/sdk/tests/integration/ContractDeleteTransactionIntegrationTests.cc b/sdk/tests/integration/ContractDeleteTransactionIntegrationTests.cc index e8d7cbee4..55cbb0878 100644 --- a/sdk/tests/integration/ContractDeleteTransactionIntegrationTests.cc +++ b/sdk/tests/integration/ContractDeleteTransactionIntegrationTests.cc @@ -19,7 +19,6 @@ */ #include "AccountId.h" #include "BaseIntegrationTest.h" -#include "Client.h" #include "ContractCreateTransaction.h" #include "ContractDeleteTransaction.h" #include "ContractFunctionParameters.h" @@ -50,7 +49,7 @@ TEST_F(ContractDeleteTransactionIntegrationTest, DeleteContractWithAdminKey) ASSERT_NO_THROW(contractId = ContractCreateTransaction() .setBytecode({}) - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.").toBytes()) .execute(getTestClient()) diff --git a/sdk/tests/integration/ContractExecuteTransactionIntegrationTests.cc b/sdk/tests/integration/ContractExecuteTransactionIntegrationTests.cc index 95916cf82..6981c5eeb 100644 --- a/sdk/tests/integration/ContractExecuteTransactionIntegrationTests.cc +++ b/sdk/tests/integration/ContractExecuteTransactionIntegrationTests.cc @@ -19,7 +19,6 @@ */ #include "AccountId.h" #include "BaseIntegrationTest.h" -#include "Client.h" #include "ContractCallQuery.h" #include "ContractCreateTransaction.h" #include "ContractDeleteTransaction.h" @@ -56,7 +55,7 @@ TEST_F(ContractExecuteTransactionIntegrationTest, ExecuteContractExecuteTransact const std::string newMessage = "new message"; FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -65,7 +64,7 @@ TEST_F(ContractExecuteTransactionIntegrationTest, ExecuteContractExecuteTransact ASSERT_NO_THROW(contractId = ContractCreateTransaction() .setBytecodeFileId(fileId) - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.").toBytes()) .execute(getTestClient()) @@ -121,7 +120,7 @@ TEST_F(ContractExecuteTransactionIntegrationTest, CannotExecuteContractWithNoFun "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137"); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -130,7 +129,7 @@ TEST_F(ContractExecuteTransactionIntegrationTest, CannotExecuteContractWithNoFun ASSERT_NO_THROW(contractId = ContractCreateTransaction() .setBytecodeFileId(fileId) - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.").toBytes()) .execute(getTestClient()) @@ -164,7 +163,7 @@ TEST_F(ContractExecuteTransactionIntegrationTest, CannotExecuteContractWithNoGas "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137"); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -173,7 +172,7 @@ TEST_F(ContractExecuteTransactionIntegrationTest, CannotExecuteContractWithNoGas ASSERT_NO_THROW(contractId = ContractCreateTransaction() .setBytecodeFileId(fileId) - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.").toBytes()) .execute(getTestClient()) diff --git a/sdk/tests/integration/ContractInfoQueryIntegrationTests.cc b/sdk/tests/integration/ContractInfoQueryIntegrationTests.cc index 5ac6e118b..b89136063 100644 --- a/sdk/tests/integration/ContractInfoQueryIntegrationTests.cc +++ b/sdk/tests/integration/ContractInfoQueryIntegrationTests.cc @@ -52,7 +52,7 @@ TEST_F(ContractInfoQueryIntegrationTest, ExecuteContractInfoQuery) const std::string memo = "[e2e::Contract]"; FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -60,7 +60,7 @@ TEST_F(ContractInfoQueryIntegrationTest, ExecuteContractInfoQuery) ContractId contractId; ASSERT_NO_THROW(contractId = ContractCreateTransaction() - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.").toBytes()) .setBytecodeFileId(fileId) @@ -102,7 +102,7 @@ TEST_F(ContractInfoQueryIntegrationTest, CanQueryContractInfoWhenAdminKeyIsNull) const std::string memo = "[e2e::Contract]"; FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) diff --git a/sdk/tests/integration/ContractNonceInfoIntegrationTest.cc b/sdk/tests/integration/ContractNonceInfoIntegrationTest.cc index 6d730af3f..dfe2af7e7 100644 --- a/sdk/tests/integration/ContractNonceInfoIntegrationTest.cc +++ b/sdk/tests/integration/ContractNonceInfoIntegrationTest.cc @@ -65,7 +65,7 @@ TEST_F(ContractNonceInfoIntegrationTest, ContractADeploysContractBInConstructor) FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestBytecodeHexWithContractNonceInfo())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -73,7 +73,7 @@ TEST_F(ContractNonceInfoIntegrationTest, ContractADeploysContractBInConstructor) TransactionResponse response; ASSERT_NO_THROW(response = ContractCreateTransaction() - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setGas(100000ULL) .setBytecodeFileId(fileId) .setMemo(memo) diff --git a/sdk/tests/integration/ContractUpdateTransactionIntegrationTests.cc b/sdk/tests/integration/ContractUpdateTransactionIntegrationTests.cc index cec18422a..e7030dd3e 100644 --- a/sdk/tests/integration/ContractUpdateTransactionIntegrationTests.cc +++ b/sdk/tests/integration/ContractUpdateTransactionIntegrationTests.cc @@ -19,7 +19,6 @@ */ #include "AccountId.h" #include "BaseIntegrationTest.h" -#include "Client.h" #include "ContractCreateTransaction.h" #include "ContractDeleteTransaction.h" #include "ContractFunctionParameters.h" @@ -53,12 +52,12 @@ TEST_F(ContractUpdateTransactionIntegrationTest, ExecuteContractUpdateTransactio // Given const std::unique_ptr operatorKey = ED25519PrivateKey::fromString( "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137"); - const std::unique_ptr newAdminKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr newAdminKey = ED25519PrivateKey::generatePrivateKey(); const auto newAutoRenewPeriod = std::chrono::hours(2016); const std::string newMemo = "[e2e::ContractUpdateTransaction]"; FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -67,7 +66,7 @@ TEST_F(ContractUpdateTransactionIntegrationTest, ExecuteContractUpdateTransactio EXPECT_NO_THROW(contractId = ContractCreateTransaction() .setBytecodeFileId(fileId) - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.").toBytes()) .setAutoRenewAccountId(AccountId(2ULL)) @@ -80,12 +79,12 @@ TEST_F(ContractUpdateTransactionIntegrationTest, ExecuteContractUpdateTransactio TransactionReceipt txReceipt; EXPECT_NO_THROW(txReceipt = ContractUpdateTransaction() .setContractId(contractId) - .setAdminKey(newAdminKey->getPublicKey().get()) + .setAdminKey(newAdminKey->getPublicKey()) .setAutoRenewPeriod(newAutoRenewPeriod) .setContractMemo(newMemo) .setDeclineStakingReward(true) .freezeWith(&getTestClient()) - .sign(newAdminKey.get()) + .sign(newAdminKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -104,7 +103,7 @@ TEST_F(ContractUpdateTransactionIntegrationTest, ExecuteContractUpdateTransactio .setContractId(contractId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(newAdminKey.get()) + .sign(newAdminKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(txReceipt = @@ -128,7 +127,7 @@ TEST_F(ContractUpdateTransactionIntegrationTest, CannotModifyImmutableContract) "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137"); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(internal::Utilities::stringToByteVector(getTestSmartContractBytecode())) .execute(getTestClient()) .getReceipt(getTestClient()) diff --git a/sdk/tests/integration/FileAppendTransactionIntegrationTests.cc b/sdk/tests/integration/FileAppendTransactionIntegrationTests.cc index 1de8cd9cb..d34741c0b 100644 --- a/sdk/tests/integration/FileAppendTransactionIntegrationTests.cc +++ b/sdk/tests/integration/FileAppendTransactionIntegrationTests.cc @@ -52,7 +52,7 @@ TEST_F(FileAppendTransactionIntegrationTest, ExecuteFileAppendTransaction) ASSERT_NO_THROW(origContents = internal::Utilities::stringToByteVector("Hedera is great!")); ASSERT_NO_THROW(appendedContents = internal::Utilities::stringToByteVector(" It is also awesome!")); ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(origContents) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -227,7 +227,7 @@ TEST_F(FileAppendTransactionIntegrationTest, CanAppendLargeContents) "aliquam maximus, velit ipsum laoreet ligula, id ullamcorper lacus nibh eget nisl. Donec eget lacus venenatis " "enim consequat auctor vel in.\n")); ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(origContents) .execute(getTestClient()) .getReceipt(getTestClient()) diff --git a/sdk/tests/integration/FileContentsQueryIntegrationTest.cc b/sdk/tests/integration/FileContentsQueryIntegrationTest.cc index 09081097f..a250f234b 100644 --- a/sdk/tests/integration/FileContentsQueryIntegrationTest.cc +++ b/sdk/tests/integration/FileContentsQueryIntegrationTest.cc @@ -49,7 +49,7 @@ TEST_F(FileContentsQueryIntegrationTest, ExecuteFileContentsQuery) "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137"); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(getTestFileContents()) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -75,7 +75,7 @@ TEST_F(FileContentsQueryIntegrationTest, CanQueryEmptyFileContents) "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137"); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .execute(getTestClient()) .getReceipt(getTestClient()) .mFileId.value()); diff --git a/sdk/tests/integration/FileCreateTransactionIntegrationTests.cc b/sdk/tests/integration/FileCreateTransactionIntegrationTests.cc index cea2783b3..5723a05be 100644 --- a/sdk/tests/integration/FileCreateTransactionIntegrationTests.cc +++ b/sdk/tests/integration/FileCreateTransactionIntegrationTests.cc @@ -50,7 +50,7 @@ TEST_F(FileCreateTransactionIntegrationTest, ExecuteFileCreateTransaction) ASSERT_NO_THROW(contents = internal::Utilities::stringToByteVector("[e2e::FileCreateTransaction]")); const std::string memo = "test file memo"; - const KeyList keys = KeyList::of({ operatorKey->getPublicKey().get() }); + const KeyList keys = KeyList::of({ operatorKey->getPublicKey() }); // When TransactionReceipt txReceipt; @@ -87,7 +87,7 @@ TEST_F(FileCreateTransactionIntegrationTest, CanCreateFileWithNoContents) operatorKey = ED25519PrivateKey::fromString( "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137")); - const KeyList keys = KeyList::of({ operatorKey->getPublicKey().get() }); + const KeyList keys = KeyList::of({ operatorKey->getPublicKey() }); // When TransactionReceipt txReceipt; diff --git a/sdk/tests/integration/FileDeleteTransactionIntegrationTests.cc b/sdk/tests/integration/FileDeleteTransactionIntegrationTests.cc index b1437d4d6..5ea94f5d2 100644 --- a/sdk/tests/integration/FileDeleteTransactionIntegrationTests.cc +++ b/sdk/tests/integration/FileDeleteTransactionIntegrationTests.cc @@ -45,7 +45,7 @@ TEST_F(FileDeleteTransactionIntegrationTest, ExecuteFileDeleteTransaction) "302e020100300506032b65700422042091132178e72057a1d7528025956fe39b0b847f200ab59b2fdd367017f3087137"); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents({}) .execute(getTestClient()) .getReceipt(getTestClient()) diff --git a/sdk/tests/integration/FileInfoQueryIntegrationTests.cc b/sdk/tests/integration/FileInfoQueryIntegrationTests.cc index c68ea3317..9b932d474 100644 --- a/sdk/tests/integration/FileInfoQueryIntegrationTests.cc +++ b/sdk/tests/integration/FileInfoQueryIntegrationTests.cc @@ -18,7 +18,6 @@ * */ #include "BaseIntegrationTest.h" -#include "Client.h" #include "ED25519PrivateKey.h" #include "FileCreateTransaction.h" #include "FileDeleteTransaction.h" @@ -52,7 +51,7 @@ TEST_F(FileInfoQueryIntegrationTest, ExecuteFileInfoQuery) ASSERT_NO_THROW(contents = internal::Utilities::stringToByteVector("[e2e::FileCreateTransaction]")); const std::string memo = "test file memo"; - const KeyList keys = KeyList::of({ operatorKey->getPublicKey().get() }); + const KeyList keys = KeyList::of({ operatorKey->getPublicKey() }); FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() diff --git a/sdk/tests/integration/FileUpdateTransactionIntegrationTests.cc b/sdk/tests/integration/FileUpdateTransactionIntegrationTests.cc index d965abc06..7d24ad269 100644 --- a/sdk/tests/integration/FileUpdateTransactionIntegrationTests.cc +++ b/sdk/tests/integration/FileUpdateTransactionIntegrationTests.cc @@ -47,7 +47,7 @@ TEST_F(FileUpdateTransactionIntegrationTest, ExecuteFileUpdateTransaction) const std::string newMemo = "update file memo"; std::unique_ptr operatorKey; - std::unique_ptr newKey; + std::shared_ptr newKey; std::vector contents; std::vector newContents; FileId fileId; @@ -61,7 +61,7 @@ TEST_F(FileUpdateTransactionIntegrationTest, ExecuteFileUpdateTransaction) ASSERT_NO_THROW(contents = internal::Utilities::stringToByteVector("[e2e::FileCreateTransaction]")); ASSERT_NO_THROW(newContents = internal::Utilities::stringToByteVector("[e2e::FileUpdateTransaction]")); ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(contents) .setFileMemo(memo) .execute(getTestClient()) @@ -72,11 +72,11 @@ TEST_F(FileUpdateTransactionIntegrationTest, ExecuteFileUpdateTransaction) TransactionReceipt txReceipt; EXPECT_NO_THROW(txReceipt = FileUpdateTransaction() .setFileId(fileId) - .setKeys({ newKey->getPublicKey().get() }) + .setKeys({ newKey->getPublicKey() }) .setContents(newContents) .setFileMemo(newMemo) .freezeWith(&getTestClient()) - .sign(newKey.get()) + .sign(newKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -86,14 +86,14 @@ TEST_F(FileUpdateTransactionIntegrationTest, ExecuteFileUpdateTransaction) EXPECT_EQ(fileInfo.mSize, contents.size()); EXPECT_FALSE(fileInfo.mIsDeleted); - EXPECT_EQ(fileInfo.mAdminKeys.toBytes(), KeyList::of({ newKey->getPublicKey().get() }).toBytes()); + EXPECT_EQ(fileInfo.mAdminKeys.toBytes(), KeyList::of({ newKey->getPublicKey() }).toBytes()); EXPECT_EQ(fileInfo.mMemo, newMemo); // Clean up ASSERT_NO_THROW(txReceipt = FileDeleteTransaction() .setFileId(fileId) .freezeWith(&getTestClient()) - .sign(newKey.get()) + .sign(newKey) .execute(getTestClient()) .getReceipt(getTestClient())); } diff --git a/sdk/tests/integration/FreezeTransactionIntegrationTest.cc b/sdk/tests/integration/FreezeTransactionIntegrationTest.cc index 1bea88618..ffd190a5f 100644 --- a/sdk/tests/integration/FreezeTransactionIntegrationTest.cc +++ b/sdk/tests/integration/FreezeTransactionIntegrationTest.cc @@ -27,8 +27,6 @@ #include "PrivateKey.h" #include "TransactionReceipt.h" #include "TransactionResponse.h" -#include "exceptions/ReceiptStatusException.h" -#include "impl/Utilities.h" #include @@ -49,7 +47,7 @@ TEST_F(FreezeTransactionIntegrationTest, DISABLED_ExecuteFreezeTransaction) FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .execute(getTestClient()) .getReceipt(getTestClient()) .mFileId.value()); diff --git a/sdk/tests/integration/ScheduleCreateTransactionIntegrationTests.cc b/sdk/tests/integration/ScheduleCreateTransactionIntegrationTests.cc index e908ac261..4d0b6d28d 100644 --- a/sdk/tests/integration/ScheduleCreateTransactionIntegrationTests.cc +++ b/sdk/tests/integration/ScheduleCreateTransactionIntegrationTests.cc @@ -19,7 +19,6 @@ */ #include "AccountCreateTransaction.h" #include "BaseIntegrationTest.h" -#include "Client.h" #include "ED25519PrivateKey.h" #include "PrivateKey.h" #include "ScheduleCreateTransaction.h" @@ -53,7 +52,7 @@ TEST_F(ScheduleCreateTransactionIntegrationTest, ExecuteScheduleCreateTransactio AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(newKey.get()) + .setKey(newKey) .setInitialBalance(Hbar(10LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -79,13 +78,13 @@ TEST_F(ScheduleCreateTransactionIntegrationTest, ExecuteScheduleCreateTransactio ScheduleInfoQuery().setScheduleId(txReceipt.mScheduleId.value()).execute(getTestClient())); // Clean up - ASSERT_NO_THROW(const TransactionReceipt txReceipt = AccountDeleteTransaction() - .setDeleteAccountId(accountId) - .setTransferAccountId(AccountId(2ULL)) - .freezeWith(&getTestClient()) - .sign(newKey.get()) - .execute(getTestClient()) - .getReceipt(getTestClient())); + ASSERT_NO_THROW(txReceipt = AccountDeleteTransaction() + .setDeleteAccountId(accountId) + .setTransferAccountId(AccountId(2ULL)) + .freezeWith(&getTestClient()) + .sign(newKey) + .execute(getTestClient()) + .getReceipt(getTestClient())); } //----- @@ -101,7 +100,7 @@ TEST_F(ScheduleCreateTransactionIntegrationTest, CanCreateScheduleCreateTransact AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(newKey.get()) + .setKey(newKey) .setInitialBalance(Hbar(10LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -124,13 +123,13 @@ TEST_F(ScheduleCreateTransactionIntegrationTest, CanCreateScheduleCreateTransact // TODO: ScheduleInfoQuery // Clean up - ASSERT_NO_THROW(const TransactionReceipt txReceipt = AccountDeleteTransaction() - .setDeleteAccountId(accountId) - .setTransferAccountId(AccountId(2ULL)) - .freezeWith(&getTestClient()) - .sign(newKey.get()) - .execute(getTestClient()) - .getReceipt(getTestClient())); + ASSERT_NO_THROW(txReceipt = AccountDeleteTransaction() + .setDeleteAccountId(accountId) + .setTransferAccountId(AccountId(2ULL)) + .freezeWith(&getTestClient()) + .sign(newKey) + .execute(getTestClient()) + .getReceipt(getTestClient())); } //----- @@ -146,7 +145,7 @@ TEST_F(ScheduleCreateTransactionIntegrationTest, CannotScheduleTwoIdenticalTrans AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(newKey.get()) + .setKey(newKey) .setInitialBalance(Hbar(10LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -179,7 +178,7 @@ TEST_F(ScheduleCreateTransactionIntegrationTest, CannotScheduleTwoIdenticalTrans .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(newKey.get()) + .sign(newKey) .execute(getTestClient()) .getReceipt(getTestClient())); } diff --git a/sdk/tests/integration/ScheduleDeleteTransactionIntegrationTests.cc b/sdk/tests/integration/ScheduleDeleteTransactionIntegrationTests.cc index ec1eb990f..aa0bc0788 100644 --- a/sdk/tests/integration/ScheduleDeleteTransactionIntegrationTests.cc +++ b/sdk/tests/integration/ScheduleDeleteTransactionIntegrationTests.cc @@ -54,7 +54,7 @@ TEST_F(ScheduleDeleteTransactionIntegrationTest, ExecuteScheduleDeleteTransactio AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(newKey.get()) + .setKey(newKey) .setInitialBalance(Hbar(10LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -81,7 +81,7 @@ TEST_F(ScheduleDeleteTransactionIntegrationTest, ExecuteScheduleDeleteTransactio .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(newKey.get()) + .sign(newKey) .execute(getTestClient()) .getReceipt(getTestClient())); } @@ -99,7 +99,7 @@ TEST_F(ScheduleDeleteTransactionIntegrationTest, CannotDeleteImmutableSchedule) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(newKey.get()) + .setKey(newKey) .setInitialBalance(Hbar(10LL)) .execute(getTestClient()) .getReceipt(getTestClient()) diff --git a/sdk/tests/integration/ScheduleInfoQueryIntegrationTests.cc b/sdk/tests/integration/ScheduleInfoQueryIntegrationTests.cc index ff2a2b963..db40da0a1 100644 --- a/sdk/tests/integration/ScheduleInfoQueryIntegrationTests.cc +++ b/sdk/tests/integration/ScheduleInfoQueryIntegrationTests.cc @@ -54,7 +54,7 @@ TEST_F(ScheduleInfoQueryIntegrationTest, ExecuteScheduleInfoQuery) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(newKey.get()) + .setKey(newKey) .setInitialBalance(Hbar(10LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -96,7 +96,7 @@ TEST_F(ScheduleInfoQueryIntegrationTest, ExecuteScheduleInfoQuery) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(newKey.get()) + .sign(newKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW( diff --git a/sdk/tests/integration/ScheduleSignTransactionIntegrationTests.cc b/sdk/tests/integration/ScheduleSignTransactionIntegrationTests.cc index 683bc6501..b5e5cd03e 100644 --- a/sdk/tests/integration/ScheduleSignTransactionIntegrationTests.cc +++ b/sdk/tests/integration/ScheduleSignTransactionIntegrationTests.cc @@ -23,7 +23,6 @@ #include "ECDSAsecp256k1PrivateKey.h" #include "ED25519PrivateKey.h" #include "ScheduleCreateTransaction.h" -#include "ScheduleDeleteTransaction.h" #include "ScheduleId.h" #include "ScheduleInfo.h" #include "ScheduleInfoQuery.h" @@ -60,11 +59,11 @@ TEST_F(ScheduleSignTransactionIntegrationTest, ExecuteScheduleSignTransaction) ASSERT_NO_THROW(newKey2 = ED25519PrivateKey::generatePrivateKey()); ASSERT_NO_THROW(newKey3 = ED25519PrivateKey::generatePrivateKey()); - const KeyList keyList = KeyList::of({ newKey1.get(), newKey2.get(), newKey3.get() }); + const auto keyList = std::make_shared(KeyList::of({ newKey1, newKey2, newKey3 })); AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(&keyList) + .setKey(keyList) .setInitialBalance(Hbar(10LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -83,9 +82,9 @@ TEST_F(ScheduleSignTransactionIntegrationTest, ExecuteScheduleSignTransaction) EXPECT_NO_THROW(const TransactionReceipt txReceipt = ScheduleSignTransaction() .setScheduleId(scheduleId) .freezeWith(&getTestClient()) - .sign(newKey1.get()) - .sign(newKey2.get()) - .sign(newKey3.get()) + .sign(newKey1) + .sign(newKey2) + .sign(newKey3) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -99,9 +98,9 @@ TEST_F(ScheduleSignTransactionIntegrationTest, ExecuteScheduleSignTransaction) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(newKey1.get()) - .sign(newKey2.get()) - .sign(newKey3.get()) + .sign(newKey1) + .sign(newKey2) + .sign(newKey3) .execute(getTestClient()) .getReceipt(getTestClient())); } diff --git a/sdk/tests/integration/SystemDeleteTransactionIntegrationTests.cc b/sdk/tests/integration/SystemDeleteTransactionIntegrationTests.cc index 0c5568903..c414fa473 100644 --- a/sdk/tests/integration/SystemDeleteTransactionIntegrationTests.cc +++ b/sdk/tests/integration/SystemDeleteTransactionIntegrationTests.cc @@ -31,7 +31,6 @@ #include "TransactionRecord.h" #include "TransactionResponse.h" #include "exceptions/PrecheckStatusException.h" -#include "exceptions/ReceiptStatusException.h" #include #include @@ -53,7 +52,7 @@ TEST_F(SystemDeleteTransactionIntegrationTest, DeleteFile) FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey.get() }) + .setKeys({ operatorKey }) .setContents(getTestFileContent()) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -78,7 +77,7 @@ TEST_F(SystemDeleteTransactionIntegrationTest, DeleteContract) FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey.get() }) + .setKeys({ operatorKey }) .setContents(getTestFileContent()) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -87,7 +86,7 @@ TEST_F(SystemDeleteTransactionIntegrationTest, DeleteContract) ContractId contractId; ASSERT_NO_THROW(contractId = ContractCreateTransaction() - .setAdminKey(operatorKey.get()) + .setAdminKey(operatorKey) .setGas(100000ULL) .setConstructorParameters(ContractFunctionParameters().addString("Hello from Hedera.").toBytes()) .setBytecodeFileId(fileId) diff --git a/sdk/tests/integration/SystemUndeleteTransactionIntegrationTests.cc b/sdk/tests/integration/SystemUndeleteTransactionIntegrationTests.cc index d2c27bf43..f4ede41ce 100644 --- a/sdk/tests/integration/SystemUndeleteTransactionIntegrationTests.cc +++ b/sdk/tests/integration/SystemUndeleteTransactionIntegrationTests.cc @@ -49,7 +49,7 @@ TEST_F(SystemUndeleteTransactionIntegrationTest, UndeleteFile) FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey.get() }) + .setKeys({ operatorKey }) .setContents(getTestFileContent()) .execute(getTestClient()) .getReceipt(getTestClient()) diff --git a/sdk/tests/integration/TokenAssociateTransactionIntegrationTests.cc b/sdk/tests/integration/TokenAssociateTransactionIntegrationTests.cc index 4c7cfa9de..587f7c366 100644 --- a/sdk/tests/integration/TokenAssociateTransactionIntegrationTests.cc +++ b/sdk/tests/integration/TokenAssociateTransactionIntegrationTests.cc @@ -57,7 +57,7 @@ TEST_F(TokenAssociateTransactionIntegrationTest, ExecuteTokenAssociateTransactio AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -86,7 +86,7 @@ TEST_F(TokenAssociateTransactionIntegrationTest, ExecuteTokenAssociateTransactio .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -95,7 +95,7 @@ TEST_F(TokenAssociateTransactionIntegrationTest, ExecuteTokenAssociateTransactio .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = @@ -118,7 +118,7 @@ TEST_F(TokenAssociateTransactionIntegrationTest, CanAssociateAccountWithNoTokens AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -128,7 +128,7 @@ TEST_F(TokenAssociateTransactionIntegrationTest, CanAssociateAccountWithNoTokens EXPECT_NO_THROW(const TransactionReceipt txReceipt = TokenAssociateTransaction() .setAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -137,7 +137,7 @@ TEST_F(TokenAssociateTransactionIntegrationTest, CanAssociateAccountWithNoTokens .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); } @@ -167,7 +167,7 @@ TEST_F(TokenAssociateTransactionIntegrationTest, CannotAssociateTokensWhenAccoun AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -203,7 +203,7 @@ TEST_F(TokenAssociateTransactionIntegrationTest, CannotAssociateTokensWhenAccoun .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = diff --git a/sdk/tests/integration/TokenBurnTransactionIntegrationTests.cc b/sdk/tests/integration/TokenBurnTransactionIntegrationTests.cc index 2ed3cc330..128b900ae 100644 --- a/sdk/tests/integration/TokenBurnTransactionIntegrationTests.cc +++ b/sdk/tests/integration/TokenBurnTransactionIntegrationTests.cc @@ -244,7 +244,7 @@ TEST_F(TokenBurnTransactionIntegrationTest, CannotBurnNftIfNftIsNotOwnedByTreasu AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -255,7 +255,7 @@ TEST_F(TokenBurnTransactionIntegrationTest, CannotBurnNftIfNftIsNotOwnedByTreasu .setTokenIds({ tokenId }) .setAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -277,14 +277,14 @@ TEST_F(TokenBurnTransactionIntegrationTest, CannotBurnNftIfNftIsNotOwnedByTreasu ASSERT_NO_THROW(txReceipt = TransferTransaction() .addNftTransfer(nftId, accountId, AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(txReceipt = AccountDeleteTransaction() .setTransferAccountId(AccountId(2ULL)) .setDeleteAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(txReceipt = diff --git a/sdk/tests/integration/TokenCreateTransactionIntegrationTests.cc b/sdk/tests/integration/TokenCreateTransactionIntegrationTests.cc index 51aeb3d95..3e4a3249f 100644 --- a/sdk/tests/integration/TokenCreateTransactionIntegrationTests.cc +++ b/sdk/tests/integration/TokenCreateTransactionIntegrationTests.cc @@ -142,7 +142,7 @@ TEST_F(TokenCreateTransactionIntegrationTest, CannotCreateTokenWithoutTreasuryAc AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); @@ -161,7 +161,7 @@ TEST_F(TokenCreateTransactionIntegrationTest, CannotCreateTokenWithoutTreasuryAc .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); } diff --git a/sdk/tests/integration/TokenDeleteTransactionIntegrationTests.cc b/sdk/tests/integration/TokenDeleteTransactionIntegrationTests.cc index 45704c4c0..06d0d8095 100644 --- a/sdk/tests/integration/TokenDeleteTransactionIntegrationTests.cc +++ b/sdk/tests/integration/TokenDeleteTransactionIntegrationTests.cc @@ -94,7 +94,7 @@ TEST_F(TokenDeleteTransactionIntegrationTest, CannotDeleteTokenWithNoAdminKeySig .setTreasuryAccountId(AccountId(2ULL)) .setAdminKey(adminKey) .freezeWith(&getTestClient()) - .sign(adminKey.get()) + .sign(adminKey) .execute(getTestClient()) .getReceipt(getTestClient()) .mTokenId.value()); @@ -108,7 +108,7 @@ TEST_F(TokenDeleteTransactionIntegrationTest, CannotDeleteTokenWithNoAdminKeySig ASSERT_NO_THROW(const TransactionReceipt txReceipt = TokenDeleteTransaction() .setTokenId(tokenId) .freezeWith(&getTestClient()) - .sign(adminKey.get()) + .sign(adminKey) .execute(getTestClient()) .getReceipt(getTestClient())); } diff --git a/sdk/tests/integration/TokenDissociateTransactionIntegrationTests.cc b/sdk/tests/integration/TokenDissociateTransactionIntegrationTests.cc index 72a6ebeef..6ff14a36e 100644 --- a/sdk/tests/integration/TokenDissociateTransactionIntegrationTests.cc +++ b/sdk/tests/integration/TokenDissociateTransactionIntegrationTests.cc @@ -56,7 +56,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, ExecuteTokenDissociateTransact AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -84,7 +84,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, ExecuteTokenDissociateTransact .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -93,7 +93,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, ExecuteTokenDissociateTransact .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -102,7 +102,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, ExecuteTokenDissociateTransact .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(txReceipt = @@ -123,7 +123,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, CanDissociateNoTokens) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -134,7 +134,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, CanDissociateNoTokens) EXPECT_NO_THROW(txReceipt = TokenDissociateTransaction() .setAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -143,7 +143,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, CanDissociateNoTokens) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); } @@ -162,7 +162,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, CannotDissociateWithNoAccountI AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -172,7 +172,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, CannotDissociateWithNoAccountI TransactionReceipt txReceipt; EXPECT_THROW(txReceipt = TokenDissociateTransaction() .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient()), PrecheckStatusException); // INVALID_ACCOUNT_ID @@ -182,7 +182,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, CannotDissociateWithNoAccountI .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); } @@ -201,7 +201,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, CannotDissociateIfDissociating AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -229,7 +229,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, CannotDissociateIfDissociating .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -246,7 +246,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, CannotDissociateIfDissociating .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(txReceipt = @@ -267,7 +267,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, CannotDissociateIfNotAssociate AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -296,7 +296,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, CannotDissociateIfNotAssociate .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient()), ReceiptStatusException); // TOKEN_NOT_ASSOCIATED_TO_ACCOUNT @@ -306,7 +306,7 @@ TEST_F(TokenDissociateTransactionIntegrationTest, CannotDissociateIfNotAssociate .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(txReceipt = diff --git a/sdk/tests/integration/TokenFreezeTransactionIntegrationTests.cc b/sdk/tests/integration/TokenFreezeTransactionIntegrationTests.cc index f2e5c8edf..b83593631 100644 --- a/sdk/tests/integration/TokenFreezeTransactionIntegrationTests.cc +++ b/sdk/tests/integration/TokenFreezeTransactionIntegrationTests.cc @@ -57,7 +57,7 @@ TEST_F(TokenFreezeTransactionIntegrationTest, ExecuteTokenFreezeTransaction) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -79,7 +79,7 @@ TEST_F(TokenFreezeTransactionIntegrationTest, ExecuteTokenFreezeTransaction) .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -88,7 +88,7 @@ TEST_F(TokenFreezeTransactionIntegrationTest, ExecuteTokenFreezeTransaction) .setAccountId(accountId) .setTokenId(tokenId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -105,7 +105,7 @@ TEST_F(TokenFreezeTransactionIntegrationTest, ExecuteTokenFreezeTransaction) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = @@ -126,7 +126,7 @@ TEST_F(TokenFreezeTransactionIntegrationTest, CannotFreezeWithNoTokenId) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -136,7 +136,7 @@ TEST_F(TokenFreezeTransactionIntegrationTest, CannotFreezeWithNoTokenId) EXPECT_THROW(const TransactionReceipt txReceipt = TokenFreezeTransaction() .setAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient()), PrecheckStatusException); // INVALID_TOKEN_ID @@ -146,7 +146,7 @@ TEST_F(TokenFreezeTransactionIntegrationTest, CannotFreezeWithNoTokenId) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); } @@ -197,7 +197,7 @@ TEST_F(TokenFreezeTransactionIntegrationTest, CannotFreezeTokenOnAccountWithNoAs AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -220,7 +220,7 @@ TEST_F(TokenFreezeTransactionIntegrationTest, CannotFreezeTokenOnAccountWithNoAs .setAccountId(accountId) .setTokenId(tokenId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient()), ReceiptStatusException); // TOKEN_NOT_ASSOCIATED_TO_ACCOUNT @@ -230,7 +230,7 @@ TEST_F(TokenFreezeTransactionIntegrationTest, CannotFreezeTokenOnAccountWithNoAs .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = diff --git a/sdk/tests/integration/TokenGrantKycTransactionIntegrationTests.cc b/sdk/tests/integration/TokenGrantKycTransactionIntegrationTests.cc index ab83b7df5..01586ab61 100644 --- a/sdk/tests/integration/TokenGrantKycTransactionIntegrationTests.cc +++ b/sdk/tests/integration/TokenGrantKycTransactionIntegrationTests.cc @@ -54,7 +54,7 @@ TEST_F(TokenGrantKycTransactionIntegrationTest, ExecuteTokenGrantKycTransaction) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -75,7 +75,7 @@ TEST_F(TokenGrantKycTransactionIntegrationTest, ExecuteTokenGrantKycTransaction) .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -84,7 +84,7 @@ TEST_F(TokenGrantKycTransactionIntegrationTest, ExecuteTokenGrantKycTransaction) .setAccountId(accountId) .setTokenId(tokenId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -93,7 +93,7 @@ TEST_F(TokenGrantKycTransactionIntegrationTest, ExecuteTokenGrantKycTransaction) .setTransferAccountId(AccountId(2ULL)) .setDeleteAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = @@ -114,7 +114,7 @@ TEST_F(TokenGrantKycTransactionIntegrationTest, CannotGrantKycToAccountWithNoTok AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -124,7 +124,7 @@ TEST_F(TokenGrantKycTransactionIntegrationTest, CannotGrantKycToAccountWithNoTok EXPECT_THROW(const TransactionReceipt txReceipt = TokenGrantKycTransaction() .setAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient()), PrecheckStatusException); // INVALID_TOKEN_ID @@ -134,7 +134,7 @@ TEST_F(TokenGrantKycTransactionIntegrationTest, CannotGrantKycToAccountWithNoTok .setTransferAccountId(AccountId(2ULL)) .setDeleteAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); } @@ -184,7 +184,7 @@ TEST_F(TokenGrantKycTransactionIntegrationTest, CannotGrantKycToAccountOnTokenIf AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -206,7 +206,7 @@ TEST_F(TokenGrantKycTransactionIntegrationTest, CannotGrantKycToAccountOnTokenIf .setAccountId(accountId) .setTokenId(tokenId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient()), ReceiptStatusException); // TOKEN_NOT_ASSOCIATED_TO_ACCOUNT @@ -216,7 +216,7 @@ TEST_F(TokenGrantKycTransactionIntegrationTest, CannotGrantKycToAccountOnTokenIf .setTransferAccountId(AccountId(2ULL)) .setDeleteAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = diff --git a/sdk/tests/integration/TokenInfoQueryIntegrationTests.cc b/sdk/tests/integration/TokenInfoQueryIntegrationTests.cc index 03b73b5af..ce336a085 100644 --- a/sdk/tests/integration/TokenInfoQueryIntegrationTests.cc +++ b/sdk/tests/integration/TokenInfoQueryIntegrationTests.cc @@ -88,7 +88,7 @@ TEST_F(TokenInfoQueryIntegrationTest, ExecuteTokenInfoQuery) .setCustomFees(customFees) .setPauseKey(pauseKey) .freezeWith(&getTestClient()) - .sign(adminKey.get()) + .sign(adminKey) .execute(getTestClient()) .getReceipt(getTestClient()) .mTokenId.value()); @@ -131,7 +131,7 @@ TEST_F(TokenInfoQueryIntegrationTest, ExecuteTokenInfoQuery) ASSERT_NO_THROW(const TransactionReceipt txReceipt = TokenDeleteTransaction() .setTokenId(tokenId) .freezeWith(&getTestClient()) - .sign(adminKey.get()) + .sign(adminKey) .execute(getTestClient()) .getReceipt(getTestClient())); } diff --git a/sdk/tests/integration/TokenPauseTransactionIntegrationTests.cc b/sdk/tests/integration/TokenPauseTransactionIntegrationTests.cc index 60c0dde76..9fd94db9c 100644 --- a/sdk/tests/integration/TokenPauseTransactionIntegrationTests.cc +++ b/sdk/tests/integration/TokenPauseTransactionIntegrationTests.cc @@ -18,7 +18,6 @@ * */ #include "AccountCreateTransaction.h" -#include "AccountDeleteTransaction.h" #include "AccountId.h" #include "BaseIntegrationTest.h" #include "Client.h" @@ -26,7 +25,6 @@ #include "PrivateKey.h" #include "TokenAssociateTransaction.h" #include "TokenCreateTransaction.h" -#include "TokenDeleteTransaction.h" #include "TokenPauseTransaction.h" #include "TransactionReceipt.h" #include "TransactionResponse.h" @@ -59,7 +57,7 @@ TEST_F(TokenPauseTransactionIntegrationTest, ExecuteTokenPauseTransaction) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() .setInitialBalance(Hbar(1LL)) - .setKey(accountKey.get()) + .setKey(accountKey) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); @@ -80,7 +78,7 @@ TEST_F(TokenPauseTransactionIntegrationTest, ExecuteTokenPauseTransaction) .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -99,7 +97,7 @@ TEST_F(TokenPauseTransactionIntegrationTest, ExecuteTokenPauseTransaction) .addTokenTransfer(tokenId, accountId, -amount) .addTokenTransfer(tokenId, AccountId(2ULL), amount) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient()), ReceiptStatusException); // TOKEN_IS_PAUSED diff --git a/sdk/tests/integration/TokenRevokeKycTransactionIntegrationTests.cc b/sdk/tests/integration/TokenRevokeKycTransactionIntegrationTests.cc index a2f3f5156..7600feea8 100644 --- a/sdk/tests/integration/TokenRevokeKycTransactionIntegrationTests.cc +++ b/sdk/tests/integration/TokenRevokeKycTransactionIntegrationTests.cc @@ -54,7 +54,7 @@ TEST_F(TokenRevokeKycTransactionIntegrationTest, ExecuteTokenRevokeKycTransactio AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -75,7 +75,7 @@ TEST_F(TokenRevokeKycTransactionIntegrationTest, ExecuteTokenRevokeKycTransactio .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -84,7 +84,7 @@ TEST_F(TokenRevokeKycTransactionIntegrationTest, ExecuteTokenRevokeKycTransactio .setAccountId(accountId) .setTokenId(tokenId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -93,7 +93,7 @@ TEST_F(TokenRevokeKycTransactionIntegrationTest, ExecuteTokenRevokeKycTransactio .setTransferAccountId(AccountId(2ULL)) .setDeleteAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = @@ -114,7 +114,7 @@ TEST_F(TokenRevokeKycTransactionIntegrationTest, CannotRevokeKycToAccountWithNoT AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -124,7 +124,7 @@ TEST_F(TokenRevokeKycTransactionIntegrationTest, CannotRevokeKycToAccountWithNoT EXPECT_THROW(const TransactionReceipt txReceipt = TokenRevokeKycTransaction() .setAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient()), PrecheckStatusException); // INVALID_TOKEN_ID @@ -134,7 +134,7 @@ TEST_F(TokenRevokeKycTransactionIntegrationTest, CannotRevokeKycToAccountWithNoT .setTransferAccountId(AccountId(2ULL)) .setDeleteAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); } @@ -184,7 +184,7 @@ TEST_F(TokenRevokeKycTransactionIntegrationTest, CannotRevokeKycToAccountOnToken AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -206,7 +206,7 @@ TEST_F(TokenRevokeKycTransactionIntegrationTest, CannotRevokeKycToAccountOnToken .setAccountId(accountId) .setTokenId(tokenId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient()), ReceiptStatusException); // TOKEN_NOT_ASSOCIATED_TO_ACCOUNT @@ -216,7 +216,7 @@ TEST_F(TokenRevokeKycTransactionIntegrationTest, CannotRevokeKycToAccountOnToken .setTransferAccountId(AccountId(2ULL)) .setDeleteAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = diff --git a/sdk/tests/integration/TokenUnfreezeTransactionIntegrationTests.cc b/sdk/tests/integration/TokenUnfreezeTransactionIntegrationTests.cc index 383d90537..f3ad56534 100644 --- a/sdk/tests/integration/TokenUnfreezeTransactionIntegrationTests.cc +++ b/sdk/tests/integration/TokenUnfreezeTransactionIntegrationTests.cc @@ -60,7 +60,7 @@ TEST_F(TokenUnfreezeTransactionIntegrationTest, ExecuteTokenUnfreezeTransaction) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -83,7 +83,7 @@ TEST_F(TokenUnfreezeTransactionIntegrationTest, ExecuteTokenUnfreezeTransaction) .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -92,7 +92,7 @@ TEST_F(TokenUnfreezeTransactionIntegrationTest, ExecuteTokenUnfreezeTransaction) .setAccountId(accountId) .setTokenId(tokenId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -115,7 +115,7 @@ TEST_F(TokenUnfreezeTransactionIntegrationTest, ExecuteTokenUnfreezeTransaction) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = @@ -136,7 +136,7 @@ TEST_F(TokenUnfreezeTransactionIntegrationTest, CannotUnfreezeWithNoTokenId) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -146,7 +146,7 @@ TEST_F(TokenUnfreezeTransactionIntegrationTest, CannotUnfreezeWithNoTokenId) EXPECT_THROW(const TransactionReceipt txReceipt = TokenUnfreezeTransaction() .setAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient()), PrecheckStatusException); // INVALID_TOKEN_ID @@ -156,7 +156,7 @@ TEST_F(TokenUnfreezeTransactionIntegrationTest, CannotUnfreezeWithNoTokenId) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); } @@ -207,7 +207,7 @@ TEST_F(TokenUnfreezeTransactionIntegrationTest, CannotUnfreezeTokenOnAccountWith AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -230,7 +230,7 @@ TEST_F(TokenUnfreezeTransactionIntegrationTest, CannotUnfreezeTokenOnAccountWith .setAccountId(accountId) .setTokenId(tokenId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient()), ReceiptStatusException); // TOKEN_NOT_ASSOCIATED_TO_ACCOUNT @@ -240,7 +240,7 @@ TEST_F(TokenUnfreezeTransactionIntegrationTest, CannotUnfreezeTokenOnAccountWith .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = diff --git a/sdk/tests/integration/TokenUnpauseTransactionIntegrationTests.cc b/sdk/tests/integration/TokenUnpauseTransactionIntegrationTests.cc index 6168f849d..d5cdcc807 100644 --- a/sdk/tests/integration/TokenUnpauseTransactionIntegrationTests.cc +++ b/sdk/tests/integration/TokenUnpauseTransactionIntegrationTests.cc @@ -59,7 +59,7 @@ TEST_F(TokenUnpauseTransactionIntegrationTest, ExecuteTokenUnpauseTransaction) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() .setInitialBalance(Hbar(2LL)) - .setKey(accountKey.get()) + .setKey(accountKey) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); @@ -81,7 +81,7 @@ TEST_F(TokenUnpauseTransactionIntegrationTest, ExecuteTokenUnpauseTransaction) .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -111,7 +111,7 @@ TEST_F(TokenUnpauseTransactionIntegrationTest, ExecuteTokenUnpauseTransaction) .setTransferAccountId(AccountId(2ULL)) .setDeleteAccountId(accountId) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); } diff --git a/sdk/tests/integration/TokenWipeTransactionIntegrationTests.cc b/sdk/tests/integration/TokenWipeTransactionIntegrationTests.cc index 2231d31d1..fe23db3a9 100644 --- a/sdk/tests/integration/TokenWipeTransactionIntegrationTests.cc +++ b/sdk/tests/integration/TokenWipeTransactionIntegrationTests.cc @@ -18,7 +18,6 @@ * */ #include "AccountCreateTransaction.h" -#include "AccountDeleteTransaction.h" #include "AccountId.h" #include "BaseIntegrationTest.h" #include "ED25519PrivateKey.h" @@ -61,7 +60,7 @@ TEST_F(TokenWipeTransactionIntegrationTest, ExecuteTokenWipeTransaction) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -87,7 +86,7 @@ TEST_F(TokenWipeTransactionIntegrationTest, ExecuteTokenWipeTransaction) .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = TokenGrantKycTransaction() @@ -128,7 +127,7 @@ TEST_F(TokenWipeTransactionIntegrationTest, CanWipeNfts) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -162,7 +161,7 @@ TEST_F(TokenWipeTransactionIntegrationTest, CanWipeNfts) .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = TokenGrantKycTransaction() @@ -203,7 +202,7 @@ TEST_F(TokenWipeTransactionIntegrationTest, CannotWipeNftsIfTheAccountDoesNotOwn AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -237,7 +236,7 @@ TEST_F(TokenWipeTransactionIntegrationTest, CannotWipeNftsIfTheAccountDoesNotOwn .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = TokenGrantKycTransaction() @@ -276,7 +275,7 @@ TEST_F(TokenWipeTransactionIntegrationTest, CannotWipeTokensIfNoAccountId) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -302,7 +301,7 @@ TEST_F(TokenWipeTransactionIntegrationTest, CannotWipeTokensIfNoAccountId) .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = TokenGrantKycTransaction() @@ -343,7 +342,7 @@ TEST_F(TokenWipeTransactionIntegrationTest, CannotWipeAccountIfNoTokenId) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -369,7 +368,7 @@ TEST_F(TokenWipeTransactionIntegrationTest, CannotWipeAccountIfNoTokenId) .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = TokenGrantKycTransaction() @@ -412,7 +411,7 @@ TEST_F(TokenWipeTransactionIntegrationTest, CanWipeAccountWithNoBalance) AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(accountKey.get()) + .setKey(accountKey) .setInitialBalance(Hbar(1LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -438,7 +437,7 @@ TEST_F(TokenWipeTransactionIntegrationTest, CanWipeAccountWithNoBalance) .setAccountId(accountId) .setTokenIds({ tokenId }) .freezeWith(&getTestClient()) - .sign(accountKey.get()) + .sign(accountKey) .execute(getTestClient()) .getReceipt(getTestClient())); ASSERT_NO_THROW(const TransactionReceipt txReceipt = TokenGrantKycTransaction() diff --git a/sdk/tests/integration/TopicUpdateTransactionIntegrationTests.cc b/sdk/tests/integration/TopicUpdateTransactionIntegrationTests.cc index c7681dbcb..478a4e161 100644 --- a/sdk/tests/integration/TopicUpdateTransactionIntegrationTests.cc +++ b/sdk/tests/integration/TopicUpdateTransactionIntegrationTests.cc @@ -70,7 +70,7 @@ TEST_F(TopicUpdateTransactionIntegrationTest, ExecuteTopicUpdateTransaction) .setAutoRenewPeriod(newAutoRenewPeriod) .setAutoRenewAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(newKey.get()) + .sign(newKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -93,7 +93,7 @@ TEST_F(TopicUpdateTransactionIntegrationTest, ExecuteTopicUpdateTransaction) ASSERT_NO_THROW(txReceipt = TopicDeleteTransaction() .setTopicId(topicId) .freezeWith(&getTestClient()) - .sign(newKey.get()) + .sign(newKey) .execute(getTestClient()) .getReceipt(getTestClient())); } diff --git a/sdk/tests/integration/TransactionIntegrationTest.cc b/sdk/tests/integration/TransactionIntegrationTest.cc index 95cc61413..5af29da8e 100644 --- a/sdk/tests/integration/TransactionIntegrationTest.cc +++ b/sdk/tests/integration/TransactionIntegrationTest.cc @@ -67,7 +67,7 @@ TEST_F(TransactionIntegrationTest, ExecuteTransactionRegenerateTransactionId) { // Given AccountCreateTransaction accountCreateTransaction = AccountCreateTransaction() - .setKey(getTestPublicKey().get()) + .setKey(getTestPublicKey()) .setTransactionId(TransactionId::generate(AccountId(2ULL))) .setValidTransactionDuration(std::chrono::seconds(30)) .freezeWith(&getTestClient()); diff --git a/sdk/tests/integration/TransactionReceiptIntegrationTest.cc b/sdk/tests/integration/TransactionReceiptIntegrationTest.cc index b2d57a1f9..086c48049 100644 --- a/sdk/tests/integration/TransactionReceiptIntegrationTest.cc +++ b/sdk/tests/integration/TransactionReceiptIntegrationTest.cc @@ -54,7 +54,7 @@ TEST_F(TransactionReceiptIntegrationTest, ExecuteAccountCreateTransactionAndChec // When TransactionReceipt txReceipt; ASSERT_NO_THROW(txReceipt = AccountCreateTransaction() - .setKey(operatorKey->getPublicKey().get()) + .setKey(operatorKey->getPublicKey()) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -84,7 +84,7 @@ TEST_F(TransactionReceiptIntegrationTest, ExecuteFileCreateTransactionAndCheckTr // When TransactionReceipt txReceipt; ASSERT_NO_THROW(txReceipt = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -112,7 +112,7 @@ TEST_F(TransactionReceiptIntegrationTest, ExecuteContractCreateTransactionAndChe FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(getTestFileContent()) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -123,7 +123,7 @@ TEST_F(TransactionReceiptIntegrationTest, ExecuteContractCreateTransactionAndChe ASSERT_NO_THROW(txReceipt = ContractCreateTransaction() .setGas(500000ULL) .setBytecodeFileId(fileId) - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setMaxTransactionFee(Hbar(16LL)) .execute(getTestClient()) .getReceipt(getTestClient())); diff --git a/sdk/tests/integration/TransactionReceiptQueryIntegrationTest.cc b/sdk/tests/integration/TransactionReceiptQueryIntegrationTest.cc index 8bdd1aa24..3d936b1f3 100644 --- a/sdk/tests/integration/TransactionReceiptQueryIntegrationTest.cc +++ b/sdk/tests/integration/TransactionReceiptQueryIntegrationTest.cc @@ -20,11 +20,7 @@ #include "AccountCreateTransaction.h" #include "AccountDeleteTransaction.h" #include "BaseIntegrationTest.h" -#include "ContractCreateTransaction.h" -#include "ContractDeleteTransaction.h" #include "ED25519PrivateKey.h" -#include "FileCreateTransaction.h" -#include "FileDeleteTransaction.h" #include "TransactionId.h" #include "TransactionReceipt.h" #include "TransactionReceiptQuery.h" @@ -46,11 +42,11 @@ class TransactionReceiptQueryIntegrationTest : public BaseIntegrationTest TEST_F(TransactionReceiptQueryIntegrationTest, CanGetTransactionReceipt) { // Given - const std::unique_ptr testPrivateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr testPrivateKey = ED25519PrivateKey::generatePrivateKey(); const std::shared_ptr testPublicKey = testPrivateKey->getPublicKey(); TransactionResponse testTxResponse; - ASSERT_NO_THROW(testTxResponse = AccountCreateTransaction().setKey(testPublicKey.get()).execute(getTestClient())); + ASSERT_NO_THROW(testTxResponse = AccountCreateTransaction().setKey(testPublicKey).execute(getTestClient())); // When / Then TransactionReceipt txReceipt; @@ -65,6 +61,6 @@ TEST_F(TransactionReceiptQueryIntegrationTest, CanGetTransactionReceipt) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(testPrivateKey.get()) + .sign(testPrivateKey) .execute(getTestClient())); } \ No newline at end of file diff --git a/sdk/tests/integration/TransactionRecordIntegrationTest.cc b/sdk/tests/integration/TransactionRecordIntegrationTest.cc index 55bf8a27d..111c9ceec 100644 --- a/sdk/tests/integration/TransactionRecordIntegrationTest.cc +++ b/sdk/tests/integration/TransactionRecordIntegrationTest.cc @@ -54,14 +54,14 @@ TEST_F(TransactionRecordIntegrationTest, ExecuteEmptyAccountCreateTransaction) TEST_F(TransactionRecordIntegrationTest, ExecuteAccountCreateTransactionAndCheckTransactionRecord) { // Given - const std::unique_ptr testPrivateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr testPrivateKey = ED25519PrivateKey::generatePrivateKey(); const auto testPublicKey = testPrivateKey->getPublicKey(); const auto testMemo = "Test memo for TransactionRecord."; // When TransactionRecord txRecord; EXPECT_NO_THROW(txRecord = AccountCreateTransaction() - .setKey(testPublicKey.get()) + .setKey(testPublicKey) .setTransactionMemo(testMemo) .execute(getTestClient()) .getRecord(getTestClient())); @@ -83,7 +83,7 @@ TEST_F(TransactionRecordIntegrationTest, ExecuteAccountCreateTransactionAndCheck .setDeleteAccountId(txRecord.mReceipt->mAccountId.value()) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(testPrivateKey.get()) + .sign(testPrivateKey) .execute(getTestClient())); } @@ -98,7 +98,7 @@ TEST_F(TransactionRecordIntegrationTest, ExecuteFileCreateTransactionAndCheckTra // When TransactionRecord txRecord; EXPECT_NO_THROW(txRecord = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setTransactionMemo(testMemo) .execute(getTestClient()) .getRecord(getTestClient())); @@ -132,7 +132,7 @@ TEST_F(TransactionRecordIntegrationTest, ExecuteContractCreateTransactionAndChec FileId fileId; ASSERT_NO_THROW(fileId = FileCreateTransaction() - .setKeys({ operatorKey->getPublicKey().get() }) + .setKeys({ operatorKey->getPublicKey() }) .setContents(getTestFileContent()) .setMaxTransactionFee(Hbar(2LL)) .execute(getTestClient()) @@ -145,7 +145,7 @@ TEST_F(TransactionRecordIntegrationTest, ExecuteContractCreateTransactionAndChec .setGas(500000ULL) .setBytecodeFileId(fileId) .setTransactionMemo(testMemo) - .setAdminKey(operatorKey->getPublicKey().get()) + .setAdminKey(operatorKey->getPublicKey()) .setMaxTransactionFee(Hbar(16LL)) .execute(getTestClient()) .getRecord(getTestClient())); diff --git a/sdk/tests/integration/TransactionRecordQueryIntegrationTest.cc b/sdk/tests/integration/TransactionRecordQueryIntegrationTest.cc index b945e67ee..ecfa60553 100644 --- a/sdk/tests/integration/TransactionRecordQueryIntegrationTest.cc +++ b/sdk/tests/integration/TransactionRecordQueryIntegrationTest.cc @@ -21,11 +21,7 @@ #include "AccountDeleteTransaction.h" #include "BaseIntegrationTest.h" #include "Client.h" -#include "ContractCreateTransaction.h" -#include "ContractDeleteTransaction.h" #include "ED25519PrivateKey.h" -#include "FileCreateTransaction.h" -#include "FileDeleteTransaction.h" #include "TransactionId.h" #include "TransactionRecord.h" #include "TransactionRecordQuery.h" @@ -45,11 +41,11 @@ class TransactionRecordQueryIntegrationTest : public BaseIntegrationTest TEST_F(TransactionRecordQueryIntegrationTest, CanGetTransactionRecord) { // Given - const std::unique_ptr testPrivateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr testPrivateKey = ED25519PrivateKey::generatePrivateKey(); const std::shared_ptr testPublicKey = testPrivateKey->getPublicKey(); TransactionResponse testTxResponse; - ASSERT_NO_THROW(testTxResponse = AccountCreateTransaction().setKey(testPublicKey.get()).execute(getTestClient())); + ASSERT_NO_THROW(testTxResponse = AccountCreateTransaction().setKey(testPublicKey).execute(getTestClient())); // When / Then TransactionRecord txRecord; @@ -61,6 +57,6 @@ TEST_F(TransactionRecordQueryIntegrationTest, CanGetTransactionRecord) .setDeleteAccountId(txRecord.mReceipt->mAccountId.value()) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(testPrivateKey.get()) + .sign(testPrivateKey) .execute(getTestClient())); } \ No newline at end of file diff --git a/sdk/tests/integration/TransferTransactionIntegrationTest.cc b/sdk/tests/integration/TransferTransactionIntegrationTest.cc index 0eb9108c7..4487f54d1 100644 --- a/sdk/tests/integration/TransferTransactionIntegrationTest.cc +++ b/sdk/tests/integration/TransferTransactionIntegrationTest.cc @@ -35,7 +35,6 @@ #include "TransferTransaction.h" #include "impl/HexConverter.h" #include "impl/TimestampConverter.h" -#include "impl/Utilities.h" #include #include @@ -77,11 +76,11 @@ TEST_F(TransferTransactionIntegrationTest, TransferNothing) TEST_F(TransferTransactionIntegrationTest, TransferOutOfNonOperatorAccount) { // Given - const std::unique_ptr privateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr privateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const Hbar amount(1LL); AccountId accountId; ASSERT_NO_THROW(accountId = AccountCreateTransaction() - .setKey(privateKey->getPublicKey().get()) + .setKey(privateKey->getPublicKey()) .setInitialBalance(Hbar(10LL)) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -93,7 +92,7 @@ TEST_F(TransferTransactionIntegrationTest, TransferOutOfNonOperatorAccount) .addHbarTransfer(AccountId(2ULL), amount) .addHbarTransfer(accountId, amount.negated()) .freezeWith(&getTestClient()) - .sign(privateKey.get()) + .sign(privateKey) .execute(getTestClient()) .getRecord(getTestClient())); @@ -105,7 +104,7 @@ TEST_F(TransferTransactionIntegrationTest, TransferOutOfNonOperatorAccount) .setDeleteAccountId(accountId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(privateKey.get()) + .sign(privateKey) .execute(getTestClient())); } @@ -113,7 +112,7 @@ TEST_F(TransferTransactionIntegrationTest, TransferOutOfNonOperatorAccount) TEST_F(TransferTransactionIntegrationTest, CanTransferHbarWithAliasID) { // Given - const std::unique_ptr privateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr privateKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const Hbar amount(1LL); const EvmAddress evmAddress = std::dynamic_pointer_cast(privateKey->getPublicKey())->toEvmAddress(); @@ -136,7 +135,7 @@ TEST_F(TransferTransactionIntegrationTest, CanTransferHbarWithAliasID) .setDeleteAccountId(aliasId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(privateKey.get()) + .sign(privateKey) .execute(getTestClient())); } @@ -144,20 +143,20 @@ TEST_F(TransferTransactionIntegrationTest, CanTransferHbarWithAliasID) TEST_F(TransferTransactionIntegrationTest, CanSpendHbarAllowance) { // Given - const std::unique_ptr allowerKey = ED25519PrivateKey::generatePrivateKey(); - const std::unique_ptr alloweeKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); + const std::shared_ptr allowerKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr alloweeKey = ECDSAsecp256k1PrivateKey::generatePrivateKey(); const Hbar balance(10LL); const Hbar amount(1LL); AccountId allowerId; AccountId alloweeId; ASSERT_NO_THROW(allowerId = AccountCreateTransaction() - .setKey(allowerKey->getPublicKey().get()) + .setKey(allowerKey->getPublicKey()) .setInitialBalance(balance) .execute(getTestClient()) .getReceipt(getTestClient()) .mAccountId.value()); ASSERT_NO_THROW(alloweeId = AccountCreateTransaction() - .setKey(alloweeKey->getPublicKey().get()) + .setKey(alloweeKey->getPublicKey()) .setInitialBalance(balance) .execute(getTestClient()) .getReceipt(getTestClient()) @@ -165,7 +164,7 @@ TEST_F(TransferTransactionIntegrationTest, CanSpendHbarAllowance) ASSERT_NO_THROW(const TransactionReceipt txReceipt = AccountAllowanceApproveTransaction() .approveHbarAllowance(allowerId, alloweeId, amount) .freezeWith(&getTestClient()) - .sign(allowerKey.get()) + .sign(allowerKey) .execute(getTestClient()) .getReceipt(getTestClient())); @@ -176,7 +175,7 @@ TEST_F(TransferTransactionIntegrationTest, CanSpendHbarAllowance) .addApprovedHbarTransfer(allowerId, amount.negated()) .setTransactionId(TransactionId::generate(alloweeId)) .freezeWith(&getTestClient()) - .sign(alloweeKey.get()) + .sign(alloweeKey) .execute(getTestClient()) .getRecord(getTestClient())); @@ -198,12 +197,12 @@ TEST_F(TransferTransactionIntegrationTest, CanSpendHbarAllowance) .setDeleteAccountId(allowerId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(allowerKey.get()) + .sign(allowerKey) .execute(getTestClient())); ASSERT_NO_THROW(AccountDeleteTransaction() .setDeleteAccountId(alloweeId) .setTransferAccountId(AccountId(2ULL)) .freezeWith(&getTestClient()) - .sign(alloweeKey.get()) + .sign(alloweeKey) .execute(getTestClient())); } diff --git a/sdk/tests/unit/AccountCreateTransactionTest.cc b/sdk/tests/unit/AccountCreateTransactionTest.cc index 2f4cee03a..9b22142c3 100644 --- a/sdk/tests/unit/AccountCreateTransactionTest.cc +++ b/sdk/tests/unit/AccountCreateTransactionTest.cc @@ -20,7 +20,6 @@ #include "AccountCreateTransaction.h" #include "Client.h" #include "Defaults.h" -#include "ECDSAsecp256k1PrivateKey.h" #include "ED25519PrivateKey.h" #include "Hbar.h" #include "PublicKey.h" @@ -136,7 +135,7 @@ TEST_F(AccountCreateTransactionTest, SetKey) AccountCreateTransaction transaction; // When - EXPECT_NO_THROW(transaction.setKey(getTestPublicKey().get())); + EXPECT_NO_THROW(transaction.setKey(getTestPublicKey())); // Then EXPECT_EQ(transaction.getKey()->toBytes(), getTestPublicKey()->toBytes()); @@ -152,7 +151,7 @@ TEST_F(AccountCreateTransactionTest, SetKeyFrozen) ASSERT_NO_THROW(transaction.freeze()); // When / Then - EXPECT_THROW(transaction.setKey(getTestPublicKey().get()), IllegalStateException); + EXPECT_THROW(transaction.setKey(getTestPublicKey()), IllegalStateException); } //----- diff --git a/sdk/tests/unit/AccountUpdateTransactionTest.cc b/sdk/tests/unit/AccountUpdateTransactionTest.cc index 8547a9fd5..ad000535c 100644 --- a/sdk/tests/unit/AccountUpdateTransactionTest.cc +++ b/sdk/tests/unit/AccountUpdateTransactionTest.cc @@ -167,7 +167,7 @@ TEST_F(AccountUpdateTransactionTest, SetKey) AccountUpdateTransaction transaction; // When - EXPECT_NO_THROW(transaction.setKey(getTestPublicKey().get())); + EXPECT_NO_THROW(transaction.setKey(getTestPublicKey())); // Then EXPECT_EQ(transaction.getKey()->toBytes(), getTestPublicKey()->toBytes()); @@ -183,7 +183,7 @@ TEST_F(AccountUpdateTransactionTest, SetKeyFrozen) ASSERT_NO_THROW(transaction.freeze()); // When / Then - EXPECT_THROW(transaction.setKey(getTestPublicKey().get()), IllegalStateException); + EXPECT_THROW(transaction.setKey(getTestPublicKey()), IllegalStateException); } //----- diff --git a/sdk/tests/unit/ClientTest.cc b/sdk/tests/unit/ClientTest.cc index 96686d7ea..579584965 100644 --- a/sdk/tests/unit/ClientTest.cc +++ b/sdk/tests/unit/ClientTest.cc @@ -18,15 +18,9 @@ * */ #include "Client.h" -#include "AccountCreateTransaction.h" #include "AccountId.h" -#include "Client.h" #include "ED25519PrivateKey.h" #include "Hbar.h" -#include "PublicKey.h" -#include "TransactionReceipt.h" -#include "TransactionResponse.h" -#include "exceptions/UninitializedException.h" #include @@ -36,7 +30,7 @@ class ClientTest : public ::testing::Test { protected: [[nodiscard]] inline const AccountId& getTestAccountId() const { return mAccountId; } - [[nodiscard]] inline const std::unique_ptr& getTestPrivateKey() const { return mPrivateKey; } + [[nodiscard]] inline const std::shared_ptr& getTestPrivateKey() const { return mPrivateKey; } [[nodiscard]] inline const std::chrono::duration& getTestNetworkUpdatePeriod() const { return mTestNetworkUpdatePeriod; @@ -44,7 +38,7 @@ class ClientTest : public ::testing::Test private: const AccountId mAccountId = AccountId(10ULL); - const std::unique_ptr mPrivateKey = ED25519PrivateKey::generatePrivateKey(); + const std::shared_ptr mPrivateKey = ED25519PrivateKey::generatePrivateKey(); const std::chrono::duration mTestNetworkUpdatePeriod = std::chrono::seconds(2); }; @@ -62,7 +56,7 @@ TEST_F(ClientTest, ConstructClient) TEST_F(ClientTest, MoveClient) { Client client; - client.setOperator(getTestAccountId(), getTestPrivateKey().get()); + client.setOperator(getTestAccountId(), getTestPrivateKey()); Client client2 = std::move(client); EXPECT_EQ(*client2.getOperatorAccountId(), getTestAccountId()); @@ -73,12 +67,12 @@ TEST_F(ClientTest, MoveClient) TEST_F(ClientTest, SetOperator) { Client client; - client.setOperator(getTestAccountId(), getTestPrivateKey().get()); + client.setOperator(getTestAccountId(), getTestPrivateKey()); EXPECT_EQ(*client.getOperatorAccountId(), getTestAccountId()); EXPECT_EQ(client.getOperatorPublicKey()->toStringDer(), getTestPrivateKey()->getPublicKey()->toStringDer()); - client.setOperator(getTestAccountId(), ED25519PrivateKey::generatePrivateKey().get()); + client.setOperator(getTestAccountId(), ED25519PrivateKey::generatePrivateKey()); // No way to grab the string value of the rvalue, just make it's not empty EXPECT_FALSE(client.getOperatorPublicKey()->toStringDer().empty()); diff --git a/sdk/tests/unit/ContractCreateFlowTest.cc b/sdk/tests/unit/ContractCreateFlowTest.cc index e79cf570c..bd47e19b6 100644 --- a/sdk/tests/unit/ContractCreateFlowTest.cc +++ b/sdk/tests/unit/ContractCreateFlowTest.cc @@ -36,7 +36,7 @@ using namespace Hedera; class ContractCreateFlowTest : public ::testing::Test { protected: - void SetUp() override { mClient.setOperator(AccountId(), ED25519PrivateKey::generatePrivateKey().get()); } + void SetUp() override { mClient.setOperator(AccountId(), ED25519PrivateKey::generatePrivateKey()); } [[nodiscard]] inline const Client& getTestClient() const { return mClient; } [[nodiscard]] inline const std::vector& getTestBytecode() const { return mTestBytecode; } @@ -102,7 +102,7 @@ TEST_F(ContractCreateFlowTest, GetSetAdminKey) ContractCreateFlow flow; // When - EXPECT_NO_THROW(flow.setAdminKey(getTestAdminKey().get())); + EXPECT_NO_THROW(flow.setAdminKey(getTestAdminKey())); // Then EXPECT_EQ(flow.getAdminKey()->toBytes(), getTestAdminKey()->toBytes()); diff --git a/sdk/tests/unit/ContractCreateTransactionTest.cc b/sdk/tests/unit/ContractCreateTransactionTest.cc index 8a38eb3a3..363713d75 100644 --- a/sdk/tests/unit/ContractCreateTransactionTest.cc +++ b/sdk/tests/unit/ContractCreateTransactionTest.cc @@ -176,7 +176,7 @@ TEST_F(ContractCreateTransactionTest, GetSetAdminKey) ContractCreateTransaction transaction; // When - EXPECT_NO_THROW(transaction.setAdminKey(getTestAdminKey().get())); + EXPECT_NO_THROW(transaction.setAdminKey(getTestAdminKey())); // Then EXPECT_EQ(transaction.getAdminKey()->toBytes(), getTestAdminKey()->toBytes()); @@ -192,7 +192,7 @@ TEST_F(ContractCreateTransactionTest, GetSetAdminKeyFrozen) ASSERT_NO_THROW(transaction.freeze()); // When / Then - EXPECT_THROW(transaction.setAdminKey(getTestAdminKey().get()), IllegalStateException); + EXPECT_THROW(transaction.setAdminKey(getTestAdminKey()), IllegalStateException); } //----- diff --git a/sdk/tests/unit/ContractUpdateTransactionTest.cc b/sdk/tests/unit/ContractUpdateTransactionTest.cc index 82118b72f..772d968fd 100644 --- a/sdk/tests/unit/ContractUpdateTransactionTest.cc +++ b/sdk/tests/unit/ContractUpdateTransactionTest.cc @@ -178,7 +178,7 @@ TEST_F(ContractUpdateTransactionTest, GetSetAdminKey) ContractUpdateTransaction transaction; // When - EXPECT_NO_THROW(transaction.setAdminKey(getTestAdminKey().get())); + EXPECT_NO_THROW(transaction.setAdminKey(getTestAdminKey())); // Then EXPECT_EQ(transaction.getAdminKey()->toBytes(), getTestAdminKey()->toBytes()); @@ -194,7 +194,7 @@ TEST_F(ContractUpdateTransactionTest, SetAdminKeyFrozen) ASSERT_NO_THROW(transaction.freeze()); // When / Then - EXPECT_THROW(transaction.setAdminKey(getTestAdminKey().get()), IllegalStateException); + EXPECT_THROW(transaction.setAdminKey(getTestAdminKey()), IllegalStateException); } //----- diff --git a/sdk/tests/unit/EthereumFlowTest.cc b/sdk/tests/unit/EthereumFlowTest.cc index c23c3b2b1..64d91ce00 100644 --- a/sdk/tests/unit/EthereumFlowTest.cc +++ b/sdk/tests/unit/EthereumFlowTest.cc @@ -36,7 +36,7 @@ class EthereumFlowTest : public ::testing::Test protected: void SetUp() override { - mClient.setOperator(AccountId(), ECDSAsecp256k1PrivateKey::generatePrivateKey().get()); + mClient.setOperator(AccountId(), ECDSAsecp256k1PrivateKey::generatePrivateKey()); mTestEthereumData = internal::HexConverter::hexToBytes( "02f87082012a022f2f83018000947e3a9eaf9bcc39e2ffa38eb30bf7a93feacbc181880de0b6b3a" "7640000831234568001a0df48f2efd10421811de2bfb125ab75b2d3c44139c4642837fb1fccce91" diff --git a/sdk/tests/unit/FileCreateTransactionTest.cc b/sdk/tests/unit/FileCreateTransactionTest.cc index c95bfb525..2c36fd044 100644 --- a/sdk/tests/unit/FileCreateTransactionTest.cc +++ b/sdk/tests/unit/FileCreateTransactionTest.cc @@ -43,21 +43,21 @@ class FileCreateTransactionTest : public ::testing::Test { return mTestExpirationTime; } - [[nodiscard]] inline const std::vector& getTestKeyVector() const { return mTestKeyVector; } + [[nodiscard]] inline const std::vector>& getTestKeyVector() const { return mTestKeyVector; } [[nodiscard]] inline const KeyList& getTestKeyList() const { return mTestKeyList; } [[nodiscard]] inline const std::vector& getTestContents() const { return mTestContents; } [[nodiscard]] inline const std::string& getTestMemo() const { return mTestMemo; } private: - const std::unique_ptr mPrivateKey1 = ED25519PrivateKey::fromString( - "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e10"); - const std::unique_ptr mPrivateKey2 = ED25519PrivateKey::fromString( - "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e11"); - const std::unique_ptr mPrivateKey3 = ED25519PrivateKey::fromString( - "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e12"); - const std::chrono::system_clock::time_point mTestExpirationTime = std::chrono::system_clock::now(); - const std::vector mTestKeyVector = { mPrivateKey1.get(), mPrivateKey2.get(), mPrivateKey3.get() }; + const std::vector> mTestKeyVector = { + ED25519PrivateKey::fromString( + "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e10"), + ED25519PrivateKey::fromString( + "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e11"), + ED25519PrivateKey::fromString( + "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e12") + }; const KeyList mTestKeyList = KeyList::of(mTestKeyVector); const std::vector mTestContents = { std::byte(0x08), std::byte(0x09), std::byte(0x10) }; const std::string mTestMemo = "test file memo"; diff --git a/sdk/tests/unit/FileInfoTest.cc b/sdk/tests/unit/FileInfoTest.cc index c7c7ab89b..abc366154 100644 --- a/sdk/tests/unit/FileInfoTest.cc +++ b/sdk/tests/unit/FileInfoTest.cc @@ -45,10 +45,8 @@ class FileInfoTest : public ::testing::Test const uint64_t mTestSize = 2ULL; const std::chrono::system_clock::time_point mTestExpirationTime = std::chrono::system_clock::now(); const bool mTestIsDeleted = true; - const KeyList mTestKeys = - KeyList::of({ PublicKey::fromStringDer( - "302A300506032B6570032100D75A980182B10AB7D54BFED3C964073A0EE172f3DAA62325AF021A68F707511A") - .get() }); + const KeyList mTestKeys = KeyList::of({ PublicKey::fromStringDer( + "302A300506032B6570032100D75A980182B10AB7D54BFED3C964073A0EE172f3DAA62325AF021A68F707511A") }); const LedgerId mTestLedgerId = LedgerId({ std::byte(0x03), std::byte(0x04), std::byte(0x05) }); }; diff --git a/sdk/tests/unit/FileUpdateTransactionTest.cc b/sdk/tests/unit/FileUpdateTransactionTest.cc index 71da8d651..aabca1eae 100644 --- a/sdk/tests/unit/FileUpdateTransactionTest.cc +++ b/sdk/tests/unit/FileUpdateTransactionTest.cc @@ -44,22 +44,22 @@ class FileUpdateTransactionTest : public ::testing::Test { return mTestExpirationTime; } - [[nodiscard]] inline const std::vector& getTestKeyVector() const { return mTestKeyVector; } + [[nodiscard]] inline const std::vector>& getTestKeyVector() const { return mTestKeyVector; } [[nodiscard]] inline const KeyList& getTestKeyList() const { return mTestKeyList; } [[nodiscard]] inline const std::vector& getTestContents() const { return mTestContents; } [[nodiscard]] inline const std::string& getTestMemo() const { return mTestMemo; } private: - const std::unique_ptr mPrivateKey1 = ED25519PrivateKey::fromString( - "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e10"); - const std::unique_ptr mPrivateKey2 = ED25519PrivateKey::fromString( - "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e11"); - const std::unique_ptr mPrivateKey3 = ED25519PrivateKey::fromString( - "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e12"); - const FileId mTestFileId = FileId(1ULL); const std::chrono::system_clock::time_point mTestExpirationTime = std::chrono::system_clock::now(); - const std::vector mTestKeyVector = { mPrivateKey1.get(), mPrivateKey2.get(), mPrivateKey3.get() }; + const std::vector> mTestKeyVector = { + ED25519PrivateKey::fromString( + "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e10"), + ED25519PrivateKey::fromString( + "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e11"), + ED25519PrivateKey::fromString( + "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e12") + }; const KeyList mTestKeyList = KeyList::of(mTestKeyVector); const std::vector mTestContents = { std::byte(0x08), std::byte(0x09), std::byte(0x10) }; const std::string mTestMemo = "test file memo"; diff --git a/sdk/tests/unit/KeyListTest.cc b/sdk/tests/unit/KeyListTest.cc index e277123b6..317037b1c 100644 --- a/sdk/tests/unit/KeyListTest.cc +++ b/sdk/tests/unit/KeyListTest.cc @@ -73,8 +73,7 @@ TEST_F(KeyListTest, FromProtobuf) TEST_F(KeyListTest, Of) { // Given / When - const KeyList keyList = - KeyList::of({ getTestPublicKey1().get(), getTestPublicKey2().get(), getTestPublicKey3().get() }); + const KeyList keyList = KeyList::of({ getTestPublicKey1(), getTestPublicKey2(), getTestPublicKey3() }); // Then EXPECT_TRUE(keyList.contains(getTestPublicKey1().get())); @@ -86,8 +85,7 @@ TEST_F(KeyListTest, Of) TEST_F(KeyListTest, ToProtobufKey) { // Given - const KeyList keyList = - KeyList::of({ getTestPublicKey1().get(), getTestPublicKey2().get(), getTestPublicKey3().get() }); + const KeyList keyList = KeyList::of({ getTestPublicKey1(), getTestPublicKey2(), getTestPublicKey3() }); // When std::unique_ptr protoKey; @@ -108,8 +106,7 @@ TEST_F(KeyListTest, ToProtobufKey) TEST_F(KeyListTest, ToProtobuf) { // Given - const KeyList keyList = - KeyList::of({ getTestPublicKey1().get(), getTestPublicKey2().get(), getTestPublicKey3().get() }); + const KeyList keyList = KeyList::of({ getTestPublicKey1(), getTestPublicKey2(), getTestPublicKey3() }); // When std::unique_ptr protoKeyList; @@ -129,8 +126,7 @@ TEST_F(KeyListTest, ToProtobuf) TEST_F(KeyListTest, Size) { // Given / When - const KeyList keyList = - KeyList::of({ getTestPublicKey1().get(), getTestPublicKey2().get(), getTestPublicKey3().get() }); + const KeyList keyList = KeyList::of({ getTestPublicKey1(), getTestPublicKey2(), getTestPublicKey3() }); const KeyList emptyKeyList; // Then @@ -142,8 +138,7 @@ TEST_F(KeyListTest, Size) TEST_F(KeyListTest, Empty) { // Given / When - const KeyList keyList = - KeyList::of({ getTestPublicKey1().get(), getTestPublicKey2().get(), getTestPublicKey3().get() }); + const KeyList keyList = KeyList::of({ getTestPublicKey1(), getTestPublicKey2(), getTestPublicKey3() }); const KeyList emptyKeyList; // Then @@ -155,8 +150,7 @@ TEST_F(KeyListTest, Empty) TEST_F(KeyListTest, Contains) { // Given / When - const KeyList keyList = - KeyList::of({ getTestPublicKey1().get(), getTestPublicKey2().get(), getTestPublicKey3().get() }); + const KeyList keyList = KeyList::of({ getTestPublicKey1(), getTestPublicKey2(), getTestPublicKey3() }); const KeyList emptyKeyList; // Then @@ -173,10 +167,10 @@ TEST_F(KeyListTest, Contains) TEST_F(KeyListTest, PushBack) { // Given - KeyList keyList = KeyList::of({ getTestPublicKey1().get(), getTestPublicKey2().get() }); + KeyList keyList = KeyList::of({ getTestPublicKey1(), getTestPublicKey2() }); // When - keyList.push_back(getTestPublicKey3().get()); + keyList.push_back(getTestPublicKey3()); // Then EXPECT_EQ(keyList.size(), 3); @@ -187,7 +181,7 @@ TEST_F(KeyListTest, PushBack) TEST_F(KeyListTest, Remove) { // Given - KeyList keyList = KeyList::of({ getTestPublicKey1().get(), getTestPublicKey2().get(), getTestPublicKey3().get() }); + KeyList keyList = KeyList::of({ getTestPublicKey1(), getTestPublicKey2(), getTestPublicKey3() }); // When keyList.remove(getTestPublicKey1().get()); @@ -203,7 +197,7 @@ TEST_F(KeyListTest, Remove) TEST_F(KeyListTest, Clear) { // Given - KeyList keyList = KeyList::of({ getTestPublicKey1().get(), getTestPublicKey2().get(), getTestPublicKey3().get() }); + KeyList keyList = KeyList::of({ getTestPublicKey1(), getTestPublicKey2(), getTestPublicKey3() }); // When keyList.clear(); diff --git a/sdk/tests/unit/ScheduleInfoUnitTests.cc b/sdk/tests/unit/ScheduleInfoUnitTests.cc index 3779d74ea..f1f036084 100644 --- a/sdk/tests/unit/ScheduleInfoUnitTests.cc +++ b/sdk/tests/unit/ScheduleInfoUnitTests.cc @@ -57,20 +57,19 @@ class ScheduleInfoTest : public ::testing::Test [[nodiscard]] inline bool getTestWaitForExpiry() const { return mTestWaitForExpiry; } private: - const std::unique_ptr mPrivateKey1 = ED25519PrivateKey::fromString( - "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e10"); - const std::unique_ptr mPrivateKey2 = ED25519PrivateKey::fromString( - "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e11"); - const std::unique_ptr mPrivateKey3 = ED25519PrivateKey::fromString( - "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e12"); - const ScheduleId mTestScheduleId = ScheduleId(1ULL, 2ULL, 3ULL); const std::chrono::system_clock::time_point mTestExecutionTime = std::chrono::system_clock::now(); const std::chrono::system_clock::time_point mTestExpirationTime = std::chrono::system_clock::now(); const WrappedTransaction mTestSchedulableTransaction = WrappedTransaction(AccountCreateTransaction()); const std::string mTestMemo = "test memo"; const std::shared_ptr mTestAdminKey = ED25519PrivateKey::generatePrivateKey()->getPublicKey(); - const KeyList mTestSigners = KeyList::of({ mPrivateKey1.get(), mPrivateKey2.get(), mPrivateKey3.get() }); + const KeyList mTestSigners = KeyList::of( + { ED25519PrivateKey::fromString( + "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e10"), + ED25519PrivateKey::fromString( + "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e11"), + ED25519PrivateKey::fromString( + "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e12") }); const AccountId mTestCreatorAccountId = AccountId(4ULL, 5ULL, 6ULL); const AccountId mTestPayerAccountId = AccountId(7ULL, 8ULL, 9ULL); const TransactionId mTestScheduledTransactionId = TransactionId::generate(AccountId(10ULL, 11ULL, 12ULL)); diff --git a/sdk/tests/unit/TransferTransactionTest.cc b/sdk/tests/unit/TransferTransactionTest.cc index 411a058d1..0a46dd64f 100644 --- a/sdk/tests/unit/TransferTransactionTest.cc +++ b/sdk/tests/unit/TransferTransactionTest.cc @@ -222,7 +222,7 @@ TEST_F(TransferTransactionTest, AddNftTransfer) EXPECT_NO_THROW(transaction.addNftTransfer(getTestNftId(), getTestAccountId1(), getTestAccountId2())); // Then - ASSERT_NO_THROW(transaction.getNftTransfers().empty()); + ASSERT_FALSE(transaction.getNftTransfers().empty()); EXPECT_EQ(transaction.getNftTransfers().cbegin()->first, getTestTokenId()); EXPECT_EQ(transaction.getNftTransfers().cbegin()->second.cbegin()->getSenderAccountId(), getTestAccountId1()); EXPECT_EQ(transaction.getNftTransfers().cbegin()->second.cbegin()->getReceiverAccountId(), getTestAccountId2()); From 8be3540357b03a0f7e620dd431154913424a0aa7 Mon Sep 17 00:00:00 2001 From: Rob Walworth Date: Wed, 11 Oct 2023 09:51:35 -0500 Subject: [PATCH 5/7] Add ConsensusPubSubWithSubmitKeyExample Signed-off-by: Rob Walworth --- sdk/examples/CMakeLists.txt | 4 + .../ConsensusPubSubWithSubmitKeyExample.cc | 89 +++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 sdk/examples/ConsensusPubSubWithSubmitKeyExample.cc diff --git a/sdk/examples/CMakeLists.txt b/sdk/examples/CMakeLists.txt index 2c61bcb13..5766b7f25 100644 --- a/sdk/examples/CMakeLists.txt +++ b/sdk/examples/CMakeLists.txt @@ -5,6 +5,7 @@ set(ACCOUNT_CREATION_WAYS_EXAMPLE_NAME ${PROJECT_NAME}-account-creation-ways-exa set(AUTO_CREATE_ACCOUNT_TRANSFER_TRANSACTION_EXAMPLE_NAME ${PROJECT_NAME}-auto-create-account-transfer-transaction-example) set(CONSENSUS_PUB_SUB_EXAMPLE_NAME ${PROJECT_NAME}-consensus-pub-sub-example) set(CONSENSUS_PUB_SUB_CHUNKED_EXAMPLE_NAME ${PROJECT_NAME}-consensus-pub-sub-chunked-example) +set(CONSENSUS_PUB_SUB_WITH_SUBMIT_KEY_EXAMPLE_NAME ${PROJECT_NAME}-consensus-pub-sub-with-submit-key-example) set(CREATE_ACCOUNT_EXAMPLE_NAME ${PROJECT_NAME}-create-account-example) set(CREATE_SIMPLE_CONTRACT_EXAMPLE_NAME ${PROJECT_NAME}-create-simple-contract-example) set(CREATE_STATEFUL_CONTRACT_EXAMPLE_NAME ${PROJECT_NAME}-create-stateful-contract-example) @@ -37,6 +38,7 @@ add_executable(${ACCOUNT_CREATION_WAYS_EXAMPLE_NAME} AccountCreationWaysExample. add_executable(${AUTO_CREATE_ACCOUNT_TRANSFER_TRANSACTION_EXAMPLE_NAME} AutoCreateAccountTransferTransactionExample.cc) add_executable(${CONSENSUS_PUB_SUB_EXAMPLE_NAME} ConsensusPubSubExample.cc) add_executable(${CONSENSUS_PUB_SUB_CHUNKED_EXAMPLE_NAME} ConsensusPubSubChunkedExample.cc) +add_executable(${CONSENSUS_PUB_SUB_WITH_SUBMIT_KEY_EXAMPLE_NAME} ConsensusPubSubWithSubmitKeyExample.cc) add_executable(${CREATE_ACCOUNT_EXAMPLE_NAME} CreateAccountExample.cc) add_executable(${CREATE_SIMPLE_CONTRACT_EXAMPLE_NAME} CreateSimpleContractExample.cc) add_executable(${CREATE_STATEFUL_CONTRACT_EXAMPLE_NAME} CreateStatefulContractExample.cc) @@ -87,6 +89,7 @@ target_link_libraries(${ACCOUNT_CREATION_WAYS_EXAMPLE_NAME} PUBLIC ${PROJECT_NAM target_link_libraries(${AUTO_CREATE_ACCOUNT_TRANSFER_TRANSACTION_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) target_link_libraries(${CONSENSUS_PUB_SUB_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) target_link_libraries(${CONSENSUS_PUB_SUB_CHUNKED_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) +target_link_libraries(${CONSENSUS_PUB_SUB_WITH_SUBMIT_KEY_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) target_link_libraries(${CREATE_ACCOUNT_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) target_link_libraries(${CREATE_SIMPLE_CONTRACT_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) target_link_libraries(${CREATE_STATEFUL_CONTRACT_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) @@ -122,6 +125,7 @@ install(TARGETS ${AUTO_CREATE_ACCOUNT_TRANSFER_TRANSACTION_EXAMPLE_NAME} ${CONSENSUS_PUB_SUB_EXAMPLE_NAME} ${CONSENSUS_PUB_SUB_CHUNKED_EXAMPLE_NAME} + ${CONSENSUS_PUB_SUB_WITH_SUBMIT_KEY_EXAMPLE_NAME} ${CREATE_ACCOUNT_EXAMPLE_NAME} ${CREATE_SIMPLE_CONTRACT_EXAMPLE_NAME} ${CREATE_STATEFUL_CONTRACT_EXAMPLE_NAME} diff --git a/sdk/examples/ConsensusPubSubWithSubmitKeyExample.cc b/sdk/examples/ConsensusPubSubWithSubmitKeyExample.cc new file mode 100644 index 000000000..dd382a09c --- /dev/null +++ b/sdk/examples/ConsensusPubSubWithSubmitKeyExample.cc @@ -0,0 +1,89 @@ +/*- + * + * Hedera C++ SDK + * + * Copyright (C) 2020 - 2023 Hedera Hashgraph, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License") + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#include "Client.h" +#include "ED25519PrivateKey.h" +#include "SubscriptionHandle.h" +#include "TopicCreateTransaction.h" +#include "TopicId.h" +#include "TopicMessage.h" +#include "TopicMessageQuery.h" +#include "TopicMessageSubmitTransaction.h" +#include "TransactionReceipt.h" +#include "TransactionResponse.h" +#include "impl/Utilities.h" + +#include +#include +#include + +using namespace Hedera; + +int main(int argc, char** argv) +{ + if (argc < 3) + { + std::cout << "Please input account ID and private key" << std::endl; + return 1; + } + + // Get a client for the Hedera testnet, and set the operator account ID and key such that all generated transactions + // will be paid for by this account and be signed by this key. + Client client = Client::forTestnet(); + client.setOperator(AccountId::fromString(argv[1]), ED25519PrivateKey::fromString(argv[2])); + + // Generate a submit key. + const std::shared_ptr submitKey = ED25519PrivateKey::generatePrivateKey(); + + // Create a topic with the submit key. + const TopicId topicId = + TopicCreateTransaction().setSubmitKey(submitKey).execute(client).getReceipt(client).mTopicId.value(); + std::cout << "Created topic " << topicId.toString() << " with submit key " << submitKey->toStringRaw() << std::endl; + + // Wait for topic to propagate to the mirror nodes. + std::cout << "Waiting to propagate to mirror nodes"; + for (int i = 0; i < 5; ++i) + { + std::this_thread::sleep_for(std::chrono::seconds(1)); + std::cout << '.'; + } + std::cout << std::endl; + + // Subscribe to the topic. + TopicMessageQuery query = TopicMessageQuery().setTopicId(topicId); + SubscriptionHandle handle = query.subscribe( + client, + [](const TopicMessage& message) + { std::cout << "Received message: " << internal::Utilities::byteVectorToString(message.mContents) << std::endl; }); + + for (int i = 0; true; ++i) + { + const TransactionReceipt txReceipt = TopicMessageSubmitTransaction() + .setTopicId(topicId) + .setMessage("Hello from HCS " + std::to_string(i)) + .freezeWith(&client) + // Due to the topic having a submit key, the submit key must sign. + .sign(submitKey) + .execute(client) + .getReceipt(client); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + } + + return 0; +} From a2dc25136f391bf61e356ad70b98e6727815dee3 Mon Sep 17 00:00:00 2001 From: Rob Walworth Date: Wed, 11 Oct 2023 16:51:52 -0500 Subject: [PATCH 6/7] Add ConstructClientExample | Add methods to Client to construct a Client from a JSON configuration Signed-off-by: Rob Walworth --- sdk/examples/CMakeLists.txt | 6 + sdk/examples/ConstructClientExample.cc | 104 +++++++++ sdk/main/include/Client.h | 37 ++++ sdk/main/include/PrivateKey.h | 20 ++ sdk/main/src/Client.cc | 212 ++++++++++++++++++- sdk/main/src/PrivateKey.cc | 39 +++- sdk/tests/integration/BaseIntegrationTest.cc | 41 +--- 7 files changed, 415 insertions(+), 44 deletions(-) create mode 100644 sdk/examples/ConstructClientExample.cc diff --git a/sdk/examples/CMakeLists.txt b/sdk/examples/CMakeLists.txt index 5766b7f25..9196126f6 100644 --- a/sdk/examples/CMakeLists.txt +++ b/sdk/examples/CMakeLists.txt @@ -6,6 +6,7 @@ set(AUTO_CREATE_ACCOUNT_TRANSFER_TRANSACTION_EXAMPLE_NAME ${PROJECT_NAME}-auto-c set(CONSENSUS_PUB_SUB_EXAMPLE_NAME ${PROJECT_NAME}-consensus-pub-sub-example) set(CONSENSUS_PUB_SUB_CHUNKED_EXAMPLE_NAME ${PROJECT_NAME}-consensus-pub-sub-chunked-example) set(CONSENSUS_PUB_SUB_WITH_SUBMIT_KEY_EXAMPLE_NAME ${PROJECT_NAME}-consensus-pub-sub-with-submit-key-example) +set(CONSTRUCT_CLIENT_EXAMPLE_NAME ${PROJECT_NAME}-construct-client-example) set(CREATE_ACCOUNT_EXAMPLE_NAME ${PROJECT_NAME}-create-account-example) set(CREATE_SIMPLE_CONTRACT_EXAMPLE_NAME ${PROJECT_NAME}-create-simple-contract-example) set(CREATE_STATEFUL_CONTRACT_EXAMPLE_NAME ${PROJECT_NAME}-create-stateful-contract-example) @@ -39,6 +40,7 @@ add_executable(${AUTO_CREATE_ACCOUNT_TRANSFER_TRANSACTION_EXAMPLE_NAME} AutoCrea add_executable(${CONSENSUS_PUB_SUB_EXAMPLE_NAME} ConsensusPubSubExample.cc) add_executable(${CONSENSUS_PUB_SUB_CHUNKED_EXAMPLE_NAME} ConsensusPubSubChunkedExample.cc) add_executable(${CONSENSUS_PUB_SUB_WITH_SUBMIT_KEY_EXAMPLE_NAME} ConsensusPubSubWithSubmitKeyExample.cc) +add_executable(${CONSTRUCT_CLIENT_EXAMPLE_NAME} ConstructClientExample.cc) add_executable(${CREATE_ACCOUNT_EXAMPLE_NAME} CreateAccountExample.cc) add_executable(${CREATE_SIMPLE_CONTRACT_EXAMPLE_NAME} CreateSimpleContractExample.cc) add_executable(${CREATE_STATEFUL_CONTRACT_EXAMPLE_NAME} CreateStatefulContractExample.cc) @@ -73,6 +75,8 @@ file(COPY ${PROJECT_SOURCE_DIR}/addressbook/testnet.pb file(COPY ${PROJECT_SOURCE_DIR}/config/hello_world.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_BUILD_TYPE}) +file(COPY ${PROJECT_SOURCE_DIR}/config/local_node.json + DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_BUILD_TYPE}) file(COPY ${PROJECT_SOURCE_DIR}/config/stateful.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_BUILD_TYPE}) @@ -90,6 +94,7 @@ target_link_libraries(${AUTO_CREATE_ACCOUNT_TRANSFER_TRANSACTION_EXAMPLE_NAME} P target_link_libraries(${CONSENSUS_PUB_SUB_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) target_link_libraries(${CONSENSUS_PUB_SUB_CHUNKED_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) target_link_libraries(${CONSENSUS_PUB_SUB_WITH_SUBMIT_KEY_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) +target_link_libraries(${CONSTRUCT_CLIENT_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) target_link_libraries(${CREATE_ACCOUNT_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) target_link_libraries(${CREATE_SIMPLE_CONTRACT_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) target_link_libraries(${CREATE_STATEFUL_CONTRACT_EXAMPLE_NAME} PUBLIC ${PROJECT_NAME}) @@ -126,6 +131,7 @@ install(TARGETS ${CONSENSUS_PUB_SUB_EXAMPLE_NAME} ${CONSENSUS_PUB_SUB_CHUNKED_EXAMPLE_NAME} ${CONSENSUS_PUB_SUB_WITH_SUBMIT_KEY_EXAMPLE_NAME} + ${CONSTRUCT_CLIENT_EXAMPLE_NAME} ${CREATE_ACCOUNT_EXAMPLE_NAME} ${CREATE_SIMPLE_CONTRACT_EXAMPLE_NAME} ${CREATE_STATEFUL_CONTRACT_EXAMPLE_NAME} diff --git a/sdk/examples/ConstructClientExample.cc b/sdk/examples/ConstructClientExample.cc new file mode 100644 index 000000000..2d1ce8109 --- /dev/null +++ b/sdk/examples/ConstructClientExample.cc @@ -0,0 +1,104 @@ +/*- + * + * Hedera C++ SDK + * + * Copyright (C) 2020 - 2023 Hedera Hashgraph, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License") + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#include "AccountId.h" +#include "Client.h" +#include "ED25519PrivateKey.h" +#include "LedgerId.h" + +#include +#include +#include + +using namespace Hedera; + +int main(int argc, char** argv) +{ + if (argc < 3) + { + std::cout << "Please enter a network name and a configuration filepath" << std::endl; + return 1; + } + + /* + * Here are some ways you can construct and configure a client. A client has a network and an operator. + * + * A Hedera network is made up of nodes -- individual servers who participate in the process of reaching consensus + * on the order and validity of transactions on the network. Three networks you likely know of are previewnet, + * testnet, and mainnet. + * + * For the purpose of connecting to it, each node has an IP address or URL and a port number. Each node also has an + * AccountId used to refer to that node for several purposes, including the paying of fees to that node when a + * client submits requests to it. + * + * You can configure what network you want a client to use -- in other words, you can specify a list of URLS and + * port numbers with associated AccountIds, and when that client is used to execute queries and transactions, the + * client will submit requests only to nodes in that list. + * + * A Client has an operator, which has an AccountId and a PublicKey, and which can sign requests. A client's + * operator can also be configured. + */ + + // Here's the simplest way to construct a client. These clients' networks are filled with default lists of nodes that + // are baked into the SDK. Their operators are not yet set, and trying to use them now will result in exceptions. + Client previewClient = Client::forPreviewnet(); + Client testClient = Client::forTestnet(); + Client mainClient = Client::forMainnet(); + + // We can also construct a client for previewnet, testnet, or mainnet depending on the value of a network name string. + // If, for example, the input string equals "testnet", this client will be configured to connect to the Hedera + // Testnet. + Client namedNetworkClient = Client::forName(argv[1]); + + // Set the operator on testClient (the AccountId and PrivateKey here are fake, this is just an example). + testClient.setOperator( + AccountId::fromString("0.0.3"), + ED25519PrivateKey::fromString( + "302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e10")); + + // Create a Client with a custom network. + const std::unordered_map network = { + {"2.testnet.hedera.com:50211", AccountId(5ULL)}, + { "3.testnet.hedera.com:50211", AccountId(6ULL)} + }; + Client customClient = Client::forNetwork(network); + + // Since the customClient's network is in this case a subset of the Hedera Testnet, we should set the LedgerId of the + // Client to testnet's LedgerId. If we don't do this, checksum validation won't work (See ValidateChecksumExample.cc). + // You can use customClient.getLedgerId() to check the ledger ID. If you attempt to validate a checksum against a + // client whose ledger ID is not set, an IllegalStateException will be thrown. + customClient.setLedgerId(LedgerId::TESTNET); + + // Let's generate a client from a config.json file. A config file may specify a network by name, or it may provide a + // custom network in the form of a list of nodes. The config file should specify the operator, so you can use a client + // constructed using fromConfigFile() immediately. + Client configClient = Client::fromConfigFile(argv[2]); + configClient.close(); + + // Always close a Client when you're done with it. + previewClient.close(); + testClient.close(); + mainClient.close(); + namedNetworkClient.close(); + customClient.close(); + + std::cout << "Success!" << std::endl; + + return 0; +} diff --git a/sdk/main/include/Client.h b/sdk/main/include/Client.h index 4e49003c4..4de057bde 100644 --- a/sdk/main/include/Client.h +++ b/sdk/main/include/Client.h @@ -21,9 +21,13 @@ #define HEDERA_SDK_CPP_CLIENT_H_ #include +#include #include #include +#include #include +#include +#include #include #include @@ -73,6 +77,15 @@ class Client */ [[nodiscard]] static Client forNetwork(const std::unordered_map& networkMap); + /** + * Construct a Client by a name. The name must be one of "mainnet", "testnet", or "previewnet", otherwise this will + * throw std::invalid_argument. + * + * @param name The name of the Client to construct. + * @return A Client object that is set-up to communicate with the input network name. + */ + [[nodiscard]] static Client forName(std::string_view name); + /** * Construct a Client pre-configured for Hedera Mainnet access. * @@ -94,6 +107,30 @@ class Client */ [[nodiscard]] static Client forPreviewnet(); + /** + * Construct a Client from a JSON configuration string. + * + * @param json The JSON configuration string. + * @return A Client object initialized with the properties specified in the JSON configuration string. + */ + [[nodiscard]] static Client fromConfig(std::string_view json); + + /** + * Construct a Client from a JSON configuration object. + * + * @param json The JSON configuration object. + * @return A Client object initialized with the properties specified in the JSON configuration object. + */ + [[nodiscard]] static Client fromConfig(const nlohmann::json& json); + + /** + * Construct a Client from a JSON configuration file. + * + * @param path The filepath to the JSON configuration file. + * @return A Client object initialized with the properties specified in the JSON configuration file. + */ + [[nodiscard]] static Client fromConfigFile(std::string_view path); + /** * Set the mirror network with which this Client should communicate. * diff --git a/sdk/main/include/PrivateKey.h b/sdk/main/include/PrivateKey.h index 2fe0ce68b..47a26cc07 100644 --- a/sdk/main/include/PrivateKey.h +++ b/sdk/main/include/PrivateKey.h @@ -55,6 +55,26 @@ class PrivateKey : public Key */ ~PrivateKey() override; + /** + * Construct a PrivateKey object from a hex-encoded, DER-encoded key string. + * + * @param key The DER-encoded hex string from which to construct a PrivateKey. + * @return A pointer to an PrivateKey representing the input DER-encoded hex string. + * @throws BadKeyException If the private key type (ED25519 or ECDSAsecp256k1) is unable to be determined or realized + * from the input hex string. + */ + [[nodiscard]] static std::unique_ptr fromStringDer(std::string_view key); + + /** + * Construct a PrivateKey object from a DER-encoded byte vector. + * + * @param bytes The vector of DER-encoded bytes from which to construct a PrivateKey. + * @return A pointer to a PrivateKey representing the input DER-encoded bytes. + * @throws BadKeyException If the private key type (ED25519 or ECDSAsecp256k1) is unable to be determined or realized + * from the input byte array. + */ + [[nodiscard]] static std::unique_ptr fromBytesDer(const std::vector& bytes); + /** * Derive a child PrivateKey from this PrivateKey. * diff --git a/sdk/main/src/Client.cc b/sdk/main/src/Client.cc index fb7e28036..8b26a8707 100644 --- a/sdk/main/src/Client.cc +++ b/sdk/main/src/Client.cc @@ -32,7 +32,7 @@ #include "impl/TLSBehavior.h" #include -#include +#include #include #include @@ -145,6 +145,25 @@ Client& Client::operator=(Client&& other) noexcept return *this; } +//----- +Client Client::forNetwork(const std::unordered_map& networkMap) +{ + Client client; + client.mImpl->mNetwork = std::make_shared(internal::Network::forNetwork(networkMap)); + return client; +} + +//----- +Client Client::forName(std::string_view name) +{ + // clang-format off + if (name == "mainnet") return Client::forMainnet(); + else if (name == "testnet") return Client::forTestnet(); + else if (name == "previewnet") return Client::forPreviewnet(); + else throw std::invalid_argument("Unknown Client name"); + // clang-format on +} + //----- Client Client::forMainnet() { @@ -173,13 +192,200 @@ Client Client::forPreviewnet() } //----- -Client Client::forNetwork(const std::unordered_map& networkMap) +Client Client::fromConfig(std::string_view json) +{ + // Make sure the input string is valid JSON. + nlohmann::json jsonObj; + try + { + jsonObj = nlohmann::json::parse(json); + } + catch (const std::exception& ex) + { + throw std::invalid_argument(std::string("Cannot parse JSON: ") + ex.what()); + } + + return fromConfig(jsonObj); +} + +//----- +Client Client::fromConfig(const nlohmann::json& json) { Client client; - client.mImpl->mNetwork = std::make_shared(internal::Network::forNetwork(networkMap)); + + // A "network" tag should always be specified. + if (!json.contains("network")) + { + throw std::invalid_argument("Network tag is not set in JSON"); + } + + // If the network tags specifies a dictionary of nodes, parse each one. + if (const nlohmann::json& jsonNetwork = json["network"]; jsonNetwork.is_object()) + { + std::unordered_map networkMap; + for (const auto& [accountId, url] : jsonNetwork.items()) + { + networkMap.try_emplace(url, AccountId::fromString(accountId)); + } + + client = Client::forNetwork(networkMap); + + // If a network name is provided, set the ledger ID based on it. + if (json.contains("networkName")) + { + try + { + client.setLedgerId(LedgerId::fromString(jsonNetwork["networkName"].get())); + } + catch (const std::exception&) + { + throw std::invalid_argument( + R"(Invalid argument for network name. Should be one of "mainnet", "testnet", or "previewnet")"); + } + } + } + + // If the network tag specifies a name, get the Client for that name. + else if (jsonNetwork.is_string()) + { + try + { + client = Client::forName(jsonNetwork.get()); + } + catch (const std::exception&) + { + throw std::invalid_argument("Invalid argument for network tag "); + } + } + + // If the network tag type is unclear, throw. + else + { + throw std::invalid_argument("Invalid argument for network tag"); + } + + // Check if there's an operator configured. + if (json.contains("operator")) + { + const nlohmann::json& jsonOperator = json["operator"]; + + if (!jsonOperator.is_object()) + { + throw std::invalid_argument("Invalid argument for operator"); + } + + // If an operator is configured, an AccountId and PrivateKey must also be configured. + if (!jsonOperator.contains("accountId") || !jsonOperator.contains("privateKey")) + { + throw std::invalid_argument("An operator must have an accountId and privateKey"); + } + + // Verify the account ID is valid. + AccountId operatorAccountId; + try + { + operatorAccountId = AccountId::fromString(jsonOperator["accountId"].get()); + } + catch (const std::exception&) + { + throw std::invalid_argument("Invalid argument for operator accountId"); + } + + // Verify the private key is valid. + std::shared_ptr operatorPrivateKey; + try + { + operatorPrivateKey = PrivateKey::fromStringDer(jsonOperator["privateKey"].get()); + } + catch (const std::exception&) + { + throw std::invalid_argument("Invalid argument for operator privateKey"); + } + + // Set the operator. + client.setOperator(operatorAccountId, operatorPrivateKey); + } + + // Check if there's a mirror network configured. + if (json.contains("mirrorNetwork")) + { + // If the mirror network tags specifies a list of nodes, parse each one. + if (const nlohmann::json& jsonMirrorNetwork = json["mirrorNetwork"]; jsonMirrorNetwork.is_array()) + { + std::vector mirrorNetwork; + for (const auto& url : jsonMirrorNetwork) + { + mirrorNetwork.push_back(url); + } + + client.setMirrorNetwork(mirrorNetwork); + } + + // If the mirror network tag specifies a name, get the mirror network for that name. + else if (jsonMirrorNetwork.is_string()) + { + try + { + const std::string_view mirrorNetworkName = jsonMirrorNetwork.get(); + if (mirrorNetworkName == "mainnet") + { + client.mImpl->mMirrorNetwork = + std::make_shared(internal::MirrorNetwork::forMainnet()); + } + else if (mirrorNetworkName == "testnet") + { + client.mImpl->mMirrorNetwork = + std::make_shared(internal::MirrorNetwork::forTestnet()); + } + else if (mirrorNetworkName == "previewnet") + { + client.mImpl->mMirrorNetwork = + std::make_shared(internal::MirrorNetwork::forPreviewnet()); + } + else + { + throw std::invalid_argument("Invalid argument for mirrorNetwork tag"); + } + } + catch (const std::exception&) + { + throw std::invalid_argument("Invalid argument for mirrorNetwork tag"); + } + } + + // If the mirrorNetwork tag type is unclear, throw. + else + { + throw std::invalid_argument("Invalid argument for mirrorNetwork tag"); + } + } + return client; } +//----- +Client Client::fromConfigFile(std::string_view path) +{ + std::ifstream infile(path); + if (!infile.is_open()) + { + throw std::invalid_argument(std::string("File cannot be found at ") + path.data()); + } + + // Make sure the input file is valid JSON. + nlohmann::json jsonObj; + try + { + jsonObj = nlohmann::json::parse(infile); + } + catch (const std::exception& ex) + { + throw std::invalid_argument(std::string("Cannot parse JSON: ") + ex.what()); + } + + return fromConfig(jsonObj); +} + //----- Client& Client::setMirrorNetwork(const std::vector& network) { diff --git a/sdk/main/src/PrivateKey.cc b/sdk/main/src/PrivateKey.cc index ec25dc4ad..8a646a8d0 100644 --- a/sdk/main/src/PrivateKey.cc +++ b/sdk/main/src/PrivateKey.cc @@ -18,9 +18,12 @@ * */ #include "PrivateKey.h" +#include "ECDSAsecp256k1PrivateKey.h" +#include "ED25519PrivateKey.h" #include "PublicKey.h" #include "exceptions/BadKeyException.h" #include "exceptions/OpenSSLException.h" +#include "impl/HexConverter.h" #include "impl/PrivateKeyImpl.h" #include "impl/Utilities.h" #include "impl/openssl_utils/OpenSSLUtils.h" @@ -32,6 +35,40 @@ namespace Hedera //----- PrivateKey::~PrivateKey() = default; +//----- +std::unique_ptr PrivateKey::fromStringDer(std::string_view key) +{ + if (const std::string_view prefix = "0x"; key.substr(0, prefix.size()) == prefix) + { + key.remove_prefix(prefix.size()); + } + + try + { + return PrivateKey::fromBytesDer(internal::HexConverter::hexToBytes(key)); + } + catch (const OpenSSLException&) + { + throw BadKeyException(std::string("Unable to decode input key string ") + key.data()); + } +} + +//----- +std::unique_ptr PrivateKey::fromBytesDer(const std::vector& bytes) +{ + if (internal::Utilities::isPrefixOf(bytes, ED25519PrivateKey::DER_ENCODED_PREFIX_BYTES)) + { + return ED25519PrivateKey::fromBytes(bytes); + } + + else if (internal::Utilities::isPrefixOf(bytes, ECDSAsecp256k1PrivateKey::DER_ENCODED_PREFIX_BYTES)) + { + return ECDSAsecp256k1PrivateKey::fromBytes(bytes); + } + + throw BadKeyException("Key type cannot be determined from input DER-encoded byte array"); +} + //----- std::vector PrivateKey::getChainCode() const { @@ -97,7 +134,7 @@ PrivateKey::PrivateKey(internal::OpenSSLUtils::EVP_PKEY&& key, std::vector keyBytes(i2d_PUBKEY(mImpl->mKey.get(), nullptr)); - if (unsigned char* rawPublicKeyBytes = internal::Utilities::toTypePtr(keyBytes.data()); + if (auto* rawPublicKeyBytes = internal::Utilities::toTypePtr(keyBytes.data()); i2d_PUBKEY(mImpl->mKey.get(), &rawPublicKeyBytes) <= 0) { throw OpenSSLException(internal::OpenSSLUtils::getErrorMessage("i2d_PUBKEY")); diff --git a/sdk/tests/integration/BaseIntegrationTest.cc b/sdk/tests/integration/BaseIntegrationTest.cc index b442cd4e0..d320a5961 100644 --- a/sdk/tests/integration/BaseIntegrationTest.cc +++ b/sdk/tests/integration/BaseIntegrationTest.cc @@ -37,46 +37,7 @@ namespace Hedera //----- void BaseIntegrationTest::SetUp() { - const string_view networkTag = "network"; - const string_view operatorTag = "operator"; - const string_view accountIdTag = "accountId"; - const string_view privateKeyTag = "privateKey"; - - const string testPathToJSON = (filesystem::current_path() / "local_node.json").string(); - - ifstream testInputFile(testPathToJSON, ios::in); - - unordered_map networksMap; - unordered_map networkAccountsMap; - unordered_map::iterator it; - - json jsonData = json::parse(testInputFile); - jsonData[networkTag].get_to(networksMap); - - for (it = networksMap.begin(); it != networksMap.end(); it++) - { - const string_view accountIdStr = (*it).first; - const string nodeAddressString = (*it).second; - - networkAccountsMap.try_emplace(nodeAddressString, AccountId::fromString(accountIdStr)); - } - - AccountId operatorAccountId; - string operatorAccountPrivateKey; - - if (jsonData[operatorTag][accountIdTag].is_string() && jsonData[operatorTag][privateKeyTag].is_string()) - { - string operatorAccountIdStr = jsonData[operatorTag][accountIdTag]; - operatorAccountPrivateKey = jsonData[operatorTag][privateKeyTag]; - - operatorAccountId = AccountId::fromString(operatorAccountIdStr); - } - - testInputFile.close(); - - mClient = Client::forNetwork(networkAccountsMap); - mClient.setOperator(operatorAccountId, ED25519PrivateKey::fromString(operatorAccountPrivateKey)); - mClient.setMirrorNetwork({ "127.0.0.1:5600" }); + mClient = Client::fromConfigFile((filesystem::current_path() / "local_node.json").string()); mClient.setNetworkUpdatePeriod(std::chrono::hours(24)); mFileContent = internal::Utilities::stringToByteVector( From e2009b9297d03142ebea65cd1f0ae49656721826 Mon Sep 17 00:00:00 2001 From: Deyan Zhekov Date: Mon, 16 Oct 2023 11:05:59 +0300 Subject: [PATCH 7/7] Fix error for missing matching function for call. Signed-off-by: Deyan Zhekov --- sdk/main/src/Client.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/main/src/Client.cc b/sdk/main/src/Client.cc index c8dd272d4..0f6127efa 100644 --- a/sdk/main/src/Client.cc +++ b/sdk/main/src/Client.cc @@ -366,7 +366,7 @@ Client Client::fromConfig(const nlohmann::json& json) //----- Client Client::fromConfigFile(std::string_view path) { - std::ifstream infile(path); + std::ifstream infile(path.data()); if (!infile.is_open()) { throw std::invalid_argument(std::string("File cannot be found at ") + path.data());