All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.fireblocks.sdk.Fireblocks Maven / Gradle / Ivy

/*
 * Fireblocks API
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * The version of the OpenAPI document: 1.6.2
 * Contact: [email protected]
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package com.fireblocks.sdk;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fireblocks.sdk.api.*;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.Flow;

public class Fireblocks {
    private final ApiClient apiClient;
    private final Algorithm signingAlgorithm;
    private final String apiKey;
    private final String userAgent;

    private ApiUserApi apiUser;
    private AssetsApi assets;
    private AuditLogsApi auditLogs;
    private BlockchainsAssetsApi blockchainsAssets;
    private ComplianceApi compliance;
    private ComplianceScreeningConfigurationApi complianceScreeningConfiguration;
    private ConsoleUserApi consoleUser;
    private ContractInteractionsApi contractInteractions;
    private ContractTemplatesApi contractTemplates;
    private ContractsApi contracts;
    private CosignersBetaApi cosignersBeta;
    private DeployedContractsApi deployedContracts;
    private ExchangeAccountsApi exchangeAccounts;
    private ExternalWalletsApi externalWallets;
    private FiatAccountsApi fiatAccounts;
    private GasStationsApi gasStations;
    private InternalWalletsApi internalWallets;
    private JobManagementApi jobManagement;
    private KeyLinkBetaApi keyLinkBeta;
    private NetworkConnectionsApi networkConnections;
    private NftsApi nfts;
    private OffExchangesApi offExchanges;
    private OtaBetaApi otaBeta;
    private PaymentsPayoutApi paymentsPayout;
    private PolicyEditorBetaApi policyEditorBeta;
    private ResetDeviceApi resetDevice;
    private SmartTransferApi smartTransfer;
    private StakingBetaApi stakingBeta;
    private TokenizationApi tokenization;
    private TransactionsApi transactions;
    private TravelRuleBetaApi travelRuleBeta;
    private UserGroupsBetaApi userGroupsBeta;
    private UsersApi users;
    private VaultsApi vaults;
    private Web3ConnectionsApi web3Connections;
    private WebhooksApi webhooks;
    private WhitelistIpAddressesApi whitelistIpAddresses;
    private WorkspaceStatusBetaApi workspaceStatusBeta;

    public Fireblocks(ConfigurationOptions conf) {
        apiKey = Optional.ofNullable(conf.getApiKey()).orElse(System.getenv("FIREBLOCKS_API_KEY"));
        if (apiKey == null || apiKey.isEmpty()) {
            throw new IllegalArgumentException(
                    "apiKey is required either in the configuration or as environment variable"
                            + " FIREBLOCKS_API_KEY");
        }

        String secretKey =
                Optional.ofNullable(conf.getSecretKey())
                        .orElse(System.getenv("FIREBLOCKS_SECRET_KEY"));
        if (secretKey == null || secretKey.isEmpty()) {
            throw new IllegalArgumentException(
                    "secretKey is required either in the configuration or as environment variable"
                            + " FIREBLOCKS_SECRET_KEY");
        } else {
            try {
                signingAlgorithm = Algorithm.RSA256(null, getPrivateKey(secretKey));
            } catch (NoSuchAlgorithmException
                    | InvalidKeySpecException
                    | IllegalArgumentException e) {
                e.printStackTrace();
                throw new IllegalArgumentException("Invalid secretKey");
            }
        }

        apiClient = new ApiClient();

        String basePath =
                Optional.ofNullable(conf.getBasePath())
                        .orElse(System.getenv("FIREBLOCKS_BASE_PATH"));
        if (basePath == null || basePath.isEmpty()) {
            throw new IllegalArgumentException(
                    "basePath is required either in the configuration or as environment variable"
                            + " FIREBLOCKS_BASE_PATH");
        } else {
            apiClient.updateBaseUri(basePath);
        }

        userAgent = UserAgentUtil.getUserAgent(conf.getAdditionalOptions());

        apiClient.setRequestInterceptor(
                request -> {
                    try {
                        request.header("Authorization", "Bearer " + signJwt(request));
                    } catch (NoSuchAlgorithmException e) {
                        throw new RuntimeException(e);
                    }
                    request.header("Content-Type", "application/json");
                    request.header("User-Agent", userAgent);
                    request.header("X-API-Key", apiKey);
                });
    }

    public ApiClient getApiClient() {
        return apiClient;
    }

    private String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

    private RSAPrivateKey getPrivateKey(String secretKey)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        String keyContent =
                new String(secretKey.getBytes(), StandardCharsets.UTF_8)
                        .replaceAll("-----(BEGIN|END) PRIVATE KEY-----", "")
                        .replaceAll("\\s", "");
        byte[] contentBytes = Base64.getDecoder().decode(keyContent);
        return (RSAPrivateKey)
                KeyFactory.getInstance("RSA")
                        .generatePrivate(new PKCS8EncodedKeySpec(contentBytes));
    }

    private String signJwt(HttpRequest.Builder builder) throws NoSuchAlgorithmException {
        HttpRequest request = builder.build();
        String path =
                request.uri().getRawPath()
                        + Optional.ofNullable(request.uri().getRawQuery())
                                .map(query -> "?" + query)
                                .orElse("");

        byte[] bytes =
                request.bodyPublisher()
                        .map(
                                p -> {
                                    HttpResponse.BodySubscriber bodySubscriber =
                                            HttpResponse.BodySubscribers.ofString(
                                                    StandardCharsets.UTF_8);
                                    Flow.Subscriber subscriber =
                                            new Flow.Subscriber<>() {
                                                @Override
                                                public void onSubscribe(
                                                        Flow.Subscription subscription) {
                                                    bodySubscriber.onSubscribe(subscription);
                                                }

                                                @Override
                                                public void onNext(ByteBuffer item) {
                                                    bodySubscriber.onNext(List.of(item));
                                                }

                                                @Override
                                                public void onError(Throwable throwable) {
                                                    bodySubscriber.onError(throwable);
                                                }

                                                @Override
                                                public void onComplete() {
                                                    bodySubscriber.onComplete();
                                                }
                                            };
                                    p.subscribe(subscriber);
                                    return bodySubscriber.getBody().toCompletableFuture().join();
                                })
                        .orElse("")
                        .getBytes();
        bytes = MessageDigest.getInstance("SHA-256").digest(bytes);
        String bodyHash = bytesToHex(bytes);

        Instant now = InstanceTimeWrapper.now();
        Date issuedAt = Date.from(now);
        Date expiresAt = Date.from(now.plusSeconds(55));

        return JWT.create()
                .withClaim("uri", path)
                .withClaim("nonce", UUID.randomUUID().toString())
                .withClaim("iat", issuedAt.getTime() / 1000)
                .withClaim("exp", expiresAt.getTime() / 1000)
                .withClaim("sub", apiKey)
                .withClaim("bodyHash", bodyHash)
                .sign(signingAlgorithm);
    }

    public ApiUserApi apiUser() {
        if (apiUser == null) {
            apiUser = new ApiUserApi(apiClient);
        }
        return apiUser;
    }

    public AssetsApi assets() {
        if (assets == null) {
            assets = new AssetsApi(apiClient);
        }
        return assets;
    }

    public AuditLogsApi auditLogs() {
        if (auditLogs == null) {
            auditLogs = new AuditLogsApi(apiClient);
        }
        return auditLogs;
    }

    public BlockchainsAssetsApi blockchainsAssets() {
        if (blockchainsAssets == null) {
            blockchainsAssets = new BlockchainsAssetsApi(apiClient);
        }
        return blockchainsAssets;
    }

    public ComplianceApi compliance() {
        if (compliance == null) {
            compliance = new ComplianceApi(apiClient);
        }
        return compliance;
    }

    public ComplianceScreeningConfigurationApi complianceScreeningConfiguration() {
        if (complianceScreeningConfiguration == null) {
            complianceScreeningConfiguration = new ComplianceScreeningConfigurationApi(apiClient);
        }
        return complianceScreeningConfiguration;
    }

    public ConsoleUserApi consoleUser() {
        if (consoleUser == null) {
            consoleUser = new ConsoleUserApi(apiClient);
        }
        return consoleUser;
    }

    public ContractInteractionsApi contractInteractions() {
        if (contractInteractions == null) {
            contractInteractions = new ContractInteractionsApi(apiClient);
        }
        return contractInteractions;
    }

    public ContractTemplatesApi contractTemplates() {
        if (contractTemplates == null) {
            contractTemplates = new ContractTemplatesApi(apiClient);
        }
        return contractTemplates;
    }

    public ContractsApi contracts() {
        if (contracts == null) {
            contracts = new ContractsApi(apiClient);
        }
        return contracts;
    }

    public CosignersBetaApi cosignersBeta() {
        if (cosignersBeta == null) {
            cosignersBeta = new CosignersBetaApi(apiClient);
        }
        return cosignersBeta;
    }

    public DeployedContractsApi deployedContracts() {
        if (deployedContracts == null) {
            deployedContracts = new DeployedContractsApi(apiClient);
        }
        return deployedContracts;
    }

    public ExchangeAccountsApi exchangeAccounts() {
        if (exchangeAccounts == null) {
            exchangeAccounts = new ExchangeAccountsApi(apiClient);
        }
        return exchangeAccounts;
    }

    public ExternalWalletsApi externalWallets() {
        if (externalWallets == null) {
            externalWallets = new ExternalWalletsApi(apiClient);
        }
        return externalWallets;
    }

    public FiatAccountsApi fiatAccounts() {
        if (fiatAccounts == null) {
            fiatAccounts = new FiatAccountsApi(apiClient);
        }
        return fiatAccounts;
    }

    public GasStationsApi gasStations() {
        if (gasStations == null) {
            gasStations = new GasStationsApi(apiClient);
        }
        return gasStations;
    }

    public InternalWalletsApi internalWallets() {
        if (internalWallets == null) {
            internalWallets = new InternalWalletsApi(apiClient);
        }
        return internalWallets;
    }

    public JobManagementApi jobManagement() {
        if (jobManagement == null) {
            jobManagement = new JobManagementApi(apiClient);
        }
        return jobManagement;
    }

    public KeyLinkBetaApi keyLinkBeta() {
        if (keyLinkBeta == null) {
            keyLinkBeta = new KeyLinkBetaApi(apiClient);
        }
        return keyLinkBeta;
    }

    public NetworkConnectionsApi networkConnections() {
        if (networkConnections == null) {
            networkConnections = new NetworkConnectionsApi(apiClient);
        }
        return networkConnections;
    }

    public NftsApi nfts() {
        if (nfts == null) {
            nfts = new NftsApi(apiClient);
        }
        return nfts;
    }

    public OffExchangesApi offExchanges() {
        if (offExchanges == null) {
            offExchanges = new OffExchangesApi(apiClient);
        }
        return offExchanges;
    }

    public OtaBetaApi otaBeta() {
        if (otaBeta == null) {
            otaBeta = new OtaBetaApi(apiClient);
        }
        return otaBeta;
    }

    public PaymentsPayoutApi paymentsPayout() {
        if (paymentsPayout == null) {
            paymentsPayout = new PaymentsPayoutApi(apiClient);
        }
        return paymentsPayout;
    }

    public PolicyEditorBetaApi policyEditorBeta() {
        if (policyEditorBeta == null) {
            policyEditorBeta = new PolicyEditorBetaApi(apiClient);
        }
        return policyEditorBeta;
    }

    public ResetDeviceApi resetDevice() {
        if (resetDevice == null) {
            resetDevice = new ResetDeviceApi(apiClient);
        }
        return resetDevice;
    }

    public SmartTransferApi smartTransfer() {
        if (smartTransfer == null) {
            smartTransfer = new SmartTransferApi(apiClient);
        }
        return smartTransfer;
    }

    public StakingBetaApi stakingBeta() {
        if (stakingBeta == null) {
            stakingBeta = new StakingBetaApi(apiClient);
        }
        return stakingBeta;
    }

    public TokenizationApi tokenization() {
        if (tokenization == null) {
            tokenization = new TokenizationApi(apiClient);
        }
        return tokenization;
    }

    public TransactionsApi transactions() {
        if (transactions == null) {
            transactions = new TransactionsApi(apiClient);
        }
        return transactions;
    }

    public TravelRuleBetaApi travelRuleBeta() {
        if (travelRuleBeta == null) {
            travelRuleBeta = new TravelRuleBetaApi(apiClient);
        }
        return travelRuleBeta;
    }

    public UserGroupsBetaApi userGroupsBeta() {
        if (userGroupsBeta == null) {
            userGroupsBeta = new UserGroupsBetaApi(apiClient);
        }
        return userGroupsBeta;
    }

    public UsersApi users() {
        if (users == null) {
            users = new UsersApi(apiClient);
        }
        return users;
    }

    public VaultsApi vaults() {
        if (vaults == null) {
            vaults = new VaultsApi(apiClient);
        }
        return vaults;
    }

    public Web3ConnectionsApi web3Connections() {
        if (web3Connections == null) {
            web3Connections = new Web3ConnectionsApi(apiClient);
        }
        return web3Connections;
    }

    public WebhooksApi webhooks() {
        if (webhooks == null) {
            webhooks = new WebhooksApi(apiClient);
        }
        return webhooks;
    }

    public WhitelistIpAddressesApi whitelistIpAddresses() {
        if (whitelistIpAddresses == null) {
            whitelistIpAddresses = new WhitelistIpAddressesApi(apiClient);
        }
        return whitelistIpAddresses;
    }

    public WorkspaceStatusBetaApi workspaceStatusBeta() {
        if (workspaceStatusBeta == null) {
            workspaceStatusBeta = new WorkspaceStatusBetaApi(apiClient);
        }
        return workspaceStatusBeta;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy