use of com.hedera.hashgraph.sdk.PrivateKey in project hedera-mirror-node by hashgraph.
the class AbstractNetworkClient method executeTransaction.
public TransactionId executeTransaction(Transaction transaction, KeyList keyList, ExpandedAccountId payer) {
int numSignatures = 0;
// set max retries on sdk
transaction.setMaxAttempts(sdkClient.getAcceptanceTestProperties().getSdkProperties().getMaxAttempts());
if (payer != null) {
transaction.setTransactionId(TransactionId.generate(payer.getAccountId()));
transaction.freezeWith(client);
transaction.sign(payer.getPrivateKey());
numSignatures++;
}
if (keyList != null) {
// Signing requires transaction to be frozen
transaction.freezeWith(client);
for (Key k : keyList) {
transaction.sign((PrivateKey) k);
}
log.debug("{} additional signatures added to transaction", keyList.size());
numSignatures += keyList.size();
}
TransactionResponse transactionResponse = retryTemplate.execute(x -> executeTransaction(transaction));
TransactionId transactionId = transactionResponse.transactionId;
log.debug("Executed transaction {} with {} signatures.", transactionId, numSignatures);
return transactionId;
}
use of com.hedera.hashgraph.sdk.PrivateKey in project hedera-mirror-node by hashgraph.
the class ExpressionConverterImpl method doConvert.
private synchronized String doConvert(Expression expression) {
if (expressions.containsKey(expression)) {
return expressions.get(expression);
}
try {
log.debug("Processing expression {}", expression);
ExpressionType type = expression.getType();
Class<? extends TransactionSupplier<?>> supplierClass = type.getTransactionType().getSupplier();
TransactionSupplier<?> transactionSupplier = supplierClass.getConstructor().newInstance();
if (transactionSupplier instanceof AdminKeyable) {
AdminKeyable adminKeyable = (AdminKeyable) transactionSupplier;
PrivateKey privateKey = PrivateKey.fromString(monitorProperties.getOperator().getPrivateKey());
adminKeyable.setAdminKey(privateKey.getPublicKey().toString());
}
if (transactionSupplier instanceof TokenCreateTransactionSupplier) {
TokenCreateTransactionSupplier tokenSupplier = (TokenCreateTransactionSupplier) transactionSupplier;
tokenSupplier.setTreasuryAccountId(monitorProperties.getOperator().getAccountId());
if (type == ExpressionType.NFT) {
tokenSupplier.setType(TokenType.NON_FUNGIBLE_UNIQUE);
}
}
// if ScheduleCreate set the properties to the inner scheduledTransactionProperties
if (transactionSupplier instanceof ScheduleCreateTransactionSupplier) {
var scheduleCreateTransactionSupplier = (ScheduleCreateTransactionSupplier) transactionSupplier;
scheduleCreateTransactionSupplier.setOperatorAccountId(monitorProperties.getOperator().getAccountId());
scheduleCreateTransactionSupplier.setPayerAccount(monitorProperties.getOperator().getAccountId());
}
PublishScenarioProperties publishScenarioProperties = new PublishScenarioProperties();
publishScenarioProperties.setName(expression.toString());
publishScenarioProperties.setTimeout(Duration.ofSeconds(30L));
publishScenarioProperties.setType(type.getTransactionType());
PublishScenario scenario = new PublishScenario(publishScenarioProperties);
// We use explicit retry instead of the SDK retry since we need to regenerate the transaction to
// avoid transaction expired errors
Retry retrySpec = Retry.backoff(Long.MAX_VALUE, Duration.ofSeconds(1L)).maxBackoff(Duration.ofSeconds(8L)).doBeforeRetry(r -> log.warn("Retry attempt #{} after failure: {}", r.totalRetries() + 1, r.failure().getMessage()));
return Mono.defer(() -> transactionPublisher.publish(PublishRequest.builder().receipt(true).scenario(scenario).timestamp(Instant.now()).transaction(transactionSupplier.get().setMaxAttempts(1).setTransactionMemo(scenario.getMemo())).build())).retryWhen(retrySpec).map(PublishResponse::getReceipt).map(type.getIdExtractor()::apply).doOnSuccess(id -> log.info("Created {} entity {}", type, id)).toFuture().join();
} catch (Exception e) {
log.error("Error converting expression {}:", expression, e);
throw new RuntimeException(e);
}
}
use of com.hedera.hashgraph.sdk.PrivateKey in project hedera-sdk-java by hashgraph.
the class ScheduleCreateIntegrationTest method canScheduleTokenTransfer.
@Test
@DisplayName("Can schedule token transfer")
void canScheduleTokenTransfer() throws Exception {
var testEnv = new IntegrationTestEnv(1).useThrowawayAccount();
PrivateKey key = PrivateKey.generateED25519();
var accountId = new AccountCreateTransaction().setReceiverSignatureRequired(true).setKey(key).setInitialBalance(new Hbar(10)).freezeWith(testEnv.client).sign(key).execute(testEnv.client).getReceipt(testEnv.client).accountId;
Objects.requireNonNull(accountId);
var tokenId = new TokenCreateTransaction().setTokenName("ffff").setTokenSymbol("F").setInitialSupply(100).setTreasuryAccountId(testEnv.operatorId).setAdminKey(testEnv.operatorKey).execute(testEnv.client).getReceipt(testEnv.client).tokenId;
Objects.requireNonNull(tokenId);
new TokenAssociateTransaction().setAccountId(accountId).setTokenIds(Collections.singletonList(tokenId)).freezeWith(testEnv.client).sign(key).execute(testEnv.client).getReceipt(testEnv.client);
var scheduleId = new TransferTransaction().addTokenTransfer(tokenId, testEnv.operatorId, -10).addTokenTransfer(tokenId, accountId, 10).schedule().execute(testEnv.client).getReceipt(testEnv.client).scheduleId;
Objects.requireNonNull(scheduleId);
var balanceQuery1 = new AccountBalanceQuery().setAccountId(accountId).execute(testEnv.client);
assertThat(balanceQuery1.tokens.get(tokenId)).isEqualTo(0);
new ScheduleSignTransaction().setScheduleId(scheduleId).freezeWith(testEnv.client).sign(key).execute(testEnv.client).getReceipt(testEnv.client);
var balanceQuery2 = new AccountBalanceQuery().setAccountId(accountId).execute(testEnv.client);
assertThat(balanceQuery2.tokens.get(tokenId)).isEqualTo(10);
testEnv.close(tokenId, accountId, key);
}
use of com.hedera.hashgraph.sdk.PrivateKey in project hedera-sdk-java by hashgraph.
the class ScheduleCreateIntegrationTest method canSignSchedule2.
@Test
@DisplayName("Can sign schedule")
void canSignSchedule2() throws Exception {
var testEnv = new IntegrationTestEnv(1);
PrivateKey key1 = PrivateKey.generateED25519();
PrivateKey key2 = PrivateKey.generateED25519();
PrivateKey key3 = PrivateKey.generateED25519();
KeyList keyList = new KeyList();
keyList.add(key1.getPublicKey());
keyList.add(key2.getPublicKey());
keyList.add(key3.getPublicKey());
// Creat the account with the `KeyList`
TransactionResponse response = new AccountCreateTransaction().setKey(keyList).setInitialBalance(new Hbar(10)).execute(testEnv.client);
// This will wait for the receipt to become available
@Var TransactionReceipt receipt = response.getReceipt(testEnv.client);
AccountId accountId = Objects.requireNonNull(receipt.accountId);
// Generate a `TransactionId`. This id is used to query the inner scheduled transaction
// after we expect it to have been executed
TransactionId transactionId = TransactionId.generate(testEnv.operatorId);
// Create a transfer transaction with 2/3 signatures.
TransferTransaction transfer = new TransferTransaction().setTransactionId(transactionId).addHbarTransfer(accountId, new Hbar(1).negated()).addHbarTransfer(testEnv.operatorId, new Hbar(1));
// Schedule the transactoin
ScheduleCreateTransaction scheduled = transfer.schedule();
receipt = scheduled.execute(testEnv.client).getReceipt(testEnv.client);
// Get the schedule ID from the receipt
ScheduleId scheduleId = Objects.requireNonNull(receipt.scheduleId);
// Get the schedule info to see if `signatories` is populated with 2/3 signatures
@Var ScheduleInfo info = new ScheduleInfoQuery().setScheduleId(scheduleId).execute(testEnv.client);
assertThat(info.executedAt).isNull();
// Finally send this last signature to Hedera. This last signature _should_ mean the transaction executes
// since all 3 signatures have been provided.
ScheduleSignTransaction signTransaction = new ScheduleSignTransaction().setScheduleId(scheduleId).freezeWith(testEnv.client);
signTransaction.sign(key1).sign(key2).sign(key3).execute(testEnv.client).getReceipt(testEnv.client);
info = new ScheduleInfoQuery().setScheduleId(scheduleId).execute(testEnv.client);
assertThat(info.executedAt).isNotNull();
new AccountDeleteTransaction().setAccountId(accountId).setTransferAccountId(testEnv.operatorId).freezeWith(testEnv.client).sign(key1).sign(key2).sign(key3).execute(testEnv.client).getReceipt(testEnv.client);
testEnv.close();
}
use of com.hedera.hashgraph.sdk.PrivateKey in project hedera-sdk-java by hashgraph.
the class ScheduledTransactionMultiSigThresholdExample method main.
// public static void main(String[] args) throws PrecheckStatusException, IOException, TimeoutException, ReceiptStatusException {
public static void main(String[] args) throws PrecheckStatusException, TimeoutException, ReceiptStatusException {
Client client = Client.forName(HEDERA_NETWORK);
// Defaults 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.setOperator(OPERATOR_ID, OPERATOR_KEY);
// Generate four new Ed25519 private, public key pairs.
PrivateKey[] privateKeys = new PrivateKey[4];
PublicKey[] publicKeys = new PublicKey[4];
for (int i = 0; i < 4; i++) {
PrivateKey key = PrivateKey.generateED25519();
privateKeys[i] = key;
publicKeys[i] = key.getPublicKey();
System.out.println("public key " + (i + 1) + ": " + publicKeys[i]);
System.out.println("private key " + (i + 1) + ": " + privateKeys[i]);
}
// require 3 of the 4 keys we generated to sign on anything modifying this account
KeyList transactionKey = KeyList.withThreshold(3);
Collections.addAll(transactionKey, publicKeys);
TransactionResponse transactionResponse = new AccountCreateTransaction().setKey(transactionKey).setInitialBalance(Hbar.fromTinybars(1)).setAccountMemo("3-of-4 multi-sig account").execute(client);
// This will wait for the receipt to become available
TransactionReceipt txAccountCreateReceipt = transactionResponse.getReceipt(client);
AccountId multiSigAccountId = Objects.requireNonNull(txAccountCreateReceipt.accountId);
System.out.println("3-of-4 multi-sig account ID: " + multiSigAccountId);
AccountBalance balance = new AccountBalanceQuery().setAccountId(multiSigAccountId).execute(client);
System.out.println("Balance of account " + multiSigAccountId + ": " + balance.hbars.toTinybars() + " tinybar.");
// schedule crypto transfer from multi-sig account to operator account
TransactionResponse transferToSchedule = new TransferTransaction().addHbarTransfer(multiSigAccountId, Hbar.fromTinybars(-1)).addHbarTransfer(Objects.requireNonNull(client.getOperatorAccountId()), Hbar.fromTinybars(1)).schedule().freezeWith(client).sign(// add 1 signature`
privateKeys[0]).execute(client);
TransactionReceipt txScheduleReceipt = transferToSchedule.getReceipt(client);
System.out.println("Schedule status: " + txScheduleReceipt.status);
ScheduleId scheduleId = Objects.requireNonNull(txScheduleReceipt.scheduleId);
System.out.println("Schedule ID: " + scheduleId);
TransactionId scheduledTxId = Objects.requireNonNull(txScheduleReceipt.scheduledTransactionId);
System.out.println("Scheduled tx ID: " + scheduledTxId);
// add 2 signature
TransactionResponse txScheduleSign1 = new ScheduleSignTransaction().setScheduleId(scheduleId).freezeWith(client).sign(privateKeys[1]).execute(client);
TransactionReceipt txScheduleSign1Receipt = txScheduleSign1.getReceipt(client);
System.out.println("1. ScheduleSignTransaction status: " + txScheduleSign1Receipt.status);
// add 3 signature
TransactionResponse txScheduleSign2 = new ScheduleSignTransaction().setScheduleId(scheduleId).freezeWith(client).sign(privateKeys[2]).execute(client);
TransactionReceipt txScheduleSign2Receipt = txScheduleSign2.getReceipt(client);
System.out.println("2. ScheduleSignTransaction status: " + txScheduleSign2Receipt.status);
// query schedule
ScheduleInfo scheduleInfo = new ScheduleInfoQuery().setScheduleId(scheduleId).execute(client);
System.out.println(scheduleInfo);
// query triggered scheduled tx
TransactionRecord recordScheduledTx = new TransactionRecordQuery().setTransactionId(scheduledTxId).execute(client);
System.out.println(recordScheduledTx);
}
Aggregations