github.com/hashgraph/hedera-sdk-go/v2@v2.48.0/client.go (about)

     1  package hedera
     2  
     3  /*-
     4   *
     5   * Hedera Go SDK
     6   *
     7   * Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC
     8   *
     9   * Licensed under the Apache License, Version 2.0 (the "License");
    10   * you may not use this file except in compliance with the License.
    11   * You may obtain a copy of the License at
    12   *
    13   *      http://www.apache.org/licenses/LICENSE-2.0
    14   *
    15   * Unless required by applicable law or agreed to in writing, software
    16   * distributed under the License is distributed on an "AS IS" BASIS,
    17   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    18   * See the License for the specific language governing permissions and
    19   * limitations under the License.
    20   *
    21   */
    22  
    23  import (
    24  	"context"
    25  	_ "embed"
    26  	"encoding/json"
    27  	"errors"
    28  	"fmt"
    29  	"io"
    30  	"os"
    31  	"time"
    32  )
    33  
    34  //go:embed addressbook/mainnet.pb
    35  var mainnetAddress []byte
    36  var mainnetNodes, _ = NodeAddressBookFromBytes(mainnetAddress)
    37  
    38  //go:embed addressbook/previewnet.pb
    39  var previewnetAddress []byte
    40  var previewnetNodes, _ = NodeAddressBookFromBytes(previewnetAddress)
    41  
    42  //go:embed addressbook/testnet.pb
    43  var testnetAddress []byte
    44  var testnetNodes, _ = NodeAddressBookFromBytes(testnetAddress)
    45  
    46  // Client is the Hedera protocol wrapper for the SDK used by all
    47  // transaction and query types.
    48  type Client struct {
    49  	defaultMaxTransactionFee Hbar
    50  	defaultMaxQueryPayment   Hbar
    51  
    52  	operator *_Operator
    53  
    54  	network                         _Network
    55  	mirrorNetwork                   *_MirrorNetwork
    56  	autoValidateChecksums           bool
    57  	defaultRegenerateTransactionIDs bool
    58  	maxAttempts                     *int
    59  
    60  	maxBackoff time.Duration
    61  	minBackoff time.Duration
    62  
    63  	requestTimeout             *time.Duration
    64  	defaultNetworkUpdatePeriod time.Duration
    65  	networkUpdateContext       context.Context
    66  	cancelNetworkUpdate        context.CancelFunc
    67  	logger                     Logger
    68  }
    69  
    70  // TransactionSigner is a closure or function that defines how transactions will be signed
    71  type TransactionSigner func(message []byte) []byte
    72  
    73  type _Operator struct {
    74  	accountID  AccountID
    75  	privateKey *PrivateKey
    76  	publicKey  PublicKey
    77  	signer     TransactionSigner
    78  }
    79  
    80  var mainnetMirror = []string{"mainnet-public.mirrornode.hedera.com:443"}
    81  var testnetMirror = []string{"testnet.mirrornode.hedera.com:443"}
    82  var previewnetMirror = []string{"previewnet.mirrornode.hedera.com:443"}
    83  
    84  // ClientForNetwork constructs a client given a set of nodes.
    85  func ClientForNetwork(network map[string]AccountID) *Client {
    86  	net := _NewNetwork()
    87  	client := _NewClient(net, []string{}, nil)
    88  	_ = client.SetNetwork(network)
    89  	net._SetLedgerID(*NewLedgerIDMainnet())
    90  	return client
    91  }
    92  
    93  // ClientForMainnet returns a preconfigured client for use with the standard
    94  // Hedera mainnet.
    95  // Most users will want to set an _Operator account with .SetOperator so
    96  // transactions can be automatically given TransactionIDs and signed.
    97  func ClientForMainnet() *Client {
    98  	return _NewClient(*_NetworkForMainnet(mainnetNodes._ToMap()), mainnetMirror, NewLedgerIDMainnet())
    99  }
   100  
   101  // ClientForTestnet returns a preconfigured client for use with the standard
   102  // Hedera testnet.
   103  // Most users will want to set an _Operator account with .SetOperator so
   104  // transactions can be automatically given TransactionIDs and signed.
   105  func ClientForTestnet() *Client {
   106  	return _NewClient(*_NetworkForTestnet(testnetNodes._ToMap()), testnetMirror, NewLedgerIDTestnet())
   107  }
   108  
   109  // ClientForPreviewnet returns a preconfigured client for use with the standard
   110  // Hedera previewnet.
   111  // Most users will want to set an _Operator account with .SetOperator so
   112  // transactions can be automatically given TransactionIDs and signed.
   113  func ClientForPreviewnet() *Client {
   114  	return _NewClient(*_NetworkForPreviewnet(previewnetNodes._ToMap()), previewnetMirror, NewLedgerIDPreviewnet())
   115  }
   116  
   117  // newClient takes in a map of _Node addresses to their respective IDS (_Network)
   118  // and returns a Client instance which can be used to
   119  func _NewClient(network _Network, mirrorNetwork []string, ledgerId *LedgerID) *Client {
   120  	ctx, cancel := context.WithCancel(context.Background())
   121  	logger := NewLogger("hedera-sdk-go", LogLevel(os.Getenv("HEDERA_SDK_GO_LOG_LEVEL")))
   122  	var defaultLogger Logger = logger
   123  
   124  	client := Client{
   125  		defaultMaxQueryPayment:          NewHbar(1),
   126  		network:                         network,
   127  		mirrorNetwork:                   _NewMirrorNetwork(),
   128  		autoValidateChecksums:           false,
   129  		maxAttempts:                     nil,
   130  		minBackoff:                      250 * time.Millisecond,
   131  		maxBackoff:                      8 * time.Second,
   132  		defaultRegenerateTransactionIDs: true,
   133  		defaultNetworkUpdatePeriod:      24 * time.Hour,
   134  		networkUpdateContext:            ctx,
   135  		cancelNetworkUpdate:             cancel,
   136  		logger:                          defaultLogger,
   137  	}
   138  
   139  	client.SetMirrorNetwork(mirrorNetwork)
   140  	if ledgerId != nil {
   141  		client.SetLedgerID(*ledgerId)
   142  	}
   143  
   144  	// We can't ask for AddressBook from non existent Mirror node
   145  	if len(mirrorNetwork) > 0 {
   146  		// Update the Addressbook, before the default timeout starts
   147  		client._UpdateAddressBook()
   148  		go client._ScheduleNetworkUpdate(ctx, client.defaultNetworkUpdatePeriod)
   149  	}
   150  
   151  	return &client
   152  }
   153  
   154  func (client *Client) _UpdateAddressBook() {
   155  	addressbook, err := NewAddressBookQuery().
   156  		SetFileID(FileIDForAddressBook()).
   157  		Execute(client)
   158  	if err == nil && len(addressbook.NodeAddresses) > 0 {
   159  		client.SetNetworkFromAddressBook(addressbook)
   160  	}
   161  }
   162  
   163  func (client *Client) _ScheduleNetworkUpdate(ctx context.Context, duration time.Duration) {
   164  	for {
   165  		select {
   166  		case <-ctx.Done():
   167  			return
   168  		case <-time.After(duration):
   169  			client._UpdateAddressBook()
   170  		}
   171  	}
   172  }
   173  
   174  // CancelScheduledNetworkUpdate cancels the scheduled network update the network address book
   175  func (client *Client) CancelScheduledNetworkUpdate() {
   176  	client.cancelNetworkUpdate()
   177  }
   178  
   179  // SetNetworkUpdatePeriod sets how often the client will update the network address book
   180  func (client *Client) SetNetworkUpdatePeriod(period time.Duration) *Client {
   181  	client.defaultNetworkUpdatePeriod = period
   182  	client.CancelScheduledNetworkUpdate()
   183  	client.networkUpdateContext, client.cancelNetworkUpdate = context.WithCancel(context.Background())
   184  	go client._ScheduleNetworkUpdate(client.networkUpdateContext, period)
   185  	return client
   186  }
   187  
   188  // GetNetworkUpdatePeriod returns the current network update period
   189  func (client *Client) GetNetworkUpdatePeriod() time.Duration {
   190  	return client.defaultNetworkUpdatePeriod
   191  }
   192  
   193  // ClientForName set up the client for the selected network.
   194  func ClientForName(name string) (*Client, error) {
   195  	switch name {
   196  	case string(NetworkNameTestnet):
   197  		return ClientForTestnet(), nil
   198  	case string(NetworkNamePreviewnet):
   199  		return ClientForPreviewnet(), nil
   200  	case string(NetworkNameMainnet):
   201  		return ClientForMainnet(), nil
   202  	case "local", "localhost":
   203  		network := make(map[string]AccountID)
   204  		network["127.0.0.1:50213"] = AccountID{Account: 3}
   205  		mirror := []string{"127.0.0.1:5600"}
   206  		client := ClientForNetwork(network)
   207  		client.SetMirrorNetwork(mirror)
   208  		return client, nil
   209  	default:
   210  		return &Client{}, fmt.Errorf("%q is not recognized as a valid Hedera _Network", name)
   211  	}
   212  }
   213  
   214  type _ConfigOperator struct {
   215  	AccountID  string `json:"accountId"`
   216  	PrivateKey string `json:"privateKey"`
   217  }
   218  
   219  // TODO: Implement complete spec: https://gitlab.com/launchbadge/hedera/sdk/python/-/issues/45
   220  type _ClientConfig struct {
   221  	Network       interface{}      `json:"network"`
   222  	MirrorNetwork interface{}      `json:"mirrorNetwork"`
   223  	Operator      *_ConfigOperator `json:"operator"`
   224  }
   225  
   226  // ClientFromConfig takes in the byte slice representation of a JSON string or
   227  // document and returns Client based on the configuration.
   228  func ClientFromConfig(jsonBytes []byte) (*Client, error) {
   229  	var clientConfig _ClientConfig
   230  	var client *Client
   231  
   232  	err := json.Unmarshal(jsonBytes, &clientConfig)
   233  	if err != nil {
   234  		return nil, err
   235  	}
   236  
   237  	network := _NewNetwork()
   238  	networkAddresses := make(map[string]AccountID)
   239  
   240  	switch net := clientConfig.Network.(type) {
   241  	case map[string]interface{}:
   242  		for url, inter := range net {
   243  			switch id := inter.(type) {
   244  			case string:
   245  				accountID, err := AccountIDFromString(id)
   246  				if err != nil {
   247  					return client, err
   248  				}
   249  				networkAddresses[url] = accountID
   250  			default:
   251  				return client, errors.New("network is expected to be map of string to string, or string")
   252  			}
   253  		}
   254  		err = network.SetNetwork(networkAddresses)
   255  		if err != nil {
   256  			return &Client{}, err
   257  		}
   258  	case string:
   259  		if len(net) > 0 {
   260  			switch net {
   261  			case string(NetworkNameMainnet):
   262  				network = *_NetworkForMainnet(mainnetNodes._ToMap())
   263  			case string(NetworkNamePreviewnet):
   264  				network = *_NetworkForPreviewnet(previewnetNodes._ToMap())
   265  			case string(NetworkNameTestnet):
   266  				network = *_NetworkForTestnet(testnetNodes._ToMap())
   267  			}
   268  		}
   269  	default:
   270  		return client, errors.New("network is expected to be map of string to string, or string")
   271  	}
   272  
   273  	switch mirror := clientConfig.MirrorNetwork.(type) {
   274  	case []interface{}:
   275  		arr := make([]string, len(mirror))
   276  		for i, inter := range mirror {
   277  			switch str := inter.(type) {
   278  			case string:
   279  				arr[i] = str
   280  			default:
   281  				return client, errors.New("mirrorNetwork is expected to be either string or an array of strings")
   282  			}
   283  		}
   284  		client = _NewClient(network, arr, nil)
   285  	case string:
   286  		if len(mirror) > 0 {
   287  			switch mirror {
   288  			case string(NetworkNameMainnet):
   289  				client = _NewClient(network, mainnetMirror, NewLedgerIDMainnet())
   290  			case string(NetworkNameTestnet):
   291  				client = _NewClient(network, testnetMirror, NewLedgerIDTestnet())
   292  			case string(NetworkNamePreviewnet):
   293  				client = _NewClient(network, previewnetMirror, NewLedgerIDPreviewnet())
   294  			}
   295  		}
   296  	case nil:
   297  		client = _NewClient(network, []string{}, nil)
   298  	default:
   299  		return client, errors.New("mirrorNetwork is expected to be a string, an array of strings or nil")
   300  	}
   301  
   302  	// if the _Operator is not provided, finish here
   303  	if clientConfig.Operator == nil {
   304  		return client, nil
   305  	}
   306  
   307  	operatorID, err := AccountIDFromString(clientConfig.Operator.AccountID)
   308  	if err != nil {
   309  		return client, err
   310  	}
   311  
   312  	operatorKey, err := PrivateKeyFromString(clientConfig.Operator.PrivateKey)
   313  
   314  	if err != nil {
   315  		return client, err
   316  	}
   317  
   318  	operator := _Operator{
   319  		accountID:  operatorID,
   320  		privateKey: &operatorKey,
   321  		publicKey:  operatorKey.PublicKey(),
   322  		signer:     operatorKey.Sign,
   323  	}
   324  
   325  	client.operator = &operator
   326  
   327  	return client, nil
   328  }
   329  
   330  // ClientFromConfigFile takes a filename string representing the path to a JSON encoded
   331  // Client file and returns a Client based on the configuration.
   332  func ClientFromConfigFile(filename string) (*Client, error) {
   333  	file, err := os.Open(filename)
   334  	if err != nil {
   335  		return nil, err
   336  	}
   337  
   338  	defer func() {
   339  		err = file.Close()
   340  	}()
   341  
   342  	configBytes, err := io.ReadAll(file)
   343  	if err != nil {
   344  		return nil, err
   345  	}
   346  
   347  	return ClientFromConfig(configBytes)
   348  }
   349  
   350  // Close is used to disconnect the Client from the _Network
   351  func (client *Client) Close() error {
   352  	client.CancelScheduledNetworkUpdate()
   353  	err := client.network._Close()
   354  	if err != nil {
   355  		return err
   356  	}
   357  	err = client.mirrorNetwork._Close()
   358  	if err != nil {
   359  		return err
   360  	}
   361  
   362  	return nil
   363  }
   364  
   365  // SetNetwork replaces all nodes in this Client with a new set of nodes.
   366  func (client *Client) SetNetwork(network map[string]AccountID) error {
   367  	return client.network.SetNetwork(network)
   368  }
   369  
   370  // GetNetwork returns the current set of nodes in this Client.
   371  func (client *Client) GetNetwork() map[string]AccountID {
   372  	return client.network._GetNetwork()
   373  }
   374  
   375  // SetMaxNodeReadmitTime The maximum amount of time to wait before attempting to
   376  // reconnect to a node that has been removed from the network.
   377  func (client *Client) SetMaxNodeReadmitTime(readmitTime time.Duration) {
   378  	client.network._SetMaxNodeReadmitPeriod(readmitTime)
   379  }
   380  
   381  // GetMaxNodeReadmitTime returns the maximum amount of time to wait before attempting to
   382  // reconnect to a node that has been removed from the network.
   383  func (client *Client) GetMaxNodeReadmitPeriod() time.Duration {
   384  	return client.network._GetMaxNodeReadmitPeriod()
   385  }
   386  
   387  // SetMinNodeReadmitTime The minimum amount of time to wait before attempting to
   388  // reconnect to a node that has been removed from the network.
   389  func (client *Client) SetMinNodeReadmitTime(readmitTime time.Duration) {
   390  	client.network._SetMinNodeReadmitPeriod(readmitTime)
   391  }
   392  
   393  // GetMinNodeReadmitTime returns the minimum amount of time to wait before attempting to
   394  // reconnect to a node that has been removed from the network.
   395  func (client *Client) GetMinNodeReadmitPeriod() time.Duration {
   396  	return client.network._GetMinNodeReadmitPeriod()
   397  }
   398  
   399  // SetMaxBackoff The maximum amount of time to wait between retries.
   400  // Every retry attempt will increase the wait time exponentially until it reaches this time.
   401  func (client *Client) SetMaxBackoff(max time.Duration) {
   402  	if max.Nanoseconds() < 0 {
   403  		panic("maxBackoff must be a positive duration")
   404  	} else if max.Nanoseconds() < client.minBackoff.Nanoseconds() {
   405  		panic("maxBackoff must be greater than or equal to minBackoff")
   406  	}
   407  	client.maxBackoff = max
   408  }
   409  
   410  // GetMaxBackoff returns the maximum amount of time to wait between retries.
   411  func (client *Client) GetMaxBackoff() time.Duration {
   412  	return client.maxBackoff
   413  }
   414  
   415  // SetMinBackoff sets the minimum amount of time to wait between retries.
   416  func (client *Client) SetMinBackoff(min time.Duration) {
   417  	if min.Nanoseconds() < 0 {
   418  		panic("minBackoff must be a positive duration")
   419  	} else if client.maxBackoff.Nanoseconds() < min.Nanoseconds() {
   420  		panic("minBackoff must be less than or equal to maxBackoff")
   421  	}
   422  	client.minBackoff = min
   423  }
   424  
   425  // GetMinBackoff returns the minimum amount of time to wait between retries.
   426  func (client *Client) GetMinBackoff() time.Duration {
   427  	return client.minBackoff
   428  }
   429  
   430  // SetMaxAttempts sets the maximum number of times to attempt a transaction or query.
   431  func (client *Client) SetMaxAttempts(max int) {
   432  	client.maxAttempts = &max
   433  }
   434  
   435  // GetMaxAttempts returns the maximum number of times to attempt a transaction or query.
   436  func (client *Client) GetMaxAttempts() int {
   437  	if client.maxAttempts == nil {
   438  		return -1
   439  	}
   440  
   441  	return *client.maxAttempts
   442  }
   443  
   444  // SetMaxNodeAttempts sets the maximum number of times to attempt a transaction or query on a single node.
   445  func (client *Client) SetMaxNodeAttempts(max int) {
   446  	client.network._SetMaxNodeAttempts(max)
   447  }
   448  
   449  // GetMaxNodeAttempts returns the maximum number of times to attempt a transaction or query on a single node.
   450  func (client *Client) GetMaxNodeAttempts() int {
   451  	return client.network._GetMaxNodeAttempts()
   452  }
   453  
   454  // Deprecated: use SetNodeMinBackoff
   455  func (client *Client) SetNodeWaitTime(nodeWait time.Duration) {
   456  	client.network._SetNodeMinBackoff(nodeWait)
   457  }
   458  
   459  // Deprecated: use GetNodeMinBackoff
   460  func (client *Client) GetNodeWaitTime() time.Duration {
   461  	return client.network._GetNodeMinBackoff()
   462  }
   463  
   464  // SetNodeMinBackoff sets the minimum amount of time to wait between retries on a single node.
   465  func (client *Client) SetNodeMinBackoff(nodeWait time.Duration) {
   466  	client.network._SetNodeMinBackoff(nodeWait)
   467  }
   468  
   469  // GetNodeMinBackoff returns the minimum amount of time to wait between retries on a single node.
   470  func (client *Client) GetNodeMinBackoff() time.Duration {
   471  	return client.network._GetNodeMinBackoff()
   472  }
   473  
   474  // SetNodeMaxBackoff sets the maximum amount of time to wait between retries on a single node.
   475  func (client *Client) SetNodeMaxBackoff(nodeWait time.Duration) {
   476  	client.network._SetNodeMaxBackoff(nodeWait)
   477  }
   478  
   479  // GetNodeMaxBackoff returns the maximum amount of time to wait between retries on a single node.
   480  func (client *Client) GetNodeMaxBackoff() time.Duration {
   481  	return client.network._GetNodeMaxBackoff()
   482  }
   483  
   484  // SetMaxNodesPerTransaction sets the maximum number of nodes to try for a single transaction.
   485  func (client *Client) SetMaxNodesPerTransaction(max int) {
   486  	client.network._SetMaxNodesPerTransaction(max)
   487  }
   488  
   489  // SetNetwork replaces all _Nodes in the Client with a new set of _Nodes.
   490  // (e.g. for an Address Book update).
   491  func (client *Client) SetMirrorNetwork(mirrorNetwork []string) {
   492  	_ = client.mirrorNetwork._SetNetwork(mirrorNetwork)
   493  }
   494  
   495  // GetNetwork returns the mirror network node list.
   496  func (client *Client) GetMirrorNetwork() []string {
   497  	return client.mirrorNetwork._GetNetwork()
   498  }
   499  
   500  // SetTransportSecurity sets if transport security should be used to connect to consensus nodes.
   501  // If transport security is enabled all connections to consensus nodes will use TLS, and
   502  // the server's certificate hash will be compared to the hash stored in the NodeAddressBook
   503  // for the given network.
   504  // *Note*: If transport security is enabled, but {@link Client#isVerifyCertificates()} is disabled
   505  // then server certificates will not be verified.
   506  func (client *Client) SetTransportSecurity(tls bool) *Client {
   507  	client.network._SetTransportSecurity(tls)
   508  
   509  	return client
   510  }
   511  
   512  // SetCertificateVerification sets if server certificates should be verified against an existing address book.
   513  func (client *Client) SetCertificateVerification(verify bool) *Client {
   514  	client.network._SetVerifyCertificate(verify)
   515  
   516  	return client
   517  }
   518  
   519  // GetCertificateVerification returns if server certificates should be verified against an existing address book.
   520  func (client *Client) GetCertificateVerification() bool {
   521  	return client.network._GetVerifyCertificate()
   522  }
   523  
   524  // Deprecated: Use SetLedgerID instead
   525  func (client *Client) SetNetworkName(name NetworkName) {
   526  	ledgerID, _ := LedgerIDFromNetworkName(name)
   527  	client.SetLedgerID(*ledgerID)
   528  }
   529  
   530  // Deprecated: Use GetLedgerID instead
   531  func (client *Client) GetNetworkName() *NetworkName {
   532  	name, _ := client.GetLedgerID().ToNetworkName()
   533  	return &name
   534  }
   535  
   536  // SetLedgerID sets the ledger ID for the Client.
   537  func (client *Client) SetLedgerID(id LedgerID) {
   538  	client.network._SetLedgerID(id)
   539  }
   540  
   541  // GetLedgerID returns the ledger ID for the Client.
   542  func (client *Client) GetLedgerID() *LedgerID {
   543  	return client.network._GetLedgerID()
   544  }
   545  
   546  // SetAutoValidateChecksums sets if an automatic entity ID checksum validation should be performed.
   547  func (client *Client) SetAutoValidateChecksums(validate bool) {
   548  	client.autoValidateChecksums = validate
   549  }
   550  
   551  // GetAutoValidateChecksums returns if an automatic entity ID checksum validation should be performed.
   552  func (client *Client) GetAutoValidateChecksums() bool {
   553  	return client.autoValidateChecksums
   554  }
   555  
   556  // SetDefaultRegenerateTransactionIDs sets if an automatic transaction ID regeneration should be performed.
   557  func (client *Client) SetDefaultRegenerateTransactionIDs(regen bool) {
   558  	client.defaultRegenerateTransactionIDs = regen
   559  }
   560  
   561  // GetDefaultRegenerateTransactionIDs returns if an automatic transaction ID regeneration should be performed.
   562  func (client *Client) GetDefaultRegenerateTransactionIDs() bool {
   563  	return client.defaultRegenerateTransactionIDs
   564  }
   565  
   566  // SetNodeMinReadmitPeriod sets the minimum amount of time to wait before attempting to
   567  // reconnect to a node that has been removed from the network.
   568  func (client *Client) SetNodeMinReadmitPeriod(period time.Duration) {
   569  	client.network._SetNodeMinReadmitPeriod(period)
   570  }
   571  
   572  // SetNodeMaxReadmitPeriod sets the maximum amount of time to wait before attempting to
   573  // reconnect to a node that has been removed from the network.
   574  func (client *Client) SetNodeMaxReadmitPeriod(period time.Duration) {
   575  	client.network._SetNodeMaxReadmitPeriod(period)
   576  }
   577  
   578  // GetNodeMinReadmitPeriod returns the minimum amount of time to wait before attempting to
   579  // reconnect to a node that has been removed from the network.
   580  func (client *Client) GetNodeMinReadmitPeriod() time.Duration {
   581  	return client.network._GetNodeMinReadmitPeriod()
   582  }
   583  
   584  // GetNodeMaxReadmitPeriod returns the maximum amount of time to wait before attempting to
   585  // reconnect to a node that has been removed from the network.
   586  func (client *Client) GetNodeMaxReadmitPeriod() time.Duration {
   587  	return client.network._GetNodeMaxReadmitPeriod()
   588  }
   589  
   590  // SetOperator sets that account that will, by default, be paying for
   591  // transactions and queries built with the client and the associated key
   592  // with which to automatically sign transactions.
   593  func (client *Client) SetOperator(accountID AccountID, privateKey PrivateKey) *Client {
   594  	client.operator = &_Operator{
   595  		accountID:  accountID,
   596  		privateKey: &privateKey,
   597  		publicKey:  privateKey.PublicKey(),
   598  		signer:     privateKey.Sign,
   599  	}
   600  
   601  	return client
   602  }
   603  
   604  // SetOperatorWith sets that account that will, by default, be paying for
   605  // transactions and queries built with the client, the account's PublicKey
   606  // and a callback that will be invoked when a transaction needs to be signed.
   607  func (client *Client) SetOperatorWith(accountID AccountID, publicKey PublicKey, signer TransactionSigner) *Client {
   608  	client.operator = &_Operator{
   609  		accountID:  accountID,
   610  		privateKey: nil,
   611  		publicKey:  publicKey,
   612  		signer:     signer,
   613  	}
   614  
   615  	return client
   616  }
   617  
   618  // SetRequestTimeout sets the timeout for all requests made by the client.
   619  func (client *Client) SetRequestTimeout(timeout *time.Duration) {
   620  	client.requestTimeout = timeout
   621  }
   622  
   623  // GetRequestTimeout returns the timeout for all requests made by the client.
   624  func (client *Client) GetRequestTimeout() *time.Duration {
   625  	return client.requestTimeout
   626  }
   627  
   628  // GetOperatorAccountID returns the ID for the _Operator
   629  func (client *Client) GetOperatorAccountID() AccountID {
   630  	if client.operator != nil {
   631  		return client.operator.accountID
   632  	}
   633  
   634  	return AccountID{}
   635  }
   636  
   637  // GetOperatorPublicKey returns the Key for the _Operator
   638  func (client *Client) GetOperatorPublicKey() PublicKey {
   639  	if client.operator != nil {
   640  		return client.operator.publicKey
   641  	}
   642  
   643  	return PublicKey{}
   644  }
   645  
   646  // Ping sends an AccountBalanceQuery to the specified _Node returning nil if no
   647  // problems occur. Otherwise, an error representing the status of the _Node will
   648  // be returned.
   649  func (client *Client) Ping(nodeID AccountID) error {
   650  	_, err := NewAccountBalanceQuery().
   651  		SetNodeAccountIDs([]AccountID{nodeID}).
   652  		SetAccountID(client.GetOperatorAccountID()).
   653  		Execute(client)
   654  
   655  	return err
   656  }
   657  
   658  func (client *Client) PingAll() {
   659  	for _, s := range client.GetNetwork() {
   660  		_ = client.Ping(s)
   661  	}
   662  }
   663  
   664  // SetNetworkFromAddressBook replaces all nodes in this Client with the nodes in the Address Book.
   665  func (client *Client) SetNetworkFromAddressBook(addressBook NodeAddressBook) *Client {
   666  	client.network._SetNetworkFromAddressBook(addressBook)
   667  	return client
   668  }
   669  
   670  // SetDefaultMaxQueryPayment sets the default maximum payment allowed for queries.
   671  func (client *Client) SetDefaultMaxQueryPayment(defaultMaxQueryPayment Hbar) error {
   672  	if defaultMaxQueryPayment.AsTinybar() < 0 {
   673  		return errors.New("DefaultMaxQueryPayment must be non-negative")
   674  	}
   675  
   676  	client.defaultMaxQueryPayment = defaultMaxQueryPayment
   677  	return nil
   678  }
   679  
   680  // GetDefaultMaxQueryPayment returns the default maximum payment allowed for queries.
   681  func (client *Client) GetDefaultMaxQueryPayment() Hbar {
   682  	return client.defaultMaxQueryPayment
   683  }
   684  
   685  // SetDefaultMaxTransactionFee sets the default maximum fee allowed for transactions.
   686  func (client *Client) SetDefaultMaxTransactionFee(defaultMaxTransactionFee Hbar) error {
   687  	if defaultMaxTransactionFee.AsTinybar() < 0 {
   688  		return errors.New("DefaultMaxTransactionFee must be non-negative")
   689  	}
   690  
   691  	client.defaultMaxTransactionFee = defaultMaxTransactionFee
   692  	return nil
   693  }
   694  
   695  // GetDefaultMaxTransactionFee returns the default maximum fee allowed for transactions.
   696  func (client *Client) GetDefaultMaxTransactionFee() Hbar {
   697  	return client.defaultMaxTransactionFee
   698  }
   699  
   700  func (client *Client) SetLogger(logger Logger) *Client {
   701  	client.logger = logger
   702  	return client
   703  }
   704  
   705  func (client *Client) GetLogger() Logger {
   706  	return client.logger
   707  }
   708  
   709  func (client *Client) SetLogLevel(level LogLevel) *Client {
   710  	client.logger.SetLevel(level)
   711  	return client
   712  }