From d149d086b63e17338e2f6bb0e9889038159982a8 Mon Sep 17 00:00:00 2001 From: "m.likhtar" Date: Tue, 16 Jul 2024 16:02:01 +0300 Subject: [PATCH 1/5] package: add "ton-proof" package --- packages/ton-proof/.eslintrc.js | 3 + packages/ton-proof/.gitignore | 6 + packages/ton-proof/.nvmrc | 1 + packages/ton-proof/LICENSE | 201 ++++++++++++++++++ packages/ton-proof/README.md | 72 +++++++ packages/ton-proof/api-extractor.json | 25 +++ packages/ton-proof/jest.config.js | 19 ++ packages/ton-proof/package.json | 61 ++++++ packages/ton-proof/project.json | 12 ++ packages/ton-proof/rollup.config.mjs | 24 +++ packages/ton-proof/src/index.ts | 1 + .../src/ton-proof-service/constants.ts | 4 + .../src/ton-proof-service/helpers.ts | 73 +++++++ .../ton-proof/src/ton-proof-service/index.ts | 5 + .../src/ton-proof-service/interfaces.ts | 17 ++ .../ton-proof-service/ton-proof-service.ts | 135 ++++++++++++ .../src/ton-proof-service/wrappers.ts | 18 ++ packages/ton-proof/tests/ton-proof.spec.ts | 121 +++++++++++ packages/ton-proof/tsconfig.json | 14 ++ packages/ton-proof/tsconfig.test.json | 12 ++ 20 files changed, 824 insertions(+) create mode 100644 packages/ton-proof/.eslintrc.js create mode 100644 packages/ton-proof/.gitignore create mode 100644 packages/ton-proof/.nvmrc create mode 100644 packages/ton-proof/LICENSE create mode 100644 packages/ton-proof/README.md create mode 100644 packages/ton-proof/api-extractor.json create mode 100644 packages/ton-proof/jest.config.js create mode 100644 packages/ton-proof/package.json create mode 100644 packages/ton-proof/project.json create mode 100644 packages/ton-proof/rollup.config.mjs create mode 100644 packages/ton-proof/src/index.ts create mode 100644 packages/ton-proof/src/ton-proof-service/constants.ts create mode 100644 packages/ton-proof/src/ton-proof-service/helpers.ts create mode 100644 packages/ton-proof/src/ton-proof-service/index.ts create mode 100644 packages/ton-proof/src/ton-proof-service/interfaces.ts create mode 100644 packages/ton-proof/src/ton-proof-service/ton-proof-service.ts create mode 100644 packages/ton-proof/src/ton-proof-service/wrappers.ts create mode 100644 packages/ton-proof/tests/ton-proof.spec.ts create mode 100644 packages/ton-proof/tsconfig.json create mode 100644 packages/ton-proof/tsconfig.test.json diff --git a/packages/ton-proof/.eslintrc.js b/packages/ton-proof/.eslintrc.js new file mode 100644 index 000000000..0ceb3998a --- /dev/null +++ b/packages/ton-proof/.eslintrc.js @@ -0,0 +1,3 @@ +module.exports = { + extends: ["../../.eslintrc.js"] +}; diff --git a/packages/ton-proof/.gitignore b/packages/ton-proof/.gitignore new file mode 100644 index 000000000..1ea8472d2 --- /dev/null +++ b/packages/ton-proof/.gitignore @@ -0,0 +1,6 @@ +../../.idea + +lib +types-dist +node_modules +.env diff --git a/packages/ton-proof/.nvmrc b/packages/ton-proof/.nvmrc new file mode 100644 index 000000000..085135ec9 --- /dev/null +++ b/packages/ton-proof/.nvmrc @@ -0,0 +1 @@ +v0.1 diff --git a/packages/ton-proof/LICENSE b/packages/ton-proof/LICENSE new file mode 100644 index 000000000..eceea2db9 --- /dev/null +++ b/packages/ton-proof/LICENSE @@ -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 2022 tonkeeper + + 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/ton-proof/README.md b/packages/ton-proof/README.md new file mode 100644 index 000000000..1bc536f72 --- /dev/null +++ b/packages/ton-proof/README.md @@ -0,0 +1,72 @@ + +# TonProofService + +## Overview + +`TonProofService` is a service for verifying proofs in the TON blockchain ecosystem. It includes methods for generating payloads and validating proofs against specified criteria. This service is primarily used for authentication and validation purposes within TON-based applications. + +## Installation + +To install the necessary dependencies, use the following commands: + +```sh +npm install @tonconnect/ton-proof +``` + +Check [documentation](https://docs.ton.org/develop/dapps/ton-connect/sign#structure-of-ton_proof) to see payload structure + +### Usage +Below is an example of how to use the TonProofService in a TypeScript project: + +```js + +import { TonProofService } from '@tonconnect/ton-proof'; + +// Initialize the service +const tonProofService = new TonProofService({ + allowedDomains: ['your-domain.com'], + tonProofPrefix: 'your-prefix/', + tonConnectPrefix: 'your-connect-prefix' +}); + +// Generate a random payload +const payload = tonProofService.generatePayload(); +console.log('Generated Payload:', payload); + +// Check proof +const isValid = await tonProofService.checkProof(yourPayload, getWalletPublicKeyFunction); +console.log('Is proof valid:', isValid); +``` + +#### Class: TonProofService +Constructor +- allowedDomains: An optional array of allowed domains for validation. +- tonProofPrefix: An optional prefix for the proof. +- tonConnectPrefix: An optional prefix for the connect. + +#### Methods +`generatePayload` +Generates a random payload. + +```js +const payload = tonProofService.generatePayload(); +console.log('Generated Payload:', payload); +``` +`checkProof` +Reference implementation of the checkProof method: +Parameters: + +- payload: An object containing the proof data. +- getWalletPublicKey: A function that takes an address and returns a public key. (If wallet isn't compatible) +Example: + +```js +const isValid = await tonProofService.checkProof(yourPayload, getWalletPublicKeyFunction); +console.log('Is proof valid:', isValid); +``` +#### Default Values +The TonProofService class has the following default values: + +- defaultTonProofPrefix: 'ton-proof-item-v2/' +- defaultTonConnectPrefix: 'ton-connect' +- defaultAllowedDomains: ['ton-connect.github.io'] diff --git a/packages/ton-proof/api-extractor.json b/packages/ton-proof/api-extractor.json new file mode 100644 index 000000000..693c75d19 --- /dev/null +++ b/packages/ton-proof/api-extractor.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "mainEntryPointFilePath": "/types-dist/index.d.ts", + "bundledPackages": [], + "dtsRollup": { + "enabled": true, + "untrimmedFilePath": "/lib/types/index.d.ts" + }, + "apiReport": { + "enabled": false + }, + "docModel": { + "enabled": false + }, + "tsdocMetadata": { + "enabled": false + }, + "messages": { + "extractorMessageReporting": { + "ae-missing-release-tag": { + "logLevel": "none" + } + } + } +} diff --git a/packages/ton-proof/jest.config.js b/packages/ton-proof/jest.config.js new file mode 100644 index 000000000..0e0a424b0 --- /dev/null +++ b/packages/ton-proof/jest.config.js @@ -0,0 +1,19 @@ +module.exports = { + preset: 'ts-jest', + roots: [ + "src", "tests" + ], + moduleDirectories: ['node_modules'], + testEnvironment: 'node', + testMatch: ["**/?(*.)+(spec|test).[jt]s?(x)"], + transform: { + '^.+\\.tsx?$': [ + 'ts-jest', + {tsconfig: './tsconfig.test.json'}, + ], + }, + moduleNameMapper: { + '^src/(.*)$': '/../../src/$1', + 'tests/(.*)$': '/../../tests/$1', + }, +}; diff --git a/packages/ton-proof/package.json b/packages/ton-proof/package.json new file mode 100644 index 000000000..d20c3dc3e --- /dev/null +++ b/packages/ton-proof/package.json @@ -0,0 +1,61 @@ +{ + "name": "@tonconnect/ton-proof", + "version": "0.0.1", + "repository": { + "type": "git", + "url": "git+https://github.com/ton-connect/sdk.git" + }, + "homepage": "https://github.com/ton-connect/sdk/tree/main/packages/protocol", + "bugs": { + "url": "https://github.com/ton-connect/sdk/issues" + }, + "keywords": [ + "TON", + "Wallet", + "ton-connect", + "Connect", + "Tonkeeper" + ], + "author": "tonconnect", + "license": "Apache-2.0", + "scripts": { + "build": "npx rimraf types-dist && npx rimraf lib && npx rollup -c rollup.config.mjs && tsc && api-extractor run && npx rimraf types-dist", + "test": "jest" + }, + "files": [ + "lib" + ], + "main": "./lib/cjs/index.cjs", + "module": "./lib/esm/index.mjs", + "types": "./lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "require": "./lib/cjs/index.cjs", + "import": "./lib/esm/index.mjs", + "default": "./lib/cjs/index.cjs" + } + }, + "dependencies": { + "@ton/core": "^0.56.3", + "@ton/crypto": "^3.2.0", + "@ton/ton": "^13.11.2", + "tweetnacl": "^1.0.3", + "tweetnacl-util": "^0.15.1" + }, + "devDependencies": { + "@rollup/plugin-typescript": "^11.0.0", + "@types/jest": "^29.2.0", + "jest": "^29.2.2", + "rollup": "^3.18.0", + "ts-jest": "^29.0.3" + }, + "nx": { + "tags": [ + "scope:protocol" + ] + }, + "typedoc": { + "entryPoint": "./src/index.ts" + } +} diff --git a/packages/ton-proof/project.json b/packages/ton-proof/project.json new file mode 100644 index 000000000..48b1a1aec --- /dev/null +++ b/packages/ton-proof/project.json @@ -0,0 +1,12 @@ +{ + "root": "packages/ton-proof/", + "targets": { + "version": { + "executor": "@jscutlery/semver:version", + "options": { + "changelogHeader": "# Changelog @tonconnect/ton-proof \n", + "push": false + } + } + } +} diff --git a/packages/ton-proof/rollup.config.mjs b/packages/ton-proof/rollup.config.mjs new file mode 100644 index 000000000..c87bb236e --- /dev/null +++ b/packages/ton-proof/rollup.config.mjs @@ -0,0 +1,24 @@ +import typescript from '@rollup/plugin-typescript'; + +export default [ + { + input: 'src/index.ts', + output: { + format: 'esm', + file: './lib/esm/index.mjs', + sourcemap: true + }, + plugins: [typescript({ compilerOptions: { declaration: false, declarationDir: undefined } })], + external: ['tweetnacl', 'tweetnacl-util'] + }, + { + input: 'src/index.ts', + output: { + format: 'cjs', + file: './lib/cjs/index.cjs', + sourcemap: true + }, + plugins: [typescript({ compilerOptions: { declaration: false, declarationDir: undefined } })], + external: ['tweetnacl', 'tweetnacl-util'] + } +]; diff --git a/packages/ton-proof/src/index.ts b/packages/ton-proof/src/index.ts new file mode 100644 index 000000000..b78900ccf --- /dev/null +++ b/packages/ton-proof/src/index.ts @@ -0,0 +1 @@ +export * from './ton-proof-service'; \ No newline at end of file diff --git a/packages/ton-proof/src/ton-proof-service/constants.ts b/packages/ton-proof/src/ton-proof-service/constants.ts new file mode 100644 index 000000000..13c2d322e --- /dev/null +++ b/packages/ton-proof/src/ton-proof-service/constants.ts @@ -0,0 +1,4 @@ +export enum CHAIN { + MAINNET = '-239', + TESTNET = '-3' +} diff --git a/packages/ton-proof/src/ton-proof-service/helpers.ts b/packages/ton-proof/src/ton-proof-service/helpers.ts new file mode 100644 index 000000000..4eef50fd4 --- /dev/null +++ b/packages/ton-proof/src/ton-proof-service/helpers.ts @@ -0,0 +1,73 @@ +import { + Slice, + StateInit, + WalletContractV1R1, + WalletContractV1R2, + WalletContractV1R3, + WalletContractV2R1, + WalletContractV2R2, + WalletContractV3R1, + WalletContractV3R2, + WalletContractV4 as WalletContractV4R2 +} from '@ton/ton'; +import { Buffer } from 'buffer'; +import { WalletContractV4R1 } from './wrappers'; + +const knownWallets = [ + { contract: WalletContractV1R1, loadData: loadWalletV1Data }, + { contract: WalletContractV1R2, loadData: loadWalletV1Data }, + { contract: WalletContractV1R3, loadData: loadWalletV1Data }, + { contract: WalletContractV2R1, loadData: loadWalletV2Data }, + { contract: WalletContractV2R2, loadData: loadWalletV2Data }, + { contract: WalletContractV3R1, loadData: loadWalletV3Data }, + { contract: WalletContractV3R2, loadData: loadWalletV3Data }, + { contract: WalletContractV4R1, loadData: loadWalletV4Data }, + { contract: WalletContractV4R2, loadData: loadWalletV4Data } +].map(({ contract, loadData }) => ({ + contract: contract, + loadData: loadData, + wallet: contract.create({ workchain: 0, publicKey: Buffer.alloc(32) }) +})); + +function loadWalletV1Data(cs: Slice) { + const seqno = cs.loadUint(32); + const publicKey = cs.loadBuffer(32); + return { seqno, publicKey }; +} + +function loadWalletV2Data(cs: Slice) { + const seqno = cs.loadUint(32); + const publicKey = cs.loadBuffer(32); + return { seqno, publicKey }; +} + +function loadWalletV3Data(cs: Slice) { + const seqno = cs.loadUint(32); + const walletId = cs.loadUint(32); + const publicKey = cs.loadBuffer(32); + return { seqno, publicKey, walletId }; +} + +function loadWalletV4Data(cs: Slice) { + const seqno = cs.loadUint(32); + const walletId = cs.loadUint(32); + const publicKey = cs.loadBuffer(32); + const plugins = cs.loadMaybeRef(); + return { seqno, publicKey, walletId, plugins }; +} + +export function tryParsePublicKey(stateInit: StateInit): Buffer | null { + if (!stateInit.code || !stateInit.data) { + return null; + } + + for (const { wallet, loadData } of knownWallets) { + try { + if (wallet.init.code.equals(stateInit.code)) { + return loadData(stateInit.data.beginParse()).publicKey; + } + } catch (e) {} + } + + return null; +} diff --git a/packages/ton-proof/src/ton-proof-service/index.ts b/packages/ton-proof/src/ton-proof-service/index.ts new file mode 100644 index 000000000..2c4c9d79d --- /dev/null +++ b/packages/ton-proof/src/ton-proof-service/index.ts @@ -0,0 +1,5 @@ +export * from './ton-proof-service'; +export * from './interfaces'; +export * from './constants'; +export * from './wrappers'; +export * from './helpers'; diff --git a/packages/ton-proof/src/ton-proof-service/interfaces.ts b/packages/ton-proof/src/ton-proof-service/interfaces.ts new file mode 100644 index 000000000..b598bbd43 --- /dev/null +++ b/packages/ton-proof/src/ton-proof-service/interfaces.ts @@ -0,0 +1,17 @@ +import { CHAIN } from './constants'; + +export interface CheckProofRequestDto { + address: string; + network: CHAIN; + public_key: string; + proof: { + timestamp: number; + domain: { + lengthBytes: number; + value: string; + }; + payload: string; + signature: string; + state_init: string; + }; +} diff --git a/packages/ton-proof/src/ton-proof-service/ton-proof-service.ts b/packages/ton-proof/src/ton-proof-service/ton-proof-service.ts new file mode 100644 index 000000000..bc7ab39d6 --- /dev/null +++ b/packages/ton-proof/src/ton-proof-service/ton-proof-service.ts @@ -0,0 +1,135 @@ +import { sha256 } from '@ton/crypto'; +import { Address, Cell, contractAddress, loadStateInit } from '@ton/ton'; +import { Buffer } from 'buffer'; +import { randomBytes, sign } from 'tweetnacl'; +import { CheckProofRequestDto } from './interfaces'; +import { tryParsePublicKey } from './helpers'; + +const defaultTonProofPrefix = 'ton-proof-item-v2/'; +const defaultTonConnectPrefix = 'ton-connect'; +const defaultAllowedDomains = ['ton-connect.github.io']; +const validAuthTime = 15 * 60; // 15 minutes + +export class TonProofService { + private allowedDomains: string[]; + private tonProofPrefix: string; + private tonConnectPrefix: string; + + constructor({ + allowedDomains, + tonProofPrefix, + tonConnectPrefix + }: { + allowedDomains?: string[]; + tonProofPrefix?: string; + tonConnectPrefix?: string; + }) { + this.allowedDomains = allowedDomains ?? defaultAllowedDomains; + this.tonProofPrefix = tonProofPrefix ?? defaultTonProofPrefix; + this.tonConnectPrefix = tonConnectPrefix ?? defaultTonConnectPrefix; + } + + /** + * Generate a random payload. + */ + public generatePayload(): string { + return Buffer.from(randomBytes(32)).toString('hex'); + } + + /** + * Reference implementation of the checkProof method: + * https://github.com/ton-blockchain/ton-connect/blob/main/requests-responses.md#address-proof-signature-ton_proof + */ + public async checkProof( + payload: CheckProofRequestDto, + getWalletPublicKey: (address: string) => Promise + ): Promise { + try { + const stateInit = loadStateInit(Cell.fromBase64(payload.proof.state_init).beginParse()); + + // 1. First, try to obtain public key via get_public_key get-method on smart contract deployed at Address. + // 2. If the smart contract is not deployed yet, or the get-method is missing, you need: + // 2.1. Parse TonAddressItemReply.walletStateInit and get public key from stateInit. You can compare the walletStateInit.code + // with the code of standard wallets contracts and parse the data according to the found wallet version. + let publicKey = + tryParsePublicKey(stateInit) ?? (await getWalletPublicKey(payload.address)); + if (!publicKey) { + return false; + } + + // 2.2. Check that TonAddressItemReply.publicKey equals to obtained public key + const wantedPublicKey = Buffer.from(payload.public_key, 'hex'); + if (!publicKey.equals(wantedPublicKey)) { + return false; + } + + // 2.3. Check that TonAddressItemReply.walletStateInit.hash() equals to TonAddressItemReply.address. .hash() means BoC hash. + const wantedAddress = Address.parse(payload.address); + const address = contractAddress(wantedAddress.workChain, stateInit); + if (!address.equals(wantedAddress)) { + return false; + } + + if (!this.allowedDomains.includes(payload.proof.domain.value)) { + return false; + } + + const now = Math.floor(Date.now() / 1000); + if (now - validAuthTime > payload.proof.timestamp) { + return false; + } + + const message = { + workchain: address.workChain, + address: address.hash, + domain: { + lengthBytes: payload.proof.domain.lengthBytes, + value: payload.proof.domain.value + }, + signature: Buffer.from(payload.proof.signature, 'base64'), + payload: payload.proof.payload, + stateInit: payload.proof.state_init, + timestamp: payload.proof.timestamp + }; + + const wc = Buffer.alloc(4); + wc.writeUInt32BE(message.workchain, 0); + + const ts = Buffer.alloc(8); + ts.writeBigUInt64LE(BigInt(message.timestamp), 0); + + const dl = Buffer.alloc(4); + dl.writeUInt32LE(message.domain.lengthBytes, 0); + + // message = utf8_encode("ton-proof-item-v2/") ++ + // Address ++ + // AppDomain ++ + // Timestamp ++ + // Payload + const msg = Buffer.concat([ + Buffer.from(this.tonProofPrefix), + wc, + message.address, + dl, + Buffer.from(message.domain.value), + ts, + Buffer.from(message.payload) + ]); + + const msgHash = Buffer.from(await sha256(msg)); + + // signature = Ed25519Sign(privkey, sha256(0xffff ++ utf8_encode("ton-connect") ++ sha256(message))) + const fullMsg = Buffer.concat([ + Buffer.from([0xff, 0xff]), + Buffer.from(this.tonConnectPrefix), + msgHash + ]); + + const result = Buffer.from(await sha256(fullMsg)); + + return sign.detached.verify(result, message.signature, publicKey); + } catch (e) { + return false; + } + } +} diff --git a/packages/ton-proof/src/ton-proof-service/wrappers.ts b/packages/ton-proof/src/ton-proof-service/wrappers.ts new file mode 100644 index 000000000..df7be7b29 --- /dev/null +++ b/packages/ton-proof/src/ton-proof-service/wrappers.ts @@ -0,0 +1,18 @@ +import { Cell, contractAddress, WalletContractV4 as WalletContractV4R2 } from '@ton/ton'; +import { Buffer } from 'buffer'; + +export class WalletContractV4R1 { + static create(args: { workchain: number; publicKey: Buffer; walletId?: number | null }) { + const wallet = WalletContractV4R2.create(args); + const { data } = wallet.init; + const code = Cell.fromBoc( + Buffer.from( + 'B5EE9C72410215010002F5000114FF00F4A413F4BCF2C80B010201200203020148040504F8F28308D71820D31FD31FD31F02F823BBF263ED44D0D31FD31FD3FFF404D15143BAF2A15151BAF2A205F901541064F910F2A3F80024A4C8CB1F5240CB1F5230CBFF5210F400C9ED54F80F01D30721C0009F6C519320D74A96D307D402FB00E830E021C001E30021C002E30001C0039130E30D03A4C8CB1F12CB1FCBFF1112131403EED001D0D3030171B0915BE021D749C120915BE001D31F218210706C7567BD228210626C6E63BDB022821064737472BDB0925F03E002FA403020FA4401C8CA07CBFFC9D0ED44D0810140D721F404305C810108F40A6FA131B3925F05E004D33FC8258210706C7567BA9131E30D248210626C6E63BAE30004060708020120090A005001FA00F404308210706C7567831EB17080185005CB0527CF165003FA02F40012CB69CB1F5210CB3F0052F8276F228210626C6E63831EB17080185005CB0527CF1624FA0214CB6A13CB1F5230CB3F01FA02F4000092821064737472BA8E3504810108F45930ED44D0810140D720C801CF16F400C9ED54821064737472831EB17080185004CB0558CF1622FA0212CB6ACB1FCB3F9410345F04E2C98040FB000201200B0C0059BD242B6F6A2684080A06B90FA0218470D4080847A4937D29910CE6903E9FF9837812801B7810148987159F31840201580D0E0011B8C97ED44D0D70B1F8003DB29DFB513420405035C87D010C00B23281F2FFF274006040423D029BE84C600201200F100019ADCE76A26840206B90EB85FFC00019AF1DF6A26840106B90EB858FC0006ED207FA00D4D422F90005C8CA0715CBFFC9D077748018C8CB05CB0222CF165005FA0214CB6B12CCCCC971FB00C84014810108F451F2A702006C810108D718C8542025810108F451F2A782106E6F746570748018C8CB05CB025004CF16821005F5E100FA0213CB6A12CB1FC971FB00020072810108D718305202810108F459F2A7F82582106473747270748018C8CB05CB025005CF16821005F5E100FA0214CB6A13CB1F12CB3FC973FB00000AF400C9ED5446A9F34F', + 'hex' + ) + )[0]!; + (wallet as any).init = { data, code }; + (wallet as any).address = contractAddress(args.workchain, wallet.init); + return wallet; + } +} diff --git a/packages/ton-proof/tests/ton-proof.spec.ts b/packages/ton-proof/tests/ton-proof.spec.ts new file mode 100644 index 000000000..42dda2016 --- /dev/null +++ b/packages/ton-proof/tests/ton-proof.spec.ts @@ -0,0 +1,121 @@ +import { beginCell, storeStateInit } from '@ton/ton'; +import { mnemonicNew, mnemonicToWalletKey, sha256 } from '@ton/crypto'; +import { sign } from 'tweetnacl'; +import { + CHAIN, + CheckProofRequestDto, + TonProofService, + WalletContractV4R1 +} from '../src/ton-proof-service'; + +describe('TonProofService', () => { + let tonProofService: TonProofService; + const customDomains = ['example.com', 'test.com']; + + beforeEach(() => { + tonProofService = new TonProofService({ allowedDomains: customDomains }); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + test('should initialize with custom allowed domains', () => { + expect((tonProofService as any).allowedDomains).toEqual(customDomains); + }); + + test('should generate a random payload', () => { + const payload = tonProofService.generatePayload(); + expect(payload).toHaveLength(64); + }); + + test('should return false if publicKey is not obtained', async () => { + const payload = { + address: 'address', + proof: { + state_init: 'state_init', + domain: { value: 'example.com', lengthBytes: 11 }, + signature: 'signature', + payload: 'payload', + timestamp: Math.floor(Date.now() / 1000) + } + }; + const getWalletPublicKey = jest.fn().mockResolvedValue(null); + + const result = await tonProofService.checkProof( + payload as CheckProofRequestDto, + getWalletPublicKey + ); + expect(result).toBe(false); + }); + + test('should return true for valid tonProof', async () => { + const proofPayload = tonProofService.generatePayload(); + const mnemonic = await mnemonicNew(); + const keyPair = await mnemonicToWalletKey(mnemonic); + const wallet = WalletContractV4R1.create({ publicKey: keyPair.publicKey, workchain: 0 }); + const payloadBuffer = Buffer.from(proofPayload, 'hex'); + const stateInit = beginCell().store(storeStateInit(wallet.init)).endCell(); + + const timestamp = Math.floor(Date.now() / 1000) + 100000; + const address = wallet.address.toRawString(); + const domain = 'example.com'; + const lengthBytes = domain.length; + + const wc = Buffer.alloc(4); + wc.writeUInt32BE(wallet.address.workChain, 0); + + const ts = Buffer.alloc(8); + ts.writeBigUInt64LE(BigInt(timestamp), 0); + + const dl = Buffer.alloc(4); + dl.writeUInt32LE(lengthBytes, 0); + + // message = utf8_encode("ton-proof-item-v2/") ++ + // Address ++ + // AppDomain ++ + // Timestamp ++ + // Payload + const msg = Buffer.concat([ + Buffer.from('ton-proof-item-v2/'), + wc, + wallet.address.hash, + dl, + Buffer.from(domain), + ts, + Buffer.from(payloadBuffer.toString('base64')) + ]); + + const msgHash = Buffer.from(await sha256(msg)); + + // signature = Ed25519Sign(privkey, sha256(0xffff ++ utf8_encode("ton-connect") ++ sha256(message))) + const fullMsg = Buffer.concat([ + Buffer.from([0xff, 0xff]), + Buffer.from('ton-connect'), + msgHash + ]); + + const buff = Buffer.from(await sha256(fullMsg)); + const payload: CheckProofRequestDto = { + address, + network: CHAIN.MAINNET, + public_key: keyPair.publicKey.toString('hex'), + proof: { + state_init: stateInit.toBoc().toString('base64'), + domain: { + value: domain, + lengthBytes + }, + signature: Buffer.from( + sign.detached(Uint8Array.from(buff), keyPair.secretKey) + ).toString('base64'), + payload: payloadBuffer.toString('base64'), + timestamp + } + }; + const getWalletPublicKey = jest.fn().mockResolvedValue(null); + + const result = await tonProofService.checkProof(payload, getWalletPublicKey); + expect(result).toBe(true); + }); +}); diff --git a/packages/ton-proof/tsconfig.json b/packages/ton-proof/tsconfig.json new file mode 100644 index 000000000..a03387c32 --- /dev/null +++ b/packages/ton-proof/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "declaration": true, + "emitDeclarationOnly": true, + "declarationDir": "./types-dist", + "baseUrl": "./", + "rootDir": "src" + }, + "include": [ + "./src" + ], + "exclude": ["./__tests__","node_modules", "./lib", "./types-dist"] +} diff --git a/packages/ton-proof/tsconfig.test.json b/packages/ton-proof/tsconfig.test.json new file mode 100644 index 000000000..93edd6be5 --- /dev/null +++ b/packages/ton-proof/tsconfig.test.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "target": "ESNext", + "outDir": "./dist-tests", + "baseUrl": "./", + "paths": { + "src/*": ["./src/*"], + "tests/*": ["./tests/*"] + } + }, +} From 9b67b22985e3f438e32854dee57a45bf111dd8ca Mon Sep 17 00:00:00 2001 From: "m.likhtar" Date: Wed, 17 Jul 2024 11:56:57 +0300 Subject: [PATCH 2/5] fix comments --- packages/ton-proof/README.md | 19 +++++++++++++++---- packages/ton-proof/package.json | 3 ++- packages/ton-proof/rollup.config.mjs | 12 ++++++++---- .../ton-proof-service/ton-proof-service.ts | 12 ++++++++---- packages/ton-proof/tests/ton-proof.spec.ts | 10 ++++++++-- 5 files changed, 41 insertions(+), 15 deletions(-) diff --git a/packages/ton-proof/README.md b/packages/ton-proof/README.md index 1bc536f72..fcb83dcea 100644 --- a/packages/ton-proof/README.md +++ b/packages/ton-proof/README.md @@ -3,7 +3,7 @@ ## Overview -`TonProofService` is a service for verifying proofs in the TON blockchain ecosystem. It includes methods for generating payloads and validating proofs against specified criteria. This service is primarily used for authentication and validation purposes within TON-based applications. +`TonProofService` is a service for verifying proofs in the TON blockchain ecosystem. It includes methods for generating payloads and validating proofs against specified criteria. This service helps ensure the validity of user addresses, which can be used for authentication and validation purposes within TON-based applications. ## Installation @@ -41,12 +41,12 @@ console.log('Is proof valid:', isValid); #### Class: TonProofService Constructor - allowedDomains: An optional array of allowed domains for validation. -- tonProofPrefix: An optional prefix for the proof. -- tonConnectPrefix: An optional prefix for the connect. +- tonProofPrefix: An optional prefix for the proof. (Using in message generation) +- tonConnectPrefix: An optional prefix for the connect. (Using in message generation) #### Methods `generatePayload` -Generates a random payload. +Generates a random payload. (in `hex`) ```js const payload = tonProofService.generatePayload(); @@ -58,6 +58,17 @@ Parameters: - payload: An object containing the proof data. - getWalletPublicKey: A function that takes an address and returns a public key. (If wallet isn't compatible) + +Compatible wallets: +- WalletContractV1R1, +- WalletContractV1R2, +- WalletContractV1R3, +- WalletContractV2R1, +- WalletContractV2R2, +- WalletContractV3R1, +- WalletContractV3R2, +- WalletContractV4R2 + Example: ```js diff --git a/packages/ton-proof/package.json b/packages/ton-proof/package.json index d20c3dc3e..0cb830549 100644 --- a/packages/ton-proof/package.json +++ b/packages/ton-proof/package.json @@ -14,7 +14,8 @@ "Wallet", "ton-connect", "Connect", - "Tonkeeper" + "Tonkeeper", + "ton proof" ], "author": "tonconnect", "license": "Apache-2.0", diff --git a/packages/ton-proof/rollup.config.mjs b/packages/ton-proof/rollup.config.mjs index c87bb236e..83154727f 100644 --- a/packages/ton-proof/rollup.config.mjs +++ b/packages/ton-proof/rollup.config.mjs @@ -8,8 +8,10 @@ export default [ file: './lib/esm/index.mjs', sourcemap: true }, - plugins: [typescript({ compilerOptions: { declaration: false, declarationDir: undefined } })], - external: ['tweetnacl', 'tweetnacl-util'] + plugins: [ + typescript({ compilerOptions: { declaration: false, declarationDir: undefined } }) + ], + external: ['tweetnacl', 'tweetnacl-util', '@ton/ton', '@ton/crypto', 'buffer'] }, { input: 'src/index.ts', @@ -18,7 +20,9 @@ export default [ file: './lib/cjs/index.cjs', sourcemap: true }, - plugins: [typescript({ compilerOptions: { declaration: false, declarationDir: undefined } })], - external: ['tweetnacl', 'tweetnacl-util'] + plugins: [ + typescript({ compilerOptions: { declaration: false, declarationDir: undefined } }) + ], + external: ['tweetnacl', 'tweetnacl-util', '@ton/ton', '@ton/crypto', 'buffer'] } ]; diff --git a/packages/ton-proof/src/ton-proof-service/ton-proof-service.ts b/packages/ton-proof/src/ton-proof-service/ton-proof-service.ts index bc7ab39d6..7ceb15c16 100644 --- a/packages/ton-proof/src/ton-proof-service/ton-proof-service.ts +++ b/packages/ton-proof/src/ton-proof-service/ton-proof-service.ts @@ -8,25 +8,29 @@ import { tryParsePublicKey } from './helpers'; const defaultTonProofPrefix = 'ton-proof-item-v2/'; const defaultTonConnectPrefix = 'ton-connect'; const defaultAllowedDomains = ['ton-connect.github.io']; -const validAuthTime = 15 * 60; // 15 minutes +const defaultValidAuthTime = 15 * 60; // 15 minutes export class TonProofService { private allowedDomains: string[]; private tonProofPrefix: string; private tonConnectPrefix: string; + private validAuthTime: number; constructor({ allowedDomains, tonProofPrefix, - tonConnectPrefix + tonConnectPrefix, + validAuthTime }: { allowedDomains?: string[]; tonProofPrefix?: string; tonConnectPrefix?: string; + validAuthTime?: number; }) { this.allowedDomains = allowedDomains ?? defaultAllowedDomains; this.tonProofPrefix = tonProofPrefix ?? defaultTonProofPrefix; this.tonConnectPrefix = tonConnectPrefix ?? defaultTonConnectPrefix; + this.validAuthTime = validAuthTime ?? defaultValidAuthTime; } /** @@ -42,7 +46,7 @@ export class TonProofService { */ public async checkProof( payload: CheckProofRequestDto, - getWalletPublicKey: (address: string) => Promise + getWalletPublicKey: (address: string) => Promise = () => Promise.resolve(null) ): Promise { try { const stateInit = loadStateInit(Cell.fromBase64(payload.proof.state_init).beginParse()); @@ -75,7 +79,7 @@ export class TonProofService { } const now = Math.floor(Date.now() / 1000); - if (now - validAuthTime > payload.proof.timestamp) { + if (now - this.validAuthTime > payload.proof.timestamp) { return false; } diff --git a/packages/ton-proof/tests/ton-proof.spec.ts b/packages/ton-proof/tests/ton-proof.spec.ts index 42dda2016..fa646de2e 100644 --- a/packages/ton-proof/tests/ton-proof.spec.ts +++ b/packages/ton-proof/tests/ton-proof.spec.ts @@ -29,6 +29,12 @@ describe('TonProofService', () => { expect(payload).toHaveLength(64); }); + test('should generate different payloads', () => { + const payload1 = tonProofService.generatePayload(); + const payload2 = tonProofService.generatePayload(); + expect(payload1).not.toBe(payload2); + }); + test('should return false if publicKey is not obtained', async () => { const payload = { address: 'address', @@ -62,6 +68,7 @@ describe('TonProofService', () => { const domain = 'example.com'; const lengthBytes = domain.length; + // we are doing it manually here, but it is usually handled automatically by TonConnect const wc = Buffer.alloc(4); wc.writeUInt32BE(wallet.address.workChain, 0); @@ -113,9 +120,8 @@ describe('TonProofService', () => { timestamp } }; - const getWalletPublicKey = jest.fn().mockResolvedValue(null); - const result = await tonProofService.checkProof(payload, getWalletPublicKey); + const result = await tonProofService.checkProof(payload); expect(result).toBe(true); }); }); From abdbee92d72ed6b5c663c38baaab8db7ff134dee Mon Sep 17 00:00:00 2001 From: "m.likhtar" Date: Tue, 6 Aug 2024 11:50:33 +0300 Subject: [PATCH 3/5] add custom wallets for ton proof --- .../src/ton-proof-service/helpers.ts | 32 +++++++++---------- .../src/ton-proof-service/interfaces.ts | 20 ++++++++++++ .../ton-proof-service/ton-proof-service.ts | 24 +++++++++++--- .../src/ton-proof-service/wrappers.ts | 9 ++++-- 4 files changed, 62 insertions(+), 23 deletions(-) diff --git a/packages/ton-proof/src/ton-proof-service/helpers.ts b/packages/ton-proof/src/ton-proof-service/helpers.ts index 4eef50fd4..2d38b65ce 100644 --- a/packages/ton-proof/src/ton-proof-service/helpers.ts +++ b/packages/ton-proof/src/ton-proof-service/helpers.ts @@ -12,22 +12,19 @@ import { } from '@ton/ton'; import { Buffer } from 'buffer'; import { WalletContractV4R1 } from './wrappers'; +import { WalletOptions } from './interfaces'; -const knownWallets = [ - { contract: WalletContractV1R1, loadData: loadWalletV1Data }, - { contract: WalletContractV1R2, loadData: loadWalletV1Data }, - { contract: WalletContractV1R3, loadData: loadWalletV1Data }, - { contract: WalletContractV2R1, loadData: loadWalletV2Data }, - { contract: WalletContractV2R2, loadData: loadWalletV2Data }, - { contract: WalletContractV3R1, loadData: loadWalletV3Data }, - { contract: WalletContractV3R2, loadData: loadWalletV3Data }, +export const DEFAULT_WALLETS: WalletOptions[] = [ + { contract: WalletContractV4R2, loadData: loadWalletV4Data }, { contract: WalletContractV4R1, loadData: loadWalletV4Data }, - { contract: WalletContractV4R2, loadData: loadWalletV4Data } -].map(({ contract, loadData }) => ({ - contract: contract, - loadData: loadData, - wallet: contract.create({ workchain: 0, publicKey: Buffer.alloc(32) }) -})); + { contract: WalletContractV3R2, loadData: loadWalletV3Data }, + { contract: WalletContractV3R1, loadData: loadWalletV3Data }, + { contract: WalletContractV2R2, loadData: loadWalletV2Data }, + { contract: WalletContractV2R1, loadData: loadWalletV2Data }, + { contract: WalletContractV1R3, loadData: loadWalletV1Data }, + { contract: WalletContractV1R2, loadData: loadWalletV1Data }, + { contract: WalletContractV1R1, loadData: loadWalletV1Data } +]; function loadWalletV1Data(cs: Slice) { const seqno = cs.loadUint(32); @@ -56,12 +53,15 @@ function loadWalletV4Data(cs: Slice) { return { seqno, publicKey, walletId, plugins }; } -export function tryParsePublicKey(stateInit: StateInit): Buffer | null { +export function tryParsePublicKey( + stateInit: StateInit, + wallets: Required[] +): Buffer | null { if (!stateInit.code || !stateInit.data) { return null; } - for (const { wallet, loadData } of knownWallets) { + for (const { wallet, loadData } of wallets) { try { if (wallet.init.code.equals(stateInit.code)) { return loadData(stateInit.data.beginParse()).publicKey; diff --git a/packages/ton-proof/src/ton-proof-service/interfaces.ts b/packages/ton-proof/src/ton-proof-service/interfaces.ts index b598bbd43..2d01c5b5b 100644 --- a/packages/ton-proof/src/ton-proof-service/interfaces.ts +++ b/packages/ton-proof/src/ton-proof-service/interfaces.ts @@ -1,3 +1,4 @@ +import { Slice, Contract, StateInit, Cell } from '@ton/core'; import { CHAIN } from './constants'; export interface CheckProofRequestDto { @@ -15,3 +16,22 @@ export interface CheckProofRequestDto { state_init: string; }; } + +export interface InitContract { + readonly init: { + data: Cell; + code: Cell; + }; +} + +interface ContractFactory { + create(args: { workchain: number; publicKey: Buffer; walletId?: number | null }): InitContract; +} + +export interface WalletOptions { + contract: ContractFactory; + loadData: (cs: Slice) => { + publicKey: Buffer; + }; + wallet?: InitContract; +} diff --git a/packages/ton-proof/src/ton-proof-service/ton-proof-service.ts b/packages/ton-proof/src/ton-proof-service/ton-proof-service.ts index 7ceb15c16..fa3c3f502 100644 --- a/packages/ton-proof/src/ton-proof-service/ton-proof-service.ts +++ b/packages/ton-proof/src/ton-proof-service/ton-proof-service.ts @@ -2,8 +2,8 @@ import { sha256 } from '@ton/crypto'; import { Address, Cell, contractAddress, loadStateInit } from '@ton/ton'; import { Buffer } from 'buffer'; import { randomBytes, sign } from 'tweetnacl'; -import { CheckProofRequestDto } from './interfaces'; -import { tryParsePublicKey } from './helpers'; +import { CheckProofRequestDto, WalletOptions } from './interfaces'; +import { DEFAULT_WALLETS, tryParsePublicKey } from './helpers'; const defaultTonProofPrefix = 'ton-proof-item-v2/'; const defaultTonConnectPrefix = 'ton-connect'; @@ -15,22 +15,34 @@ export class TonProofService { private tonProofPrefix: string; private tonConnectPrefix: string; private validAuthTime: number; + private wallets: Required[]; constructor({ allowedDomains, tonProofPrefix, tonConnectPrefix, - validAuthTime + validAuthTime, + wallets = [] }: { allowedDomains?: string[]; tonProofPrefix?: string; tonConnectPrefix?: string; validAuthTime?: number; + wallets?: WalletOptions[]; }) { this.allowedDomains = allowedDomains ?? defaultAllowedDomains; this.tonProofPrefix = tonProofPrefix ?? defaultTonProofPrefix; this.tonConnectPrefix = tonConnectPrefix ?? defaultTonConnectPrefix; this.validAuthTime = validAuthTime ?? defaultValidAuthTime; + this.wallets = this.prepareWallets([...DEFAULT_WALLETS, ...wallets]); + } + + private prepareWallets(options: WalletOptions[]): Required[] { + return options.map(({ contract, loadData, wallet }) => ({ + contract: contract, + loadData: loadData, + wallet: wallet ?? contract.create({ workchain: 0, publicKey: Buffer.alloc(32) }) + })); } /** @@ -46,7 +58,8 @@ export class TonProofService { */ public async checkProof( payload: CheckProofRequestDto, - getWalletPublicKey: (address: string) => Promise = () => Promise.resolve(null) + getWalletPublicKey: (address: string) => Promise = () => + Promise.resolve(null) ): Promise { try { const stateInit = loadStateInit(Cell.fromBase64(payload.proof.state_init).beginParse()); @@ -56,7 +69,8 @@ export class TonProofService { // 2.1. Parse TonAddressItemReply.walletStateInit and get public key from stateInit. You can compare the walletStateInit.code // with the code of standard wallets contracts and parse the data according to the found wallet version. let publicKey = - tryParsePublicKey(stateInit) ?? (await getWalletPublicKey(payload.address)); + tryParsePublicKey(stateInit, this.wallets) ?? + (await getWalletPublicKey(payload.address)); if (!publicKey) { return false; } diff --git a/packages/ton-proof/src/ton-proof-service/wrappers.ts b/packages/ton-proof/src/ton-proof-service/wrappers.ts index df7be7b29..87137951a 100644 --- a/packages/ton-proof/src/ton-proof-service/wrappers.ts +++ b/packages/ton-proof/src/ton-proof-service/wrappers.ts @@ -1,8 +1,13 @@ -import { Cell, contractAddress, WalletContractV4 as WalletContractV4R2 } from '@ton/ton'; +import { Cell, Contract, contractAddress, WalletContractV4 as WalletContractV4R2 } from '@ton/ton'; import { Buffer } from 'buffer'; +import { InitContract } from './interfaces'; export class WalletContractV4R1 { - static create(args: { workchain: number; publicKey: Buffer; walletId?: number | null }) { + static create(args: { + workchain: number; + publicKey: Buffer; + walletId?: number | null; + }): InitContract { const wallet = WalletContractV4R2.create(args); const { data } = wallet.init; const code = Cell.fromBoc( From e86ff6dd22b70f352f3354600d2997c1447d836c Mon Sep 17 00:00:00 2001 From: "m.likhtar" Date: Tue, 6 Aug 2024 12:33:31 +0300 Subject: [PATCH 4/5] improve readme for custom wallets --- packages/ton-proof/README.md | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/packages/ton-proof/README.md b/packages/ton-proof/README.md index fcb83dcea..7f0302ed6 100644 --- a/packages/ton-proof/README.md +++ b/packages/ton-proof/README.md @@ -43,6 +43,7 @@ Constructor - allowedDomains: An optional array of allowed domains for validation. - tonProofPrefix: An optional prefix for the proof. (Using in message generation) - tonConnectPrefix: An optional prefix for the connect. (Using in message generation) +- wallets: An optional list of custom wallets. #### Methods `generatePayload` @@ -69,15 +70,40 @@ Compatible wallets: - WalletContractV3R2, - WalletContractV4R2 -Example: +#### You can add your own custom wallet using `wallets` parameter: ```js -const isValid = await tonProofService.checkProof(yourPayload, getWalletPublicKeyFunction); -console.log('Is proof valid:', isValid); +export class CustomContract { + static create(): InitContract { + const init = { + data: Cell.fromBase64('...your code'), + code: Cell.fromBase64('...your code') + }; + return { init }; + } +} + +function loadCustomContractData(cs: Slice) { + const seqno = cs.loadUint(32); + const publicKey = cs.loadBuffer(32); + return { seqno, publicKey }; +} + +const customContractData: WalletOptions = { + contract: CustomContract, + loadData: loadCustomContractData +}; + +const tonProofService = new TonProofService({ + wallets: [customContractData] +}); + ``` + #### Default Values The TonProofService class has the following default values: - defaultTonProofPrefix: 'ton-proof-item-v2/' - defaultTonConnectPrefix: 'ton-connect' - defaultAllowedDomains: ['ton-connect.github.io'] +- wallets: DEFAULT_WALLETS From 7a48658c610400a29a46a668b895aaf3a745af72 Mon Sep 17 00:00:00 2001 From: "m.likhtar" Date: Tue, 6 Aug 2024 13:55:49 +0300 Subject: [PATCH 5/5] update readme for ton proof --- packages/ton-proof/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ton-proof/README.md b/packages/ton-proof/README.md index 7f0302ed6..c9afc6a11 100644 --- a/packages/ton-proof/README.md +++ b/packages/ton-proof/README.md @@ -76,7 +76,7 @@ Compatible wallets: export class CustomContract { static create(): InitContract { const init = { - data: Cell.fromBase64('...your code'), + data: Cell.fromBase64('...your data'), code: Cell.fromBase64('...your code') }; return { init };