diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index c8aebcf651..13ac2d8088 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -116,6 +116,7 @@ /packages/eth-json-rpc-middleware/src/wallet.* @MetaMask/confirmations @MetaMask/wallet-api-platform-engineers /packages/eth-json-rpc-provider @MetaMask/wallet-integrations @MetaMask/core-platform /packages/foundryup @MetaMask/mobile-platform @MetaMask/extension-platform +/packages/java-tron-up @MetaMask/mobile-platform @MetaMask/extension-platform @MetaMask/networks /packages/json-rpc-engine @MetaMask/wallet-integrations @MetaMask/core-platform /packages/json-rpc-middleware-stream @MetaMask/wallet-integrations @MetaMask/core-platform /packages/keyring-controller @MetaMask/accounts-engineers @MetaMask/core-platform @@ -223,6 +224,8 @@ /packages/app-metadata-controller/CHANGELOG.md @MetaMask/mobile-platform @MetaMask/core-platform /packages/foundryup/package.json @MetaMask/mobile-platform @MetaMask/extension-platform @MetaMask/core-platform /packages/foundryup/CHANGELOG.md @MetaMask/mobile-platform @MetaMask/extension-platform @MetaMask/core-platform +/packages/java-tron-up/package.json @MetaMask/mobile-platform @MetaMask/extension-platform @MetaMask/networks @MetaMask/core-platform +/packages/java-tron-up/CHANGELOG.md @MetaMask/mobile-platform @MetaMask/extension-platform @MetaMask/networks @MetaMask/core-platform /packages/seedless-onboarding-controller/package.json @MetaMask/web3auth @MetaMask/core-platform /packages/seedless-onboarding-controller/CHANGELOG.md @MetaMask/web3auth @MetaMask/core-platform /packages/shield-controller/package.json @MetaMask/web3auth @MetaMask/core-platform diff --git a/README.md b/README.md index 64a2300566..4883356e42 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ Each package in this repository has its own README where you can find installati - [`@metamask/gas-fee-controller`](packages/gas-fee-controller) - [`@metamask/gator-permissions-controller`](packages/gator-permissions-controller) - [`@metamask/geolocation-controller`](packages/geolocation-controller) +- [`@metamask/java-tron-up`](packages/java-tron-up) - [`@metamask/json-rpc-engine`](packages/json-rpc-engine) - [`@metamask/json-rpc-middleware-stream`](packages/json-rpc-middleware-stream) - [`@metamask/keyring-controller`](packages/keyring-controller) @@ -153,6 +154,7 @@ linkStyle default opacity:0.5 gas_fee_controller(["@metamask/gas-fee-controller"]); gator_permissions_controller(["@metamask/gator-permissions-controller"]); geolocation_controller(["@metamask/geolocation-controller"]); + java_tron_up(["@metamask/java-tron-up"]); json_rpc_engine(["@metamask/json-rpc-engine"]); json_rpc_middleware_stream(["@metamask/json-rpc-middleware-stream"]); keyring_controller(["@metamask/keyring-controller"]); diff --git a/packages/java-tron-up/CHANGELOG.md b/packages/java-tron-up/CHANGELOG.md new file mode 100644 index 0000000000..dbcda20253 --- /dev/null +++ b/packages/java-tron-up/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- Add the `@metamask/java-tron-up` package ([#8825](https://github.com/MetaMask/core/pull/8825)). + +[Unreleased]: https://github.com/MetaMask/core/ diff --git a/packages/java-tron-up/LICENSE b/packages/java-tron-up/LICENSE new file mode 100644 index 0000000000..9ec4f4514e --- /dev/null +++ b/packages/java-tron-up/LICENSE @@ -0,0 +1,6 @@ +This project is licensed under either of + + * MIT license ([LICENSE.MIT](LICENSE.MIT)) + * Apache License, Version 2.0 ([LICENSE.APACHE2](LICENSE.APACHE2)) + +at your option. diff --git a/packages/java-tron-up/LICENSE.APACHE2 b/packages/java-tron-up/LICENSE.APACHE2 new file mode 100644 index 0000000000..e6e77b0890 --- /dev/null +++ b/packages/java-tron-up/LICENSE.APACHE2 @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/java-tron-up/LICENSE.MIT b/packages/java-tron-up/LICENSE.MIT new file mode 100644 index 0000000000..fe29e78e0f --- /dev/null +++ b/packages/java-tron-up/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 MetaMask + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/java-tron-up/README.md b/packages/java-tron-up/README.md new file mode 100644 index 0000000000..9a0ea827b8 --- /dev/null +++ b/packages/java-tron-up/README.md @@ -0,0 +1,124 @@ +# `@metamask/java-tron-up` + +`java-tron-up` installs a pinned native java-tron runtime for local development +and CI. It follows the same runtime-only shape as `@metamask/foundryup`: this +package installs external runtime artifacts into the MetaMask cache and exposes +binaries in `node_modules/.bin`; the consuming test harness owns process +startup, private-network config, readiness checks, and seeding. + +This package does not use Docker and does not start or seed a TRON node. + +## Usage + +Install the package in the consuming repo: + +```bash +yarn add @metamask/java-tron-up +npm install @metamask/java-tron-up +``` + +For Yarn v4 projects, it is usually simplest to add package scripts in the +consuming repo: + +```json +{ + "scripts": { + "java-tron-up": "node_modules/.bin/java-tron-up", + "java-tron": "node_modules/.bin/java-tron" + } +} +``` + +Install java-tron and its managed Java runtime: + +```bash +yarn java-tron-up install +``` + +Run the installed node wrapper: + +```bash +node_modules/.bin/java-tron -c /absolute/path/to/fullnode.conf --witness +``` + +For MetaMask Extension E2E tests, the Tron seeder should spawn +`node_modules/.bin/java-tron`, pass its generated private-network config, poll +java-tron's HTTP APIs directly, and perform all account/token/staking seeding +itself. + +## Installed Artifacts + +`java-tron-up` installs: + +- a platform-specific `FullNode.jar` +- a managed Java runtime matching java-tron's architecture requirements +- a `node_modules/.bin/java-tron` wrapper that runs: + +```bash +java -jar FullNode.jar "$@" +``` + +## CLI + +```bash +java-tron-up [install] [options] +java-tron-up cache clean [options] +``` + +Options: + +- `--bin-directory `: directory for generated wrappers. Defaults to + `node_modules/.bin`. +- `--cache-directory `: artifact cache directory. Defaults to + `.metamask/cache`. +- `--full-node-url ` and `--full-node-checksum `: override the + FullNode jar for the current platform. +- `--java-runtime-url ` and `--java-runtime-checksum `: override the + Java runtime archive for the current platform. +- `--platform `: override platform selection, for example + `linux-x64`. + +## Default Release + +The package currently pins java-tron `GreatVoyage-v4.8.1` for `darwin-arm64`, +`darwin-x64`, `linux-arm64`, and `linux-x64`. + +java-tron `4.8.1` requires JDK 8 for x86_64 and JDK 17 for arm64, so this +package installs Azul Zulu Java 8 on x64 platforms and Azul Zulu Java 17 on +arm64 platforms. + +## Cache + +The cache defaults to `.metamask/cache` in the current repo. If `.yarnrc.yml` +contains `enableGlobalCache: true`, the cache moves to `~/.cache/metamask`, +matching the `@metamask/foundryup` behavior. + +Clean only this package's cache namespace: + +```bash +yarn java-tron-up cache clean +``` + +## Package Config + +The consuming repo can override the pinned artifact URLs and checksums in its +root `package.json`: + +```json +{ + "javaTronUp": { + "fullNode": { + "version": "GreatVoyage-v4.8.1", + "platforms": { + "linux-x64": { + "url": "https://github.com/tronprotocol/java-tron/releases/download/GreatVoyage-v4.8.1/FullNode.jar", + "checksum": "0e67b2fe75d7077750e73c4fa20725c6e9824657275d96be256ae5da681f9945" + } + } + } + } +} +``` + +Supported package config keys are `javaTronUp`, `javatronup`, and +`java-tron-up`. diff --git a/packages/java-tron-up/jest.config.js b/packages/java-tron-up/jest.config.js new file mode 100644 index 0000000000..e29b7194b9 --- /dev/null +++ b/packages/java-tron-up/jest.config.js @@ -0,0 +1,32 @@ +/* + * For a detailed explanation regarding each configuration property and type check, visit: + * https://jestjs.io/docs/configuration + */ + +const merge = require('deepmerge'); +const path = require('path'); + +const baseConfig = require('../../jest.config.packages'); + +const displayName = path.basename(__dirname); + +module.exports = merge(baseConfig, { + // The display name when running multiple projects + displayName, + + // The CLI entrypoint is exercised through package builds and installed-bin smoke tests. + coveragePathIgnorePatterns: [ + ...baseConfig.coveragePathIgnorePatterns, + './src/bin/java-tron-up.ts', + ], + + // An object that configures minimum threshold enforcement for coverage results + coverageThreshold: { + global: { + branches: 35, + functions: 60, + lines: 65, + statements: 65, + }, + }, +}); diff --git a/packages/java-tron-up/package.json b/packages/java-tron-up/package.json new file mode 100644 index 0000000000..b8672458c9 --- /dev/null +++ b/packages/java-tron-up/package.json @@ -0,0 +1,71 @@ +{ + "name": "@metamask/java-tron-up", + "version": "0.0.0", + "description": "java-tron runtime installer for MetaMask E2E tests", + "keywords": [ + "Ethereum", + "MetaMask" + ], + "homepage": "https://github.com/MetaMask/core/tree/main/packages/java-tron-up#readme", + "bugs": { + "url": "https://github.com/MetaMask/core/issues" + }, + "license": "(MIT OR Apache-2.0)", + "repository": { + "type": "git", + "url": "https://github.com/MetaMask/core.git" + }, + "bin": "./dist/bin/java-tron-up.mjs", + "files": [ + "dist/" + ], + "sideEffects": false, + "main": "./dist/index.cjs", + "types": "./dist/index.d.cts", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + }, + "./package.json": "./package.json" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "scripts": { + "build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references", + "build:all": "ts-bridge --project tsconfig.build.json --verbose --clean", + "build:docs": "typedoc", + "changelog:update": "../../scripts/update-changelog.sh @metamask/java-tron-up", + "changelog:validate": "../../scripts/validate-changelog.sh @metamask/java-tron-up", + "messenger-action-types:check": "tsx ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --check", + "messenger-action-types:generate": "tsx ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --generate", + "since-latest-release": "../../scripts/since-latest-release.sh", + "test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter", + "test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache", + "test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose", + "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch" + }, + "devDependencies": { + "@metamask/auto-changelog": "^6.1.0", + "@ts-bridge/cli": "^0.6.4", + "@types/jest": "^29.5.14", + "deepmerge": "^4.2.2", + "jest": "^29.7.0", + "ts-jest": "^29.2.5", + "tsx": "^4.20.5", + "typedoc": "^0.25.13", + "typedoc-plugin-missing-exports": "^2.0.0", + "typescript": "~5.3.3" + }, + "engines": { + "node": "^18.18 || >=20" + } +} diff --git a/packages/java-tron-up/src/bin/java-tron-up.ts b/packages/java-tron-up/src/bin/java-tron-up.ts new file mode 100644 index 0000000000..a32b97bc7f --- /dev/null +++ b/packages/java-tron-up/src/bin/java-tron-up.ts @@ -0,0 +1,65 @@ +#!/usr/bin/env node +/* eslint-disable no-restricted-globals */ +import { + cleanJavaTronCache, + installJavaTron, + parseJavaTronInstallCliOptions, + readJavaTronInstallOptionsFromPackageJson, +} from '../install'; + +async function main(): Promise { + const [command, ...args] = process.argv.slice(2); + + if (command === '--help' || command === 'help') { + printHelp(); + return; + } + + if (command === 'cache' && args[0] === 'clean') { + await cleanJavaTronCache({ + ...readJavaTronInstallOptionsFromPackageJson(), + ...parseJavaTronInstallCliOptions(args.slice(1)), + }); + console.log('[java-tron-up] cache cleaned'); + return; + } + + const installArgs = command === 'install' ? args : process.argv.slice(2); + const result = await installJavaTron({ + ...readJavaTronInstallOptionsFromPackageJson(), + ...parseJavaTronInstallCliOptions(installArgs), + }); + + console.log( + `[java-tron-up] java-tron ${ + result.cacheHit ? 'found in cache' : 'installed' + } at ${result.fullNodeJar}`, + ); + console.log(`[java-tron-up] Java runtime installed at ${result.javaBinary}`); + console.log(`[java-tron-up] binary installed at ${result.binaryPath}`); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); + +function printHelp(): void { + console.log(`Usage: java-tron-up [install] [options] + java-tron-up cache clean [options] + +Commands: + install Install java-tron and the managed Java runtime. Default command. + cache clean Remove cached java-tron-up artifacts. + +Options: + --bin-directory Directory for the java-tron executable. + Defaults to node_modules/.bin. + --cache-directory Cache directory. Defaults to .metamask/cache. + --full-node-url FullNode.jar URL for the current platform. + --full-node-checksum Expected FullNode.jar SHA-256 checksum. + --java-runtime-url Java runtime archive URL for the current platform. + --java-runtime-checksum Expected Java runtime SHA-256 checksum. + --platform Override platform key, e.g. linux-x64. + --help Show this help text.`); +} diff --git a/packages/java-tron-up/src/index.ts b/packages/java-tron-up/src/index.ts new file mode 100644 index 0000000000..12992703cd --- /dev/null +++ b/packages/java-tron-up/src/index.ts @@ -0,0 +1,18 @@ +export { + JAVA_TRON_DEFAULT_FULL_NODE, + JAVA_TRON_DEFAULT_JAVA_RUNTIME, + cleanJavaTronCache, + getJavaTronCacheDirectory, + installJavaRuntime, + installJavaTron, + parseJavaTronInstallCliOptions, + readJavaTronInstallOptionsFromPackageJson, +} from './install'; +export type { + JavaTronArtifactConfig, + JavaTronArtifactPlatformConfig, + JavaTronInstallDependencies, + JavaTronInstallOptions, + JavaTronInstallResult, + JavaTronJavaRuntimeConfig, +} from './install'; diff --git a/packages/java-tron-up/src/install.test.ts b/packages/java-tron-up/src/install.test.ts new file mode 100644 index 0000000000..f36699a4cb --- /dev/null +++ b/packages/java-tron-up/src/install.test.ts @@ -0,0 +1,352 @@ +/* eslint-disable jest/expect-expect, n/no-sync */ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + chmodSync, + existsSync, + lstatSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { + JAVA_TRON_DEFAULT_FULL_NODE, + cleanJavaTronCache, + getJavaTronCacheDirectory, + installJavaTron, + parseJavaTronInstallCliOptions, + readJavaTronInstallOptionsFromPackageJson, +} from './install'; +import type { JavaTronInstallDependencies } from './install'; + +describe('java-tron-up installer', () => { + let tempDirs: string[] = []; + + afterEach(() => { + for (const tempDir of tempDirs) { + rmSync(tempDir, { force: true, recursive: true }); + } + tempDirs = []; + }); + + it('pins the current latest java-tron release', () => { + assert.equal(JAVA_TRON_DEFAULT_FULL_NODE.version, 'GreatVoyage-v4.8.1'); + assert.equal( + JAVA_TRON_DEFAULT_FULL_NODE.platforms['darwin-arm64']?.checksum, + '694431860ee76fc986ed495f9ec19f29ed3bd752a394386e7b3b9886b2292f59', + ); + assert.equal( + JAVA_TRON_DEFAULT_FULL_NODE.platforms['linux-x64']?.checksum, + '0e67b2fe75d7077750e73c4fa20725c6e9824657275d96be256ae5da681f9945', + ); + }); + + it('uses the local MetaMask cache when Yarn global cache is disabled', () => { + const cwd = createTempDir(); + writeFileSync(join(cwd, '.yarnrc.yml'), 'enableGlobalCache: false\n'); + + assert.equal( + getJavaTronCacheDirectory({ cwd }), + join(cwd, '.metamask', 'cache'), + ); + }); + + it('reads pinned installer options from package.json', () => { + const cwd = createTempDir(); + writeFileSync( + join(cwd, 'package.json'), + JSON.stringify({ + javaTronUp: { + fullNode: { + platforms: { + 'linux-x64': { + checksum: sha256('jar-from-package-json'), + url: 'https://example.test/FullNode.jar', + }, + }, + version: 'test-version', + }, + }, + }), + ); + + assert.deepEqual(readJavaTronInstallOptionsFromPackageJson({ cwd }), { + fullNode: { + platforms: { + 'linux-x64': { + checksum: sha256('jar-from-package-json'), + url: 'https://example.test/FullNode.jar', + }, + }, + version: 'test-version', + }, + }); + }); + + it('parses installer CLI options', () => { + assert.deepEqual( + parseJavaTronInstallCliOptions([ + '--cache-directory', + '/tmp/cache', + '--bin-directory', + '/tmp/bin', + '--full-node-url', + 'https://example.test/FullNode.jar', + '--full-node-checksum', + 'abc123', + ]), + { + binDirectory: '/tmp/bin', + cacheDirectory: '/tmp/cache', + fullNode: { + platforms: { + current: { + checksum: 'abc123', + url: 'https://example.test/FullNode.jar', + }, + }, + }, + }, + ); + }); + + it('downloads, verifies, caches, and installs the java-tron wrapper', async () => { + const cwd = createTempDir(); + const cacheDirectory = join(cwd, '.metamask', 'cache'); + const binDirectory = join(cwd, 'node_modules', '.bin'); + const downloads: { destination: string; url: string }[] = []; + const fullNodeContent = 'fake fullnode jar'; + const javaArchiveContent = 'fake java archive'; + const dependencies = createDependencies({ + downloads, + fullNodeContent, + javaArchiveContent, + }); + + const result = await installJavaTron( + { + binDirectory, + cacheDirectory, + cwd, + fullNode: { + platforms: { + 'darwin-arm64': { + checksum: sha256(fullNodeContent), + url: 'https://example.test/FullNode-aarch64.jar', + }, + }, + version: 'test-java-tron', + }, + javaRuntime: { + platforms: { + 'darwin-arm64': { + checksum: sha256(javaArchiveContent), + url: 'https://example.test/java.tar.gz', + }, + }, + version: 'test-java', + }, + platform: 'darwin-arm64', + }, + dependencies, + ); + + assert.equal(result.cacheHit, false); + assert.equal(result.version, 'test-java-tron'); + assert.equal(result.binaryPath, join(binDirectory, 'java-tron')); + assert.equal(readFileSync(result.fullNodeJar, 'utf8'), fullNodeContent); + assert.ok(result.javaBinary.endsWith('/bin/java')); + assert.ok(existsSync(result.binaryPath)); + assert.deepEqual( + downloads.map(({ url }) => url), + [ + 'https://example.test/java.tar.gz', + 'https://example.test/FullNode-aarch64.jar', + ], + ); + + const wrapperOutput = execFileSync( + process.execPath, + [result.binaryPath, '-v'], + { + encoding: 'utf8', + }, + ); + assert.equal(wrapperOutput.trim(), 'java -jar FullNode.jar -v'); + }); + + it('replaces stale bin symlinks without modifying their targets', async () => { + const cwd = createTempDir(); + const cacheDirectory = join(cwd, '.metamask', 'cache'); + const binDirectory = join(cwd, 'node_modules', '.bin'); + const fullNodeContent = 'fake fullnode jar'; + const javaArchiveContent = 'fake java archive'; + const staleTarget = join(cwd, 'stale-java-tron-target'); + + await mkdir(binDirectory, { recursive: true }); + writeFileSync(staleTarget, 'do not overwrite'); + symlinkSync(staleTarget, join(binDirectory, 'java-tron')); + + const result = await installJavaTron( + { + binDirectory, + cacheDirectory, + cwd, + fullNode: { + platforms: { + 'darwin-arm64': { + checksum: sha256(fullNodeContent), + url: 'https://example.test/FullNode-aarch64.jar', + }, + }, + }, + javaRuntime: { + platforms: { + 'darwin-arm64': { + checksum: sha256(javaArchiveContent), + url: 'https://example.test/java.tar.gz', + }, + }, + }, + platform: 'darwin-arm64', + }, + createDependencies({ fullNodeContent, javaArchiveContent }), + ); + + assert.equal(readFileSync(staleTarget, 'utf8'), 'do not overwrite'); + assert.equal(lstatSync(result.binaryPath).isSymbolicLink(), false); + }); + + it('reuses cached artifacts without downloading again', async () => { + const cwd = createTempDir(); + const cacheDirectory = join(cwd, '.metamask', 'cache'); + const binDirectory = join(cwd, 'node_modules', '.bin'); + const fullNodeContent = 'cached fullnode jar'; + const javaArchiveContent = 'cached java archive'; + + await installJavaTron( + { + binDirectory, + cacheDirectory, + cwd, + fullNode: { + platforms: { + 'linux-x64': { + checksum: sha256(fullNodeContent), + url: 'https://example.test/FullNode.jar', + }, + }, + version: 'cached-version', + }, + javaRuntime: { + platforms: { + 'linux-x64': { + checksum: sha256(javaArchiveContent), + url: 'https://example.test/java.tar.gz', + }, + }, + version: 'cached-java', + }, + platform: 'linux-x64', + }, + createDependencies({ fullNodeContent, javaArchiveContent }), + ); + + const result = await installJavaTron( + { + binDirectory, + cacheDirectory, + cwd, + fullNode: { + platforms: { + 'linux-x64': { + checksum: sha256(fullNodeContent), + url: 'https://example.test/FullNode.jar', + }, + }, + version: 'cached-version', + }, + javaRuntime: { + platforms: { + 'linux-x64': { + checksum: sha256(javaArchiveContent), + url: 'https://example.test/java.tar.gz', + }, + }, + version: 'cached-java', + }, + platform: 'linux-x64', + }, + { + downloadFile: async () => { + throw new Error('cache miss'); + }, + }, + ); + + assert.equal(result.cacheHit, true); + assert.equal(readFileSync(result.fullNodeJar, 'utf8'), fullNodeContent); + }); + + it('cleans only the java-tron-up cache namespace', async () => { + const cwd = createTempDir(); + const cacheDirectory = join(cwd, '.metamask', 'cache'); + await mkdir(join(cacheDirectory, 'java-tron-up', 'old'), { + recursive: true, + }); + await mkdir(join(cacheDirectory, 'foundryup', 'kept'), { + recursive: true, + }); + + await cleanJavaTronCache({ cacheDirectory, cwd }); + + assert.equal(existsSync(join(cacheDirectory, 'java-tron-up')), false); + assert.equal(existsSync(join(cacheDirectory, 'foundryup', 'kept')), true); + }); + + function createTempDir(): string { + const tempDir = mkdtempSync(join(tmpdir(), 'java-tron-up-test-')); + tempDirs.push(tempDir); + return tempDir; + } +}); + +function createDependencies({ + downloads = [], + fullNodeContent, + javaArchiveContent, +}: { + downloads?: { destination: string; url: string }[]; + fullNodeContent: string; + javaArchiveContent: string; +}): JavaTronInstallDependencies { + return { + downloadFile: async (url, destination): Promise => { + downloads.push({ destination, url }); + await writeFile( + destination, + url.includes('FullNode') ? fullNodeContent : javaArchiveContent, + ); + }, + extractArchive: async (_archivePath, destination): Promise => { + const javaBinary = join(destination, 'jdk', 'bin', 'java'); + await mkdir(join(destination, 'jdk', 'bin'), { recursive: true }); + await writeFile( + javaBinary, + '#!/bin/sh\nflag="$1"\njar="$2"\nshift 2\necho "java $flag $(basename "$jar") $*"\n', + ); + chmodSync(javaBinary, 0o755); + }, + }; +} + +function sha256(value: string): string { + return createHash('sha256').update(value).digest('hex'); +} diff --git a/packages/java-tron-up/src/install.ts b/packages/java-tron-up/src/install.ts new file mode 100644 index 0000000000..7412f6a551 --- /dev/null +++ b/packages/java-tron-up/src/install.ts @@ -0,0 +1,715 @@ +/* eslint-disable import-x/no-nodejs-modules, no-restricted-globals */ +import { spawn, spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + createWriteStream, + existsSync, + readdirSync, + readFileSync, + statSync, +} from 'node:fs'; +import { + chmod, + mkdir, + readFile, + rename, + rm, + unlink, + writeFile, +} from 'node:fs/promises'; +import { request as requestHttp } from 'node:http'; +import { request as requestHttps } from 'node:https'; +import { arch as osArch, homedir, platform as osPlatform } from 'node:os'; +import { dirname, join, relative } from 'node:path'; +import { pipeline } from 'node:stream/promises'; + +const JAVA_TRON_CACHE_NAMESPACE = 'java-tron-up'; +const FULL_NODE_CACHE_NAMESPACE = 'fullnode'; +const JAVA_CACHE_NAMESPACE = 'java'; + +export type JavaTronArtifactConfig = { + platforms: Record; + version?: string; +}; + +export type JavaTronArtifactPlatformConfig = { + checksum: string; + size?: number; + url: string; +}; + +export type JavaTronJavaRuntimeConfig = JavaTronArtifactConfig; + +export type JavaTronInstallOptions = { + binDirectory?: string; + cacheDirectory?: string; + cwd?: string; + fullNode?: JavaTronArtifactConfig; + javaBinary?: string; + javaRuntime?: JavaTronJavaRuntimeConfig; + platform?: string; +}; + +export type JavaTronInstallResult = { + binaryPath: string; + cacheHit: boolean; + checksum: string; + fullNodeJar: string; + javaBinary: string; + version?: string; +}; + +export type JavaTronInstallDependencies = { + downloadFile?: (url: string, destination: string) => Promise; + extractArchive?: (archivePath: string, destination: string) => Promise; +}; + +type JavaTronPackageJson = { + 'java-tron-up'?: JavaTronPackageJsonConfig; + javaTronUp?: JavaTronPackageJsonConfig; + javatronup?: JavaTronPackageJsonConfig; +}; + +type JavaTronPackageJsonConfig = Pick< + JavaTronInstallOptions, + 'binDirectory' | 'cacheDirectory' | 'fullNode' | 'javaRuntime' +>; + +export const JAVA_TRON_DEFAULT_FULL_NODE: JavaTronArtifactConfig = { + version: 'GreatVoyage-v4.8.1', + platforms: { + 'darwin-arm64': { + checksum: + '694431860ee76fc986ed495f9ec19f29ed3bd752a394386e7b3b9886b2292f59', + size: 202_460_186, + url: 'https://github.com/tronprotocol/java-tron/releases/download/GreatVoyage-v4.8.1/FullNode-aarch64.jar', + }, + 'darwin-x64': { + checksum: + '0e67b2fe75d7077750e73c4fa20725c6e9824657275d96be256ae5da681f9945', + size: 145_863_030, + url: 'https://github.com/tronprotocol/java-tron/releases/download/GreatVoyage-v4.8.1/FullNode.jar', + }, + 'linux-arm64': { + checksum: + '694431860ee76fc986ed495f9ec19f29ed3bd752a394386e7b3b9886b2292f59', + size: 202_460_186, + url: 'https://github.com/tronprotocol/java-tron/releases/download/GreatVoyage-v4.8.1/FullNode-aarch64.jar', + }, + 'linux-x64': { + checksum: + '0e67b2fe75d7077750e73c4fa20725c6e9824657275d96be256ae5da681f9945', + size: 145_863_030, + url: 'https://github.com/tronprotocol/java-tron/releases/download/GreatVoyage-v4.8.1/FullNode.jar', + }, + }, +}; + +export const JAVA_TRON_DEFAULT_JAVA_RUNTIME: JavaTronJavaRuntimeConfig = { + version: 'zulu-java8-x64-java17-arm64', + platforms: { + 'darwin-arm64': { + checksum: + 'f2bd5afaaaa4c23eb4bf2c78913c7eb7d3d228e44209ffec652fb72388a2f25c', + size: 192_646_000, + url: 'https://cdn.azul.com/zulu/bin/zulu17.66.19-ca-jdk17.0.19-macosx_aarch64.tar.gz', + }, + 'darwin-x64': { + checksum: + '4ac2efcae5d49afe1f2419ceb09bd3fb4af9df8411ab80184795960fc18fb5f6', + size: 41_346_500, + url: 'https://cdn.azul.com/zulu/bin/zulu8.94.0.17-ca-jre8.0.492-macosx_x64.tar.gz', + }, + 'linux-arm64': { + checksum: + 'c17d5657a673c0cfc099e9d803ed30498495894d7359fd1064d463093ed9850b', + size: 199_156_000, + url: 'https://cdn.azul.com/zulu/bin/zulu17.66.19-ca-jdk17.0.19-linux_aarch64.tar.gz', + }, + 'linux-x64': { + checksum: + '39abf1dc6798b5f6b8e9dca4e78994da316a3f990e444c2c483ea04f7f882cf2', + size: 42_504_400, + url: 'https://cdn.azul.com/zulu/bin/zulu8.94.0.17-ca-jre8.0.492-linux_x64.tar.gz', + }, + }, +}; + +export function getJavaTronCacheDirectory({ + cwd = process.cwd(), + homeDirectory = homedir(), +}: { + cwd?: string; + homeDirectory?: string; +} = {}): string { + const yarnRcPath = join(cwd, '.yarnrc.yml'); + + try { + const yarnRc = readFileSync(yarnRcPath, 'utf8'); + if (/^\s*enableGlobalCache:\s*true\s*$/mu.test(yarnRc)) { + return join(homeDirectory, '.cache', 'metamask'); + } + } catch (error) { + if (!isFileMissingError(error)) { + console.warn( + `Warning: Error reading ${yarnRcPath}, using local java-tron-up cache:`, + error, + ); + } + } + + return join(cwd, '.metamask', 'cache'); +} + +export function readJavaTronInstallOptionsFromPackageJson({ + cwd = process.cwd(), + packageJsonPath = join(cwd, 'package.json'), +}: { + cwd?: string; + packageJsonPath?: string; +} = {}): JavaTronInstallOptions { + const packageJson = JSON.parse( + readFileSync(packageJsonPath, 'utf8'), + ) as JavaTronPackageJson; + const config = + packageJson.javaTronUp ?? + packageJson.javatronup ?? + packageJson['java-tron-up']; + const options: JavaTronInstallOptions = {}; + + if (config?.binDirectory) { + options.binDirectory = config.binDirectory; + } + if (config?.cacheDirectory) { + options.cacheDirectory = config.cacheDirectory; + } + if (config?.fullNode) { + options.fullNode = config.fullNode; + } + if (config?.javaRuntime) { + options.javaRuntime = config.javaRuntime; + } + + return options; +} + +export function parseJavaTronInstallCliOptions( + args: string[], +): JavaTronInstallOptions { + const options: JavaTronInstallOptions = {}; + const fullNode: Partial = {}; + const javaRuntime: Partial = {}; + + for (let index = 0; index < args.length; index += 1) { + const arg = args[index]; + const value = args[index + 1]; + + switch (arg) { + case '--bin-directory': + options.binDirectory = readCliValue(arg, value); + index += 1; + break; + case '--cache-directory': + options.cacheDirectory = readCliValue(arg, value); + index += 1; + break; + case '--full-node-checksum': + fullNode.checksum = readCliValue(arg, value); + index += 1; + break; + case '--full-node-url': + fullNode.url = readCliValue(arg, value); + index += 1; + break; + case '--java-runtime-checksum': + javaRuntime.checksum = readCliValue(arg, value); + index += 1; + break; + case '--java-runtime-url': + javaRuntime.url = readCliValue(arg, value); + index += 1; + break; + case '--platform': + options.platform = readCliValue(arg, value); + index += 1; + break; + default: + throw new Error(`Unknown java-tron-up install option: ${arg}`); + } + } + + if (fullNode.url || fullNode.checksum) { + options.fullNode = { + platforms: { + current: requireCompletePlatformConfig( + fullNode, + 'FullNode CLI options', + ), + }, + }; + } + + if (javaRuntime.url || javaRuntime.checksum) { + options.javaRuntime = { + platforms: { + current: requireCompletePlatformConfig( + javaRuntime, + 'Java runtime CLI options', + ), + }, + }; + } + + return options; +} + +export async function installJavaTron( + options: JavaTronInstallOptions = {}, + dependencies: JavaTronInstallDependencies = {}, +): Promise { + const cwd = options.cwd ?? process.cwd(); + const cacheDirectory = + options.cacheDirectory ?? getJavaTronCacheDirectory({ cwd }); + const binDirectory = + options.binDirectory ?? join(cwd, 'node_modules', '.bin'); + const platformKey = options.platform ?? getPlatformKey(); + const fullNodeConfig = resolvePlatformConfig( + options.fullNode ?? JAVA_TRON_DEFAULT_FULL_NODE, + platformKey, + 'java-tron FullNode', + ); + const javaBinary = + options.javaBinary ?? + (await installJavaRuntime( + { + cacheDirectory, + javaRuntime: options.javaRuntime ?? JAVA_TRON_DEFAULT_JAVA_RUNTIME, + platform: platformKey, + }, + dependencies, + )); + const fullNodeResult = await installFullNodeJar( + { + cacheDirectory, + config: fullNodeConfig, + }, + dependencies, + ); + const binaryPath = await installJavaTronBinary({ + binDirectory, + fullNodeJar: fullNodeResult.fullNodeJar, + javaBinary, + }); + + return { + binaryPath, + cacheHit: fullNodeResult.cacheHit, + checksum: fullNodeConfig.checksum, + fullNodeJar: fullNodeResult.fullNodeJar, + javaBinary, + version: (options.fullNode ?? JAVA_TRON_DEFAULT_FULL_NODE).version, + }; +} + +export async function cleanJavaTronCache( + options: Pick = {}, +): Promise { + const cwd = options.cwd ?? process.cwd(); + const cacheDirectory = + options.cacheDirectory ?? getJavaTronCacheDirectory({ cwd }); + + await rm(join(cacheDirectory, JAVA_TRON_CACHE_NAMESPACE), { + force: true, + recursive: true, + }); +} + +export async function installJavaRuntime( + { + cacheDirectory = getJavaTronCacheDirectory(), + javaRuntime = JAVA_TRON_DEFAULT_JAVA_RUNTIME, + platform = getPlatformKey(), + }: { + cacheDirectory?: string; + javaRuntime?: JavaTronJavaRuntimeConfig; + platform?: string; + } = {}, + dependencies: JavaTronInstallDependencies = {}, +): Promise { + const platformConfig = resolvePlatformConfig( + javaRuntime, + platform, + 'java-tron Java runtime', + ); + const cacheKey = getCacheKey(platformConfig); + const cacheRoot = join( + cacheDirectory, + JAVA_TRON_CACHE_NAMESPACE, + JAVA_CACHE_NAMESPACE, + cacheKey, + ); + const existingJavaBinary = findJavaBinary(cacheRoot); + + if (existingJavaBinary) { + return existingJavaBinary; + } + + const tempRoot = `${cacheRoot}.downloading`; + const archivePath = join(tempRoot, 'java-runtime.tar.gz'); + const downloadFile = dependencies.downloadFile ?? downloadFileFromUrl; + const extractArchive = dependencies.extractArchive ?? extractTarGzArchive; + + await rm(tempRoot, { force: true, recursive: true }); + await rm(cacheRoot, { force: true, recursive: true }); + await mkdir(tempRoot, { recursive: true }); + + try { + await downloadFile(platformConfig.url, archivePath); + await verifyFileChecksum( + archivePath, + platformConfig.checksum, + 'Downloaded Java runtime', + ); + await extractArchive(archivePath, tempRoot); + + const javaBinary = findJavaBinary(tempRoot); + if (!javaBinary) { + throw new Error( + `Java runtime archive for ${platform} did not contain bin/java.`, + ); + } + + await mkdir(dirname(cacheRoot), { recursive: true }); + await rename(tempRoot, cacheRoot); + + return javaBinary.replace(tempRoot, cacheRoot); + } catch (error) { + await rm(tempRoot, { force: true, recursive: true }); + await rm(cacheRoot, { force: true, recursive: true }); + throw error; + } +} + +async function installFullNodeJar( + { + cacheDirectory, + config, + }: { + cacheDirectory: string; + config: JavaTronArtifactPlatformConfig; + }, + dependencies: JavaTronInstallDependencies, +): Promise<{ cacheHit: boolean; fullNodeJar: string }> { + const cacheKey = getCacheKey(config); + const cacheRoot = join( + cacheDirectory, + JAVA_TRON_CACHE_NAMESPACE, + FULL_NODE_CACHE_NAMESPACE, + cacheKey, + ); + const fullNodeJar = join(cacheRoot, 'FullNode.jar'); + + if (existsSync(fullNodeJar)) { + await verifyFileChecksum( + fullNodeJar, + config.checksum, + 'Cached java-tron FullNode', + ); + return { cacheHit: true, fullNodeJar }; + } + + const tempRoot = `${cacheRoot}.downloading`; + const tempFullNodeJar = join(tempRoot, 'FullNode.jar'); + const downloadFile = dependencies.downloadFile ?? downloadFileFromUrl; + + await rm(tempRoot, { force: true, recursive: true }); + await rm(cacheRoot, { force: true, recursive: true }); + await mkdir(tempRoot, { recursive: true }); + + try { + await downloadFile(config.url, tempFullNodeJar); + await verifyFileChecksum( + tempFullNodeJar, + config.checksum, + 'Downloaded java-tron FullNode', + ); + await mkdir(dirname(cacheRoot), { recursive: true }); + await rename(tempRoot, cacheRoot); + + return { cacheHit: false, fullNodeJar }; + } catch (error) { + await rm(tempRoot, { force: true, recursive: true }); + await rm(cacheRoot, { force: true, recursive: true }); + throw error; + } +} + +async function installJavaTronBinary({ + binDirectory, + fullNodeJar, + javaBinary, +}: { + binDirectory: string; + fullNodeJar: string; + javaBinary: string; +}): Promise { + const binaryPath = join(binDirectory, 'java-tron'); + const relativeJavaBinary = relative(binDirectory, javaBinary); + const relativeFullNodeJar = relative(binDirectory, fullNodeJar); + + await mkdir(binDirectory, { recursive: true }); + await unlink(binaryPath).catch((error) => { + if (!isFileMissingError(error)) { + throw error; + } + }); + await writeFile( + binaryPath, + `#!/usr/bin/env node +const { spawnSync } = require('node:child_process'); +const path = require('node:path'); + +const javaBinary = path.resolve(__dirname, ${JSON.stringify(relativeJavaBinary)}); +const fullNodeJar = path.resolve(__dirname, ${JSON.stringify(relativeFullNodeJar)}); +const result = spawnSync(javaBinary, ['-jar', fullNodeJar, ...process.argv.slice(2)], { + stdio: 'inherit', +}); + +if (result.error) { + console.error(result.error.message); + process.exit(1); +} + +if (result.signal) { + process.kill(process.pid, result.signal); +} + +process.exit(result.status ?? 0); +`, + ); + await chmod(binaryPath, 0o755); + + return binaryPath; +} + +function resolvePlatformConfig( + config: JavaTronArtifactConfig, + platform: string, + label: string, +): JavaTronArtifactPlatformConfig { + const platformConfig = config.platforms[platform] ?? config.platforms.current; + + if (!platformConfig) { + throw new Error(`No ${label} is configured for ${platform}.`); + } + + return platformConfig; +} + +function requireCompletePlatformConfig( + config: Partial, + label: string, +): JavaTronArtifactPlatformConfig { + if (!config.url || !config.checksum) { + throw new Error(`${label} require both a URL and a checksum.`); + } + + return { + checksum: config.checksum, + url: config.url, + }; +} + +function getCacheKey(config: JavaTronArtifactPlatformConfig): string { + return createHash('sha256') + .update(`${config.url}:${config.checksum}`) + .digest('hex'); +} + +async function verifyFileChecksum( + filePath: string, + expectedChecksum: string, + label: string, +): Promise { + const checksum = createHash('sha256') + .update(await readFile(filePath)) + .digest('hex'); + + if (checksum !== expectedChecksum) { + throw new Error( + `${label} checksum mismatch. Expected ${expectedChecksum}, got ${checksum}.`, + ); + } +} + +async function downloadFileFromUrl( + url: string, + destination: string, +): Promise { + await mkdir(dirname(destination), { recursive: true }); + await pipeline( + await openDownloadStream(new URL(url)), + createWriteStream(destination), + ); +} + +async function openDownloadStream( + url: URL, + redirectsRemaining = 5, +): Promise { + const request = url.protocol === 'http:' ? requestHttp : requestHttps; + + return await new Promise((resolvePromise, rejectPromise) => { + const req = request(url, (response) => { + const { headers, statusCode, statusMessage } = response; + + if ( + statusCode && + statusCode >= 300 && + statusCode < 400 && + headers.location + ) { + response.resume(); + if (redirectsRemaining <= 0) { + rejectPromise(new Error(`Too many redirects downloading ${url}`)); + return; + } + + openDownloadStream( + new URL(headers.location, url), + redirectsRemaining - 1, + ) + .then(resolvePromise) + .catch(rejectPromise); + return; + } + + if (!statusCode || statusCode < 200 || statusCode >= 300) { + response.resume(); + rejectPromise( + new Error( + `Request to ${url} failed with ${statusCode ?? 'unknown'} ${ + statusMessage ?? '' + }`.trim(), + ), + ); + return; + } + + resolvePromise(response); + }); + + req.on('error', rejectPromise); + req.end(); + }); +} + +async function extractTarGzArchive( + archivePath: string, + destination: string, +): Promise { + await runCommand('tar', ['-xzf', archivePath, '-C', destination]); +} + +async function runCommand(command: string, args: string[]): Promise { + await new Promise((resolvePromise, rejectPromise) => { + const child = spawn(command, args, { + shell: false, + stdio: ['ignore', 'ignore', 'pipe'], + }); + let stderr = ''; + + child.stderr.on('data', (chunk) => { + stderr += chunk.toString(); + }); + child.on('error', rejectPromise); + child.on('close', (code) => { + if (code === 0) { + resolvePromise(); + return; + } + + rejectPromise( + new Error( + `${command} ${args.join(' ')} exited with code ${code}: ${stderr}`, + ), + ); + }); + }); +} + +function findJavaBinary(root: string): string | undefined { + if (!isDirectory(root)) { + return undefined; + } + + const candidate = join(root, 'bin', 'java'); + if (isFile(candidate)) { + return candidate; + } + + for (const entry of readdirSync(root)) { + const child = join(root, entry); + if (!isDirectory(child)) { + continue; + } + + const found = findJavaBinary(child); + if (found) { + return found; + } + } + + return undefined; +} + +function isDirectory(path: string): boolean { + try { + return statSync(path).isDirectory(); + } catch { + return false; + } +} + +function isFile(path: string): boolean { + try { + return statSync(path).isFile(); + } catch { + return false; + } +} + +function getPlatformKey(): string { + return `${osPlatform()}-${normalizeSystemArchitecture()}`; +} + +function normalizeSystemArchitecture(architecture = osArch()): string { + if (architecture === 'x64' && osPlatform() === 'darwin') { + const result = spawnSync('sysctl', ['-n', 'sysctl.proc_translated'], { + encoding: 'utf8', + shell: false, + stdio: ['ignore', 'pipe', 'ignore'], + }); + if (result.stdout.trim() === '1') { + return 'arm64'; + } + } + + return architecture; +} + +function readCliValue(option: string, value: string | undefined): string { + if (!value || value.startsWith('--')) { + throw new Error(`${option} requires a value.`); + } + return value; +} + +function isFileMissingError(error: unknown): boolean { + return ( + typeof error === 'object' && + error !== null && + Object.prototype.hasOwnProperty.call(error, 'code') && + (error as NodeJS.ErrnoException).code === 'ENOENT' + ); +} diff --git a/packages/java-tron-up/tsconfig.build.json b/packages/java-tron-up/tsconfig.build.json new file mode 100644 index 0000000000..02a0eea03f --- /dev/null +++ b/packages/java-tron-up/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.packages.build.json", + "compilerOptions": { + "baseUrl": "./", + "outDir": "./dist", + "rootDir": "./src" + }, + "references": [], + "include": ["../../types", "./src"] +} diff --git a/packages/java-tron-up/tsconfig.json b/packages/java-tron-up/tsconfig.json new file mode 100644 index 0000000000..025ba2ef7f --- /dev/null +++ b/packages/java-tron-up/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.packages.json", + "compilerOptions": { + "baseUrl": "./" + }, + "references": [], + "include": ["../../types", "./src"] +} diff --git a/packages/java-tron-up/typedoc.json b/packages/java-tron-up/typedoc.json new file mode 100644 index 0000000000..c9da015dbf --- /dev/null +++ b/packages/java-tron-up/typedoc.json @@ -0,0 +1,7 @@ +{ + "entryPoints": ["./src/index.ts"], + "excludePrivate": true, + "hideGenerator": true, + "out": "docs", + "tsconfig": "./tsconfig.build.json" +} diff --git a/teams.json b/teams.json index 2c19709511..320612969a 100644 --- a/teams.json +++ b/teams.json @@ -68,6 +68,7 @@ "metamask/eth-json-rpc-middleware": "team-core-platform,team-confirmations,team-wallet-integrations", "metamask/eth-json-rpc-provider": "team-wallet-integrations,team-core-platform", "metamask/foundryup": "team-mobile-platform,team-extension-platform", + "metamask/java-tron-up": "team-mobile-platform,team-extension-platform,team-networks", "metamask/json-rpc-engine": "team-wallet-integrations,team-core-platform", "metamask/json-rpc-middleware-stream": "team-wallet-integrations,team-core-platform", "metamask/keyring-controller": "team-accounts-framework,team-core-platform", diff --git a/tsconfig.build.json b/tsconfig.build.json index 1604f654f5..1437a59b83 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -127,6 +127,9 @@ { "path": "./packages/geolocation-controller/tsconfig.build.json" }, + { + "path": "./packages/java-tron-up/tsconfig.build.json" + }, { "path": "./packages/json-rpc-engine/tsconfig.build.json" }, diff --git a/tsconfig.json b/tsconfig.json index 9ca28b560c..5fb72893df 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -122,6 +122,9 @@ { "path": "./packages/geolocation-controller" }, + { + "path": "./packages/java-tron-up" + }, { "path": "./packages/json-rpc-engine" }, diff --git a/yarn.lock b/yarn.lock index d177fa888e..2bbe20535f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4173,6 +4173,25 @@ __metadata: languageName: unknown linkType: soft +"@metamask/java-tron-up@workspace:packages/java-tron-up": + version: 0.0.0-use.local + resolution: "@metamask/java-tron-up@workspace:packages/java-tron-up" + dependencies: + "@metamask/auto-changelog": "npm:^6.1.0" + "@ts-bridge/cli": "npm:^0.6.4" + "@types/jest": "npm:^29.5.14" + deepmerge: "npm:^4.2.2" + jest: "npm:^29.7.0" + ts-jest: "npm:^29.2.5" + tsx: "npm:^4.20.5" + typedoc: "npm:^0.25.13" + typedoc-plugin-missing-exports: "npm:^2.0.0" + typescript: "npm:~5.3.3" + bin: + java-tron-up: ./dist/bin/java-tron-up.mjs + languageName: unknown + linkType: soft + "@metamask/json-rpc-engine@npm:^10.0.0, @metamask/json-rpc-engine@npm:^10.0.2, @metamask/json-rpc-engine@npm:^10.1.0, @metamask/json-rpc-engine@npm:^10.1.1, @metamask/json-rpc-engine@npm:^10.2.4, @metamask/json-rpc-engine@npm:^10.5.0, @metamask/json-rpc-engine@workspace:packages/json-rpc-engine": version: 0.0.0-use.local resolution: "@metamask/json-rpc-engine@workspace:packages/json-rpc-engine"