ServiceHub
Keywords: net.corda.core.node.ServiceHub interface
Date: 2023-09-18

net.corda.core.node

## Interface ServiceHub

- All Superinterfaces:
    ServicesForResolution
  All Known Subinterfaces:
    AppServiceHub
  All Known Implementing Classes:
    MockServices

      public ServiceHub
      extends ServicesForResolution

  A service hub is the starting point for most operations you can do inside the node. You are provided with one when a class annotated with `annotationclass CordaService` is constructed, and you have access to one inside flows. Most RPCs simply forward to the services found here after some access checking.

  The APIs are organised roughly by category, with a few very important top level APIs available on the ServiceHub itself. Inside a flow, it's safe to keep a reference to services found here on the stack: checkpointing will do the right thing (it won't try to serialise the internals of the service).

  In unit test environments, some of those services may be missing or mocked out.

  See Also:
    `annotationclass CordaService`

- - ### Constructor Detail

    - #### ServiceHub

          public ServiceHub()

  - ### Method Detail

    - #### getVaultService

          @NotNull
          VaultService getVaultService()

      The vault service lets you observe, soft lock and add notes to states that involve you or are relevant to your node in some way. Additionally you may query and track states that correspond to various criteria.

    - #### getKeyManagementService

          @NotNull
          KeyManagementService getKeyManagementService()

      The key management service is responsible for storing and using private keys to sign things. An implementation of this may, for example, call out to a hardware security module that enforces various auditing and frequency-of-use requirements.

      You don't normally need to use this directly. If you have a `class TransactionBuilder` and wish to sign it to get a `class SignedTransaction`, look at signInitialTransaction.

      See Also:
        `class TransactionBuilder`, `class SignedTransaction`

    - #### getContractUpgradeService

          @NotNull
          ContractUpgradeService getContractUpgradeService()

      The `interface ContractUpgradeService` is responsible for securely upgrading contract state objects according to a specified and mutually agreed (amongst participants) contract version.

      See Also:
        `interface ContractUpgradeService`, `class ContractUpgradeFlow`

    - #### getValidatedTransactions

          @NotNull
          TransactionStorage getValidatedTransactions()

      A map of hash->tx where tx has been signature/contract validated and the states are known to be correct. The signatures aren't technically needed after that point, but we keep them around so that we can relay the transaction data to other nodes that need it.

    - #### getNetworkMapCache

          @NotNull
          NetworkMapCache getNetworkMapCache()

      A network map contains lists of nodes on the network along with information about their identity keys, services they provide and host names or IP addresses where they can be connected to. The cache wraps around a map fetched from an authoritative service, and adds easy lookup of the data stored within it. Generally it would be initialised with a specified network map service, which it fetches data from and then subscribes to updates of.

    - #### getDiagnosticsService

          @NotNull
          DiagnosticsService getDiagnosticsService()

      The `interface DiagnosticsService` provides diagnostic level information about the node, including the current version of the node, and the CorDapps currently installed on the node. Note that this information should be used to provide diagnostics only, and no functional decisions should be made based on this.

      See Also:
        `interface DiagnosticsService`

    - #### getTelemetryService

          @NotNull
          TelemetryService getTelemetryService()

      Provides operations to support telemetry and telemetry data between nodes.

    - #### getClock

          @NotNull
          java.time.Clock getClock()

      A Clock representing the node's current time. This should be used in preference to directly accessing the clock so the current time can be controlled during unit testing.

      See Also:
        Clock

    - #### getMyInfo

          @NotNull
          NodeInfo getMyInfo()

      The `class NodeInfo` object corresponding to our own entry in the network map.

      See Also:
        `class NodeInfo`

    - #### cordaService

          @NotNull
          <T extends SerializeAsToken> T cordaService(@NotNull
                                                               java.lang.Class<T> type)

      Return the singleton instance of the given Corda service type. This is a class that is annotated with `annotationclass CordaService` and will have automatically been registered by the node.

      Throws:
        `IllegalArgumentException` - If `type` is not annotated with `annotationclass CordaService` or if the instance is not found.
      See Also:
        `annotationclass CordaService`

    - #### cordaTelemetryComponent

          @NotNull
          <T extends TelemetryComponent> T cordaTelemetryComponent(@NotNull
                                                                            java.lang.Class<T> type)

      Return the singleton instance of the given Corda telemetry component type. This is a class that implements TelemetryComponent and will have automatically been registered by the node.

      Throws:
        `IllegalArgumentException` - If the instance is not found.

    - #### recordTransactions

          void recordTransactions(boolean notifyVault,
                                  @NotNull
                                  java.lang.Iterable<net.corda.core.transactions.SignedTransaction> txs)

      Stores the given `class SignedTransaction`s in the local transaction storage and then sends them to the vault for further processing if `notifyVault` is true. This is expected to be run within a database transaction.

      Parameters:
        `notifyVault` - indicate if the vault should be notified for the update.
        `txs` - The transactions to record.
      See Also:
        `class SignedTransaction`, `notifyVault`

    - #### recordTransactions

          void recordTransactions(boolean notifyVault,
                                  @NotNull
                                  SignedTransaction first,
                                  @NotNull
                                  net.corda.core.transactions.SignedTransaction... remaining)

      Stores the given `class SignedTransaction`s in the local transaction storage and then sends them to the vault for further processing if `notifyVault` is true. This is expected to be run within a database transaction.

      See Also:
        `class SignedTransaction`, `notifyVault`

    - #### recordTransactions

          void recordTransactions(@NotNull
                                  StatesToRecord statesToRecord,
                                  @NotNull
                                  java.lang.Iterable<net.corda.core.transactions.SignedTransaction> txs)

      Stores the given `class SignedTransaction`s in the local transaction storage and then sends them to the vault for further processing if `statesToRecord` is not StatesToRecord.NONE. This is expected to be run within a database transaction.

      Parameters:
        `statesToRecord` - how the vault should treat the output states of the transaction.
        `txs` - The transactions to record.
      See Also:
        `class SignedTransaction`, `statesToRecord`

    - #### recordTransactions

          void recordTransactions(@NotNull
                                  SignedTransaction first,
                                  @NotNull
                                  net.corda.core.transactions.SignedTransaction... remaining)

      Stores the given `class SignedTransaction`s in the local transaction storage and then sends them to the vault for further processing. This is expected to be run within a database transaction.

      See Also:
        `class SignedTransaction`

    - #### recordTransactions

          void recordTransactions(@NotNull
                                  java.lang.Iterable<net.corda.core.transactions.SignedTransaction> txs)

      Stores the given `class SignedTransaction`s in the local transaction storage and then sends them to the vault for further processing. This is expected to be run within a database transaction.

      See Also:
        `class SignedTransaction`

    - #### toStateAndRef

          @NotNull
          <T extends ContractState> StateAndRef<T> toStateAndRef(@NotNull
                                                                          StateRef stateRef)

      Converts the given `class StateRef` into a `class StateAndRef` object.

      Throws:
        `TransactionResolutionException` - if `stateRef` points to a non-existent transaction.
      See Also:
        `class StateRef`, `class StateAndRef`

    - #### signInitialTransaction

          @NotNull
          SignedTransaction signInitialTransaction(@NotNull
                                                            TransactionBuilder builder,
                                                            @NotNull
                                                            java.security.PublicKey publicKey)

      Helper method to construct an initial partially signed transaction from a `class TransactionBuilder` using keys stored inside the node. Signature metadata is added automatically.

      Parameters:
        `builder` - The `class TransactionBuilder` to seal with the node's signature.Any existing signatures on the builder will be preserved.
        `publicKey` - The PublicKey matched to the internal java.security.PrivateKey to use in signing this transaction.If the passed in key is actually a CompositeKey the code searches for the first child key hosted within this nodeto sign with.
      Returns:
        Returns a SignedTransaction with the new node signature attached.
      See Also:
        `class TransactionBuilder`

    - #### signInitialTransaction

          @NotNull
          SignedTransaction signInitialTransaction(@NotNull
                                                            TransactionBuilder builder)

      Helper method to construct an initial partially signed transaction from a TransactionBuilder using the default identity key contained in the node. The legal identity key is used to sign.

      Parameters:
        `builder` - The TransactionBuilder to seal with the node's signature.Any existing signatures on the builder will be preserved.
      Returns:
        Returns a SignedTransaction with the new node signature attached.

    - #### signInitialTransaction

          @NotNull
          SignedTransaction signInitialTransaction(@NotNull
                                                            TransactionBuilder builder,
                                                            @NotNull
                                                            java.lang.Iterable<? extends java.security.PublicKey> signingPubKeys)

      Helper method to construct an initial partially signed transaction from a `class TransactionBuilder` using a set of keys all held in this node.

      Parameters:
        `builder` - The `class TransactionBuilder` to seal with the node's signature.Any existing signatures on the builder will be preserved.
        `signingPubKeys` - A list of PublicKeys used to lookup the matching java.security.PrivateKey and sign.
      Returns:
        Returns a `class SignedTransaction` with the new node signature attached.
      Throws:
        `IllegalArgumentException` - is thrown if any keys are unavailable locally.
      See Also:
        `class TransactionBuilder`

    - #### createSignature

          @NotNull
          TransactionSignature createSignature(@NotNull
                                                        SignedTransaction signedTransaction,
                                                        @NotNull
                                                        java.security.PublicKey publicKey)

      Helper method to create an additional signature for an existing (partially) `class SignedTransaction`. Additional `class SignatureMetadata`, including the platform version used during signing and the cryptographic signature scheme use, is added to the signature.

      Parameters:
        `signedTransaction` - The `class SignedTransaction` to which the signature will apply.
        `publicKey` - The PublicKey matching to a signing java.security.PrivateKey hosted in the node.If the PublicKey is actually a `class CompositeKey` the first leaf key found locally will be usedfor signing.
      Returns:
        The `class TransactionSignature` generated by signing with the internally held java.security.PrivateKey.
      See Also:
        `class SignedTransaction`, `class SignatureMetadata`

    - #### createSignature

          @NotNull
          TransactionSignature createSignature(@NotNull
                                                        SignedTransaction signedTransaction)

      Helper method to create a signature for an existing (partially) `class SignedTransaction` using the default identity signing key of the node. The legal identity key is used to sign. Additional `class SignatureMetadata`, including the platform version used during signing and the cryptographic signature scheme use, is added to the signature.

      Parameters:
        `signedTransaction` - The SignedTransaction to which the signature will apply.
      Returns:
        the TransactionSignature generated by signing with the internally held identity PrivateKey.
      See Also:
        `class SignedTransaction`, `class SignatureMetadata`

    - #### addSignature

          @NotNull
          SignedTransaction addSignature(@NotNull
                                                  SignedTransaction signedTransaction,
                                                  @NotNull
                                                  java.security.PublicKey publicKey)

      Helper method to append an additional signature to an existing (partially) `class SignedTransaction`.

      Parameters:
        `signedTransaction` - The `class SignedTransaction` to which the signature will be added.
        `publicKey` - The PublicKey matching to a signing java.security.PrivateKey hosted in the node.If the PublicKey is actually a `class CompositeKey` the first leaf key found locally will be usedfor signing.
      Returns:
        A new `class SignedTransaction` with the addition of the new signature.
      See Also:
        `class SignedTransaction`

    - #### addSignature

          @NotNull
          SignedTransaction addSignature(@NotNull
                                                  SignedTransaction signedTransaction)

      Helper method to append an additional signature for an existing (partially) `class SignedTransaction` using the default identity signing key of the node.

      Parameters:
        `signedTransaction` - The `class SignedTransaction` to which the signature will be added.
      Returns:
        A new `class SignedTransaction` with the addition of the new signature.
      See Also:
        `class SignedTransaction`

    - #### createSignature

          @NotNull
          TransactionSignature createSignature(@NotNull
                                                        FilteredTransaction filteredTransaction,
                                                        @NotNull
                                                        java.security.PublicKey publicKey)

      Helper method to create a signature for a FilteredTransaction. Additional `class SignatureMetadata`, including the platform version used during signing and the cryptographic signature scheme use, is added to the signature.

      Parameters:
        `filteredTransaction` - the `class FilteredTransaction` to which the signature will apply.
        `publicKey` - The PublicKey matching to a signing java.security.PrivateKey hosted in the node.If the PublicKey is actually a `class CompositeKey` the first leaf key found locally will be usedfor signing.
      Returns:
        The `class TransactionSignature` generated by signing with the internally held java.security.PrivateKey.
      See Also:
        `class SignatureMetadata`

    - #### createSignature

          @NotNull
          TransactionSignature createSignature(@NotNull
                                                        FilteredTransaction filteredTransaction)

      Helper method to create a signature for a FilteredTransaction using the default identity signing key of the node. The legal identity key is used to sign. Additional `class SignatureMetadata`, including the platform version used during signing and the cryptographic signature scheme use, is added to the signature.

      Parameters:
        `filteredTransaction` - the FilteredTransaction to which the signature will apply.
      Returns:
        the `class TransactionSignature` generated by signing with the internally held identity java.security.PrivateKey.
      See Also:
        `class SignatureMetadata`

    - #### jdbcSession

          @NotNull
          java.sql.Connection jdbcSession()

      Exposes a JDBC connection (session) object using the currently configured database. Applications can use this to execute arbitrary SQL queries (native, direct, prepared, callable) against its Node database tables (including custom contract tables defined by extending `interface QueryableState`).

      When used within a flow, this session automatically forms part of the enclosing flow transaction boundary, and thus queryable data will include everything committed as of the last checkpoint.

      We want to make sure users have a restricted access to administrative functions, this function will return a RestrictedConnection instance. The following methods are blocked:

      - abort(executor: Executor?)

      - clearWarnings()

      - close()

      - commit()

      - setSavepoint()

      - setSavepoint(name : String?)

      - releaseSavepoint(savepoint: Savepoint?)

      - rollback()

      - rollback(savepoint: Savepoint?)

      - setCatalog(catalog : String?)

      - setTransactionIsolation(level: Int)

      - setTypeMap(map: MutableMap>?)

      - setHoldability(holdability: Int)

      - setSchema(schema: String?)

      - setNetworkTimeout(executor: Executor?, milliseconds: Int)

      - setAutoCommit(autoCommit: Boolean)

      - setReadOnly(readOnly: Boolean)

      Returns:
        A Connection
      Throws:
        `IllegalStateException` - if called outside of a transaction.
      See Also:
        `interface QueryableState`, RestrictedConnection

    - #### withEntityManager

          <T> T withEntityManager(@NotNull
                                  kotlin.jvm.functions.Function1<? super javax.persistence.EntityManager,? extends T> block)

      Exposes the Java Persistence API (JPA) to flows via a restricted EntityManager. This method can be used to persist and query entities which inherit from MappedSchema. This is particularly useful if off-ledger data needs to be kept in conjunction with on-ledger state data.

      NOTE: Suspendable flow operations such as send, receive, subFlow and sleep, cannot be called within the lambda.

      Parameters:
        `block` -

        a lambda function with access to an EntityManager.

        We want to make sure users have a restricted access to administrative functions. The following methods are blocked:

        - close()

        - unwrap(cls: Class?)

        - getDelegate(): Any

        - getMetamodel()

        - joinTransaction()

        - lock(entity: Any?, lockMode: LockModeType?)

        - lock(entity: Any?, lockMode: LockModeType?, properties: MutableMap?)

        - setProperty(propertyName: String?, value: Any?)

        getTransaction returns a RestrictedEntityTransaction to prevent unsafe manipulation of a flow's underlying database transaction. The following methods are blocked:

        - begin()

        - commit()

        - rollback()

      See Also:
        MappedSchema

    - #### withEntityManager

          void withEntityManager(@NotNull
                                 java.util.function.Consumer<javax.persistence.EntityManager> block)

      Exposes the Java Persistence API (JPA) to flows via a restricted EntityManager. This method can be used to persist and query entities which inherit from MappedSchema. This is particularly useful if off-ledger data needs to be kept in conjunction with on-ledger state data.

      NOTE: Suspendable flow operations such as send, receive, subFlow and sleep, cannot be called within the lambda.

      Parameters:
        `block` -

        a lambda function with access to an EntityManager.

        We want to make sure users have a restricted access to administrative functions. The following methods are blocked:

        - close()

        - unwrap(cls: Class?)

        - getDelegate(): Any

        - getMetamodel()

        - joinTransaction()

        - lock(entity: Any?, lockMode: LockModeType?)

        - lock(entity: Any?, lockMode: LockModeType?, properties: MutableMap?)

        - setProperty(propertyName: String?, value: Any?)

        getTransaction returns a RestrictedEntityTransaction to prevent unsafe manipulation of a flow's underlying database transaction. The following methods are blocked:

        - begin()

        - commit()

        - rollback()

      See Also:
        MappedSchema

    - #### registerUnloadHandler

          void registerUnloadHandler(@NotNull
                                     kotlin.jvm.functions.Function0<kotlin.Unit> runOnStop)

      Allows the registration of a callback that may inform services when the app is shutting down.

      The intent is to allow the cleaning up of resources - e.g. releasing ports.

      You should not rely on this to clean up executing flows - that's what quasar is for.

      Please note that the shutdown handler is not guaranteed to be called. In production the node process may crash, be killed by the operating system and other forms of fatal termination may occur that result in this code never running. So you should use this functionality only for unit/integration testing or for code that can optimise this shutdown e.g. by cleaning up things that would otherwise trigger a slow recovery process next time the node starts.

    - #### getAppContext

          @NotNull
          CordappContext getAppContext()

      See `CordappProvider.getAppContext`

      See Also:
        `CordappProvider.getAppContext`