Search in sources :

Example 26 with AccountId

use of com.hedera.hashgraph.sdk.AccountId in project hedera-sdk-java by hashgraph.

the class IntegrationTestEnv method createTestEnvClient.

@SuppressWarnings("EmptyCatch")
private static Client createTestEnvClient() throws Exception {
    if (System.getProperty("HEDERA_NETWORK").equals("previewnet")) {
        return Client.forPreviewnet();
    } else if (System.getProperty("HEDERA_NETWORK").equals("testnet")) {
        return Client.forTestnet();
    } else if (System.getProperty("HEDERA_NETWORK").equals("localhost")) {
        var network = new HashMap<String, AccountId>();
        network.put("127.0.0.1:50213", new AccountId(3));
        network.put("127.0.0.1:50214", new AccountId(4));
        network.put("127.0.0.1:50215", new AccountId(5));
        return Client.forNetwork(network);
    } else if (!System.getProperty("CONFIG_FILE").equals("")) {
        try {
            return Client.fromConfigFile(System.getProperty("CONFIG_FILE"));
        } catch (Exception configFileException) {
            configFileException.printStackTrace();
        }
    }
    throw new IllegalStateException("Failed to construct client for IntegrationTestEnv");
}
Also used : AccountId(com.hedera.hashgraph.sdk.AccountId) HashMap(java.util.HashMap) TimeoutException(java.util.concurrent.TimeoutException) PrecheckStatusException(com.hedera.hashgraph.sdk.PrecheckStatusException) ReceiptStatusException(com.hedera.hashgraph.sdk.ReceiptStatusException)

Example 27 with AccountId

use of com.hedera.hashgraph.sdk.AccountId in project hedera-sdk-java by hashgraph.

the class ClientIntegrationTest method testReplaceNodes.

@Test
@DisplayName("setNetwork() functions correctly")
void testReplaceNodes() throws Exception {
    @Var Map<String, AccountId> network = new HashMap<>();
    network.put("0.testnet.hedera.com:50211", new AccountId(3));
    network.put("1.testnet.hedera.com:50211", new AccountId(4));
    var testEnv = new IntegrationTestEnv(1);
    testEnv.client.setMaxQueryPayment(new Hbar(2)).setRequestTimeout(Duration.ofMinutes(2)).setNetwork(network);
    assertThat(testEnv.operatorId).isNotNull();
    // Execute two simple queries so we create a channel for each network node.
    new AccountBalanceQuery().setAccountId(testEnv.operatorId).execute(testEnv.client);
    new AccountBalanceQuery().setAccountId(testEnv.operatorId).execute(testEnv.client);
    network = new HashMap<>();
    network.put("1.testnet.hedera.com:50211", new AccountId(4));
    network.put("2.testnet.hedera.com:50211", new AccountId(5));
    testEnv.client.setNetwork(network);
    network = new HashMap<>();
    network.put("35.186.191.247:50211", new AccountId(4));
    network.put("35.192.2.25:50211", new AccountId(5));
    testEnv.client.setNetwork(network);
    testEnv.close();
}
Also used : AccountId(com.hedera.hashgraph.sdk.AccountId) HashMap(java.util.HashMap) Var(com.google.errorprone.annotations.Var) AccountBalanceQuery(com.hedera.hashgraph.sdk.AccountBalanceQuery) Hbar(com.hedera.hashgraph.sdk.Hbar) Test(org.junit.jupiter.api.Test) DisplayName(org.junit.jupiter.api.DisplayName)

Example 28 with AccountId

use of com.hedera.hashgraph.sdk.AccountId in project hedera-sdk-java by hashgraph.

the class ValidateChecksumExample method main.

public static void main(String[] args) throws TimeoutException, PrecheckStatusException {
    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);
    /*
         * 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 an
         * IllegalArgumentException 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 inputted 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 which network the client is connected to (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 null.
         *
         * Generally speaking, AccountId objects can come from three places:
         * 1) AccountId.fromString(inString)
         * 2) new 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.
         */
    System.out.println("An example of manual checksum validation:");
    while (true) {
        try {
            System.out.print("Enter an account ID with checksum: ");
            String inString = INPUT_SCANNER.nextLine();
            // Throws IllegalArgumentException if incorrectly formatted
            AccountId id = AccountId.fromString(inString);
            System.out.println("The ID with no checksum is " + id.toString());
            System.out.println("The ID with the correct checksum is " + id.toStringWithChecksum(client));
            if (id.getChecksum() == null) {
                System.out.println("You must enter a checksum.");
                continue;
            }
            System.out.println("The checksum entered was " + id.getChecksum());
            // Throws BadEntityIdException if checksum is incorrect
            id.validateChecksum(client);
            AccountBalance balance = new AccountBalanceQuery().setAccountId(id).execute(client);
            System.out.println(balance);
            // exit the loop
            break;
        } catch (IllegalArgumentException exc) {
            System.out.println(exc.getMessage());
        } catch (BadEntityIdException exc) {
            System.out.println(exc.getMessage());
            System.out.println("You entered " + exc.shard + "." + exc.realm + "." + exc.num + "-" + exc.presentChecksum + ", the expected checksum was " + exc.expectedChecksum);
        }
    }
    /*
         * 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 IllegalArgumentException if an
         * invalid checksum is encountered.
         */
    System.out.println("An example of automatic checksum validation:");
    client.setAutoValidateChecksums(true);
    while (true) {
        try {
            System.out.print("Enter an account ID with checksum: ");
            AccountId id = AccountId.fromString(INPUT_SCANNER.nextLine());
            if (id.getChecksum() == null) {
                System.out.println("You must enter a checksum.");
                continue;
            }
            AccountBalance balance = new AccountBalanceQuery().setAccountId(id).execute(client);
            System.out.println(balance);
            // exit the loop
            break;
        } catch (IllegalArgumentException exc) {
            System.out.println(exc.getMessage());
        }
    }
    System.out.println("Example complete!");
    client.close();
}
Also used : BadEntityIdException(com.hedera.hashgraph.sdk.BadEntityIdException) AccountId(com.hedera.hashgraph.sdk.AccountId) AccountBalance(com.hedera.hashgraph.sdk.AccountBalance) AccountBalanceQuery(com.hedera.hashgraph.sdk.AccountBalanceQuery) Client(com.hedera.hashgraph.sdk.Client)

Example 29 with AccountId

use of com.hedera.hashgraph.sdk.AccountId in project hedera-sdk-java by hashgraph.

the class TransactionIntegrationTest method transactionFromToBytes2.

// TODO: this test has a bunch of things hard-coded into it, which is kinda dumb, but it's a good idea for a test.
// Any way to fix it and bring it back?
@Disabled
@Test
@DisplayName("transaction can be serialized into bytes, deserialized, signature added and executed")
void transactionFromToBytes2() {
    assertThatNoException().isThrownBy(() -> {
        var id = TransactionId.generate(new AccountId(542348));
        var transactionBodyBuilder = TransactionBody.newBuilder();
        transactionBodyBuilder.setTransactionID(TransactionID.newBuilder().setTransactionValidStart(Timestamp.newBuilder().setNanos(id.validStart.getNano()).setSeconds(id.validStart.getEpochSecond()).build()).setAccountID(AccountID.newBuilder().setAccountNum(542348).setRealmNum(0).setShardNum(0).build()).build()).setNodeAccountID(AccountID.newBuilder().setAccountNum(3).setRealmNum(0).setShardNum(0).build()).setTransactionFee(200_000_000).setTransactionValidDuration(Duration.newBuilder().setSeconds(120).build()).setGenerateRecord(false).setMemo("").setCryptoTransfer(CryptoTransferTransactionBody.newBuilder().setTransfers(TransferList.newBuilder().addAccountAmounts(AccountAmount.newBuilder().setAccountID(AccountID.newBuilder().setAccountNum(47439).setRealmNum(0).setShardNum(0).build()).setAmount(10).build()).addAccountAmounts(AccountAmount.newBuilder().setAccountID(AccountID.newBuilder().setAccountNum(542348).setRealmNum(0).setShardNum(0).build()).setAmount(-10).build()).build()).build());
        var bodyBytes = transactionBodyBuilder.build().toByteString();
        var key1 = PrivateKey.fromString("302e020100300506032b6570042204203e7fda6dde63c3cdb3cb5ecf5264324c5faad7c9847b6db093c088838b35a110");
        var key2 = PrivateKey.fromString("302e020100300506032b65700422042032d3d5a32e9d06776976b39c09a31fbda4a4a0208223da761c26a2ae560c1755");
        var key3 = PrivateKey.fromString("302e020100300506032b657004220420195a919056d1d698f632c228dbf248bbbc3955adf8a80347032076832b8299f9");
        var key4 = PrivateKey.fromString("302e020100300506032b657004220420b9962f17f94ffce73a23649718a11638cac4b47095a7a6520e88c7563865be62");
        var key5 = PrivateKey.fromString("302e020100300506032b657004220420fef68591819080cd9d48b0cbaa10f65f919752abb50ffb3e7411ac66ab22692e");
        var publicKey1 = key1.getPublicKey();
        var publicKey2 = key2.getPublicKey();
        var publicKey3 = key3.getPublicKey();
        var publicKey4 = key4.getPublicKey();
        var publicKey5 = key5.getPublicKey();
        var signature1 = key1.sign(bodyBytes.toByteArray());
        var signature2 = key2.sign(bodyBytes.toByteArray());
        var signature3 = key3.sign(bodyBytes.toByteArray());
        var signature4 = key4.sign(bodyBytes.toByteArray());
        var signature5 = key5.sign(bodyBytes.toByteArray());
        var signedBuilder = SignedTransaction.newBuilder();
        signedBuilder.setBodyBytes(bodyBytes).setSigMap(SignatureMap.newBuilder().addSigPair(SignaturePair.newBuilder().setEd25519(ByteString.copyFrom(signature1)).setPubKeyPrefix(ByteString.copyFrom(publicKey1.toBytes())).build()).addSigPair(SignaturePair.newBuilder().setEd25519(ByteString.copyFrom(signature2)).setPubKeyPrefix(ByteString.copyFrom(publicKey2.toBytes())).build()).addSigPair(SignaturePair.newBuilder().setEd25519(ByteString.copyFrom(signature3)).setPubKeyPrefix(ByteString.copyFrom(publicKey3.toBytes())).build()).addSigPair(SignaturePair.newBuilder().setEd25519(ByteString.copyFrom(signature4)).setPubKeyPrefix(ByteString.copyFrom(publicKey4.toBytes())).build()).addSigPair(SignaturePair.newBuilder().setEd25519(ByteString.copyFrom(signature5)).setPubKeyPrefix(ByteString.copyFrom(publicKey5.toBytes())).build()));
        @Var var byts = signedBuilder.build().toByteString();
        byts = TransactionList.newBuilder().addTransactionList(com.hedera.hashgraph.sdk.proto.Transaction.newBuilder().setSignedTransactionBytes(byts).build()).build().toByteString();
        var tx = (TransferTransaction) Transaction.fromBytes(byts.toByteArray());
        var testEnv = new IntegrationTestEnv(1);
        assertThat(tx.getHbarTransfers().get(new AccountId(542348)).toTinybars()).isEqualTo(-10);
        assertThat(tx.getHbarTransfers().get(new AccountId(47439)).toTinybars()).isEqualTo(10);
        assertThat(tx.getNodeAccountIds()).isNotNull();
        assertThat(tx.getNodeAccountIds().size()).isEqualTo(1);
        assertThat(tx.getNodeAccountIds().get(0)).isEqualTo(new AccountId(3));
        var signatures = tx.getSignatures();
        assertThat(Arrays.toString(signatures.get(new AccountId(3)).get(publicKey1))).isEqualTo(Arrays.toString(signature1));
        assertThat(Arrays.toString(signatures.get(new AccountId(3)).get(publicKey2))).isEqualTo(Arrays.toString(signature2));
        assertThat(Arrays.toString(signatures.get(new AccountId(3)).get(publicKey3))).isEqualTo(Arrays.toString(signature3));
        assertThat(Arrays.toString(signatures.get(new AccountId(3)).get(publicKey4))).isEqualTo(Arrays.toString(signature4));
        assertThat(Arrays.toString(signatures.get(new AccountId(3)).get(publicKey5))).isEqualTo(Arrays.toString(signature5));
        var resp = tx.execute(testEnv.client);
        resp.getReceipt(testEnv.client);
        testEnv.close();
    });
}
Also used : AccountId(com.hedera.hashgraph.sdk.AccountId) Var(com.google.errorprone.annotations.Var) TransferTransaction(com.hedera.hashgraph.sdk.TransferTransaction) Test(org.junit.jupiter.api.Test) DisplayName(org.junit.jupiter.api.DisplayName) Disabled(org.junit.jupiter.api.Disabled)

Example 30 with AccountId

use of com.hedera.hashgraph.sdk.AccountId in project hedera-sdk-java by hashgraph.

the class ConstructClientExample method main.

public static void main(String[] args) throws Exception {
    /*
         * 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:
    Client previewClient = Client.forPreviewnet();
    Client testClient = Client.forTestnet();
    Client mainClient = Client.forMainnet();
    // 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.
    // 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 testnet.
    Client namedNetworkClient = Client.forName(HEDERA_NETWORK);
    // Let's set the operator on testClient.
    // (The AccountId and PrivateKey here are fake, this is just an example.)
    testClient.setOperator(AccountId.fromString("0.0.3"), PrivateKey.fromString("302e020100300506032b657004220420db484b828e64b2d8f12ce3c0a0e93a0b8cce7af1bb8f39c97732394482538e10"));
    // Let's create a client with a custom network.
    Map<String, AccountId> customNetwork = new HashMap<String, AccountId>();
    customNetwork.put("2.testnet.hedera.com:50211", new AccountId(5));
    customNetwork.put("3.testnet.hedera.com:50211", new AccountId(6));
    Client customClient = Client.forNetwork(customNetwork);
    // since our customClient's network is in this case a subset of testnet, we should set the
    // network's name to testnet. If we don't do this, checksum validation won't work.
    // See ValidateChecksumExample.java.  You can use customClient.getNetworkName()
    // to check the network name.  If not set, it will return null.
    // If you attempt to validate a checksum against a client whose networkName is not set,
    // an IllegalStateException will be thrown.
    customClient.setNetworkName(NetworkName.TESTNET);
    // using fromConfigFile() immediately.
    if (CONFIG_FILE != null) {
        Client configClient = Client.fromConfigFile(CONFIG_FILE);
        configClient.close();
    }
    // Always close a client when you're done with it
    previewClient.close();
    testClient.close();
    mainClient.close();
    namedNetworkClient.close();
    customClient.close();
    System.out.println("Success!");
}
Also used : AccountId(com.hedera.hashgraph.sdk.AccountId) HashMap(java.util.HashMap) Client(com.hedera.hashgraph.sdk.Client)

Aggregations

AccountId (com.hedera.hashgraph.sdk.AccountId)35 Client (com.hedera.hashgraph.sdk.Client)20 PrivateKey (com.hedera.hashgraph.sdk.PrivateKey)17 Hbar (com.hedera.hashgraph.sdk.Hbar)16 TransferTransaction (com.hedera.hashgraph.sdk.TransferTransaction)16 AccountCreateTransaction (com.hedera.hashgraph.sdk.AccountCreateTransaction)15 TransactionResponse (com.hedera.hashgraph.sdk.TransactionResponse)14 TransactionReceipt (com.hedera.hashgraph.sdk.TransactionReceipt)11 AccountBalanceQuery (com.hedera.hashgraph.sdk.AccountBalanceQuery)10 KeyList (com.hedera.hashgraph.sdk.KeyList)9 PublicKey (com.hedera.hashgraph.sdk.PublicKey)9 Var (com.google.errorprone.annotations.Var)8 ExpandedAccountId (com.hedera.mirror.test.e2e.acceptance.props.ExpandedAccountId)7 AccountDeleteTransaction (com.hedera.hashgraph.sdk.AccountDeleteTransaction)6 ScheduleId (com.hedera.hashgraph.sdk.ScheduleId)5 ScheduleInfoQuery (com.hedera.hashgraph.sdk.ScheduleInfoQuery)5 ScheduleSignTransaction (com.hedera.hashgraph.sdk.ScheduleSignTransaction)5 TimeoutException (java.util.concurrent.TimeoutException)5 AccountBalance (com.hedera.hashgraph.sdk.AccountBalance)4 ScheduleCreateTransaction (com.hedera.hashgraph.sdk.ScheduleCreateTransaction)4