Repository: toncenter/ton-wallet
Branch: master
Commit: a62f67cb079b
Files: 77
Total size: 701.8 KB
Directory structure:
gitextract_8l00d9tb/
├── .github/
│ └── ISSUE_TEMPLATE/
│ └── bug_report.yaml
├── .gitignore
├── build/
│ ├── gulp/
│ │ ├── config.js
│ │ ├── copy.js
│ │ ├── css.js
│ │ ├── env.js
│ │ ├── html.js
│ │ ├── manifest.js
│ │ ├── pack.js
│ │ ├── remove.js
│ │ ├── script.js
│ │ └── start.js
│ ├── gulpfile.js
│ ├── readme.md
│ └── safari/
│ ├── TON Wallet/
│ │ ├── AppDelegate.swift
│ │ ├── Assets.xcassets/
│ │ │ ├── AccentColor.colorset/
│ │ │ │ └── Contents.json
│ │ │ ├── AppIcon.appiconset/
│ │ │ │ └── Contents.json
│ │ │ └── Contents.json
│ │ ├── Base.lproj/
│ │ │ ├── Main.html
│ │ │ └── Main.storyboard
│ │ ├── Resources/
│ │ │ ├── Script.js
│ │ │ └── Style.css
│ │ ├── TON_Wallet.entitlements
│ │ └── ViewController.swift
│ ├── TON Wallet Extension/
│ │ ├── Info.plist
│ │ ├── SafariWebExtensionHandler.swift
│ │ └── TON_Wallet_Extension.entitlements
│ └── TON Wallet.xcodeproj/
│ ├── project.pbxproj
│ ├── project.xcworkspace/
│ │ ├── contents.xcworkspacedata
│ │ ├── xcshareddata/
│ │ │ └── IDEWorkspaceChecks.plist
│ │ └── xcuserdata/
│ │ └── sergei.xcuserdatad/
│ │ └── UserInterfaceState.xcuserstate
│ └── xcuserdata/
│ └── sergei.xcuserdatad/
│ └── xcschemes/
│ └── xcschememanagement.plist
├── docs/
│ ├── assets/
│ │ ├── favicon/
│ │ │ ├── browserconfig.xml
│ │ │ └── site.webmanifest
│ │ └── lottie/
│ │ ├── confirm.tgs
│ │ ├── created.tgs
│ │ ├── diamond.tgs
│ │ ├── done.tgs
│ │ ├── empty.tgs
│ │ ├── intro.tgs
│ │ ├── lock.tgs
│ │ ├── money.tgs
│ │ └── paper.tgs
│ ├── index.html
│ ├── js/
│ │ ├── Controller.js
│ │ └── View.js
│ ├── libs/
│ │ ├── aes-js-3.1.2.js
│ │ └── noble-ed25519-1.7.3.js
│ └── main.css
├── license
├── package.json
├── readme.md
└── src/
├── assets/
│ ├── favicon/
│ │ ├── browserconfig.xml
│ │ └── site.webmanifest
│ └── lottie/
│ ├── confirm.tgs
│ ├── created.tgs
│ ├── diamond.tgs
│ ├── done.tgs
│ ├── empty.tgs
│ ├── intro.tgs
│ ├── lock.tgs
│ ├── money.tgs
│ └── paper.tgs
├── css/
│ └── main.css
├── index.html
├── js/
│ ├── Controller.js
│ ├── extension/
│ │ ├── background.js
│ │ ├── content.js
│ │ └── provider.js
│ ├── util/
│ │ ├── encryption.js
│ │ └── storage.js
│ └── view/
│ ├── DropDown.js
│ ├── Lottie.js
│ ├── Utils.js
│ └── View.js
└── libs/
├── aes-js-3.1.2.js
└── noble-ed25519-1.7.3.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.yaml
================================================
name: Bug Report
description: Report of critical bug such as UX inconsistencies, logical contradictions and functional shortcomings.
labels: 'Bug Report'
body:
- type: dropdown
id: bug_type
attributes:
label: Bug Type
description: Select the bug type
options:
- Functional
- UX
- UI
- Performance
- Security
- Localization
- Other
validations:
required: true
- type: textarea
id: reproduction-steps
attributes:
label: Reproduction steps
description: Steps to reproduce a bug (you are welcome to attach screenshots here)
placeholder: 1. Click diamond 2. HODL
validations:
required: true
- type: textarea
id: actual-result
attributes:
label: Actual result
description: What was seen
placeholder: When action is done, something happens
validations:
required: true
- type: textarea
id: expected-result
attributes:
label: Expected result
description: What was expected
placeholder: When action is done, nothing happens
validations:
required: true
- type: dropdown
id: suggested-severity
attributes:
label: Suggested Severity
description: Severity of the bug
options:
- Vulnerability
- Critical
- High
- Medium
- Low
validations:
required: true
# - type: dropdown
# id: browsers
# attributes:
# label: "Browsers"
# description: What browsers are you seeing the problem on ?
# multiple: true
# options:
# - Chrome
# - Safari
# - Firefox
# - Microsoft Edge
# - Brave
# validations:
# required: false
# - type: dropdown
# id: os
# attributes:
# label: "OS"
# description: What is the impacted environment ?
# multiple: true
# options:
# - Windows
# - Linux
# - Mac
# validations:
# required: false
- type: textarea
id: device
attributes:
label: Device
description: Information about device
value: |
Desktop (please complete the following information):
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
Smartphone (please complete the following information):
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
validations:
required: true
- type: textarea
id: additional-context
attributes:
label: Additional Context
description: Add any other context about the problem here. You can also attach any extra screenshots or screencasts here.
placeholder: e.g. device was rooted
validations:
required: false
================================================
FILE: .gitignore
================================================
.idea
.vscode
artifacts
node_modules
.DS_Store
.env
================================================
FILE: build/gulp/config.js
================================================
/**
* Path to ".env" file relative to project root directory
*/
const DOTENV_PATH = '.env';
/**
* Required for any task environment variables (see .env.example file in project root directory)
* keys - required environment variable name
* values - task and target mask kind "{task_name}.{target_name}", any part of it or full mask
* may be replaced by "*" symbol which mean any of task, target or its combination
*/
const REQUIRED_ENV_VARS = {
'TONCENTER_API_KEY_WEB_MAIN': '*',
'TONCENTER_API_KEY_WEB_TEST': '*',
'TONCENTER_API_KEY_EXT_MAIN': '*',
'TONCENTER_API_KEY_EXT_TEST': '*',
'MOZILLA_ADDONS_API_KEY': 'publish.firefox',
'MOZILLA_ADDONS_API_SECRET': 'publish.firefox',
'MOZILLA_EXTENSION_ID': 'publish.firefox'
};
/**
* Possible build targets identifiers to names map
*/
const TARGETS = {
WEB: 'web',
CHROMIUM: 'chromium',
FIREFOX: 'firefox',
SAFARI: 'safari'
};
/**
* Possible build destinations identifiers to paths map
* Different targets can match same destinations, for example,
* FIREFOX and SAFARI require V2 build destination
*/
const BUILD_DESTS = {
WEB: 'docs',
V3: 'artifacts/v3',
V2: 'artifacts/v2'
};
/**
* Targets and build destinations conformity
*/
const TARGETS_BUILD_DESTS = {
[TARGETS.WEB]: BUILD_DESTS.WEB,
[TARGETS.CHROMIUM]: BUILD_DESTS.V3,
[TARGETS.FIREFOX]: BUILD_DESTS.V2,
[TARGETS.SAFARI]: BUILD_DESTS.V2
};
/**
* Globs for watch task
*/
const WATCH_GLOBS = ['src/**/*'];
/**
* Port for web wallet start task HTTP server
*/
const START_WEB_PORT = 8080;
module.exports = {
DOTENV_PATH,
REQUIRED_ENV_VARS,
TARGETS,
BUILD_DESTS,
TARGETS_BUILD_DESTS,
WATCH_GLOBS,
START_WEB_PORT
};
================================================
FILE: build/gulp/copy.js
================================================
const { dest, src } = require('gulp');
const { BUILD_DESTS } = require('./config');
/**
* Build destinations and required files conformity
* keys - build destination or "*" for all
* value - list of required files globs
*/
const BUILD_DESTS_GLOBS = {
'*': [
'src/assets/fonts/**/*',
'src/assets/lottie/**/*',
'src/assets/ui/**/*',
'src/libs/**/*'
],
[BUILD_DESTS.WEB]: [
'src/assets/favicon/**/*'
],
[BUILD_DESTS.V3]: [
'src/assets/extension/**/*',
'src/js/extension/**/*',
// Favicons need only for Chromium-based browsers (it show favicon as window icon),
// if other browser full migrate to manifest v3, need create separate destination
// for Chromium with favicons, now v3 used only for Chromium and its ok
// to add favicons to v3 destination
'src/assets/favicon/favicon.ico',
'src/assets/favicon/favicon-32x32.png',
'src/assets/favicon/favicon-16x16.png',
'src/assets/favicon/192x192.png'
],
[BUILD_DESTS.V2]: [
'src/assets/extension/**/*',
'src/js/extension/**/*'
]
};
const copy = buildDest => {
return src([...BUILD_DESTS_GLOBS['*'], ...BUILD_DESTS_GLOBS[buildDest]], { base: 'src' })
.pipe(dest(buildDest));
};
module.exports = copy;
================================================
FILE: build/gulp/css.js
================================================
const { dest, src } = require('gulp');
const css = buildDest => {
return src('src/css/**/*.css').pipe(dest(buildDest));
};
module.exports = css;
================================================
FILE: build/gulp/env.js
================================================
const { existsSync, readFileSync } = require('fs');
const { DOTENV_PATH, REQUIRED_ENV_VARS } = require('./config');
/**
* RegExp for matching rows in ".env" file
*
* @example
* # Comment
* KEY1 = VALUE1 # Trim spaces around key and value
* # Replace "\n" combination by newline symbol in value
* KEY2 = First line\nSecond line
* # Newline symbols inside quoted value (by any of ', " or ` quotes types)
* KEY3 = "Multiline
* quoted
* value"
*/
const ROW_REGEXP =
/^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(('|"|`)(?:\\\3|(?!\3)[\s\S])*\3|[^#\n]+)?\s*(?:#.*)?$/gm;
/**
* Read ".env" file in project root directory and set parsed rows to environment variables
*/
const loadEnvFile = () => {
if (!existsSync(DOTENV_PATH)) return;
const source = readFileSync(DOTENV_PATH, 'utf8').replace(/\r\n?/g, '\n');
[...source.matchAll(ROW_REGEXP)].forEach(match => {
let value = match[2];
const maybeQuote = value[0];
// If value was quoted, replace escaped quotes inside
if (maybeQuote === "'" || maybeQuote === '"' || maybeQuote === '`') {
value = value.replace(new RegExp('\\\\' + maybeQuote, 'g'), maybeQuote);
}
// Unquote value
value = value.replace(/^(['"`])([\s\S]*)\1$/g, '$2');
// Replace "\n" in value by newline symbol
value = value.replace(/\\n/g, '\n');
process.env[match[1]] = value;
});
};
/**
* Check passed environment variables names exists in shell environment
*
* @param {string} taskName
* @param {string} targetName
*/
const checkRequiredEnvVars = (taskName, targetName) => {
const requiredEnvVarsNames = [];
// Filter required environment variables by passed task and target names
Object.keys(REQUIRED_ENV_VARS).forEach(envVarName => {
let mask = REQUIRED_ENV_VARS[envVarName];
if (mask === '*') mask = '*.*';
const [taskMask, targetMask] = mask.split('.');
const taskMatch = taskMask === '*' || taskMask === taskName;
const targetMatch = targetMask === '*' || targetName === 'all' || targetMask === targetName;
if (!taskMatch || !targetMatch) return;
requiredEnvVarsNames.push(envVarName);
});
let haveUnspecifiedEnvVars = false;
requiredEnvVarsNames.forEach(envVarName => {
if (process.env[envVarName]) return;
console.error(`Specify "${envVarName}" environment variable`);
haveUnspecifiedEnvVars = true;
});
if (haveUnspecifiedEnvVars) {
console.error('See ".env.example" file in project root directory for more');
process.exit(1);
}
};
module.exports = {
loadEnvFile,
checkRequiredEnvVars
};
================================================
FILE: build/gulp/html.js
================================================
const { dest, src } = require('gulp');
const replace = require('gulp-replace');
const { BUILD_DESTS } = require('./config');
const { version } = require('../../package.json');
const html = buildDest => {
let stream = src('src/index.html').pipe(replace('{{VERSION}}', version));
// For extensions add body class and remove Controller.js including
if (buildDest !== BUILD_DESTS.WEB) {
stream = stream.pipe(replace('
', ''))
.pipe(replace(/^.* {
if (buildDest === BUILD_DESTS.WEB) return;
const content = JSON.parse(JSON.stringify(base));
// Changes to manifest V3
if (buildDest === BUILD_DESTS.V3) {
// Change manifest version
content.manifest_version = 3;
// New storage API permissions
content.permissions.push('storage');
// Permissions for content script and provider update
// content.permissions.push('tabs', 'scripting');
// Matches for content script and provider update
content.host_permissions = matches;
// Browser action field name change
content.action = content.browser_action;
delete(content.browser_action);
// Background script field change
const backgroundScript = content.background.scripts[0];
content.background = { service_worker: backgroundScript };
// Web accessible resources field change
const webAccessibleResources = content.web_accessible_resources;
content.web_accessible_resources = [{
resources: webAccessibleResources,
matches: matches
}];
// Extension page content security policy field change
content.content_security_policy = { extension_pages: content.content_security_policy };
}
writeFileSync(`${buildDest}/manifest.json`, JSON.stringify(content, null, 4));
};
module.exports = manifest;
================================================
FILE: build/gulp/pack.js
================================================
const { spawn } = require('child_process');
const { dest, src } = require('gulp');
const zip = require('gulp-zip');
const { TARGETS, TARGETS_BUILD_DESTS } = require('./config');
const { version } = require('../../package.json');
const pack = async targetName => {
if (targetName === TARGETS.WEB) {
console.log('Pack target "web" not available now');
return;
}
if (targetName === TARGETS.SAFARI) {
if (process.platform !== 'darwin') {
console.log('Pack target "safari" available only on MacOS');
return;
}
return new Promise((resolve, reject) => {
const child = spawn(
'xcodebuild',
[
'-project', 'build/safari/TON Wallet.xcodeproj',
'BUILD_DIR=../../artifacts/safari',
'CONFIGURATION_BUILD_DIR=../../artifacts/safari',
'SYMROOT=../../artifacts/safari'
],
{ stdio: 'inherit' }
);
child.on('close', code => {
if (code === 0) resolve();
else reject(new Error(`Child process fail with code ${code}`));
});
});
}
return src(`${TARGETS_BUILD_DESTS[targetName]}/**/*`)
.pipe(zip(`${targetName}-ton-wallet-${version}.zip`))
.pipe(dest('artifacts'));
};
module.exports = pack;
================================================
FILE: build/gulp/remove.js
================================================
const { existsSync, rmSync, rmdirSync } = require('fs');
const remove = async buildDest => {
if (!existsSync(buildDest)) return;
// fs.rm api was added in Node.js v14, in v16 recursive fs.rmdir is deprecated
(rmSync ? rmSync : rmdirSync)(buildDest, { recursive: true });
};
module.exports = remove;
================================================
FILE: build/gulp/script.js
================================================
const { resolve } = require('path');
const webpack = require('webpack');
const script = (buildDest, done) => {
webpack({
mode: 'none',
entry: {
Controller: './src/js/Controller.js',
View: './src/js/view/View.js'
},
plugins: [new webpack.DefinePlugin({
TONCENTER_API_KEY_WEB_MAIN: `'${process.env.TONCENTER_API_KEY_WEB_MAIN}'`,
TONCENTER_API_KEY_WEB_TEST: `'${process.env.TONCENTER_API_KEY_WEB_TEST}'`,
TONCENTER_API_KEY_EXT_MAIN: `'${process.env.TONCENTER_API_KEY_EXT_MAIN}'`,
TONCENTER_API_KEY_EXT_TEST: `'${process.env.TONCENTER_API_KEY_EXT_TEST}'`
})],
optimization: {
concatenateModules: true,
minimize: false
},
output: {
filename: '[name].js',
path: resolve(process.cwd(), `./${buildDest}/js`)
},
}, (err, stats) => {
if (err) return done(err);
if (stats.hasErrors()) return done(new Error(stats));
done();
});
};
module.exports = script;
================================================
FILE: build/gulp/start.js
================================================
const { access, readFile } = require('fs');
const { createServer } = require('http');
const open = require('open');
const { join, normalize, parse } = require('path');
const { TARGETS, START_WEB_PORT } = require('./config');
const cwd = process.cwd();
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.ico': 'image/x-icon',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.xml': 'text/xml',
'.webmanifest': 'application/manifest+json'
};
const startServer = (port, basePath) => {
const server = createServer();
server.on('request', (req, res) => {
const url = new URL(req.url, 'http://localhost');
if(url.pathname === '/') url.pathname = '/index.html';
const path = join(cwd, basePath, normalize(url.pathname).replace(/^(\.\.[\/\\])+/, ''));
access(path, err => {
if (err) {
res.statusCode = 404;
res.end(`File ${path} not found`);
return;
}
readFile(path, (err, data) => {
if(err){
res.statusCode = 500;
res.end(`Error in reading file ${path}`);
return;
}
res.setHeader(
'Content-type', mimeTypes[parse(path).ext] || 'application/octet-stream'
);
res.end(data);
});
});
});
return new Promise((resolve, reject) => {
server.on('error', reject);
server.listen(port, resolve);
});
};
const start = async targetName => {
if (targetName !== TARGETS.WEB) {
console.log(`Start target "${targetName}" not available`);
return;
}
const port = +process.env.START_WEB_PORT || START_WEB_PORT;
await startServer(port, 'docs');
const address = `http://localhost:${port}`;
console.log(`App available on ${address}`);
await open(address);
};
module.exports = start;
================================================
FILE: build/gulpfile.js
================================================
const { series, task, watch } = require('gulp');
const { TARGETS, BUILD_DESTS, TARGETS_BUILD_DESTS, WATCH_GLOBS } = require('./gulp/config');
const { checkRequiredEnvVars, loadEnvFile } = require('./gulp/env');
const copy = require('./gulp/copy');
const css = require('./gulp/css');
const html = require('./gulp/html');
const manifest = require('./gulp/manifest');
const pack = require('./gulp/pack');
const remove = require('./gulp/remove');
const script = require('./gulp/script');
const start = require('./gulp/start');
const taskName = process.argv[2];
const targetName = process.argv.pop();
const targetNames = ['all', ...Object.values(TARGETS)];
if (!targetName || !targetNames.includes(targetName)) {
console.error(`Pass one of possible target names: "${targetNames.join('", "')}"`);
process.exit(1);
}
loadEnvFile();
checkRequiredEnvVars(taskName, targetName);
const createBuildDestSeries = buildDest => {
return series(
remove.bind(null, buildDest),
copy.bind(null, buildDest),
css.bind(null, buildDest),
script.bind(null, buildDest),
html.bind(null, buildDest),
manifest.bind(null, buildDest)
);
};
let buildTasks;
let startTasks;
let packTasks;
if (targetName === 'all') {
buildTasks = series(
...Object.values(BUILD_DESTS).map(buildDest => createBuildDestSeries(buildDest))
);
startTasks = series(...Object.values(TARGETS).map(targetName => start.bind(null, targetName)));
packTasks = series(...Object.values(TARGETS).map(targetName => pack.bind(null, targetName)));
} else {
buildTasks = createBuildDestSeries(TARGETS_BUILD_DESTS[targetName]);
startTasks = start.bind(null, targetName);
packTasks = pack.bind(null, targetName);
}
task('dev', buildTasks);
task('watch', watch.bind(null, WATCH_GLOBS, { ignoreInitial: false }, buildTasks));
task('start', series(buildTasks, startTasks, watch.bind(null, WATCH_GLOBS, buildTasks)));
task('build', buildTasks);
task('pack', series(buildTasks, packTasks));
================================================
FILE: build/readme.md
================================================
# Source code
We deliberately use plain js and do not use frameworks, due to the direct access to the user's private keys. We also try to use the minimum number of third party libraries and consciously include them as static files rather than NPM packages to prevent accidental upgrade to a potentially malicious versions.
# Preparation
Set required for build environment variables in shell or `.env` file in project root directory. See `.env.example` with required variables names and their description.
If need, update `version` field in `package.json` to increase version in output manifest.json files, source files and update anti-cache parameters values.
Install development dependencies:
```
npm install
```
# Tasks
To run build task use next template:
```
npm run {task} {target}
```
Possible tasks:
- `build` - create bundles in targets destination directories
- `watch` - autorebuild bundles on sources change
- `start` - open target in web-browser and autorebuild bundles on sources change (only for `web` target to test website wallet local)
- `pack` - create bundles and prepare it to publuish-ready form
Possible targets and bundle files destinations folder:
- `web` - docs
- `chromium` - artifacts/v3
- `firefox` - artifacts/v2
- `safari` - artifacts/v2
- `all` - run all targets
Possible targets for pack task and output files destinations:
- `chromium` - artifacts/chromium-ton-wallet-{version}.zip
- `firefox` - artifacts/firefox-ton-wallet-{version}.zip
- `safari` - build xcode project to ton-wallet/artifacts/safari
- `all` - run all targets
Where {version} - value from package.json "version" field
# Chromium-based browsers Extension Developer Mode
- Open web browser
- Go to `chrome://extensions/`
- Enable "Developer Mode" in top right corner
- Click "Load unpacked extension" and specify `artifacts/v3` folder
# Mozilla Firefox Add-on Developer Mode
- Open Mozilla Firefox
- Go to `about:debugging#/runtime/this-firefox`
- Click "Load Temporary Add-on" and select `artifacts/v2/manifest.json` file
# Safari Extension Developer Mode
- Install Xcode Command Line Tools
- Open Safari and choose Safari > Preferences
- Select the Advanced tab, then select the "Show Develop menu in menu bar" checkbox
- Choose Develop > Allow Unsigned Extensions (the Allow Unsigned Extensions setting is reset when a user quits Safari, you must set it again the next time Safari is launched)
- Pack extension for Safari by command `npm run pack safari`
- Extension will automatically added to Safari
## Switch between clear console and debug mode
- Support from 1.1.36 version
- Open menu in right-top corner and select `About` item
- Click on `Version:` label with Alt key pressed
================================================
FILE: build/safari/TON Wallet/AppDelegate.swift
================================================
//
// AppDelegate.swift
// TON Wallet
//
// Created by Сергей Иваньков on 15.03.2022.
//
import Cocoa
@main
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
// Override point for customization after application launch.
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
}
================================================
FILE: build/safari/TON Wallet/Assets.xcassets/AccentColor.colorset/Contents.json
================================================
{
"colors" : [
{
"color" : {
"color-space" : "srgb",
"components" : {
"alpha" : "1.000",
"blue" : "0.799",
"green" : "0.533",
"red" : "0.000"
}
},
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
================================================
FILE: build/safari/TON Wallet/Assets.xcassets/AppIcon.appiconset/Contents.json
================================================
{
"images" : [
{
"idiom" : "mac",
"scale" : "1x",
"size" : "16x16",
"filename": "16.png"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "16x16",
"filename": "32.png"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "32x32",
"filename": "32.png"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "32x32",
"filename": "64.png"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "128x128",
"filename": "128.png"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "128x128",
"filename": "256.png"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "256x256",
"filename": "256.png"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "256x256",
"filename": "512.png"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "512x512",
"filename": "512.png"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "512x512",
"filename": "1024.png"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
================================================
FILE: build/safari/TON Wallet/Assets.xcassets/Contents.json
================================================
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
================================================
FILE: build/safari/TON Wallet/Base.lproj/Main.html
================================================
You can turn on TON Wallet’s extension in Safari Extensions preferences.
TON Wallet’s extension is currently on. You can turn it off in Safari Extensions preferences.
TON Wallet’s extension is currently off. You can turn it on in Safari Extensions preferences.
================================================
FILE: build/safari/TON Wallet/Base.lproj/Main.storyboard
================================================
================================================
FILE: build/safari/TON Wallet/Resources/Script.js
================================================
function show(enabled) {
if (typeof enabled === "boolean") {
document.body.classList.toggle(`state-on`, enabled);
document.body.classList.toggle(`state-off`, !enabled);
} else {
document.body.classList.remove(`state-on`);
document.body.classList.remove(`state-off`);
}
}
function openPreferences() {
webkit.messageHandlers.controller.postMessage("open-preferences");
}
document.querySelector("button.open-preferences").addEventListener("click", openPreferences);
================================================
FILE: build/safari/TON Wallet/Resources/Style.css
================================================
* {
-webkit-user-select: none;
-webkit-user-drag: none;
cursor: default;
}
:root {
color-scheme: light dark;
--spacing: 20px;
}
html {
height: 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
gap: var(--spacing);
margin: 0 calc(var(--spacing) * 2);
height: 100%;
font: -apple-system-short-body;
text-align: center;
}
body:not(.state-on, .state-off) :is(.state-on, .state-off) {
display: none;
}
body.state-on :is(.state-off, .state-unknown) {
display: none;
}
body.state-off :is(.state-on, .state-unknown) {
display: none;
}
button {
font-size: 1em;
}
================================================
FILE: build/safari/TON Wallet/TON_Wallet.entitlements
================================================
com.apple.security.app-sandbox
com.apple.security.files.user-selected.read-only
================================================
FILE: build/safari/TON Wallet/ViewController.swift
================================================
//
// ViewController.swift
// TON Wallet
//
// Created by Сергей Иваньков on 15.03.2022.
//
import Cocoa
import SafariServices
import WebKit
let extensionBundleIdentifier = "org.ton.wallet.extension"
class ViewController: NSViewController, WKNavigationDelegate, WKScriptMessageHandler {
@IBOutlet var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.webView.navigationDelegate = self
self.webView.configuration.userContentController.add(self, name: "controller")
self.webView.loadFileURL(Bundle.main.url(forResource: "Main", withExtension: "html")!, allowingReadAccessTo: Bundle.main.resourceURL!)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
SFSafariExtensionManager.getStateOfSafariExtension(withIdentifier: extensionBundleIdentifier) { (state, error) in
guard let state = state, error == nil else {
// Insert code to inform the user that something went wrong.
return
}
DispatchQueue.main.async {
webView.evaluateJavaScript("show(\(state.isEnabled))")
}
}
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if (message.body as! String != "open-preferences") {
return;
}
SFSafariApplication.showPreferencesForExtension(withIdentifier: extensionBundleIdentifier) { error in
DispatchQueue.main.async {
NSApplication.shared.terminate(nil)
}
}
}
}
================================================
FILE: build/safari/TON Wallet Extension/Info.plist
================================================
NSExtension
NSExtensionPointIdentifier
com.apple.Safari.web-extension
NSExtensionPrincipalClass
$(PRODUCT_MODULE_NAME).SafariWebExtensionHandler
================================================
FILE: build/safari/TON Wallet Extension/SafariWebExtensionHandler.swift
================================================
//
// SafariWebExtensionHandler.swift
// TON Wallet Extension
//
// Created by Сергей Иваньков on 15.03.2022.
//
import SafariServices
import os.log
let SFExtensionMessageKey = "message"
class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling {
func beginRequest(with context: NSExtensionContext) {
let item = context.inputItems[0] as! NSExtensionItem
let message = item.userInfo?[SFExtensionMessageKey]
os_log(.default, "Received message from browser.runtime.sendNativeMessage: %@", message as! CVarArg)
let response = NSExtensionItem()
response.userInfo = [ SFExtensionMessageKey: [ "Response to": message ] ]
context.completeRequest(returningItems: [response], completionHandler: nil)
}
}
================================================
FILE: build/safari/TON Wallet Extension/TON_Wallet_Extension.entitlements
================================================
com.apple.security.app-sandbox
com.apple.security.files.user-selected.read-only
================================================
FILE: build/safari/TON Wallet.xcodeproj/project.pbxproj
================================================
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 55;
objects = {
/* Begin PBXBuildFile section */
850824D227E0F882005B1F54 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 850824D127E0F882005B1F54 /* AppDelegate.swift */; };
850824D627E0F882005B1F54 /* Main.html in Resources */ = {isa = PBXBuildFile; fileRef = 850824D427E0F882005B1F54 /* Main.html */; };
850824D827E0F882005B1F54 /* Icon.png in Resources */ = {isa = PBXBuildFile; fileRef = 850824D727E0F882005B1F54 /* Icon.png */; };
850824DA27E0F882005B1F54 /* Style.css in Resources */ = {isa = PBXBuildFile; fileRef = 850824D927E0F882005B1F54 /* Style.css */; };
850824DC27E0F882005B1F54 /* Script.js in Resources */ = {isa = PBXBuildFile; fileRef = 850824DB27E0F882005B1F54 /* Script.js */; };
850824DE27E0F882005B1F54 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 850824DD27E0F882005B1F54 /* ViewController.swift */; };
850824E127E0F882005B1F54 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 850824DF27E0F882005B1F54 /* Main.storyboard */; };
850824E327E0F885005B1F54 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 850824E227E0F885005B1F54 /* Assets.xcassets */; };
850824EB27E0F885005B1F54 /* TON Wallet Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 850824EA27E0F885005B1F54 /* TON Wallet Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
850824F027E0F885005B1F54 /* SafariWebExtensionHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 850824EF27E0F885005B1F54 /* SafariWebExtensionHandler.swift */; };
858F762C27E794CB0020E363 /* js in Resources */ = {isa = PBXBuildFile; fileRef = 858F762627E794CB0020E363 /* js */; };
858F762D27E794CB0020E363 /* main.css in Resources */ = {isa = PBXBuildFile; fileRef = 858F762727E794CB0020E363 /* main.css */; };
858F762E27E794CB0020E363 /* index.html in Resources */ = {isa = PBXBuildFile; fileRef = 858F762827E794CB0020E363 /* index.html */; };
858F762F27E794CB0020E363 /* assets in Resources */ = {isa = PBXBuildFile; fileRef = 858F762927E794CB0020E363 /* assets */; };
858F763027E794CB0020E363 /* libs in Resources */ = {isa = PBXBuildFile; fileRef = 858F762A27E794CB0020E363 /* libs */; };
858F763127E794CB0020E363 /* manifest.json in Resources */ = {isa = PBXBuildFile; fileRef = 858F762B27E794CB0020E363 /* manifest.json */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
850824EC27E0F885005B1F54 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 850824C627E0F882005B1F54 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 850824E927E0F885005B1F54;
remoteInfo = "TON Wallet Extension";
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
8508250927E0F885005B1F54 /* Embed App Extensions */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 13;
files = (
850824EB27E0F885005B1F54 /* TON Wallet Extension.appex in Embed App Extensions */,
);
name = "Embed App Extensions";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
850824CE27E0F882005B1F54 /* TON Wallet.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "TON Wallet.app"; sourceTree = BUILT_PRODUCTS_DIR; };
850824D127E0F882005B1F54 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; };
850824D527E0F882005B1F54 /* Base */ = {isa = PBXFileReference; lastKnownFileType = text.html; name = Base; path = ../Base.lproj/Main.html; sourceTree = ""; };
850824D727E0F882005B1F54 /* Icon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Icon.png; sourceTree = ""; };
850824D927E0F882005B1F54 /* Style.css */ = {isa = PBXFileReference; lastKnownFileType = text.css; path = Style.css; sourceTree = ""; };
850824DB27E0F882005B1F54 /* Script.js */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.javascript; path = Script.js; sourceTree = ""; };
850824DD27E0F882005B1F54 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; };
850824E027E0F882005B1F54 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; };
850824E227E0F885005B1F54 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; };
850824E427E0F885005B1F54 /* TON_Wallet.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = TON_Wallet.entitlements; sourceTree = ""; };
850824EA27E0F885005B1F54 /* TON Wallet Extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = "TON Wallet Extension.appex"; sourceTree = BUILT_PRODUCTS_DIR; };
850824EF27E0F885005B1F54 /* SafariWebExtensionHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SafariWebExtensionHandler.swift; sourceTree = ""; };
8508250227E0F885005B1F54 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
8508250327E0F885005B1F54 /* TON_Wallet_Extension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = TON_Wallet_Extension.entitlements; sourceTree = ""; };
858F762627E794CB0020E363 /* js */ = {isa = PBXFileReference; lastKnownFileType = folder; name = js; path = ../../../artifacts/v2/js; sourceTree = ""; };
858F762727E794CB0020E363 /* main.css */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.css; name = main.css; path = ../../../artifacts/v2/main.css; sourceTree = ""; };
858F762827E794CB0020E363 /* index.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; name = index.html; path = ../../../artifacts/v2/index.html; sourceTree = ""; };
858F762927E794CB0020E363 /* assets */ = {isa = PBXFileReference; lastKnownFileType = folder; name = assets; path = ../../../artifacts/v2/assets; sourceTree = ""; };
858F762A27E794CB0020E363 /* libs */ = {isa = PBXFileReference; lastKnownFileType = folder; name = libs; path = ../../../artifacts/v2/libs; sourceTree = ""; };
858F762B27E794CB0020E363 /* manifest.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; name = manifest.json; path = ../../../artifacts/v2/manifest.json; sourceTree = ""; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
850824CB27E0F882005B1F54 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
850824E727E0F885005B1F54 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
850824C527E0F882005B1F54 = {
isa = PBXGroup;
children = (
850824D027E0F882005B1F54 /* TON Wallet */,
850824EE27E0F885005B1F54 /* TON Wallet Extension */,
850824CF27E0F882005B1F54 /* Products */,
);
sourceTree = "";
};
850824CF27E0F882005B1F54 /* Products */ = {
isa = PBXGroup;
children = (
850824CE27E0F882005B1F54 /* TON Wallet.app */,
850824EA27E0F885005B1F54 /* TON Wallet Extension.appex */,
);
name = Products;
sourceTree = "";
};
850824D027E0F882005B1F54 /* TON Wallet */ = {
isa = PBXGroup;
children = (
850824D127E0F882005B1F54 /* AppDelegate.swift */,
850824DD27E0F882005B1F54 /* ViewController.swift */,
850824DF27E0F882005B1F54 /* Main.storyboard */,
850824E227E0F885005B1F54 /* Assets.xcassets */,
850824E427E0F885005B1F54 /* TON_Wallet.entitlements */,
850824D327E0F882005B1F54 /* Resources */,
);
path = "TON Wallet";
sourceTree = "";
};
850824D327E0F882005B1F54 /* Resources */ = {
isa = PBXGroup;
children = (
850824D427E0F882005B1F54 /* Main.html */,
850824D727E0F882005B1F54 /* Icon.png */,
850824D927E0F882005B1F54 /* Style.css */,
850824DB27E0F882005B1F54 /* Script.js */,
);
path = Resources;
sourceTree = "";
};
850824EE27E0F885005B1F54 /* TON Wallet Extension */ = {
isa = PBXGroup;
children = (
858E09B927E1038E00500609 /* Resources */,
850824EF27E0F885005B1F54 /* SafariWebExtensionHandler.swift */,
8508250227E0F885005B1F54 /* Info.plist */,
8508250327E0F885005B1F54 /* TON_Wallet_Extension.entitlements */,
);
path = "TON Wallet Extension";
sourceTree = "";
};
858E09B927E1038E00500609 /* Resources */ = {
isa = PBXGroup;
children = (
858F762927E794CB0020E363 /* assets */,
858F762827E794CB0020E363 /* index.html */,
858F762627E794CB0020E363 /* js */,
858F762A27E794CB0020E363 /* libs */,
858F762727E794CB0020E363 /* main.css */,
858F762B27E794CB0020E363 /* manifest.json */,
);
name = Resources;
sourceTree = "";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
850824CD27E0F882005B1F54 /* TON Wallet */ = {
isa = PBXNativeTarget;
buildConfigurationList = 8508250A27E0F885005B1F54 /* Build configuration list for PBXNativeTarget "TON Wallet" */;
buildPhases = (
850824CA27E0F882005B1F54 /* Sources */,
850824CB27E0F882005B1F54 /* Frameworks */,
850824CC27E0F882005B1F54 /* Resources */,
8508250927E0F885005B1F54 /* Embed App Extensions */,
);
buildRules = (
);
dependencies = (
850824ED27E0F885005B1F54 /* PBXTargetDependency */,
);
name = "TON Wallet";
productName = "TON Wallet";
productReference = 850824CE27E0F882005B1F54 /* TON Wallet.app */;
productType = "com.apple.product-type.application";
};
850824E927E0F885005B1F54 /* TON Wallet Extension */ = {
isa = PBXNativeTarget;
buildConfigurationList = 8508250627E0F885005B1F54 /* Build configuration list for PBXNativeTarget "TON Wallet Extension" */;
buildPhases = (
850824E627E0F885005B1F54 /* Sources */,
850824E727E0F885005B1F54 /* Frameworks */,
850824E827E0F885005B1F54 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = "TON Wallet Extension";
productName = "TON Wallet Extension";
productReference = 850824EA27E0F885005B1F54 /* TON Wallet Extension.appex */;
productType = "com.apple.product-type.app-extension";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
850824C627E0F882005B1F54 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1320;
LastUpgradeCheck = 1320;
TargetAttributes = {
850824CD27E0F882005B1F54 = {
CreatedOnToolsVersion = 13.2.1;
};
850824E927E0F885005B1F54 = {
CreatedOnToolsVersion = 13.2.1;
};
};
};
buildConfigurationList = 850824C927E0F882005B1F54 /* Build configuration list for PBXProject "TON Wallet" */;
compatibilityVersion = "Xcode 13.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 850824C527E0F882005B1F54;
productRefGroup = 850824CF27E0F882005B1F54 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
850824CD27E0F882005B1F54 /* TON Wallet */,
850824E927E0F885005B1F54 /* TON Wallet Extension */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
850824CC27E0F882005B1F54 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
850824D827E0F882005B1F54 /* Icon.png in Resources */,
850824E127E0F882005B1F54 /* Main.storyboard in Resources */,
850824DC27E0F882005B1F54 /* Script.js in Resources */,
850824D627E0F882005B1F54 /* Main.html in Resources */,
850824E327E0F885005B1F54 /* Assets.xcassets in Resources */,
850824DA27E0F882005B1F54 /* Style.css in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
850824E827E0F885005B1F54 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
858F763027E794CB0020E363 /* libs in Resources */,
858F762E27E794CB0020E363 /* index.html in Resources */,
858F762F27E794CB0020E363 /* assets in Resources */,
858F762D27E794CB0020E363 /* main.css in Resources */,
858F763127E794CB0020E363 /* manifest.json in Resources */,
858F762C27E794CB0020E363 /* js in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
850824CA27E0F882005B1F54 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
850824DE27E0F882005B1F54 /* ViewController.swift in Sources */,
850824D227E0F882005B1F54 /* AppDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
850824E627E0F885005B1F54 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
850824F027E0F885005B1F54 /* SafariWebExtensionHandler.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
850824ED27E0F885005B1F54 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 850824E927E0F885005B1F54 /* TON Wallet Extension */;
targetProxy = 850824EC27E0F885005B1F54 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
850824D427E0F882005B1F54 /* Main.html */ = {
isa = PBXVariantGroup;
children = (
850824D527E0F882005B1F54 /* Base */,
);
name = Main.html;
sourceTree = "";
};
850824DF27E0F882005B1F54 /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
850824E027E0F882005B1F54 /* Base */,
);
name = Main.storyboard;
sourceTree = "";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
8508250427E0F885005B1F54 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 12.1;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
8508250527E0F885005B1F54 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 12.1;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
8508250727E0F885005B1F54 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = "TON Wallet Extension/TON_Wallet_Extension.entitlements";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
ENABLE_HARDENED_RUNTIME = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = "TON Wallet Extension/Info.plist";
INFOPLIST_KEY_CFBundleDisplayName = "TON Wallet";
INFOPLIST_KEY_NSHumanReadableCopyright = "";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
"@executable_path/../../../../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 10.14;
MARKETING_VERSION = 1.1.35;
OTHER_LDFLAGS = (
"-framework",
SafariServices,
);
PRODUCT_BUNDLE_IDENTIFIER = org.ton.wallet.extension;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Debug;
};
8508250827E0F885005B1F54 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_ENTITLEMENTS = "TON Wallet Extension/TON_Wallet_Extension.entitlements";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
ENABLE_HARDENED_RUNTIME = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = "TON Wallet Extension/Info.plist";
INFOPLIST_KEY_CFBundleDisplayName = "TON Wallet";
INFOPLIST_KEY_NSHumanReadableCopyright = "";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
"@executable_path/../../../../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 10.14;
MARKETING_VERSION = 1.1.35;
OTHER_LDFLAGS = (
"-framework",
SafariServices,
);
PRODUCT_BUNDLE_IDENTIFIER = org.ton.wallet.extension;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Release;
};
8508250B27E0F885005B1F54 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = "TON Wallet/TON Wallet.entitlements";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
ENABLE_HARDENED_RUNTIME = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_CFBundleDisplayName = "TON Wallet";
INFOPLIST_KEY_NSHumanReadableCopyright = "";
INFOPLIST_KEY_NSMainStoryboardFile = Main;
INFOPLIST_KEY_NSPrincipalClass = NSApplication;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 10.14;
MARKETING_VERSION = 1.1.35;
OTHER_LDFLAGS = (
"-framework",
SafariServices,
"-framework",
WebKit,
);
PRODUCT_BUNDLE_IDENTIFIER = org.ton.wallet;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Debug;
};
8508250C27E0F885005B1F54 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = "TON Wallet/TON Wallet.entitlements";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
ENABLE_HARDENED_RUNTIME = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_CFBundleDisplayName = "TON Wallet";
INFOPLIST_KEY_NSHumanReadableCopyright = "";
INFOPLIST_KEY_NSMainStoryboardFile = Main;
INFOPLIST_KEY_NSPrincipalClass = NSApplication;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 10.14;
MARKETING_VERSION = 1.1.35;
OTHER_LDFLAGS = (
"-framework",
SafariServices,
"-framework",
WebKit,
);
PRODUCT_BUNDLE_IDENTIFIER = org.ton.wallet;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
850824C927E0F882005B1F54 /* Build configuration list for PBXProject "TON Wallet" */ = {
isa = XCConfigurationList;
buildConfigurations = (
8508250427E0F885005B1F54 /* Debug */,
8508250527E0F885005B1F54 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
8508250627E0F885005B1F54 /* Build configuration list for PBXNativeTarget "TON Wallet Extension" */ = {
isa = XCConfigurationList;
buildConfigurations = (
8508250727E0F885005B1F54 /* Debug */,
8508250827E0F885005B1F54 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
8508250A27E0F885005B1F54 /* Build configuration list for PBXNativeTarget "TON Wallet" */ = {
isa = XCConfigurationList;
buildConfigurations = (
8508250B27E0F885005B1F54 /* Debug */,
8508250C27E0F885005B1F54 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 850824C627E0F882005B1F54 /* Project object */;
}
================================================
FILE: build/safari/TON Wallet.xcodeproj/project.xcworkspace/contents.xcworkspacedata
================================================
================================================
FILE: build/safari/TON Wallet.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
================================================
IDEDidComputeMac32BitWarning
================================================
FILE: build/safari/TON Wallet.xcodeproj/xcuserdata/sergei.xcuserdatad/xcschemes/xcschememanagement.plist
================================================
SchemeUserState
TON Wallet.xcscheme_^#shared#^_
orderHint
0
================================================
FILE: docs/assets/favicon/browserconfig.xml
================================================
#ffffff
================================================
FILE: docs/assets/favicon/site.webmanifest
================================================
{
"name": "TON Wallet",
"short_name": "TON Wallet",
"icons": [
{
"src": "36x36.png",
"sizes": "36x36",
"type": "image/png"
},
{
"src": "48x48.png",
"sizes": "48x48",
"type": "image/png"
},
{
"src": "72x72.png",
"sizes": "72x72",
"type": "image/png"
},
{
"src": "96x96.png",
"sizes": "96x96",
"type": "image/png"
},
{
"src": "144x144.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "256x256.png",
"sizes": "256x256",
"type": "image/png"
},
{
"src": "384x384.png",
"sizes": "384x384",
"type": "image/png"
},
{
"src": "512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
}
================================================
FILE: docs/index.html
================================================
TON Wallet
TON Wallet
TON wallet allows you to make fast and
secure blockchain-based payments
without intermediaries.
24 Secret Words
Please restore access to your non-hardware wallet by
entering the 24 secret words you wrote
down when creating the wallet.
Congratulations
Your TON wallet has just been created.
Only you control it.
To be able to always have access to it,
please set up a secure password and write
down secret words.
24 secret words
Write down these 24 words in the correct
order and store them in secret place.
Use these secret words to restore access to
your wallet if you lose your password or
access to this device.
Test Time!
Now let's check that you wrote your secret
words correctly.
Please enter the words , and below:
Ready to go!
You're all set. Now you have a wallet that
only you control - directly, without
middlemen or bankers.
Your balance
================================================
FILE: docs/js/Controller.js
================================================
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
;// CONCATENATED MODULE: ./src/js/util/storage.js
/**
* `localStorage` polyfill for Chrome Extension environment
*/
/* harmony default export */ const storage = (self.localStorage || {
/**
* @param key {string}
* @param value {string}
* @return {Promise}
*/
setItem(key, value) {
return chrome.storage.local.set({[key]: value});
},
/**
* @param key {string}
* @return {Promise}
*/
getItem(key) {
return chrome.storage.local.get(key)
.then(({[key]: value}) => value);
},
/**
* @param key {string}
* @return {Promise}
*/
removeItem(key) {
return chrome.storage.local.remove(key);
},
/**
* @return {Promise}
*/
clear() {
return chrome.storage.local.clear();
},
});
;// CONCATENATED MODULE: ./src/js/util/encryption.js
// This JS library implements TON message comment encryption and decryption for Web
// Reference C++ code - SimpleEncryptionV2 - https://github.com/ton-blockchain/ton/blob/cc0eb453cb3bf69f92693160103d33112856c056/tonlib/tonlib/keys/SimpleEncryption.cpp#L110
// Dependencies:
// - TonWeb 0.0.60
// - aes-js - 3.1.2 - https://github.com/ricmoo/aes-js/releases/tag/v3.1.2 - for aes-cbc without padding
// - noble-ed25519 - 1.7.3 - // https://github.com/paulmillr/noble-ed25519/releases/tag/1.7.3 - for getSharedKey
const ed25519 = self.nobleEd25519;
/**
* @param key {Uint8Array}
* @param data {Uint8Array}
* @return {Promise}
*/
const hmac_sha512 = async (key, data) => {
const hmacAlgo = {name: "HMAC", hash: "SHA-512"};
/** @type {CryptoKey} */
const hmacKey = await self.crypto.subtle.importKey("raw", key, hmacAlgo, false, ["sign"]);
/** @type {ArrayBuffer} */
const signature = await self.crypto.subtle.sign(hmacAlgo, hmacKey, data);
const result = new Uint8Array(signature);
if (result.length !== 512 / 8) throw new Error();
return result;
}
/**
* @param hash {Uint8Array}
* @return {Promise} aesjs.ModeOfOperation.cbc
*/
const getAesCbcState = async (hash) => {
if (hash.length < 48) throw new Error();
const key = hash.slice(0, 32);
const iv = hash.slice(32, 32 + 16);
// Note that native crypto.subtle AES-CBC not suitable here because
// even if the data IS a multiple of 16 bytes, padding will still be added
// So we use aes-js
return new aesjs.ModeOfOperation.cbc(key, iv);
}
/**
* @param dataLength {number}
* @param minPadding {number}
* @return {Uint8Array}
*/
const getRandomPrefix = (dataLength, minPadding) => {
const prefixLength = ((minPadding + 15 + dataLength) & -16) - dataLength;
/** @type {Uint8Array} */
const prefix = self.crypto.getRandomValues(new Uint8Array(prefixLength));
prefix[0] = prefixLength;
if ((prefixLength + dataLength) % 16 !== 0) throw new Error();
return prefix;
}
/**
* @param a {Uint8Array}
* @param b {Uint8Array}
* @return {Promise}
*/
const combineSecrets = async (a, b) => {
return hmac_sha512(a, b);
}
/**
* @param data {Uint8Array}
* @param sharedSecret {Uint8Array}
* @param salt {Uint8Array}
* @return {Promise}
*/
const encryptDataWithPrefix = async (data, sharedSecret, salt) => {
if (data.length % 16 !== 0) throw new Error();
/** @type {Uint8Array} */
const dataHash = await combineSecrets(salt, data);
/** @type {Uint8Array} */
const msgKey = dataHash.slice(0, 16);
const res = new Uint8Array(data.length + 16);
res.set(msgKey, 0);
/** @type {Uint8Array} */
const cbcStateSecret = await combineSecrets(sharedSecret, msgKey);
/** @type {Uint8Array} */
const encrypted = (await getAesCbcState(cbcStateSecret)).encrypt(data);
res.set(encrypted, 16);
return res;
}
/**
* @param data {Uint8Array}
* @param sharedSecret {Uint8Array}
* @param salt {Uint8Array}
* @return {Promise}
*/
const encryptDataImpl = async (data, sharedSecret, salt) => {
/** @type {Uint8Array} */
const prefix = await getRandomPrefix(data.length, 16);
const combined = new Uint8Array(prefix.length + data.length);
combined.set(prefix, 0);
combined.set(data, prefix.length);
return encryptDataWithPrefix(combined, sharedSecret, salt);
}
/**
* @param data {Uint8Array}
* @param myPublicKey {Uint8Array}
* @param theirPublicKey {Uint8Array}
* @param privateKey {Uint8Array}
* @param salt {Uint8Array}
* @return {Promise}
*/
const encryptData = async (data, myPublicKey, theirPublicKey, privateKey, salt) => {
/** @type {Uint8Array} */
const sharedSecret = await ed25519.getSharedSecret(privateKey, theirPublicKey);
/** @type {Uint8Array} */
const encrypted = await encryptDataImpl(data, sharedSecret, salt);
const prefixedEncrypted = new Uint8Array(myPublicKey.length + encrypted.length);
for (let i = 0; i < myPublicKey.length; i++) {
prefixedEncrypted[i] = theirPublicKey[i] ^ myPublicKey[i];
}
prefixedEncrypted.set(encrypted, myPublicKey.length);
return prefixedEncrypted;
}
/**
* @param bytes {Uint8Array}
* @return {Cell}
*/
const makeSnakeCells = (bytes) => {
const ROOT_CELL_BYTE_LENGTH = 35 + 4;
const CELL_BYTE_LENGTH = 127;
/** @type {Cell} */
const root = new TonWeb.boc.Cell();
root.bits.writeBytes(bytes.slice(0, Math.min(bytes.length, ROOT_CELL_BYTE_LENGTH)));
const cellCount = Math.ceil((bytes.length - ROOT_CELL_BYTE_LENGTH) / CELL_BYTE_LENGTH);
if (cellCount > 16) {
throw new Error('Text too long');
}
/** @type {Cell} */
let cell = root;
for (let i = 0; i < cellCount; i++) {
/** @type {Cell} */
const prevCell = cell;
cell = new TonWeb.boc.Cell();
const cursor = ROOT_CELL_BYTE_LENGTH + i * CELL_BYTE_LENGTH;
cell.bits.writeBytes(bytes.slice(cursor, Math.min(bytes.length, cursor + CELL_BYTE_LENGTH)));
prevCell.refs[0] = cell;
}
return root;
}
/**
* @param cell {Cell}
* @return {Uint8Array}
*/
const parseSnakeCells = (cell) => {
/** @type {Cell} */
let c = cell;
/** @type {Uint8Array} */
let result = new Uint8Array(0);
while (c) {
/** @type {Uint8Array} */
const newResult = new Uint8Array(result.length + c.bits.array.length);
newResult.set(result);
newResult.set(c.bits.array, result.length);
result = newResult;
c = c.refs[0];
}
return result;
}
/**
* @param comment {string}
* @param myPublicKey {Uint8Array}
* @param theirPublicKey {Uint8Array}
* @param myPrivateKey {Uint8Array}
* @param senderAddress {string | Address}
* @return {Promise} full message binary payload with 0x2167da4b prefix
*/
const encryptMessageComment = async (comment, myPublicKey, theirPublicKey, myPrivateKey, senderAddress) => {
if (!comment || !comment.length) throw new Error('empty comment');
if (myPrivateKey.length === 64) {
myPrivateKey = myPrivateKey.slice(0, 32); // convert nacl private key
}
/** @type {Uint8Array} */
const commentBytes = new TextEncoder().encode(comment);
/** @type {Uint8Array} */
const salt = new TextEncoder().encode(new TonWeb.utils.Address(senderAddress).toString(true, true, true, false));
/** @type {Uint8Array} */
const encryptedBytes = await encryptData(commentBytes, myPublicKey, theirPublicKey, myPrivateKey, salt);
const payload = new Uint8Array(encryptedBytes.length + 4);
payload[0] = 0x21; // encrypted text prefix
payload[1] = 0x67;
payload[2] = 0xda;
payload[3] = 0x4b;
payload.set(encryptedBytes, 4);
return makeSnakeCells(payload);
}
/**
* @param cbcStateSecret {Uint8Array}
* @param msgKey {Uint8Array}
* @param encryptedData {Uint8Array}
* @param salt {Uint8Array}
* @return {Promise}
*/
const doDecrypt = async (cbcStateSecret, msgKey, encryptedData, salt) => {
/** @type {Uint8Array} */
const decryptedData = (await getAesCbcState(cbcStateSecret)).decrypt(encryptedData);
/** @type {Uint8Array} */
const dataHash = await combineSecrets(salt, decryptedData);
/** @type {Uint8Array} */
const gotMsgKey = dataHash.slice(0, 16);
if (msgKey.join(',') !== gotMsgKey.join(',')) {
throw new Error('Failed to decrypt: hash mismatch')
}
const prefixLength = decryptedData[0];
if (prefixLength > decryptedData.length || prefixLength < 16) {
throw new Error('Failed to decrypt: invalid prefix size');
}
return decryptedData.slice(prefixLength);
}
/**
* @param encryptedData {Uint8Array}
* @param sharedSecret {Uint8Array}
* @param salt {Uint8Array}
* @return {Promise}
*/
const decryptDataImpl = async (encryptedData, sharedSecret, salt) => {
if (encryptedData.length < 16) throw new Error('Failed to decrypt: data is too small');
if (encryptedData.length % 16 !== 0) throw new Error('Failed to decrypt: data size is not divisible by 16');
/** @type {Uint8Array} */
const msgKey = encryptedData.slice(0, 16);
/** @type {Uint8Array} */
const data = encryptedData.slice(16);
/** @type {Uint8Array} */
const cbcStateSecret = await combineSecrets(sharedSecret, msgKey);
/** @type {Uint8Array} */
const res = await doDecrypt(cbcStateSecret, msgKey, data, salt);
return res;
}
/**
* @param data {Uint8Array}
* @param publicKey {Uint8Array}
* @param privateKey {Uint8Array}
* @param salt {Uint8Array}
* @return {Promise}
*/
const decryptData = async (data, publicKey, privateKey, salt) => {
if (data.length < publicKey.length) {
throw new Error('Failed to decrypt: data is too small');
}
const theirPublicKey = new Uint8Array(publicKey.length);
for (let i = 0; i < publicKey.length; i++) {
theirPublicKey[i] = data[i] ^ publicKey[i];
}
/** @type {Uint8Array} */
const sharedSecret = await ed25519.getSharedSecret(privateKey, theirPublicKey);
/** @type {Uint8Array} */
const decrypted = await decryptDataImpl(data.slice(publicKey.length), sharedSecret, salt);
return decrypted;
}
/**
* @param encryptedData {Uint8Array} encrypted data without 0x2167da4b prefix
* @param myPublicKey {Uint8Array}
* @param myPrivateKey {Uint8Array}
* @param senderAddress {string | Address}
* @return {Promise} decrypted text comment
*/
const decryptMessageComment = async (encryptedData, myPublicKey, myPrivateKey, senderAddress) => {
if (myPrivateKey.length === 64) {
myPrivateKey = myPrivateKey.slice(0, 32); // convert nacl private key
}
/** @type {Uint8Array} */
const salt = new TextEncoder().encode(new TonWeb.utils.Address(senderAddress).toString(true, true, true, false));
/** @type {Uint8Array} */
const decryptedBytes = await decryptData(encryptedData, myPublicKey, myPrivateKey, salt);
return new TextDecoder().decode(decryptedBytes);
}
;// CONCATENATED MODULE: ./src/js/Controller.js
const TONCONNECT_MAINNET = '-239';
const TONCONNECT_TESTNET = '-3';
let extensionWindowId = -1;
let contentScriptPorts = new Set();
let popupPort = null;
const queueToPopup = [];
/**
* @type {Promise | null}
*/
let dAppPromise = null;
const createDappPromise = () => {
if (dAppPromise) dAppPromise.resolve(false);
let resolve;
let reject;
dAppPromise = new Promise((localResolve, localReject) => {
resolve = localResolve;
reject = localReject;
});
dAppPromise.resolve = (...args) => {
resolve(...args);
dAppPromise = null;
};
dAppPromise.reject = (...args) => {
reject(...args);
dAppPromise = null;
};
};
const showExtensionWindow = () => {
return new Promise(async resolve => {
if (extensionWindowId > -1) {
chrome.windows.update(extensionWindowId, {focused: true});
return resolve();
}
const windowState = (await storage.getItem('windowState')) || {};
windowState.top = windowState.top || 0;
windowState.left = windowState.left || 0;
windowState.height = windowState.height || 800;
windowState.width = windowState.width || 480;
chrome.windows.create(Object.assign(windowState, {
url: 'index.html',
type: 'popup',
focused: true
}), window => {
extensionWindowId = window.id;
resolve();
});
});
};
const BN = TonWeb.utils.BN;
const nacl = TonWeb.utils.nacl;
const Address = TonWeb.utils.Address;
const formatNanograms = TonWeb.utils.fromNano;
// ENCRYPTION
/**
* @param plaintext {string}
* @param password {string}
* @return {Promise}
*/
async function encrypt(plaintext, password) {
const pwUtf8 = new TextEncoder().encode(password); // encode password as UTF-8
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8); // hash the password
const iv = crypto.getRandomValues(new Uint8Array(12)); // get 96-bit random iv
const alg = {name: 'AES-GCM', iv: iv}; // specify algorithm to use
const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt']); // generate key from pw
const ptUint8 = new TextEncoder().encode(plaintext); // encode plaintext as UTF-8
const ctBuffer = await crypto.subtle.encrypt(alg, key, ptUint8); // encrypt plaintext using key
const ctArray = Array.from(new Uint8Array(ctBuffer)); // ciphertext as byte array
const ctStr = ctArray.map(byte => String.fromCharCode(byte)).join(''); // ciphertext as string
const ctBase64 = btoa(ctStr); // encode ciphertext as base64
const ivHex = Array.from(iv).map(b => ('00' + b.toString(16)).slice(-2)).join(''); // iv as hex string
return ivHex + ctBase64; // return iv+ciphertext
}
/**
* @param ciphertext {string}
* @param password {string}
* @return {Promise}
*/
async function decrypt(ciphertext, password) {
const pwUtf8 = new TextEncoder().encode(password); // encode password as UTF-8
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8); // hash the password
const iv = ciphertext.slice(0, 24).match(/.{2}/g).map(byte => parseInt(byte, 16)); // get iv from ciphertext
const alg = {name: 'AES-GCM', iv: new Uint8Array(iv)}; // specify algorithm to use
const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['decrypt']); // use pw to generate key
const ctStr = atob(ciphertext.slice(24)); // decode base64 ciphertext
const ctUint8 = new Uint8Array(ctStr.match(/[\s\S]/g).map(ch => ch.charCodeAt(0))); // ciphertext as Uint8Array
// note: why doesn't ctUint8 = new TextEncoder().encode(ctStr) work?
const plainBuffer = await crypto.subtle.decrypt(alg, key, ctUint8); // decrypt ciphertext using key
const plaintext = new TextDecoder().decode(plainBuffer); // decode password from UTF-8
return plaintext; // return the plaintext
}
// CONTROLLER
const IS_EXTENSION = !!(self.chrome && chrome.runtime && chrome.runtime.onConnect);
const ACCOUNT_NUMBER = 0;
const DEFAULT_WALLET_VERSION = 'v3R2';
const DEFAULT_LEDGER_WALLET_VERSION = 'v3R1';
class Controller {
constructor() {
/** @type {boolean} */
this.isTestnet = false;
/** @type {boolean} */
this.isDebug = false;
/** @type {string} */
this.myAddress = null;
/** @type {string} */
this.publicKeyHex = null;
/** @type {string[]} */
this.myMnemonicWords = null;
/** @type {BN | null} */
this.balance = null;
/** @type {WalletContract} */
this.walletContract = null;
this.transactions = [];
/** @type {number} */
this.updateIntervalId = 0;
/** @type {null | {totalAmount: BN, bodyHashBase64: string }} */
this.sendingData = null;
/** @type {boolean} */
this.processingVisible = false;
this.ledgerApp = null;
/** @type {boolean} */
this.isLedger = false;
/** @type {(words: string[]) => Promise | null} */
this.afterEnterPassword = null;
if (self.view) {
self.view.controller = this;
}
this.pendingMessageResolvers = new Map();
this._lastMsgId = 1;
if (IS_EXTENSION) {
setInterval(() => storage.setItem('__time', Date.now()), 5 * 1000);
}
this.whenReady = this._init();
}
debug(...args) {
if (!this.isDebug) return;
console.log(...args);
}
/**
* @param words {string[]}
* @return {Promise} base64
*/
static async wordsToPrivateKey(words) {
const keyPair = await TonWeb.mnemonic.mnemonicToKeyPair(words);
return TonWeb.utils.bytesToBase64(keyPair.secretKey.slice(0, 32));
}
/**
* @param words {string[]}
* @param password {string}
* @return {Promise}
*/
static async saveWords(words, password) {
await storage.setItem('words', await encrypt(words.join(','), password));
}
/**
* @param password {string}
* @return {Promise}
*/
static async loadWords(password) {
return (await decrypt(await storage.getItem('words'), password)).split(',');
}
/**
* @param isTestnet {boolean}
* @return {string}
*/
getApiKey(isTestnet) {
const webApiKey = isTestnet
? '4f96a149e04e0821d20f9e99ee716e20ff52db7238f38663226b1c0f303003e0'
: '4f96a149e04e0821d20f9e99ee716e20ff52db7238f38663226b1c0f303003e0';
const extensionApiKey = isTestnet
? '503af517296765c3f1729fcb301b063a00650a50a881eeaddb6307d5d45e21aa'
: '503af517296765c3f1729fcb301b063a00650a50a881eeaddb6307d5d45e21aa';
return IS_EXTENSION ? extensionApiKey : webApiKey;
}
async _init() {
return new Promise(async (resolve) => {
await storage.removeItem('pwdHash');
this.isTestnet = IS_EXTENSION ? (await storage.getItem('isTestnet')) : (self.location.href.indexOf('testnet') > -1);
this.isDebug = IS_EXTENSION ? (await storage.getItem('isDebug')) : (self.location.href.indexOf('debug') > -1);
const mainnetRpc = 'https://toncenter.com/api/v2/jsonRPC';
const testnetRpc = 'https://testnet.toncenter.com/api/v2/jsonRPC';
if (IS_EXTENSION && !(await storage.getItem('address'))) {
await this._restoreDeprecatedStorage();
}
this.ton = new TonWeb(new TonWeb.HttpProvider(this.isTestnet ? testnetRpc : mainnetRpc, {apiKey: this.getApiKey(this.isTestnet)}));
this.myAddress = await storage.getItem('address');
if (this.myAddress) {
this.myAddress = new TonWeb.utils.Address(this.myAddress).toString(true, true, false, this.isTestnet);
}
this.publicKeyHex = await storage.getItem('publicKey');
if (!this.myAddress || !(await storage.getItem('words'))) {
await storage.clear();
this.sendToView('showScreen', {name: 'start', noAnimation: true});
} else {
if ((await storage.getItem('isLedger')) === 'true') {
this.isLedger = true;
this.sendToView('setIsLedger', this.isLedger);
}
await this.showMain();
}
this.sendToView('setIsTestnet', this.isTestnet);
resolve();
});
}
async _restoreDeprecatedStorage() {
const {
address, words, walletVersion, magic, proxy,
} = await this.sendToView('restoreDeprecatedStorage', undefined, true, true);
if (!address || !words) {
return;
}
await Promise.all([
storage.setItem('address', address),
storage.setItem('words', words),
storage.setItem('walletVersion', walletVersion),
storage.setItem('magic', magic),
storage.setItem('proxy', proxy),
]);
}
async toggleTestnet() {
this.isTestnet = !this.isTestnet;
if (this.isTestnet) {
await storage.setItem('isTestnet', 'true');
} else {
await storage.removeItem('isTestnet');
}
this.clearVars();
await this._init();
await this.sendToView('setIsTestnet', this.isTestnet);
}
async toggleDebug() {
this.isDebug = !this.isDebug;
if (this.isDebug) {
await storage.setItem('isDebug', 'true');
} else {
await storage.removeItem('isDebug');
}
}
// INDEXED API
/**
* @private
* @param method {string}
* @param params {any}
* @return {Promise}
*/
async sendToIndex(method, params) {
const mainnetRpc = 'https://toncenter.com/api/v3/';
const testnetRpc = 'https://testnet.toncenter.com/api/v3/';
const rpc = this.isTestnet ? testnetRpc : mainnetRpc;
const headers = {
'Content-Type': 'application/json',
'X-API-Key': this.getApiKey(this.isTestnet)
};
const response = await fetch(rpc + method + '?' + new URLSearchParams(params), {
method: 'GET',
headers: headers,
});
return await response.json();
}
/**
* @private
* @param address {string}
* @return {Promise<{seqno: number | null}>}
*/
async getWalletInfoFromIndex(address) {
return this.sendToIndex('wallet', {
address: address
});
}
/**
* @private
* @param address {string}
* @return {Promise<{balance: string, status: string}>}
*/
async getAccountInfoFromIndex(address) {
return this.sendToIndex('account', {
address: address
});
}
/**
* @return {Promise} seqno
*/
async getMySeqno() {
const walletInfo = await this.getWalletInfoFromIndex(this.myAddress);
return walletInfo.seqno || 0;
}
/**
* @param address {string}
* @return {Promise} in nanotons
*/
async getBalance(address) {
const accountInfo = await this.getAccountInfoFromIndex(address);
return new BN(accountInfo.balance);
}
/**
* @param address {string}
* @return {Promise}
*/
async checkContractInitialized(address) {
const accountInfo = await this.getAccountInfoFromIndex(address);
return accountInfo.status === "active";
}
/**
* @private
* @param address {string}
* @param limit {number}
* @return {Promise}
*/
async getTransactionsFromIndex(address, limit) {
return this.sendToIndex('transactions', {
account: address,
limit: limit
});
}
/**
* @param limit? {number}
* @return {Promise} transactions
*/
async getTransactions(limit = 10) {
/**
* @param msg {any} raw.message
* @return {string}
*/
function getComment(msg) {
if (!msg.message_content) return '';
if (!msg.message_content.decoded) return '';
if (msg.message_content.decoded['type'] !== 'text_comment') return '';
return msg.message_content.decoded.comment;
}
/**
* @param msg {any} raw.message
* @return {string} '' or base64
*/
function getEncryptedComment(msg) {
if (!msg.message_content) return '';
if (!msg.message_content.body) return '';
if (msg.opcode !== "0x2167da4b") return '';
/** @type {string} */
const cellBase64 = msg.message_content.body;
/** @type {Cell} */
const cell = TonWeb.boc.Cell.oneFromBoc(TonWeb.utils.base64ToBytes(cellBase64));
return TonWeb.utils.bytesToBase64(parseSnakeCells(cell).slice(4)); // skip 4 bytes of prefix 0x2167da4b
}
const arr = [];
const transactionsResponse= await this.getTransactionsFromIndex(this.myAddress, limit);
const transactions = transactionsResponse.transactions; // index.transaction[]
const addressBook = transactionsResponse.address_book;
/**
* @param rawAddress {string}
* @return {string}
*/
const formatTxAddress = (rawAddress) => {
return addressBook[rawAddress].user_friendly;
}
for (const t of transactions) {
let amount = new BN(t.in_msg.value);
for (const outMsg of t.out_msgs) {
amount = amount.sub(new BN(outMsg.value));
}
let from_addr = "";
let to_addr = "";
let comment = "";
let encryptedComment = "";
let inbound = false;
if (t.in_msg.source) { // internal message with Toncoins, set source
inbound = true;
from_addr = formatTxAddress(t.in_msg.source);
to_addr = formatTxAddress(t.in_msg.destination);
comment = getComment(t.in_msg);
encryptedComment = getEncryptedComment(t.in_msg);
} else if (t.out_msgs.length) { // external message, we sending Toncoins
inbound = false;
from_addr = formatTxAddress(t.out_msgs[0].source);
to_addr = formatTxAddress(t.out_msgs[0].destination);
comment = getComment(t.out_msgs[0]);
encryptedComment = getEncryptedComment(t.out_msgs[0]);
//TODO support many out messages. We need to show separate outgoing payment for each? How to show fees?
} else {
// Deploying wallet contract onchain
}
/** @type {BN} */
let fee = new BN(t.total_fees);
for (let outMsg of t.out_msgs) {
fee = fee.add(new BN(outMsg.fwd_fee));
fee = fee.add(new BN(outMsg.ihr_fee));
}
if (to_addr) {
arr.push({
bodyHashBase64: t.in_msg.message_content.hash, // base64
inbound,
hash: t.hash, // base64
amount: amount.toString(),
from_addr: from_addr,
to_addr: to_addr,
fee: fee.toString(), // string BN
comment: comment,
encryptedComment: encryptedComment,
date: t.now * 1000
});
}
}
return arr;
}
/**
* @param request {{expireAt?: number, messages: [{amount: BN, toAddress: string, comment?: string | Uint8Array | Cell, needEncryptComment: boolean, stateInit?: Cell}]}}
* @param keyPair {nacl.KeyPair | null} null if estimates fee, keyPair if real sending
* @return Promise<{{send: () => Promise<*>, getQuery: () => Promise, estimateFee: () => Promise<*>}}> transfer object
*/
async sign(request, keyPair) {
/** @type {number} */
const seqno = await this.getMySeqno();
/** @type {Uint8Array | null} */
const secretKey = keyPair ? keyPair.secretKey : null;
return this.walletContract.methods.transfers({
secretKey: secretKey,
seqno: seqno,
expireAt: request.expireAt,
messages: request.messages.map(message => {
return {
toAddress: message.toAddress,
amount: message.amount,
payload: message.comment,
sendMode: 3,
stateInit: message.stateInit
}
})
});
}
// CREATE WALLET
async showCreated() {
this.sendToView('showScreen', {name: 'created'});
this.sendToView('disableCreated', true);
this.myMnemonicWords = await TonWeb.mnemonic.generateMnemonic();
const privateKey = await Controller.wordsToPrivateKey(this.myMnemonicWords);
const keyPair = nacl.sign.keyPair.fromSeed(TonWeb.utils.base64ToBytes(privateKey));
const walletVersion = DEFAULT_WALLET_VERSION;
const WalletClass = this.ton.wallet.all[walletVersion];
this.walletContract = new WalletClass(this.ton.provider, {
publicKey: keyPair.publicKey,
wc: 0
});
this.myAddress = (await this.walletContract.getAddress()).toString(true, true, false, this.isTestnet);
this.publicKeyHex = TonWeb.utils.bytesToHex(keyPair.publicKey);
await storage.setItem('publicKey', this.publicKeyHex);
await storage.setItem('walletVersion', walletVersion);
this.sendToView('disableCreated', false);
}
async createPrivateKey() {
this.showBackup(this.myMnemonicWords, true);
}
// BACKUP WALLET
onBackupWalletClick() {
this.afterEnterPassword = async mnemonicWords => {
this.showBackup(mnemonicWords);
};
this.sendToView('showPopup', {name: 'enterPassword'});
}
showBackup(words, isFirst) {
this.sendToView('showScreen', {name: 'backup', words, isFirst});
}
async onBackupDone() {
if (await storage.getItem('words')) {
this.sendToView('showScreen', {name: 'main'});
} else {
this.sendToView('showScreen', {name: 'wordsConfirm', words: this.myMnemonicWords});
}
}
onConfirmDone(words) {
if (words) {
let isValid = true;
Object.keys(words).forEach(index => {
if (this.myMnemonicWords[index] !== words[index]) {
isValid = false;
}
});
if (!isValid) {
return;
}
this.showCreatePassword();
}
}
// IMPORT LEDGER
async createLedger(transportType) {
let transport;
switch (transportType) {
case 'hid':
transport = await TonWeb.ledger.TransportWebHID.create();
break;
case 'ble':
transport = await TonWeb.ledger.BluetoothTransport.create();
break;
default:
throw new Error('unknown transportType' + transportType);
}
transport.setDebugMode(true);
this.isLedger = true;
this.ledgerApp = new TonWeb.ledger.AppTon(transport, this.ton);
const ledgerVersion = (await this.ledgerApp.getAppConfiguration()).version;
this.debug('ledgerAppConfig=', ledgerVersion);
if (!ledgerVersion.startsWith('2')) {
alert('Please update your Ledger TON-app to v2.0.1 or upper or use old wallet version https://tonwallet.me/prev/');
throw new Error('outdated ledger ton-app version');
}
const {publicKey} = await this.ledgerApp.getPublicKey(ACCOUNT_NUMBER, false); // todo: можно сохранять publicKey и не запрашивать это
const WalletClass = this.ton.wallet.all[DEFAULT_LEDGER_WALLET_VERSION];
const wallet = new WalletClass(this.ton.provider, {
publicKey: publicKey,
wc: 0
});
this.walletContract = wallet;
const address = await wallet.getAddress();
this.myAddress = address.toString(true, true, false, this.isTestnet);
this.publicKeyHex = TonWeb.utils.bytesToHex(publicKey);
}
async importLedger(transportType) {
await this.createLedger(transportType);
await storage.setItem('walletVersion', this.walletContract.getName());
await storage.setItem('address', this.myAddress);
await storage.setItem('isLedger', 'true');
await storage.setItem('ledgerTransportType', transportType);
await storage.setItem('words', 'ledger');
await storage.setItem('publicKey', this.publicKeyHex);
this.sendToView('setIsLedger', this.isLedger);
this.sendToView('showScreen', {name: 'readyToGo'});
}
// IMPORT WALLET
showImport() {
this.sendToView('showScreen', {name: 'import'});
}
async import(words) {
this.myMnemonicWords = words;
if (this.myMnemonicWords) {
try {
const privateKey = await Controller.wordsToPrivateKey(this.myMnemonicWords);
const keyPair = nacl.sign.keyPair.fromSeed(TonWeb.utils.base64ToBytes(privateKey));
let hasBalance = [];
for (let WalletClass of this.ton.wallet.list) {
const wallet = new WalletClass(this.ton.provider, {
publicKey: keyPair.publicKey,
wc: 0
});
const walletAddress = (await wallet.getAddress()).toString(true, true, false, this.isTestnet);
const walletBalance = await this.getBalance(walletAddress);
if (walletBalance.gt(new BN(0))) {
hasBalance.push({balance: walletBalance, clazz: WalletClass});
}
this.debug(wallet.getName(), walletAddress, walletBalance.toString());
}
let walletClass = this.ton.wallet.all[DEFAULT_WALLET_VERSION];
if (hasBalance.length > 0) {
hasBalance.sort((a, b) => {
return a.balance.cmp(b.balance);
});
walletClass = hasBalance[hasBalance.length - 1].clazz;
}
await this.importImpl(keyPair, walletClass);
this.sendToView('importCompleted', {state: 'success'});
} catch (e) {
this.debug(e);
this.sendToView('importCompleted', {state: 'failure'});
}
} else {
this.sendToView('importCompleted', {state: 'failure'});
}
}
async importImpl(keyPair, WalletClass) {
this.walletContract = new WalletClass(this.ton.provider, {
publicKey: keyPair.publicKey,
wc: 0
});
this.myAddress = (await this.walletContract.getAddress()).toString(true, true, false, this.isTestnet);
this.publicKeyHex = TonWeb.utils.bytesToHex(keyPair.publicKey);
await storage.setItem('publicKey', this.publicKeyHex);
await storage.setItem('walletVersion', this.walletContract.getName());
this.showCreatePassword();
}
// PASSWORD
showCreatePassword() {
this.sendToView('showScreen', {name: 'createPassword'});
}
/**
* @param password {string}
* @return {Promise}
*/
async savePrivateKey(password) {
this.isLedger = false;
await storage.setItem('isLedger', 'false');
await storage.setItem('address', this.myAddress);
await Controller.saveWords(this.myMnemonicWords, password);
this.myMnemonicWords = null;
this.sendToView('setIsLedger', this.isLedger);
this.sendToView('showScreen', {name: 'readyToGo'});
this.sendToView('privateKeySaved');
}
/**
* @param oldPassword {string}
* @param newPassword {string}
* @return {Promise}
*/
async onChangePassword(oldPassword, newPassword) {
let words;
try {
words = await Controller.loadWords(oldPassword);
} catch (e) {
this.sendToView('showChangePasswordError');
return;
}
await Controller.saveWords(words, newPassword);
this.sendToView('closePopup');
this.sendToView('passwordChanged');
}
/**
* @param password {string}
* @return {Promise}
*/
async onEnterPassword(password) {
let words;
try {
words = await Controller.loadWords(password);
} catch (e) {
this.sendToView('showEnterPasswordError');
return;
}
this.afterEnterPassword(words);
this.sendToView('passwordEntered');
}
// MAIN
/**
* @return {Promise}
*/
async showMain() {
this.sendToView('showScreen', {name: 'main', myAddress: this.myAddress});
if (!this.walletContract) {
const walletVersion = await storage.getItem('walletVersion');
const walletClass = walletVersion ? this.ton.wallet.all[walletVersion] : this.ton.wallet.default;
this.walletContract = new walletClass(this.ton.provider, {
address: this.myAddress,
publicKey: this.publicKeyHex ? TonWeb.utils.hexToBytes(this.publicKeyHex) : undefined,
wc: 0
});
}
this.updateIntervalId = setInterval(() => this.update(false), 5000);
this.update(true);
this.sendToDapp('ton_accounts', [this.myAddress]);
}
/**
* @return {Promise}
*/
async initDapp() {
this.sendToDapp('ton_accounts', this.myAddress ? [this.myAddress] : []);
this.doMagic((await storage.getItem('magic')) === 'true');
this.doProxy((await storage.getItem('proxy')) === 'true');
}
/**
* @return {Promise}
*/
async initView() {
if (!this.myAddress || !(await storage.getItem('words'))) {
this.sendToView('showScreen', {name: 'start', noAnimation: true});
} else {
this.sendToView('showScreen', {name: 'main', myAddress: this.myAddress});
if (this.balance !== null) {
this.sendToView('setBalance', {balance: this.balance.toString(), txs: this.transactions});
}
}
this.sendToView('setIsMagic', (await storage.getItem('magic')) === 'true');
this.sendToView('setIsProxy', (await storage.getItem('proxy')) === 'true');
this.sendToView('setIsTestnet', this.isTestnet);
}
/**
* @return {Promise} successfully updated
*/
async updateBalance() {
try {
this.balance = await this.getBalance(this.myAddress);
return true;
} catch (e) {
console.error(e);
return false;
}
}
/**
* @param force {boolean}
* @return {Promise} successfully updated
*/
async update(force) {
try {
// if (!document.hasFocus()) {
// return true;
// }
const needUpdate = (this.processingVisible && this.sendingData) || (this.balance === null) || force;
if (!needUpdate) return true;
if (!(await this.updateBalance())) return false;
const txs = await this.getTransactions();
if (txs.length > 0) {
this.transactions = txs;
if (this.processingVisible && this.sendingData) {
for (let tx of txs) {
if (tx.bodyHashBase64 === this.sendingData.bodyHashBase64) {
this.sendToView('showPopup', {
name: 'done',
message: formatNanograms(this.sendingData.totalAmount) + ' TON have been sent'
});
this.processingVisible = false;
this.sendingData = null;
break;
}
}
}
}
this.sendToView('setBalance', {balance: this.balance.toString(), txs: this.transactions});
return true;
} catch (e) {
console.error(e);
return false;
}
}
async showAddressOnDevice() {
if (!this.ledgerApp) {
await this.createLedger((await storage.getItem('ledgerTransportType')) || 'hid');
}
const {address} = await this.ledgerApp.getAddress(ACCOUNT_NUMBER, true, this.ledgerApp.ADDRESS_FORMAT_USER_FRIENDLY + this.ledgerApp.ADDRESS_FORMAT_URL_SAFE + this.ledgerApp.ADDRESS_FORMAT_BOUNCEABLE);
this.debug(address.toString(true, true, true));
}
// DECRYPT MESSAGE COMMENT
/**
* @param hash {string}
* @param encryptedComment {string} base64
* @param senderAddress {string | Address}
*/
onDecryptComment(hash, encryptedComment, senderAddress) {
this.afterEnterPassword = async mnemonicWords => {
const keyPair = await TonWeb.mnemonic.mnemonicToKeyPair(mnemonicWords);
let decryptedComment = ''
try {
decryptedComment = await decryptMessageComment(TonWeb.utils.base64ToBytes(encryptedComment), keyPair.publicKey, keyPair.secretKey, senderAddress);
} catch (e) {
console.error(e);
}
this.sendToView('decryptedComment', {hash, decryptedComment});
};
this.sendToView('showPopup', {name: 'enterPassword'});
}
// SEND TONCOIN
/**
* @param request {{expireAt?: number, messages: [{amount: BN, toAddress: string, comment?: string | Uint8Array | Cell, needEncryptComment: boolean, stateInit?: Cell}]}}
* @return {Promise} total fees in nanotons
*/
async getFees(request) {
/** @type {{expireAt?: number, messages: [{amount: BN, toAddress: string, comment?: string | Uint8Array | Cell, needEncryptComment: boolean, stateInit?: Cell}]}} */
const tempRequest = {
expireAt: request.expireAt,
messages: []
};
for (const message of request.messages) {
let tempComment = message.comment
if (message.needEncryptComment) {
const tempKeyPair = TonWeb.utils.newKeyPair(); // encrypt with random key just to get estimage fees
const tempEncryptedCommentCell = await encryptMessageComment(message.comment, tempKeyPair.publicKey, tempKeyPair.publicKey, tempKeyPair.secretKey, this.myAddress);
tempComment = tempEncryptedCommentCell;
}
tempRequest.messages.push({
amount: message.amount,
toAddress: message.toAddress,
comment: tempComment,
needEncryptComment: message.needEncryptComment,
stateInit: message.stateInit
});
}
const query = await this.sign(tempRequest, null);
const all_fees = await query.estimateFee();
const fees = all_fees.source_fees;
const in_fwd_fee = new BN(fees.in_fwd_fee); // External processing fee
const storage_fee = new BN(fees.storage_fee);
const gas_fee = new BN(fees.gas_fee);
const fwd_fee = new BN(fees.fwd_fee);
return in_fwd_fee.add(storage_fee).add(gas_fee).add(fwd_fee);
};
/**
* @param request {{expireAt?: number, messages: [{amount: BN, toAddress: string, comment?: string | Uint8Array | Cell, needEncryptComment: boolean, stateInit?: Cell}]}}
* @param needQueue? {boolean}
* @return {Promise} successfully sent BoC
*/
async showSendConfirm(request, needQueue) {
createDappPromise();
if (!request.messages) throw new Error('no messages');
if (!request.messages.length) throw new Error('no messages to send');
if (request.messages.length > 4) throw new Error('maximum 4 message at once');
/** @type {BN} */
let totalAmount = new BN(0);
for (const message of request.messages) {
// message.address
if (!message.amount) throw new Error('no amount');
if (!message.amount.gte(new BN(0))) {
this.sendToView('sendCheckFailed', {message: 'Amount must be positive'});
return null;
}
if (message.amount.eq(new BN(0)) && !message.comment) {
this.sendToView('sendCheckFailed', {message: 'You can send 0 TON only with comment'});
return null;
}
totalAmount = totalAmount.add(message.amount);
// message.toAddress
if (!message.toAddress) throw new Error('no toAddress');
if (!Address.isValid(message.toAddress)) {
try {
message.toAddress = message.toAddress.toLowerCase();
if (!message.toAddress.endsWith('.ton') && !message.toAddress.endsWith('.t.me')) {
throw new Error();
}
message.toAddress = await this.ton.dns.getWalletAddress(message.toAddress);
if (!message.toAddress) {
throw new Error();
}
if (!Address.isValid(message.toAddress)) {
throw new Error();
}
message.toAddress = message.toAddress.toString(true, true, true, this.isTestnet);
} catch (e) {
this.sendToView('sendCheckFailed', {message: 'Invalid address or domain'});
return null;
}
}
// make toAddress non-bounceable if destination contract uninitialized
if (!(await this.checkContractInitialized(message.toAddress))) {
message.toAddress = (new Address(message.toAddress)).toString(true, true, false);
}
// message.payload
if (!message.comment) {
message.needEncryptComment = false;
}
// serialize long text comment
if (!message.needEncryptComment && (typeof message.comment === 'string')) {
if (message.comment.length > 0) {
const commentBytes = new TextEncoder().encode(message.comment);
const payloadBytes = new Uint8Array(4 + commentBytes.length);
payloadBytes[0] = 0; // zero uint32 means simple text message
payloadBytes[1] = 0;
payloadBytes[2] = 0;
payloadBytes[3] = 0;
payloadBytes.set(commentBytes, 4);
message.comment = makeSnakeCells(payloadBytes);
}
}
// get destination public key for encryption
if (message.needEncryptComment) {
let toPublicKey = null;
try {
const toPublicKeyBN = await this.ton.provider.call2(message.toAddress, 'get_public_key');
let toPublicKeyHex = toPublicKeyBN.toString(16);
if (toPublicKeyHex.length % 2 !== 0) {
toPublicKeyHex = '0' + toPublicKeyHex;
}
toPublicKey = TonWeb.utils.hexToBytes(toPublicKeyHex);
} catch (e) {
console.error(e);
}
if (!toPublicKey) {
this.sendToView('sendCheckCantPublicKey', {});
return null;
}
message.toPublicKey = toPublicKey;
}
}
// check balance
if (!(await this.updateBalance())) {
this.sendToView('sendCheckFailed', {message: 'API request error'});
return null;
}
if (this.balance.lt(totalAmount)) {
this.sendToView('sendCheckFailed', {
message: 'Not enough balance'
});
return null;
}
let fee;
try {
fee = await this.getFees(request);
} catch (e) {
console.error(e);
this.sendToView('sendCheckFailed', {message: 'API request error'});
return null;
}
if (this.balance.sub(fee).lt(totalAmount)) {
this.sendToView('sendCheckCantPayFee', {fee});
return null;
}
// start
if (this.isLedger) {
const message = request.messages[0];
this.sendToView('showPopup', {
name: 'sendConfirm',
amount: message.amount.toString(),
toAddress: message.toAddress,
needEncryptComment: false,
fee: fee.toString()
}, needQueue);
const sentBoc = await this.send(request, null, totalAmount);
if (sentBoc) {
dAppPromise.resolve(sentBoc);
} else {
this.sendToView('sendCheckFailed', {message: 'API request error'});
dAppPromise.resolve(null);
}
} else {
this.afterEnterPassword = async words => {
this.processingVisible = true;
this.sendToView('showPopup', {name: 'processing'});
const keyPair = await TonWeb.mnemonic.mnemonicToKeyPair(words);
for (const message of request.messages) {
if (message.needEncryptComment) {
const encryptedCommentCell = await encryptMessageComment(message.comment, keyPair.publicKey, message.toPublicKey, keyPair.secretKey, this.myAddress);
message.comment = encryptedCommentCell;
}
}
const privateKeyBase64 = await Controller.wordsToPrivateKey(words);
const sentBoc = await this.send(request, privateKeyBase64, totalAmount);
this.onCancelAction = null;
if (sentBoc) {
dAppPromise.resolve(sentBoc);
} else {
this.sendToView('sendCheckFailed', {message: 'API request error'});
dAppPromise.resolve(null);
}
};
this.onCancelAction = () => {
dAppPromise.resolve(null);
};
this.sendToView('showPopup', {
name: 'sendConfirm',
amount: totalAmount.toString(),
toAddress: request.messages.length === 1 ? request.messages[0].toAddress : `${request.messages.length} addresses`,
fee: fee.toString(),
needEncryptComment: request.messages[0].needEncryptComment // todo
}, needQueue);
}
this.sendToView('sendCheckSucceeded');
return dAppPromise;
}
/**
* @param request {{expireAt?: number, messages: [{amount: BN, toAddress: string, comment?: string | Uint8Array | Cell, needEncryptComment: boolean, stateInit?: Cell}]}}
* @param privateKeyBase64 {string | null} null if Ledger
* @param totalAmount {BN}
* @return {Promise} successfully sent BoC
*/
async send(request, privateKeyBase64, totalAmount) {
try {
let query;
if (this.isLedger) {
if (request.messages.length !== 1) {
throw new Error('Ledger support only 1 message at once');
}
const message = request.messages[0];
if (message.needEncryptComment) {
throw new Error('encrypted comment dont supported by Ledger');
}
if (message.stateInit) {
throw new Error('stateInit dont supported by Ledger');
}
if (!this.ledgerApp) {
await this.createLedger((await storage.getItem('ledgerTransportType')) || 'hid');
}
let addressFormat = 0;
const toAddress = new Address(message.toAddress);
if (toAddress.isUserFriendly) {
addressFormat += this.ledgerApp.ADDRESS_FORMAT_USER_FRIENDLY;
if (toAddress.isUrlSafe) {
addressFormat += this.ledgerApp.ADDRESS_FORMAT_URL_SAFE;
}
if (toAddress.isBounceable) {
addressFormat += this.ledgerApp.ADDRESS_FORMAT_BOUNCEABLE;
}
if (toAddress.isTestOnly) {
addressFormat += this.ledgerApp.ADDRESS_FORMAT_TEST_ONLY;
}
}
const seqno = await this.getMySeqno();
query = await this.ledgerApp.transfer(ACCOUNT_NUMBER, this.walletContract, message.toAddress, message.amount, seqno, addressFormat);
this.sendToView('showPopup', {name: 'processing'});
this.processingVisible = true;
} else {
const keyPair = nacl.sign.keyPair.fromSeed(TonWeb.utils.base64ToBytes(privateKeyBase64));
query = await this.sign(request, keyPair);
}
/** @type {Cell | null} */
const sentBoc = await this.sendQuery(query);
if (!sentBoc) return null;
/** @type {Cell} */
const bodyCell = await query.getBody();
/** @type {Uint8Array} */
const bodyHash = await bodyCell.hash();
this.sendingData = {
bodyHashBase64: TonWeb.utils.bytesToBase64(bodyHash),
totalAmount: totalAmount
};
return sentBoc;
} catch (e) {
this.debug(e);
this.sendToView('closePopup');
alert('Error sending');
return null;
}
}
/**
* @param hexToSign {string} hex to sign
* @param privateKey {string}
* @returns {Promise} signature in hex
*/
rawSign(hexToSign, privateKey) {
const keyPair = nacl.sign.keyPair.fromSeed(TonWeb.utils.base64ToBytes(privateKey));
const signature = nacl.sign.detached(TonWeb.utils.hexToBytes(hexToSign), keyPair.secretKey);
return TonWeb.utils.bytesToHex(signature);
}
/**
* @param query {{send: () => Promise<*>, getQuery: () => Promise}}
* @return {Promise} successfully sent BoC
*/
async sendQuery(query) {
const sendResponse = await query.send();
if (sendResponse["@type"] === "ok") { // response from ton-http-api
// wait for transaction, then show Done popup
return query.getQuery();
} else {
this.sendToView('closePopup');
alert('Send error');
return null;
}
}
// RAW SIGN
/**
* @param hexToSign {string} hex data to sign
* @param isConnect {boolean}
* @param needQueue {boolean}
* @returns {Promise} signature in hex
*/
showSignConfirm(hexToSign, isConnect, needQueue) {
return new Promise((resolve, reject) => {
if (this.isLedger) {
alert('sign not supported by Ledger');
reject();
} else {
this.onCancelAction = () => {
reject('User cancel');
};
this.afterEnterPassword = async words => {
this.sendToView('closePopup');
const privateKeyBase64 = await Controller.wordsToPrivateKey(words);
const signature = this.rawSign(hexToSign, privateKeyBase64);
resolve(signature);
};
this.sendToView('showPopup', {
name: 'signConfirm',
data: hexToSign,
isConnect: isConnect
}, needQueue);
}
});
}
/**
* Ask user for password and set `this.publicKeyHex`
* @param needQueue {boolean}
* @return {Promise}
*/
requestPublicKey(needQueue) {
return new Promise(async (resolve, reject) => {
await showExtensionWindow();
this.onCancelAction = () => {
reject('User cancel');
};
this.afterEnterPassword = async words => {
const privateKey = await Controller.wordsToPrivateKey(words);
const keyPair = nacl.sign.keyPair.fromSeed(TonWeb.utils.base64ToBytes(privateKey));
this.publicKeyHex = TonWeb.utils.bytesToHex(keyPair.publicKey);
await storage.setItem('publicKey', this.publicKeyHex);
resolve();
};
this.sendToView('showPopup', {name: 'enterPassword'}, needQueue);
});
}
/**
* @param needQueue {boolean}
* @returns {Promise}
*/
showConnectConfirm(needQueue) {
return new Promise((resolve, reject) => {
this.onCancelAction = () => {
reject({
message: 'Reject request',
code: 300 // USER_REJECTS_ERROR
});
};
this.onConnectConfirmed = async () => {
this.sendToView('closePopup');
resolve();
};
this.sendToView('showPopup', {
name: 'connectConfirm',
}, needQueue);
});
}
// DISCONNECT WALLET
clearVars() {
this.myAddress = null;
this.publicKeyHex = null;
this.balance = null;
this.walletContract = null;
this.transactions = [];
this.sendingData = null;
this.processingVisible = false;
this.isLedger = false;
this.ledgerApp = null;
clearInterval(this.updateIntervalId);
}
async onDisconnectClick() {
this.clearVars();
await storage.clear();
this.sendToView('showScreen', {name: 'start'});
this.sendToDapp('ton_accounts', []);
}
// MAGIC
doMagic(enabled) {
try {
this.sendToDapp('ton_doMagic', enabled);
} catch (e) {
}
}
// PROXY
doProxy(enabled) {
}
// TRANSPORT WITH VIEW
/**
* @param method {string}
* @param params? {any} boolean or object, not array
* @param needQueue? {boolean}
* @param needResult? {boolean}
* @return {void | Promise<{magic: (string|null), proxy: (string|null), address: (string|null), words: (string|null), walletVersion: (string|null)}>}
*/
sendToView(method, params, needQueue, needResult) {
if (self.view) {
const result = self.view.onMessage(method, params);
if (needResult) {
return result;
}
} else {
const msg = {method, params};
const exec = () => {
if (popupPort) {
popupPort.postMessage(msg);
} else if (needQueue) {
queueToPopup.push(msg);
}
};
if (!needResult) {
exec();
return;
}
return new Promise((resolve) => {
msg.id = this._lastMsgId++;
this.pendingMessageResolvers.set(msg.id, resolve);
exec();
});
}
}
/**
* @param method {string}
* @param params? {any} boolean or object, not array
* @return {Promise}
*/
async onViewMessage(method, params) {
switch (method) {
case 'showScreen':
switch (params.name) {
case 'created':
await this.showCreated();
break;
case 'import':
this.showImport();
break;
case 'importLedger':
await this.importLedger(params.transportType);
break;
}
break;
case 'import':
await this.import(params.words);
break;
case 'createPrivateKey':
await this.createPrivateKey();
break;
case 'passwordCreated':
await this.savePrivateKey(params.password);
break;
case 'update':
this.update(true);
break;
case 'showAddressOnDevice':
await this.showAddressOnDevice();
break;
case 'onCancelAction':
if (this.onCancelAction) {
await this.onCancelAction();
this.onCancelAction = null;
}
break;
case 'onConnectConfirmed':
if (this.onConnectConfirmed) {
this.onConnectConfirmed();
this.onConnectConfirmed = null;
}
break;
case 'onEnterPassword':
await this.onEnterPassword(params.password);
break;
case 'decryptComment':
await this.onDecryptComment(params.hash, params.encryptedComment, params.senderAddress);
break;
case 'onChangePassword':
await this.onChangePassword(params.oldPassword, params.newPassword);
break;
case 'onSend':
await this.showSendConfirm({
messages: [
{
amount: new BN(params.amount),
toAddress: params.toAddress,
comment: params.comment,
needEncryptComment: params.needEncryptComment
}
]
}, false);
break;
case 'onBackupDone':
await this.onBackupDone();
break;
case 'onConfirmBack':
this.showBackup(this.myMnemonicWords);
break;
case 'onImportBack':
this.sendToView('showScreen', {name: 'start'});
break;
case 'onConfirmDone':
this.onConfirmDone(params.words);
break;
case 'showMain':
await this.showMain();
break;
case 'onBackupWalletClick':
this.onBackupWalletClick();
break;
case 'disconnect':
await this.onDisconnectClick();
break;
case 'onClosePopup':
this.processingVisible = false;
break;
case 'onMagicClick':
await storage.setItem('magic', params ? 'true' : 'false');
this.doMagic(params);
break;
case 'onProxyClick':
await storage.setItem('proxy', params ? 'true' : 'false');
this.doProxy(params);
break;
case 'toggleTestnet':
await this.toggleTestnet();
break;
case 'toggleDebug':
await this.toggleDebug();
break;
case 'onWindowUpdate':
await storage.setItem('windowState', {
top: params.top,
left: params.left,
// -2 need for remove frames size
// TODO: check in linux and macos
height: params.height - 2,
width: params.width - 2
});
break;
}
}
// TRANSPORT WITH DAPP
/**
* @param method {string}
* @param params {any | any[]}
*/
sendToDapp(method, params) {
contentScriptPorts.forEach(port => {
port.postMessage(JSON.stringify({
type: 'gramWalletAPI',
message: {jsonrpc: '2.0', method: method, params: params}
}));
});
}
/**
* @param needQueue {boolean}
* @return {Promise<{name: 'ton_addr', address: string, network: string, walletStateInit: string, publicKey: string }>}
*/
async createTonAddrItemReply(needQueue) {
if (!this.myAddress) {
throw {
message: 'Missing connection',
code: 1 // BAD_REQUEST_ERROR
};
}
if (!this.publicKeyHex) {
await this.requestPublicKey(needQueue);
}
const walletVersion = await storage.getItem('walletVersion');
const rawAddressString = new TonWeb.utils.Address(this.myAddress).toString(false);
const WalletClass = walletVersion ? this.ton.wallet.all[walletVersion] : this.ton.wallet.default;
const wallet = new WalletClass(this.ton.provider, {
publicKey: TonWeb.utils.hexToBytes(this.publicKeyHex),
wc: 0
});
const {stateInit} = await wallet.createStateInit();
const stateInitBase64 = TonWeb.utils.bytesToBase64(await stateInit.toBoc(false));
return {
name: 'ton_addr',
address: rawAddressString,
network: this.isTestnet ? TONCONNECT_TESTNET : TONCONNECT_MAINNET,
walletStateInit: stateInitBase64,
publicKey: this.publicKeyHex
};
}
/**
* @param origin {string}
* @param payload {string}
* @param needQueue {boolean}
* @return {any} ton_proof item
*/
async createTonProofItemReply(origin, payload, needQueue) {
if (!this.myAddress) {
throw {
message: 'Missing connection',
code: 1 // BAD_REQUEST_ERROR
};
}
const timestamp = Math.round(Date.now() / 1000);
const timestampBuffer = new BigInt64Array(1);
timestampBuffer[0] = BigInt(timestamp);
const domain = new URL(origin).host;
const domainBuffer = new TextEncoder().encode(domain);
const domainLengthBuffer = new Int32Array(1);
domainLengthBuffer[0] = domainBuffer.byteLength;
const address = new TonWeb.utils.Address(this.myAddress);
const addressWorkchainBuffer = new Int32Array(1);
addressWorkchainBuffer[0] = address.wc;
const addressBuffer = new Uint8Array(4 + address.hashPart.length);
addressBuffer.set(addressWorkchainBuffer, 0);
addressBuffer.set(address.hashPart, 4);
const prefixBuffer = new TextEncoder().encode('ton-proof-item-v2/');
const payloadBuffer = new TextEncoder().encode(payload);
const messageBuffer = new Uint8Array(prefixBuffer.byteLength + addressBuffer.byteLength + domainLengthBuffer.byteLength + domainBuffer.byteLength + timestampBuffer.byteLength + payloadBuffer.byteLength);
let offset = 0;
messageBuffer.set(prefixBuffer, offset);
offset += prefixBuffer.byteLength;
messageBuffer.set(addressBuffer, offset);
offset += addressBuffer.byteLength;
messageBuffer.set(domainLengthBuffer, offset);
offset += domainLengthBuffer.byteLength;
messageBuffer.set(domainBuffer, offset);
offset += domainBuffer.byteLength;
messageBuffer.set(new Uint8Array(timestampBuffer.buffer), offset);
offset += 8;
messageBuffer.set(payloadBuffer, offset);
const ffffPrefix = new Uint8Array([0xff, 0xff]);
const tonconnectPrefix = new TextEncoder().encode('ton-connect')
const messageBufferHash = new Uint8Array(await TonWeb.utils.sha256(messageBuffer));
const bufferToSign = new Uint8Array(ffffPrefix.byteLength + tonconnectPrefix.byteLength + messageBufferHash.byteLength);
offset = 0;
bufferToSign.set(ffffPrefix, offset);
offset += ffffPrefix.byteLength;
bufferToSign.set(tonconnectPrefix, offset);
offset += tonconnectPrefix.byteLength;
bufferToSign.set(messageBufferHash, offset);
const hexToSign = TonWeb.utils.bytesToHex(new Uint8Array(await TonWeb.utils.sha256(bufferToSign)));
const signatureHex = await this.showSignConfirm(hexToSign, true, needQueue);
console.log({signatureHex});
const signatureBase64 = TonWeb.utils.bytesToBase64(TonWeb.utils.hexToBytes(signatureHex));
console.log({signatureBase64});
return {
name: 'ton_proof',
proof: {
timestamp: timestamp, // 64-bit unix epoch time of the signing operation (seconds)
domain: {
lengthBytes: domainBuffer.byteLength, // AppDomain Length
value: domain, // app domain name (as url part, without encoding)
},
signature: signatureBase64, // base64-encoded signature
payload: payload, // payload from the request
},
}
}
async onDappMessage(method, params, origin) {
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1102.md
await this.whenReady;
const needQueue = !popupPort;
switch (method) {
case 'tonConnect_connect':
await showExtensionWindow();
if (!this.myAddress) {
throw {
message: 'Missing connection',
code: 1 // BAD_REQUEST_ERROR
}
}
const data = params[0];
const tonProof = data.items.find((item) => item.name === 'ton_proof');
if (!tonProof &&
!(await storage.getItem('tonconnect_' + this.myAddress + '_' + (this.isTestnet ? 'testnet' : 'mainnet') + '_' + origin))) {
await this.showConnectConfirm(needQueue);
}
await storage.setItem('tonconnect_' + this.myAddress + '_' + (this.isTestnet ? 'testnet' : 'mainnet') + '_' + origin, 'true');
const connectResult = [
await this.createTonAddrItemReply(needQueue),
];
if (tonProof) {
connectResult.push(await this.createTonProofItemReply(origin, tonProof.payload, needQueue))
}
return connectResult;
case 'tonConnect_reconnect':
if (!this.myAddress ||
!(await storage.getItem('tonconnect_' + this.myAddress + '_' + (this.isTestnet ? 'testnet' : 'mainnet') + '_' + origin))) {
throw {
message: 'Missing connection',
code: 1 // BAD_REQUEST_ERROR
}
}
return [
await this.createTonAddrItemReply(needQueue)
];
case 'tonConnect_disconnect':
await storage.removeItem('tonconnect_' + this.myAddress + '_' + (this.isTestnet ? 'testnet' : 'mainnet') + '_' + origin);
return;
case 'tonConnect_sendTransaction':
await showExtensionWindow();
const tx = params[0];
console.log('tonConnect_sendTransaction', params, origin, tx);
// check is dapp connected to wallet
if (!this.myAddress) {
throw {
message: 'Missing connection',
code: 1 // BAD_REQUEST_ERROR
}
}
if (!(await storage.getItem('tonconnect_' + this.myAddress + '_' + (this.isTestnet ? 'testnet' : 'mainnet') + '_' + origin))) {
throw {
message: 'dApp don\'t have an access to wallet',
code: 1 // BAD_REQUEST_ERROR
}
}
// check tonConnect_sendTransaction request
/** @type {number | undefined} */
let expireAt = undefined;
if (tx.valid_until) {
expireAt = Number(tx.valid_until);
if (isNaN(expireAt)) {
throw {
message: 'invalid validUntil',
code: 1 // BAD_REQUEST_ERROR
}
}
if (expireAt > 9999999999) {
expireAt = expireAt / 1000; // convert millis to seconds, todo: it's not good
}
if (expireAt < Date.now() / 1000) {
throw {
message: 'expired',
code: 1 // BAD_REQUEST_ERROR
}
}
}
if (tx.from) {
if (!Address.isValid(tx.from)) {
throw {
message: 'Invalid source address',
code: 1 // BAD_REQUEST_ERROR
}
}
if (new TonWeb.utils.Address(tx.from).toString(false) !== new TonWeb.utils.Address(this.myAddress).toString(false)) {
throw {
message: 'Different source address',
code: 1 // BAD_REQUEST_ERROR
}
}
}
if (tx.network) {
if (tx.network !== TONCONNECT_TESTNET && tx.network !== TONCONNECT_MAINNET) {
throw {
message: 'Invalid network',
code: 1 // BAD_REQUEST_ERROR
}
}
if ((tx.network === TONCONNECT_TESTNET) !== !!this.isTestnet) {
throw {
message: 'Different network',
code: 1 // BAD_REQUEST_ERROR
}
}
}
if (!tx.messages || !tx.messages.length) {
throw {
message: 'no messages',
code: 1 // BAD_REQUEST_ERROR
}
}
const convertTonconnectMessage = (message) => {
try {
if (!message.address) {
throw new Error('no address')
}
if (!Address.isValid(message.address)) {
throw new Error('invalid address');
}
if (!message.amount) {
throw new Error('no amount')
}
message.amount = new BN(message.amount);
if (message.payload) {
message.payload = TonWeb.boc.Cell.oneFromBoc(TonWeb.utils.base64ToBytes(message.payload));
}
if (message.stateInit) {
message.stateInit = TonWeb.boc.Cell.oneFromBoc(TonWeb.utils.base64ToBytes(message.stateInit));
}
return {
amount: message.amount,
toAddress: message.address,
comment: message.payload,
needEncryptComment: false,
stateInit: message.stateInit
}
} catch (e) {
throw {
message: e.message,
code: 1 // BAD_REQUEST_ERROR
}
}
}
const messages = [];
for (const message of tx.messages) {
messages.push(convertTonconnectMessage(message));
}
this.sendToView('showPopup', {
name: 'loader',
});
/** @type {Cell | null} */
const sentBoc = await this.showSendConfirm(
{
expireAt: expireAt,
messages
},
needQueue
);
if (!sentBoc) {
this.sendToView('closePopup');
throw {
message: 'Reject request',
code: 300 // USER_REJECTS_ERROR
}
}
return TonWeb.utils.bytesToBase64(await sentBoc.toBoc(false));
case 'ton_requestAccounts':
return (this.myAddress ? [this.myAddress] : []);
case 'ton_requestWallets':
if (!this.myAddress) {
return [];
}
if (!this.publicKeyHex) {
await this.requestPublicKey(needQueue);
}
const walletVersion = await storage.getItem('walletVersion');
return [{
address: this.myAddress,
publicKey: this.publicKeyHex,
walletVersion: walletVersion
}];
case 'ton_getBalance':
await this.updateBalance();
return (this.balance ? this.balance.toString() : '');
case 'ton_sendTransaction':
const param = params[0];
await showExtensionWindow();
if (param.data) {
if (param.dataType === 'hex') {
param.data = TonWeb.utils.hexToBytes(param.data);
} else if (param.dataType === 'base64') {
param.data = TonWeb.utils.base64ToBytes(param.data);
} else if (param.dataType === 'boc') {
param.data = TonWeb.boc.Cell.oneFromBoc(TonWeb.utils.base64ToBytes(param.data));
}
}
if (param.stateInit) {
param.stateInit = TonWeb.boc.Cell.oneFromBoc(TonWeb.utils.base64ToBytes(param.stateInit));
}
this.sendToView('showPopup', {
name: 'loader',
});
const result = await this.showSendConfirm(
{
messages: [{
amount: new BN(param.value),
toAddress: param.to,
comment: param.data,
needEncryptComment: false,
stateInit: param.stateInit,
}]
},
needQueue
);
if (!result) {
this.sendToView('closePopup');
}
return !!result;
case 'ton_rawSign':
const signParam = params[0];
await showExtensionWindow();
return this.showSignConfirm(signParam.data, false, needQueue);
case 'flushMemoryCache':
await chrome.webRequest.handlerBehaviorChanged();
return true;
default:
throw {
message: `Method "${method}" not implemented`,
code: 400 // METHOD_NOT_SUPPORTED
};
}
}
}
const controller = new Controller();
if (IS_EXTENSION) {
chrome.runtime.onConnect.addListener(port => {
if (port.name === 'gramWalletContentScript') { // dapp
contentScriptPorts.add(port)
port.onMessage.addListener(async (msg, port) => {
if (msg.type === 'gramWalletAPI_ton_provider_connect') {
controller.whenReady.then(() => {
controller.initDapp();
});
}
if (!msg.message) return;
const origin = decodeURIComponent(msg.message.origin);
let result = undefined;
let error = undefined;
try {
result = await controller.onDappMessage(msg.message.method, msg.message.params, origin);
} catch (e) {
console.error(e);
error = {
message: e.message,
code: e.code || 0
};
}
if (port) {
port.postMessage(JSON.stringify({
type: 'gramWalletAPI',
message: {jsonrpc: '2.0', id: msg.message.id, method: msg.message.method, result, error}
}));
}
});
port.onDisconnect.addListener(port => {
contentScriptPorts.delete(port)
})
} else if (port.name === 'gramWalletPopup') { // view
popupPort = port;
popupPort.onMessage.addListener(function (msg) {
if (msg.method === 'response') {
const resolver = controller.pendingMessageResolvers.get(msg.id);
if (resolver) {
resolver(msg.result);
controller.pendingMessageResolvers.delete(msg.id);
}
} else {
controller.onViewMessage(msg.method, msg.params);
}
});
popupPort.onDisconnect.addListener(() => {
popupPort = null;
});
const runQueueToPopup = () => {
queueToPopup.forEach(msg => popupPort.postMessage(msg));
queueToPopup.length = 0;
};
if (!controller.myAddress) { // if controller not initialized yet
runQueueToPopup();
}
controller.whenReady.then(async () => {
await controller.initView();
runQueueToPopup();
});
}
});
let actionApiName = 'action';
if (chrome.runtime.getManifest().manifest_version === 2) actionApiName = 'browserAction';
chrome[actionApiName].onClicked.addListener(showExtensionWindow);
chrome.windows.onRemoved.addListener(removedWindowId => {
if (dAppPromise) dAppPromise.resolve(false);
if (removedWindowId !== extensionWindowId) return;
extensionWindowId = -1;
});
}
/******/ })()
;
================================================
FILE: docs/js/View.js
================================================
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ // The require scope
/******/ var __webpack_require__ = {};
/******/
/************************************************************************/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
;// CONCATENATED MODULE: ./src/js/view/Utils.js
// UI Utils
/**
* @param selector {string}
* @return {HTMLElement | null}
*/
function $(selector) {
return document.querySelector(selector);
}
/**
* @param selector {string}
* @return {NodeListOf}
*/
function $$(selector) {
return document.querySelectorAll(selector);
}
/**
* @param div {HTMLElement}
* @param visible {boolean | 'none' | 'block' | 'flex' | 'inline-block'}
*/
function toggle(div, visible) {
let d = visible;
if (visible === true) d = 'block';
if (visible === false) d = 'none';
div.style.display = d;
}
/**
* @param div {HTMLElement}
* @param isVisible {boolean}
* @param params? {{isBack?: boolean}}
*/
function toggleFaded(div, isVisible, params) {
params = params || {};
if (params.isBack) {
div.classList.add('isBack');
} else {
div.classList.remove('isBack');
}
if (isVisible) {
div.classList.add('faded-show');
div.classList.remove('faded-hide');
} else {
div.classList.remove('faded-show');
div.classList.add('faded-hide');
}
}
/**
* @param div {HTMLElement}
* @param className {string}
* @param duration {number}
*/
function triggerClass(div, className, duration) {
div.classList.add(className);
setTimeout(() => {
div.classList.remove(className);
}, duration);
}
/**
* @param params {{tag: string, clazz?: string | (string | undefined)[], text?: string, child?: (HTMLElement | undefined)[], style?: Object}}
* @return {HTMLElement}
*/
function createElement(params) {
const item = document.createElement(params.tag);
if (params.clazz) {
if (Array.isArray(params.clazz)) {
for (let c of params.clazz) {
if (c) {
item.classList.add(c);
}
}
} else {
item.classList.add(params.clazz);
}
}
if (params.text) item.innerText = params.text;
if (params.child) {
for (let c of params.child) {
if (c) {
item.appendChild(c);
}
}
}
if (params.style) {
for (let key in params.style) {
item.style[key] = params.style[key];
}
}
return item;
}
/**
* @param el {HTMLElement}
* @param s {string}
* @return {HTMLElement}
*/
function setAddr(el, s) {
el.innerHTML = '';
el.appendChild(document.createTextNode(s.substring(0, s.length / 2)));
el.appendChild(document.createElement('wbr'));
el.appendChild(document.createTextNode(s.substring(s.length / 2)));
return el;
}
/**
* @param el {HTMLElement}
*/
function clearElement(el) {
el.innerHTML = '';
}
/**
* @param input {HTMLElement}
* @param handler {(e: Event) => void}
*/
function onInput(input, handler) {
input.addEventListener('change', handler);
input.addEventListener('input', handler);
input.addEventListener('cut', handler);
input.addEventListener('paste', handler);
}
/**
* @param n {number}
* @return {string}
*/
function doubleZero(n) {
if (n < 10) return '0' + n;
return n.toString();
}
/**
* @param date {Date}
* @return {string}
*/
function formatTime(date) {
return doubleZero(date.getHours()) + ':' + doubleZero(date.getMinutes());
}
const MONTH_NAMES = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
/**
* @param date {Date}
* @return {string}
*/
function formatDate(date) {
return MONTH_NAMES[date.getMonth()] + ' ' + date.getDate();
}
/**
* @param date {Date}
* @return {string}
*/
function formatDateFull(date) {
return date.toString();
}
/**
* @param text {string}
* @return {boolean}
*/
function copyToClipboard(text) {
/** @type {HTMLTextAreaElement} */
const textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.position = "fixed"; //avoid scrolling to bottom
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
/** @type {boolean} */
let result = false;
try {
result = document.execCommand('copy');
} catch (err) {
}
document.body.removeChild(textArea);
return result;
}
const IMPORT_WORDS_COUNT = 24;
const CONFIRM_WORDS_COUNT = 3;
;// CONCATENATED MODULE: ./src/js/view/Lottie.js
/**
* @type {Object} lottie name -> lottie element
*/
const lotties = {};
/**
* @param div {HTMLElement}
* @return {Promise}
*/
function initLottie(div) {
return new Promise((resolve, reject) => {
const url = div.getAttribute('src');
const name = div.getAttribute('data-name');
const w = Number(div.getAttribute('width'));
const h = Number(div.getAttribute('height'));
const xmlHttp = new XMLHttpRequest();
xmlHttp.responseType = 'arraybuffer';
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
const canvas = document.createElement('canvas');
canvas.setAttribute('width', w * window.devicePixelRatio);
canvas.setAttribute('height', h * window.devicePixelRatio);
canvas.style.width = w + 'px';
canvas.style.height = h + 'px';
div.appendChild(canvas);
const ctx = canvas.getContext('2d');
const animationData = JSON.parse(new TextDecoder('utf-8').decode(pako.inflate(xmlHttp.response)));
lotties[name] = {
ctx: ctx,
player: lottie.loadAnimation({
renderer: 'canvas',
loop: name === 'processing' || name === 'start' || name === 'about' || name === 'symbol',
autoplay: false,
animationData,
rendererSettings: {
context: ctx,
scaleMode: 'noScale',
clearCanvas: true
},
})
};
ctx.clearRect(0, 0, 1000, 1000);
resolve();
} else {
reject();
}
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
});
}
/**
* @return {Promise}
*/
async function initLotties() {
const divs = $$('tgs-player');
for (let i = 0; i < divs.length; i++) {
try {
await initLottie(divs[i]);
} catch (e) {
}
}
}
/**
* @param lottie? {any}
* @param visible {boolean}
* @param params? {{hideDelay?: number}}
*/
function toggleLottie(lottie, visible, params) {
if (!lottie) return;
params = params || {};
clearTimeout(lottie.hideTimeout);
if (visible) {
lottie.player.play();
} else {
lottie.player.stop();
if (params.hideDelay) {
lottie.hideTimeout = setTimeout(() => {
lottie.ctx.clearRect(0, 0, 1000, 1000);
}, params.hideDelay);
} else {
lottie.ctx.clearRect(0, 0, 1000, 1000);
}
}
}
;// CONCATENATED MODULE: ./src/js/view/DropDown.js
class DropDown {
/**
* @param container {HTMLElement}
* @param onEnter {(input: HTMLInputElement) => void}
* @param mnemonicWords {string[]}
*/
constructor(container, onEnter, mnemonicWords) {
/** @type {HTMLElement} */
this.container = container;
/** @type {(input: HTMLInputElement) => void} */
this.onEnter = onEnter;
/** @type {string[]} */
this.mnemonicWords = mnemonicWords;
/** @type {number} */
this.selectedI = -1;
}
/**
* @param input {HTMLInputElement}
* @param text {string}
*/
show(input, text) {
clearElement(this.container);
/**
* @param e {MouseEvent}
*/
const onMouseDown = e => {
input.value = e.target.innerText;
input.classList.remove('error');
this.hide();
e.preventDefault();
this.onEnter(input);
};
this.mnemonicWords
.filter(w => w.indexOf(text) === 0)
.forEach(w => {
const item = createElement({tag: 'div', clazz: 'words-popup-item', text: w});
item.addEventListener('mousedown', onMouseDown);
this.container.appendChild(item);
});
this.selectedI = -1;
if (this.container.children.length > 0) this.select(0);
this.container.style.left = input.offsetLeft + 'px';
this.container.style.top = (input.offsetTop + input.offsetHeight) + 'px';
toggle(this.container, true);
};
hide() {
toggle(this.container, false);
clearElement(this.container);
this.selectedI = -1;
}
/**
* @param i {number}
*/
select(i) {
if (this.selectedI > -1) {
this.container.children[this.selectedI].classList.remove('selected');
}
this.selectedI = i;
if (this.selectedI > -1) {
this.container.children[this.selectedI].classList.add('selected');
const ITEM_HEIGHT = 30;
this.container.scrollTo(0, ITEM_HEIGHT * this.selectedI);
}
}
/**
* @return {null | string}
*/
getSelectedText() {
if (this.selectedI === -1) return null;
return this.container.children[this.selectedI].innerText;
}
up() {
if (this.selectedI === -1) return;
if (this.selectedI > 0) {
this.select(this.selectedI - 1);
}
}
down() {
if (this.selectedI === -1) return;
if (this.selectedI < this.container.children.length - 1) {
this.select(this.selectedI + 1);
}
}
}
;// CONCATENATED MODULE: ./src/js/view/View.js
const toNano = TonWeb.utils.toNano;
const fromNano = TonWeb.utils.fromNano;
const BN = TonWeb.utils.BN;
const IS_EXTENSION = !!(self.chrome && chrome.runtime && chrome.runtime.onConnect);
const IS_FIREFOX = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
/**
* @param text {string}
* @param containerSelector {string}
*/
const drawQRCode = (text, containerSelector) => {
const $container = $(containerSelector);
clearElement($container);
new QRCode($container, {
text: text,
width: 185 * window.devicePixelRatio,
height: 185 * window.devicePixelRatio,
colorDark: '#303757',
logo: "assets/ui/qr-logo.png",
logoBackgroundTransparent: false,
logoWidth: 44 * window.devicePixelRatio,
logoHeight: 44 * window.devicePixelRatio,
correctLevel: QRCode.CorrectLevel.L
});
const canvas = $container.querySelector('canvas');
canvas.style.width = '185px';
canvas.style.height = '185px';
};
class View {
/**
* @param mnemonicWords {string[]}
*/
constructor(mnemonicWords) {
/** @type {string[]} */
this.mnemonicWords = mnemonicWords;
/** @type {Controller | null} */
this.controller = null;
/** @type {any | null} */
this.port = null;
/** @type {string | null} */
this.myAddress = null;
/** @type {string | null} */
this.address = null;
/** @type {BN | null} */
this.balance = null;
/** @type {string | null} */
this.currentScreenName = null;
/** @type {boolean} */
this.isTestnet = false;
/** @type {string} */
this.popup = ''; // current opened popup name
/** @type {boolean} */
this.isBack = false;
/** @type {number} */
this.backupShownTime = 0;
/** @type {any | null} */
this.currentOpenTransaction = null;
/** @type {string | null} */
this.currentTransactionAddr = null;
this.createWordInputs({
count: IMPORT_WORDS_COUNT,
dropdownId: '#wordsPopup',
inputId: '#importsInput',
containerId: '#importWords',
multiColumns: true
});
this.createWordInputs({
count: CONFIRM_WORDS_COUNT,
dropdownId: '#wordsConfirmPopup',
inputId: '#confirmInput',
containerId: '#confirmWords',
multiColumns: false
});
/** @type {Promise} */
this._initLotties = initLotties().then(() => {
if (this.currentScreenName) {
toggleLottie(lotties[this.currentScreenName], true);
toggleLottie(lotties.symbol, this.currentScreenName === 'main');
}
});
/**
* @param e {Event}
*/
function resetErrors(e) {
const input = e.target;
input.classList.remove('error');
}
onInput($('#amountInput'), resetErrors);
onInput($('#toWalletInput'), resetErrors);
onInput($('#commentInput'), resetErrors);
onInput($('#createPassword_repeatInput'), resetErrors);
onInput($('#enterPassword_input'), resetErrors);
onInput($('#changePassword_oldInput'), resetErrors);
onInput($('#changePassword_newInput'), resetErrors);
onInput($('#changePassword_repeatInput'), resetErrors);
/**
* @param e {ClipboardEvent}
* @return {string}
*/
function getClipboardData(e) {
const s = (e.clipboardData || window.clipboardData).getData('text');
try {
return decodeURI(s).replaceAll(/%23/g, '#');
} catch (e) { // URIError
return s;
}
}
$('#toWalletInput').addEventListener('paste', e => {
const urlString = getClipboardData(e);
if (!urlString.startsWith('ton://')) return;
/** @type {{address: string, amount?: string, text?: string} | null } */
let parsedTransferUrl = null;
try {
parsedTransferUrl = TonWeb.utils.parseTransferUrl(urlString);
} catch (e) {
$('#notify').innerText = 'Parse transfer URL error';
triggerClass($('#notify'), 'faded-show', 2000);
return;
}
$('#toWalletInput').value = parsedTransferUrl.address;
if (parsedTransferUrl.amount) {
$('#amountInput').value = fromNano(new BN(parsedTransferUrl.amount));
}
if (parsedTransferUrl.text) {
$('#commentInput').value = parsedTransferUrl.text;
}
e.preventDefault();
});
onInput($('#invoice_amountInput'), () => this.updateInvoiceLink());
onInput($('#invoice_commentInput'), () => this.updateInvoiceLink());
$("#start_createBtn").addEventListener('click', () => this.sendMessage('showScreen', {name: 'created'}));
$("#start_importBtn").addEventListener('click', () => this.sendMessage('showScreen', {name: 'import'}));
/** @type {boolean} */
let needShowLedger = false;
try {
needShowLedger = window.location.href.indexOf('ledgerReview') > -1;
} catch (e) {
}
if (needShowLedger) {
toggle($("#start_importLedgerHidBtn"), 'inline-block');
}
$("#start_importLedgerHidBtn").addEventListener('click', () => {
this.showPopup('connectLedger');
this.sendMessage('showScreen', {name: 'importLedger', transportType: 'hid'});
});
// $("#start_importLedgerBleBtn").addEventListener('click', () => this.sendMessage('showScreen', {name: 'importLedger', transportType: 'ble'}));
// $('#main_buyBtn').addEventListener('click', () => {
// window.open('https://exchange.mercuryo.io/?currency=TONCOIN&address=' + this.myAddress, '_blank');
// });
$('#import_backBtn').addEventListener('click', () => {
this.isBack = true;
this.sendMessage('onImportBack');
});
$('#import_alertBtn').addEventListener('click', () => {
this.showAlert({
title: 'Too Bad',
message: 'Without the secret words, you can\'t restore access to your wallet.',
buttons: [
{
label: 'CANCEL',
callback: () => {
this.isBack = true;
this.sendMessage('onImportBack');
}
},
{
label: 'ENTER WORDS',
callback: () => {
this.closePopup();
}
},
]
});
});
$('#import_continueBtn').addEventListener('click', async (e) => {
this.toggleButtonLoader(e.currentTarget, true);
this.sendMessage('import', {words: await this.getImportWords()});
});
$('#createdContinueButton').addEventListener('click', () => this.sendMessage('createPrivateKey'));
$('#backup_continueBtn').addEventListener('click', () => {
const currentTime = Date.now();
if (currentTime - this.backupShownTime < 60000) { // 1 minute
this.showAlert({
title: 'Sure done?',
message: 'You didn\'t have enough time to write these words down.',
buttons: [
{
label: 'I\'M SURE',
callback: () => {
this.sendMessage('onBackupDone');
}
},
{
label: 'OK, SORRY',
callback: () => {
this.closePopup();
}
},
]
});
} else {
this.sendMessage('onBackupDone');
}
});
$('#wordsConfirm_backBtn').addEventListener('click', () => {
this.isBack = true;
this.sendMessage('onConfirmBack');
});
$('#wordsConfirm_continueBtn').addEventListener('click', () => {
const confirmWords = this.getConfirmWords();
if (!confirmWords.isWordsFromList) {
return;
}
if (!confirmWords.isRightWords) {
this.showAlert({
title: 'Incorrect words',
message: 'The secret words you have entered do not match the ones in the list.',
buttons: [
{
label: 'SEE WORDS',
callback: () => {
this.isBack = true;
this.sendMessage('onConfirmBack');
}
},
{
label: 'TRY AGAIN',
callback: () => {
this.closePopup();
}
},
]
});
} else {
this.sendMessage('onConfirmDone', {words: confirmWords.words});
}
});
$('#createPassword_continueBtn').addEventListener('click', (e) => {
/** @type {string} */
const password = $('#createPassword_input').value;
/** @type {string} */
const passwordRepeat = $('#createPassword_repeatInput').value;
const isEmpty = password.length === 0 && !this.isTestnet;
if (isEmpty) {
$('#createPassword_input').classList.add('error');
} else if (password !== passwordRepeat) {
$('#createPassword_repeatInput').classList.add('error');
} else {
this.toggleButtonLoader(e.currentTarget, true);
this.sendMessage('passwordCreated', {password});
}
});
$('#readyToGo_continueBtn').addEventListener('click', () => this.sendMessage('showMain'));
$('#main_refreshBtn').addEventListener('click', () => {
this.setUpdating(true);
this.sendMessage('update');
});
$('#main_settingsButton').addEventListener('click', () => this.onSettingsClick());
$('#main_receiveBtn').addEventListener('click', () => {
toggle($('#receive_showAddressOnDeviceBtn'), !!this.isLedger);
this.showPopup('receive');
});
$('#sendButton').addEventListener('click', () => this.onMessage('showPopup', {name: 'send'}));
$('#modal').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup();
});
if (IS_FIREFOX) {
toggle($('#menu_magic'), false);
toggle($('.about-magic'), false);
}
$('#menu_magic').addEventListener('click', () => {
$('#menu_magic .dropdown-toggle').classList.toggle('toggle-on');
const isTurnedOn = $('#menu_magic .dropdown-toggle').classList.contains('toggle-on');
$('#menu_telegram').classList.toggle('menu_telegram-show', isTurnedOn);
this.sendMessage('onMagicClick', isTurnedOn);
});
$('#menu_telegram').addEventListener('click', () => {
window.open('https://web.telegram.org/z', '_blank');
});
$('#menu_proxy').addEventListener('click', () => {
$('#menu_proxy .dropdown-toggle').classList.toggle('toggle-on');
this.sendMessage('onProxyClick', $('#menu_proxy .dropdown-toggle').classList.contains('toggle-on'));
});
$('#menu_extension_chrome').addEventListener('click', () => window.open('https://chrome.google.com/webstore/detail/ton-wallet/nphplpgoakhhjchkkhmiggakijnkhfnd', '_blank'));
$('#menu_extension_firefox').addEventListener('click', () => window.open('https://addons.mozilla.org/ru/firefox/addon/', '_blank'));
$('#menu_about').addEventListener('click', () => this.showPopup('about'));
$('#menu_changePassword').addEventListener('click', () => this.onMessage('showPopup', {name: 'changePassword'}));
$('#menu_backupWallet').addEventListener('click', () => this.sendMessage('onBackupWalletClick'));
$('#menu_delete').addEventListener('click', () => this.showPopup('delete'));
$('#receive_showAddressOnDeviceBtn').addEventListener('click', () => this.onShowAddressOnDevice());
$('#receive_invoiceBtn').addEventListener('click', () => this.onCreateInvoiceClick());
$('#receive_shareBtn').addEventListener('click', () => this.onShareAddressClick(false));
$('#receive .addr').addEventListener('click', () => this.onShareAddressClick(true));
$('#receive_closeBtn').addEventListener('click', () => this.closePopup());
$('#invoice_qrBtn').addEventListener('click', () => this.onCreateInvoiceQrClick());
$('#invoice_shareBtn').addEventListener('click', () => this.onShareInvoiceClick());
$('#invoice_closeBtn').addEventListener('click', () => this.showPopup('receive'));
$('#invoiceQr_shareBtn').addEventListener('click', () => this.onShareInvoiceClick());
$('#invoiceQr_closeBtn').addEventListener('click', () => this.showPopup('invoice'));
$('#transaction_sendBtn').addEventListener('click', () => this.onTransactionButtonClick());
$('#transaction_closeBtn').addEventListener('click', () => this.closePopup());
$('#connectLedger_cancelBtn').addEventListener('click', () => this.closePopup());
$('#send_btn').addEventListener('click', (e) => {
/** @type {string} */
const amount = $('#amountInput').value;
/** @type {BN} */
const amountNano = toNano(amount);
if (!amountNano.gt(new BN(0)) || this.balance.lt(amountNano)) {
$('#amountInput').classList.add('error');
return;
}
/** @type {string} */
const toAddressString = $('#toWalletInput').value;
/** @type {Address | null} */
let toAddress = null;
try {
toAddress = new TonWeb.utils.Address(toAddressString);
} catch (e) {
}
if (!toAddressString.toLowerCase().endsWith('.ton') && !toAddressString.toLowerCase().endsWith('.t.me') && !toAddress) {
$('#toWalletInput').classList.add('error');
return;
}
/** @type {string} */
const comment = $('#commentInput').value;
/** @type {boolean} */
const needEncryptComment = $('#encryptCommentCheckbox').checked;
if (comment.length > 1024) {
$('#commentInput').classList.add('error');
$('#notify').innerText = 'Maximum 1024 symbols';
triggerClass($('#notify'), 'faded-show', 2000);
return;
}
// from https://github.com/tonkeeper/ton-assets/blob/main/accounts.json with "require_memo": true
const exchangeAddresses = [
'0:5f00decb7da51881764dc3959cec60609045f6ca1b89e646bde49d492705d77f', // OKX
'0:b31535e934db05bbc220267467903c8108bdabcbc2a06588838b726ddf589ef0', // FTX
'0:57eb74407604a19f7e04005315ef70aeb7b675e6551977586756f6baf12125ee', // MEXC
'0:7994848c1fcbcbc57a6a5a987b66eb424b8b54e10759b6b514a66b600c2b0eef', // EXMO
'0:8d195793baad9a08c46dc353aebe999341dabd07721b9725f19e18abc3d10d92', // EXMO Cold Storage 1
'0:26ab8ae763a3a7c3067d882b7b01cd5d37254cb8768f57b6a47c00028effc7b8', // EXMO Cold Storage 2
'0:0130c77346e9ed82df677d107ad6a775c11f9c18f6a05c0dd17906b355850dad', // EXMO Deposit
'0:342a359e38357c083968129fddddf049ef5c47315bfbef27505a356bf9f02d65', // CoinEx
'0:555f3053e257130374bb831ae0e219e5e5f9ec0ca8f8a0d133369d3d690c64c2', // Huobi Deposit
'0:85af78e8d035e920117cda654615cdf371d464480b629e110d3c5310d85ab362', // Huobi
'0:80d4123841167ca989ac912443cc99a4b9c1a87584536427ff6fd85c92395ae9', // Kucoin
'0:a14b1f452385b2bb984ad2c4441e1d23cae071fdfc096dfba53ebba3b6ff1d10', // Lbank.info
'0:c3f1da8ecda8f8cd42bace224ea3f1b6971eaa7f54c492d4d190527b4f573f7c', // Bybit
'0:008bb088e81e38d583826901093567027cc1575ec744ac354fa4eeec302d166d', // bit.com
]
const isExchange = toAddress && (exchangeAddresses.indexOf(toAddress.toString(false)) > -1);
if (isExchange) {
if (!comment) {
$('#notify').innerText = 'Exchange require text comment (MEMO) for deposit';
triggerClass($('#notify'), 'faded-show', 2000);
return;
}
if (comment && needEncryptComment) {
$('#notify').innerText = `Can't encrypt comment when depositing on exchange`;
triggerClass($('#notify'), 'faded-show', 2000);
return;
}
}
this.toggleButtonLoader(e.currentTarget, true);
this.sendMessage('onSend', {
amount: amountNano.toString(),
toAddress: toAddressString,
comment,
needEncryptComment
});
});
$('#send_closeBtn').addEventListener('click', () => this.closePopup());
$('#sendConfirm_closeBtn').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup();
});
$('#sendConfirm_cancelBtn').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup();
});
$('#sendConfirm_okBtn').addEventListener('click', () => this.onMessage('showPopup', {name: 'enterPassword'}));
$('#signConfirm_closeBtn').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup()
});
$('#signConfirm_cancelBtn').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup()
});
$('#signConfirm_okBtn').addEventListener('click', () => this.onMessage('showPopup', {name: 'enterPassword'}));
$('#connectConfirm_closeBtn').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup()
});
$('#connectConfirm_cancelBtn').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup()
});
$('#connectConfirm_okBtn').addEventListener('click', () => {
this.sendMessage('onConnectConfirmed', {});
});
$('#processing_closeBtn').addEventListener('click', () => this.closePopup());
$('#done_closeBtn').addEventListener('click', () => this.closePopup());
$('#about_closeBtn').addEventListener('click', () => this.closePopup());
$('#about_version').addEventListener('click', (e) => {
if (e.shiftKey) {
this.showAlert({
title: 'Are you sure you want to switch between mainnet/testnet?',
message: 'You can switch back the network by clicking on the version with the Shift key pressed',
buttons: [
{
label: 'I\'M SURE',
callback: () => {
this.sendMessage('toggleTestnet');
}
},
{
label: 'BACK',
callback: () => {
this.closePopup();
}
},
]
});
} else if (e.altKey) {
this.showAlert({
title: 'Are you sure you want to switch between clear console/debug mode?',
message: 'You can switch back the clear console by clicking on the version with the Alt key pressed',
buttons: [
{
label: 'I\'M SURE',
callback: () => {
this.sendMessage('toggleDebug');
}
},
{
label: 'BACK',
callback: () => {
this.closePopup();
}
},
]
});
}
});
$('#changePassword_cancelBtn').addEventListener('click', () => this.closePopup());
$('#changePassword_okBtn').addEventListener('click', async (e) => {
/** @type {string} */
const oldPassword = $('#changePassword_oldInput').value;
/** @type {string} */
const newPassword = $('#changePassword_newInput').value;
/** @type {string} */
const passwordRepeat = $('#changePassword_repeatInput').value;
const isEmpty = newPassword.length === 0 && !this.isTestnet;
if (isEmpty) {
$('#changePassword_newInput').classList.add('error');
return;
}
if (newPassword !== passwordRepeat) {
$('#changePassword_repeatInput').classList.add('error');
return;
}
this.toggleButtonLoader(e.currentTarget, true);
this.sendMessage('onChangePassword', {oldPassword, newPassword});
});
$('#enterPassword_cancelBtn').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup();
});
$('#enterPassword_okBtn').addEventListener('click', async (e) => {
/** @type {string} */
const password = $('#enterPassword_input').value;
this.toggleButtonLoader(e.currentTarget, true);
this.sendMessage('onEnterPassword', {password});
});
$('#delete_cancelBtn').addEventListener('click', () => this.closePopup());
$('#delete_okBtn').addEventListener('click', () => this.sendMessage('disconnect'));
$('#transactionDecryptCommentButton').addEventListener('click', () => {
if (!this.currentOpenTransaction) return;
this.sendMessage('decryptComment', {
hash: this.currentOpenTransaction.hash,
senderAddress: this.currentOpenTransaction.from_addr,
encryptedComment: this.currentOpenTransaction.encryptedComment,
});
});
}
// COMMON
/**
* @param name {string}
*/
showScreen(name) {
this.closePopup();
const screens = ['start', 'created', 'backup', 'wordsConfirm', 'import', 'createPassword', 'readyToGo', 'main'];
screens.forEach(screen => {
toggleFaded($('#' + screen), name === screen, {
isBack: this.isBack,
});
toggleLottie(lotties[screen], name === screen, {hideDelay: 300}); // 300ms, as for screen show/hide animation duration in CSS
});
toggleLottie(lotties.symbol, name === 'main', {hideDelay: 300});
this.currentScreenName = name;
this.isBack = false;
window.scrollTo(0, 0);
}
/**
* @param el {HTMLElement}
* @param enable {boolean}
*/
toggleButtonLoader(el, enable) {
el.disabled = enable;
enable ? el.classList.add('btn-loader') : el.classList.remove('btn-loader');
}
/**
* @param params {{title: string, message: string, buttons?: {label: string, callback: () => void}[]}}
*/
showAlert(params) {
$('#alert .popup-title').innerText = params.title;
$('#alert .popup-black-text').innerText = params.message;
$('#alert .popup-footer').innerHTML = '';
if (params.buttons) {
params.buttons.forEach(button => {
const el = createElement({
tag: 'button',
clazz: 'btn-lite',
text: button.label
});
$('#alert .popup-footer').appendChild(el);
el.addEventListener('click', button.callback);
});
}
this.showPopup('alert');
}
/**
* @param name {string}
*/
showPopup(name) {
this.popup = name;
$('#enterPassword_input').value = '';
//popups switching without animations
if (this.popup && name) {
triggerClass(document.body, 'disable-animations', 20);
}
toggleFaded($('#modal'), name !== '');
const popups = ['alert', 'receive', 'invoice', 'invoiceQr', 'send', 'sendConfirm', 'signConfirm', 'connectConfirm', 'processing', 'done', 'menuDropdown', 'about', 'delete', 'changePassword', 'enterPassword', 'transaction', 'connectLedger', 'loader'];
popups.forEach(popup => {
toggleFaded($('#' + popup), name === popup);
toggleLottie(lotties[popup], name === popup);
});
}
closePopup() {
this.currentOpenTransaction = null;
this.showPopup('');
this.sendMessage('onClosePopup');
}
// BACKUP SCREEN
/**
* @param words {string[]}
*/
setBackupWords(words) {
/**
* @param n {number}
*/
const createBackupWord = n => {
$('#createWords').appendChild(
createElement({
tag: 'div',
clazz: 'create-word-item',
child: [
createElement({
tag: 'span',
clazz: 'word-num',
text: (n + 1) + '.'
}),
createElement({
tag: 'span',
style: {
'font-weight': 'bold'
},
text: words[n]
})
]
})
);
};
clearElement($('#createWords'));
for (let i = 0; i < words.length / 2; i++) {
createBackupWord(i);
createBackupWord(i + 12);
}
}
clearBackupWords() {
clearElement($('#createWords'));
}
// IMPORT && CONFIRM SCREENS
/**
* @param params {{count: number, containerId: string, inputId: string, dropdownId: string, multiColumns: boolean}}
*/
createWordInputs(params) {
/**
* @param input {HTMLInputElement}
*/
const onEnter = input => {
const i = Number(input.getAttribute('tabindex'));
if (i === params.count) {
} else {
$(params.inputId + i).focus();
}
};
const dropdown = new DropDown($(params.dropdownId), onEnter, this.mnemonicWords);
/** @type {HTMLInputElement | null} */
let lastInput = null;
/**
* @param input {HTMLInputElement}
*/
const showWordsPopup = input => {
const text = input.value;
if (text === null || text.length === 0) {
toggle($(params.dropdownId), false);
return;
}
dropdown.show(input, text.toLowerCase());
};
/**
* @param e {Event}
*/
function onWordInput(e) {
/** @type {HTMLInputElement} */
const input = e.target;
input.classList.remove('error');
showWordsPopup(input);
}
/**
* @param e {Event}
*/
const onFocusIn = (e) => {
/** @type {HTMLInputElement} */
const input = e.target;
lastInput = input;
showWordsPopup(input);
};
/**
* @param e {Event}
*/
const onFocusOut = (e) => {
toggle($(params.dropdownId), false);
if (lastInput) {
const value = lastInput.value.toLowerCase().trim();
if (value.length > 0 && this.mnemonicWords.indexOf(value) === -1) {
lastInput.classList.add('error');
} else {
lastInput.classList.remove('error');
}
}
};
/**
* @param e {KeyboardEvent}
*/
const onKeyDown = (e) => {
/** @type {HTMLInputElement} */
const input = e.target;
switch (e.key) {
case 'Enter':
const selectedText = dropdown.getSelectedText();
if (selectedText) {
input.value = selectedText;
input.classList.remove('error');
dropdown.hide();
}
onEnter(input);
break;
case 'ArrowUp':
dropdown.up();
break;
case 'ArrowDown':
dropdown.down();
break;
}
};
/**
* @param event {ClipboardEvent}
*/
const onPaste = (event) => {
const text = (event.clipboardData || window.clipboardData).getData('text');
let arr = text.split(' ');
if (arr.length !== params.count) {
arr = text.split(',');
}
if (arr.length === params.count) {
for (let i = 0; i < params.count; i++) {
/** @type {HTMLInputElement} */
const input = $(params.inputId + i);
const value = arr[i].toLowerCase().trim();
if (!value || this.mnemonicWords.indexOf(value) === -1) {
input.classList.add('error');
} else {
input.classList.remove('error');
}
input.value = value;
}
event.preventDefault();
}
};
/**
* @param n {number}
*/
const createInput = (n) => {
const inputContainer = createElement({tag: 'div', clazz: 'word-item'});
const span = createElement({tag: 'span', clazz: 'word-num', text: (n + 1) + '.'});
inputContainer.appendChild(span);
/** @type {HTMLInputElement} */
const input = createElement({tag: 'input'});
input.id = params.inputId.slice(1) + n;
input.type = 'text';
input.tabIndex = n + 1;
input.autocomplete = 'off';
inputContainer.appendChild(input);
input.addEventListener('focusin', onFocusIn);
input.addEventListener('focusout', onFocusOut);
input.addEventListener('keydown', onKeyDown);
input.addEventListener('paste', onPaste);
onInput(input, onWordInput);
$(params.containerId).appendChild(inputContainer);
};
if (params.multiColumns) {
for (let i = 0; i < params.count / 2; i++) {
createInput(i);
createInput(i + params.count / 2);
}
} else {
for (let i = 0; i < params.count; i++) {
createInput(i);
}
}
}
clearImportWords() {
toggle($('#wordsPopup'), false);
for (let i = 0; i < IMPORT_WORDS_COUNT; i++) {
/** @type {HTMLInputElement} */
const input = $('#importsInput' + i);
input.value = '';
input.classList.remove('error');
}
}
clearConfirmWords() {
toggle($('#wordsConfirmPopup'), false);
for (let i = 0; i < CONFIRM_WORDS_COUNT; i++) {
/** @type {HTMLInputElement} */
const input = $('#confirmInput' + i);
input.value = '';
input.setAttribute('data-word', '');
input.classList.remove('error');
}
}
/**
* @param words {string[]}
*/
setConfirmWords(words) {
/** @type {number[]} */
const nums = Array(IMPORT_WORDS_COUNT)
.fill(0)
.map((_, index) => ({index, rnd: Math.random()}))
.sort((a, b) => a.rnd - b.rnd)
.map(item => item.index)
.slice(0, CONFIRM_WORDS_COUNT)
.sort((a, b) => a - b);
const spans = $$('#confirmWordsNums span');
for (let i = 0; i < CONFIRM_WORDS_COUNT; i++) {
/** @type {HTMLInputElement} */
const input = $('#confirmInput' + i);
input.setAttribute('data-index', nums[i].toString());
input.setAttribute('data-word', words[nums[i]]);
spans[i].innerText = (nums[i] + 1).toString();
input.parentNode.children[0].innerText = (nums[i] + 1) + '.';
}
}
/**
* @return {Promise}
*/
async getImportWords() {
/** @type {boolean} */
let isValid = true;
/** @type {string[]} */
const words = [];
for (let i = 0; i < IMPORT_WORDS_COUNT; i++) {
/** @type {HTMLInputElement} */
const input = $('#importsInput' + i);
/** @type {string} */
const value = input.value.toLowerCase().trim();
if (!value || this.mnemonicWords.indexOf(value) === -1) {
input.classList.add('error');
isValid = false;
}
words.push(value);
}
if (isValid) {
isValid = await TonWeb.mnemonic.validateMnemonic(words);
if (!isValid) {
for (let i = 0; i < IMPORT_WORDS_COUNT; i++) {
const input = $('#importsInput' + i);
input.classList.add('error');
}
}
}
return isValid ? words : null;
}
/**
* @return {{isWordsFromList: boolean, isRightWords: boolean, words: null | Object}} words - index to word
*/
getConfirmWords() {
/** @type {boolean} */
let isWordsFromList = true;
/** @type {boolean} */
let isRightWords = true;
/** @type {Object} */
const words = {};
for (let i = 0; i < CONFIRM_WORDS_COUNT; i++) {
/** @type {HTMLInputElement} */
const input = $('#confirmInput' + i);
/** @type {string} */
const value = input.value.toLowerCase().trim();
/** @type {string} */
const index = input.getAttribute('data-index');
/** @type {string} */
const validValue = input.getAttribute('data-word');
if (!value || this.mnemonicWords.indexOf(value) === -1) {
input.classList.add('error');
isWordsFromList = false;
}
if (value !== validValue) {
isRightWords = false;
}
words[index] = value;
}
return {
isWordsFromList,
isRightWords,
words: isWordsFromList && isRightWords ? words : null
};
}
// CREATE PASSWORD SCREEN
clearCreatePassword() {
$('#createPassword_input').value = '';
$('#createPassword_repeatInput').value = '';
}
// CHANGE PASSWORD POPUP
clearChangePassword() {
$('#changePassword_oldInput').value = '';
$('#changePassword_newInput').value = '';
$('#changePassword_repeatInput').value = '';
}
// MAIN SCREEN
/**
* @param updating {boolean}
*/
setUpdating(updating) {
$('#updateLabel').innerText = updating ? 'updating..' : 'updated just now';
}
onSettingsClick() {
toggleFaded($('#modal'), true);
toggleFaded($('#menuDropdown'), true);
toggle($('#menu_changePassword'), !this.isLedger);
toggle($('#menu_backupWallet'), !this.isLedger);
}
clearBalance() {
clearElement($('#balance'));
clearElement($('#transactionsList'));
toggle($('#walletCreated'), false);
}
/**
* @param balance {BN}
* @param txs {any[]}
*/
setBalance(balance, txs) {
this.balance = balance;
/** @type {string} */
let s = fromNano(balance);
if (s === '0') s = '0.00';
const i = s.indexOf('.');
const first = s.substring(0, i);
const last = s.substring(i);
clearElement($('#balance'));
$('#balance').appendChild(createElement({tag: 'span', text: first}));
$('#balance').appendChild(createElement({tag: 'span', style: {'font-size': '24px'}, text: last}));
$('#sendBalance').innerText = 'Balance: ' + s + ' 💎';
toggle($('#sendButton'), balance.gt(new BN(0)) ? 'inline-block' : 'none');
this.setTransactions(txs);
this.setUpdating(false);
}
/**
* @param txs {any[]}
*/
setTransactions(txs) {
clearElement($('#transactionsList'));
/** @type {string} */
let date = '';
toggle($('#walletCreated'), txs.length === 0);
txs.forEach(tx => {
tx.amount = new BN(tx.amount);
tx.fee = new BN(tx.fee);
tx.date = new Date(tx.date);
/** @type {string} */
const txDate = formatDate(tx.date);
if (date !== txDate) {
this.addDateSeparator(txDate);
date = txDate;
}
this.addTx(tx);
});
}
/**
* @param dateString {string}
*/
addDateSeparator(dateString) {
$('#transactionsList').appendChild(createElement({tag: 'div', clazz: 'date-separator', text: dateString}));
}
/**
* @param tx {any}
*/
addTx(tx) {
/** @type {boolean} */
const isReceive = tx.inbound;
/** @type {string} */
const amountFormatted = fromNano(tx.amount);
/** @type {string} */
const addr = isReceive ? tx.from_addr : tx.to_addr;
const item = createElement({
tag: 'div',
clazz: 'tx-item',
child: [
createElement({
tag: 'div',
child: isReceive ? [
createElement({
tag: 'span',
clazz: ['tx-amount', 'tx-amount-green'],
text: '+' + amountFormatted
}),
createElement({tag: 'span', text: ' 💎'}),
createElement({tag: 'span', clazz: 'tx-from', text: ' from:'})
] : [
createElement({tag: 'span', clazz: 'tx-amount', text: amountFormatted}),
createElement({tag: 'span', text: ' 💎'}),
createElement({tag: 'span', clazz: 'tx-from', text: ' to:'})
]
}),
setAddr(createElement({tag: 'div', clazz: ['tx-addr', 'addr']}), addr),
tx.encryptedComment ? createElement({tag: 'div', clazz: 'tx-item-encrypted-icon'}) : undefined,
tx.comment ? createElement({tag: 'div', clazz: 'tx-comment', text: tx.comment}) : undefined,
createElement({tag: 'div', clazz: 'tx-fee', text: `blockchain fees: ${fromNano(tx.fee)}`}),
createElement({tag: 'div', clazz: 'tx-item-date', text: formatTime(tx.date)})
]
});
item.addEventListener('click', () => this.onTransactionClick(tx));
$('#transactionsList').appendChild(item);
}
// TRANSACTION POPUP
/**
* @param tx {any}
*/
onTransactionClick(tx) {
this.currentOpenTransaction = tx;
this.showPopup('transaction');
/** @type {boolean} */
const isReceive = tx.inbound;
/** @type {string} */
const amountFormatted = fromNano(tx.amount);
/** @type {string} */
const addr = isReceive ? tx.from_addr : tx.to_addr;
this.currentTransactionAddr = addr;
$('#transactionAmount').innerText = (isReceive ? '+' + amountFormatted : amountFormatted) + ' 💎';
$('#transactionFee').innerText = fromNano(tx.fee) + ' transaction fee';
$('#transactionSenderLabel').innerText = isReceive ? 'Sender' : 'Recipient';
setAddr($('#transactionSender'), addr);
toggle($('#transactionCommentLabel'), !!tx.comment || !!tx.encryptedComment);
toggle($('#transactionDecryptCommentButton'), !!tx.encryptedComment);
toggle($('#transactionComment'), !!tx.comment);
$('#transactionComment').innerText = tx.comment;
$('#transactionDate').innerText = formatDateFull(tx.date);
}
onTransactionButtonClick() {
this.onMessage('showPopup', {name: 'send', toAddr: this.currentTransactionAddr});
}
// SEND POPUP
clearSend() {
$('#toWalletInput').value = '';
$('#amountInput').value = '';
$('#commentInput').value = '';
$('#encryptCommentCheckbox').checked = false;
}
// RECEIVE POPUP
/**
* @param address {string}
*/
setMyAddress(address) {
setAddr($('#receive .addr'), address);
drawQRCode(TonWeb.utils.formatTransferUrl(address), '#qr');
this.address = address;
this.loadDiamond(address);
}
/**
* @param address {string}
* @return {Promise}
*/
async loadDiamond(address) {
toggle($('.balance-symbol'), true);
toggle($('.balance-diamond-container'), false);
toggle($('#diamond'), false);
try {
if (this.isTestnet) return;
const res = await fetch('https://ton.diamonds/api/wallet/diamond_nfts?address=' + address + '&perPage=1¤t=1');
if (res.status !== 200) return;
const json = await res.json();
if (json.ok !== true) return;
if (json.result.total < 1) return;
const nftNumber = json.result.rows[0].nftNumber;
const diamondImageUrl = 'https://nft.ton.diamonds/nft/' + nftNumber + '/' + nftNumber + '_diamond.svg';
if (address === this.address) {
toggle($('.balance-symbol'), false);
$('#diamond').style.backgroundImage = 'url("' + diamondImageUrl + '")';
toggle($('.balance-diamond-container'), true);
toggle($('#diamond'), true);
}
} catch (e) {
console.error('Diamonds Error', e);
}
}
/**
* @param onyAddress {boolean} share address or transfer link
*/
onShareAddressClick(onyAddress) {
const data = onyAddress ? this.myAddress : TonWeb.utils.formatTransferUrl(this.myAddress);
const text = onyAddress ? 'Wallet address copied to clipboard' : 'Transfer link copied to clipboard';
$('#notify').innerText = copyToClipboard(data) ? text : 'Can\'t copy link';
triggerClass($('#notify'), 'faded-show', 2000);
}
onShowAddressOnDevice() {
this.sendMessage('showAddressOnDevice');
$('#notify').innerText = 'Please check the address on your device';
triggerClass($('#notify'), 'faded-show', 2000);
}
// RECEIVE INVOICE POPUP
onCreateInvoiceClick() {
this.onMessage('showPopup', {name: 'invoice'});
}
updateInvoiceLink() {
$('#invoice_link').innerText = this.getInvoiceLink();
};
/**
* @return {string}
*/
getInvoiceLink() {
const amountString = $('#invoice_amountInput').value;
/** @type {string | undefined} */
const amount = amountString ? toNano(amountString).toString() : undefined;
return TonWeb.utils.formatTransferUrl(this.myAddress, amount, $('#invoice_commentInput').value);
}
onShareInvoiceClick() {
$('#notify').innerText = copyToClipboard(this.getInvoiceLink()) ? 'Transfer link copied to clipboard' : 'Can\'t copy link';
triggerClass($('#notify'), 'faded-show', 2000);
}
// RECEIVE INVOICE QR POPUP
onCreateInvoiceQrClick() {
this.onMessage('showPopup', {name: 'invoiceQr'});
}
/**
* @param link {string}
*/
drawInvoiceQr(link) {
drawQRCode(link, '#invoiceQrImg');
}
// TRANSPORT WITH CONTROLLER
/**
* Send message to Controller.js
* @param method {string}
* @param params? {any} boolean or object, not array
*/
sendMessage(method, params) {
if (this.controller) {
this.controller.onViewMessage(method, params);
} else {
this.port.postMessage({method, params});
}
}
/**
* Receive message from Controller.js
* @param method {string}
* @param params? {any} boolean or object, not array
* @return {undefined | {magic: string | null, proxy: string | null, address: string | null, words: string | null, walletVersion: string | null}}
*/
onMessage(method, params) {
switch (method) {
case 'disableCreated':
$('#createdContinueButton').disabled = params;
break;
case 'setIsTestnet':
this.isTestnet = params;
$('.your-balance').innerText = params ? 'Your testnet balance' : 'Your mainnet balance';
break;
case 'setBalance':
this.setBalance(new BN(params.balance), params.txs);
break;
case 'setIsLedger':
this.isLedger = params;
break;
case 'setIsMagic':
const isTurnedOn = params;
$('#menu_magic .dropdown-toggle').classList.toggle('toggle-on', isTurnedOn && !IS_FIREFOX);
$('#menu_telegram').classList.toggle('menu_telegram-show', isTurnedOn && !IS_FIREFOX);
break;
case 'setIsProxy':
if (params) {
$('#menu_proxy .dropdown-toggle').classList.add('toggle-on');
} else {
$('#menu_proxy .dropdown-toggle').classList.remove('toggle-on');
}
break;
case 'privateKeySaved':
this.toggleButtonLoader($('#createPassword_continueBtn'), false);
break;
case 'passwordChanged':
this.toggleButtonLoader($('#changePassword_okBtn'), false);
break;
case 'showChangePasswordError':
this.toggleButtonLoader($('#changePassword_okBtn'), false);
$('#changePassword_oldInput').classList.add('error');
break;
case 'passwordEntered':
this.toggleButtonLoader($('#enterPassword_okBtn'), false);
break;
case 'showEnterPasswordError':
this.toggleButtonLoader($('#enterPassword_okBtn'), false);
$('#enterPassword_input').classList.add('error');
break;
case 'importCompleted':
this.toggleButtonLoader($('#import_continueBtn'), false);
break;
case 'sendCheckFailed':
if (params && params.message) {
$('#notify').innerText = params.message;
triggerClass($('#notify'), 'faded-show', 3000);
}
this.toggleButtonLoader($('#send_btn'), false);
break;
case 'sendCheckSucceeded':
this.toggleButtonLoader($('#send_btn'), false);
break;
case 'sendCheckCantPublicKey':
this.toggleButtonLoader($('#send_btn'), false);
$('#notify').innerText = `To encrypt a message, the destination wallet must have at least one outgoing transfer`;
triggerClass($('#notify'), 'faded-show', 3000);
break;
case 'sendCheckCantPayFee':
this.toggleButtonLoader($('#send_btn'), false);
$('#amountInput').classList.add('error');
$('#notify').innerText = `Estimated fee is ~${fromNano(params.fee)} TON`;
triggerClass($('#notify'), 'faded-show', 3000);
break;
case 'decryptedComment':
if (this.currentOpenTransaction && this.currentOpenTransaction.hash === params.hash) {
this.currentOpenTransaction.encryptedComment = null;
this.currentOpenTransaction.comment = params.decryptedComment;
this.onTransactionClick(this.currentOpenTransaction);
}
break;
case 'showScreen':
if (params.noAnimation) {
triggerClass(document.body, 'disable-animations', 300);
}
this.showScreen(params.name);
switch (params.name) {
case 'start':
this.clearBalance();
this.clearImportWords();
break;
case 'created':
break;
case 'import':
this.clearImportWords();
$('#importsInput0').focus();
break;
case 'backup':
this.clearConfirmWords();
this.setBackupWords(params.words);
this.backupShownTime = params.isFirst ? (+new Date()) : 0;
break;
case 'wordsConfirm':
this.clearConfirmWords();
this.clearBackupWords();
$('#confirmInput0').focus();
this.setConfirmWords(params.words);
break;
case 'createPassword':
this.clearImportWords();
this.clearConfirmWords();
this.clearCreatePassword();
$('#createPassword_input').focus();
break;
case 'readyToGo':
this.clearCreatePassword();
break;
case 'main':
this.clearBackupWords();
if (params.myAddress) {
this.myAddress = params.myAddress;
this.setMyAddress(params.myAddress);
}
break;
}
break;
case 'showPopup':
this.showPopup(params.name);
switch (params.name) {
case 'changePassword':
this.clearChangePassword();
$('#changePassword_oldInput').focus();
break;
case 'enterPassword':
$('#enterPassword_input').focus();
break;
case 'done':
$('#done .popup-grey-text').innerText = params.message;
break;
case 'invoice':
$('#invoice_amountInput').value = '';
$('#invoice_commentInput').value = '';
this.updateInvoiceLink();
$('#invoice_amountInput').focus();
break;
case 'invoiceQr':
this.drawInvoiceQr(this.getInvoiceLink());
$('#invoiceQrAmount').innerText = $('#invoice_amountInput').value;
break;
case 'send':
this.clearSend();
if (params.toAddr) {
$('#toWalletInput').value = params.toAddr;
}
toggle($('#commentInput'), !this.isLedger);
toggle($('#encryptCommentCheckboxContainer'), !this.isLedger ? 'flex' : false);
$('#toWalletInput').focus();
break;
case 'sendConfirm':
$('#sendConfirmAmount').innerText = fromNano(new BN(params.amount)) + ' TON';
setAddr($('#sendConfirmAddr'), params.toAddress);
$('#sendConfirmFee').innerText = params.fee ? 'Fee: ~' + fromNano(new BN(params.fee)) + ' TON' : '';
toggle($('#sendConfirmNotEncryptedNote'), !params.needEncryptComment);
toggle($('#sendConfirm .popup-footer'), !this.isLedger);
toggle($('#sendConfirm_closeBtn'), !this.isLedger);
// todo: show label 'Please approve on device'
break;
case 'signConfirm':
$('#signConfirmText').innerText = params.isConnect ? 'Do you want to connect your wallet to this page?' : 'Do you want to sign:';
toggle($('#signConfirmData'), !params.isConnect);
toggle($('#signConfirmAlert'), !params.isConnect);
const hex = params.data.length > 48 ? params.data.substring(0, 47) + '…' : params.data;
setAddr($('#signConfirmData'), hex);
break;
case 'connectConfirm':
break;
}
break;
case 'closePopup':
this.closePopup();
break;
case 'restoreDeprecatedStorage':
const address = localStorage.getItem('address');
const words = localStorage.getItem('words');
const walletVersion = localStorage.getItem('walletVersion');
const magic = localStorage.getItem('magic');
const proxy = localStorage.getItem('proxy');
localStorage.clear();
return {address, words, walletVersion, magic, proxy};
}
}
}
window.view = new View(TonWeb.mnemonic.wordlists.EN);
if (IS_EXTENSION) {
// connect to background process
const connectToBackground = () => {
const port = chrome.runtime.connect({name: 'gramWalletPopup'});
window.view.port = port;
port.onMessage.addListener(data => {
const result = window.view.onMessage(data.method, data.params);
if (result && data.id) {
port.postMessage({method: 'response', id: data.id, result});
}
});
port.onDisconnect.addListener(() => {
connectToBackground();
});
}
connectToBackground();
// remember extension position and size
const startTrackWindowPositionAndSize = async () => {
let prevWindow = await chrome.windows.getCurrent();
setInterval(async () => {
const currentWindow = await chrome.windows.getCurrent();
if (
currentWindow.top !== prevWindow.top ||
currentWindow.left !== prevWindow.left ||
currentWindow.height !== prevWindow.height ||
currentWindow.width !== prevWindow.width
) {
prevWindow = currentWindow;
window.view.sendMessage('onWindowUpdate', {
top: currentWindow.top,
left: currentWindow.left,
height: currentWindow.height,
width: currentWindow.width
});
}
}, 3000);
}
startTrackWindowPositionAndSize();
}
// show attention message in browser console
if (window.top == window && window.console) {
/** @type {Object} */
const selfXssAttentions = {
'ru-RU': ['Внимание!', 'Используя эту консоль, вы можете подвергнуться атаке Self-XSS, что позволит злоумышленникам завладеть вашим кошельком.\nНе вводите и не вставляйте программный код, который не понимаете.'],
'*': ['Attention!', 'Using this console, you can be exposed to a Self-XSS attack, allowing attackers to take over your wallet.\nDo not enter or paste program code that you do not understand.']
};
/** @type {string} */
const userLanguage = navigator.language || navigator.userLanguage;
/** @type {string[]} */
let localizedSelfXssAttention = selfXssAttentions[userLanguage];
if (!localizedSelfXssAttention) localizedSelfXssAttention = selfXssAttentions['*'];
console.log(
'%c%s', 'color: red; background: yellow; font-size: 24px;', localizedSelfXssAttention[0]
);
console.log('%c%s', 'font-size: 18px;', localizedSelfXssAttention[1]);
}
/******/ })()
;
================================================
FILE: docs/libs/aes-js-3.1.2.js
================================================
/*! MIT License. Copyright 2015-2018 Richard Moore . See LICENSE.txt. */
(function(root) {
"use strict";
function checkInt(value) {
return (parseInt(value) === value);
}
function checkInts(arrayish) {
if (!checkInt(arrayish.length)) { return false; }
for (var i = 0; i < arrayish.length; i++) {
if (!checkInt(arrayish[i]) || arrayish[i] < 0 || arrayish[i] > 255) {
return false;
}
}
return true;
}
function coerceArray(arg, copy) {
// ArrayBuffer view
if (arg.buffer && arg.name === 'Uint8Array') {
if (copy) {
if (arg.slice) {
arg = arg.slice();
} else {
arg = Array.prototype.slice.call(arg);
}
}
return arg;
}
// It's an array; check it is a valid representation of a byte
if (Array.isArray(arg)) {
if (!checkInts(arg)) {
throw new Error('Array contains invalid value: ' + arg);
}
return new Uint8Array(arg);
}
// Something else, but behaves like an array (maybe a Buffer? Arguments?)
if (checkInt(arg.length) && checkInts(arg)) {
return new Uint8Array(arg);
}
throw new Error('unsupported array-like object');
}
function createArray(length) {
return new Uint8Array(length);
}
function copyArray(sourceArray, targetArray, targetStart, sourceStart, sourceEnd) {
if (sourceStart != null || sourceEnd != null) {
if (sourceArray.slice) {
sourceArray = sourceArray.slice(sourceStart, sourceEnd);
} else {
sourceArray = Array.prototype.slice.call(sourceArray, sourceStart, sourceEnd);
}
}
targetArray.set(sourceArray, targetStart);
}
var convertUtf8 = (function() {
function toBytes(text) {
var result = [], i = 0;
text = encodeURI(text);
while (i < text.length) {
var c = text.charCodeAt(i++);
// if it is a % sign, encode the following 2 bytes as a hex value
if (c === 37) {
result.push(parseInt(text.substr(i, 2), 16))
i += 2;
// otherwise, just the actual byte
} else {
result.push(c)
}
}
return coerceArray(result);
}
function fromBytes(bytes) {
var result = [], i = 0;
while (i < bytes.length) {
var c = bytes[i];
if (c < 128) {
result.push(String.fromCharCode(c));
i++;
} else if (c > 191 && c < 224) {
result.push(String.fromCharCode(((c & 0x1f) << 6) | (bytes[i + 1] & 0x3f)));
i += 2;
} else {
result.push(String.fromCharCode(((c & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f)));
i += 3;
}
}
return result.join('');
}
return {
toBytes: toBytes,
fromBytes: fromBytes,
}
})();
var convertHex = (function() {
function toBytes(text) {
var result = [];
for (var i = 0; i < text.length; i += 2) {
result.push(parseInt(text.substr(i, 2), 16));
}
return result;
}
// http://ixti.net/development/javascript/2011/11/11/base64-encodedecode-of-utf8-in-browser-with-js.html
var Hex = '0123456789abcdef';
function fromBytes(bytes) {
var result = [];
for (var i = 0; i < bytes.length; i++) {
var v = bytes[i];
result.push(Hex[(v & 0xf0) >> 4] + Hex[v & 0x0f]);
}
return result.join('');
}
return {
toBytes: toBytes,
fromBytes: fromBytes,
}
})();
// Number of rounds by keysize
var numberOfRounds = {16: 10, 24: 12, 32: 14}
// Round constant words
var rcon = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91];
// S-box and Inverse S-box (S is for Substitution)
var S = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16];
var Si =[0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d];
// Transformations for encryption
var T1 = [0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a];
var T2 = [0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616];
var T3 = [0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16];
var T4 = [0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c];
// Transformations for decryption
var T5 = [0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742];
var T6 = [0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, 0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10, 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015, 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, 0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, 0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, 0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, 0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8, 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6, 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, 0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95, 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857];
var T7 = [0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3, 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, 0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655, 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, 0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, 0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, 0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, 0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, 0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, 0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8];
var T8 = [0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, 0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9, 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced, 0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4, 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60, 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, 0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, 0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, 0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff, 0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0];
// Transformations for decryption key expansion
var U1 = [0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3];
var U2 = [0x00000000, 0x0b0e090d, 0x161c121a, 0x1d121b17, 0x2c382434, 0x27362d39, 0x3a24362e, 0x312a3f23, 0x58704868, 0x537e4165, 0x4e6c5a72, 0x4562537f, 0x74486c5c, 0x7f466551, 0x62547e46, 0x695a774b, 0xb0e090d0, 0xbbee99dd, 0xa6fc82ca, 0xadf28bc7, 0x9cd8b4e4, 0x97d6bde9, 0x8ac4a6fe, 0x81caaff3, 0xe890d8b8, 0xe39ed1b5, 0xfe8ccaa2, 0xf582c3af, 0xc4a8fc8c, 0xcfa6f581, 0xd2b4ee96, 0xd9bae79b, 0x7bdb3bbb, 0x70d532b6, 0x6dc729a1, 0x66c920ac, 0x57e31f8f, 0x5ced1682, 0x41ff0d95, 0x4af10498, 0x23ab73d3, 0x28a57ade, 0x35b761c9, 0x3eb968c4, 0x0f9357e7, 0x049d5eea, 0x198f45fd, 0x12814cf0, 0xcb3bab6b, 0xc035a266, 0xdd27b971, 0xd629b07c, 0xe7038f5f, 0xec0d8652, 0xf11f9d45, 0xfa119448, 0x934be303, 0x9845ea0e, 0x8557f119, 0x8e59f814, 0xbf73c737, 0xb47dce3a, 0xa96fd52d, 0xa261dc20, 0xf6ad766d, 0xfda37f60, 0xe0b16477, 0xebbf6d7a, 0xda955259, 0xd19b5b54, 0xcc894043, 0xc787494e, 0xaedd3e05, 0xa5d33708, 0xb8c12c1f, 0xb3cf2512, 0x82e51a31, 0x89eb133c, 0x94f9082b, 0x9ff70126, 0x464de6bd, 0x4d43efb0, 0x5051f4a7, 0x5b5ffdaa, 0x6a75c289, 0x617bcb84, 0x7c69d093, 0x7767d99e, 0x1e3daed5, 0x1533a7d8, 0x0821bccf, 0x032fb5c2, 0x32058ae1, 0x390b83ec, 0x241998fb, 0x2f1791f6, 0x8d764dd6, 0x867844db, 0x9b6a5fcc, 0x906456c1, 0xa14e69e2, 0xaa4060ef, 0xb7527bf8, 0xbc5c72f5, 0xd50605be, 0xde080cb3, 0xc31a17a4, 0xc8141ea9, 0xf93e218a, 0xf2302887, 0xef223390, 0xe42c3a9d, 0x3d96dd06, 0x3698d40b, 0x2b8acf1c, 0x2084c611, 0x11aef932, 0x1aa0f03f, 0x07b2eb28, 0x0cbce225, 0x65e6956e, 0x6ee89c63, 0x73fa8774, 0x78f48e79, 0x49deb15a, 0x42d0b857, 0x5fc2a340, 0x54ccaa4d, 0xf741ecda, 0xfc4fe5d7, 0xe15dfec0, 0xea53f7cd, 0xdb79c8ee, 0xd077c1e3, 0xcd65daf4, 0xc66bd3f9, 0xaf31a4b2, 0xa43fadbf, 0xb92db6a8, 0xb223bfa5, 0x83098086, 0x8807898b, 0x9515929c, 0x9e1b9b91, 0x47a17c0a, 0x4caf7507, 0x51bd6e10, 0x5ab3671d, 0x6b99583e, 0x60975133, 0x7d854a24, 0x768b4329, 0x1fd13462, 0x14df3d6f, 0x09cd2678, 0x02c32f75, 0x33e91056, 0x38e7195b, 0x25f5024c, 0x2efb0b41, 0x8c9ad761, 0x8794de6c, 0x9a86c57b, 0x9188cc76, 0xa0a2f355, 0xabacfa58, 0xb6bee14f, 0xbdb0e842, 0xd4ea9f09, 0xdfe49604, 0xc2f68d13, 0xc9f8841e, 0xf8d2bb3d, 0xf3dcb230, 0xeecea927, 0xe5c0a02a, 0x3c7a47b1, 0x37744ebc, 0x2a6655ab, 0x21685ca6, 0x10426385, 0x1b4c6a88, 0x065e719f, 0x0d507892, 0x640a0fd9, 0x6f0406d4, 0x72161dc3, 0x791814ce, 0x48322bed, 0x433c22e0, 0x5e2e39f7, 0x552030fa, 0x01ec9ab7, 0x0ae293ba, 0x17f088ad, 0x1cfe81a0, 0x2dd4be83, 0x26dab78e, 0x3bc8ac99, 0x30c6a594, 0x599cd2df, 0x5292dbd2, 0x4f80c0c5, 0x448ec9c8, 0x75a4f6eb, 0x7eaaffe6, 0x63b8e4f1, 0x68b6edfc, 0xb10c0a67, 0xba02036a, 0xa710187d, 0xac1e1170, 0x9d342e53, 0x963a275e, 0x8b283c49, 0x80263544, 0xe97c420f, 0xe2724b02, 0xff605015, 0xf46e5918, 0xc544663b, 0xce4a6f36, 0xd3587421, 0xd8567d2c, 0x7a37a10c, 0x7139a801, 0x6c2bb316, 0x6725ba1b, 0x560f8538, 0x5d018c35, 0x40139722, 0x4b1d9e2f, 0x2247e964, 0x2949e069, 0x345bfb7e, 0x3f55f273, 0x0e7fcd50, 0x0571c45d, 0x1863df4a, 0x136dd647, 0xcad731dc, 0xc1d938d1, 0xdccb23c6, 0xd7c52acb, 0xe6ef15e8, 0xede11ce5, 0xf0f307f2, 0xfbfd0eff, 0x92a779b4, 0x99a970b9, 0x84bb6bae, 0x8fb562a3, 0xbe9f5d80, 0xb591548d, 0xa8834f9a, 0xa38d4697];
var U3 = [0x00000000, 0x0d0b0e09, 0x1a161c12, 0x171d121b, 0x342c3824, 0x3927362d, 0x2e3a2436, 0x23312a3f, 0x68587048, 0x65537e41, 0x724e6c5a, 0x7f456253, 0x5c74486c, 0x517f4665, 0x4662547e, 0x4b695a77, 0xd0b0e090, 0xddbbee99, 0xcaa6fc82, 0xc7adf28b, 0xe49cd8b4, 0xe997d6bd, 0xfe8ac4a6, 0xf381caaf, 0xb8e890d8, 0xb5e39ed1, 0xa2fe8cca, 0xaff582c3, 0x8cc4a8fc, 0x81cfa6f5, 0x96d2b4ee, 0x9bd9bae7, 0xbb7bdb3b, 0xb670d532, 0xa16dc729, 0xac66c920, 0x8f57e31f, 0x825ced16, 0x9541ff0d, 0x984af104, 0xd323ab73, 0xde28a57a, 0xc935b761, 0xc43eb968, 0xe70f9357, 0xea049d5e, 0xfd198f45, 0xf012814c, 0x6bcb3bab, 0x66c035a2, 0x71dd27b9, 0x7cd629b0, 0x5fe7038f, 0x52ec0d86, 0x45f11f9d, 0x48fa1194, 0x03934be3, 0x0e9845ea, 0x198557f1, 0x148e59f8, 0x37bf73c7, 0x3ab47dce, 0x2da96fd5, 0x20a261dc, 0x6df6ad76, 0x60fda37f, 0x77e0b164, 0x7aebbf6d, 0x59da9552, 0x54d19b5b, 0x43cc8940, 0x4ec78749, 0x05aedd3e, 0x08a5d337, 0x1fb8c12c, 0x12b3cf25, 0x3182e51a, 0x3c89eb13, 0x2b94f908, 0x269ff701, 0xbd464de6, 0xb04d43ef, 0xa75051f4, 0xaa5b5ffd, 0x896a75c2, 0x84617bcb, 0x937c69d0, 0x9e7767d9, 0xd51e3dae, 0xd81533a7, 0xcf0821bc, 0xc2032fb5, 0xe132058a, 0xec390b83, 0xfb241998, 0xf62f1791, 0xd68d764d, 0xdb867844, 0xcc9b6a5f, 0xc1906456, 0xe2a14e69, 0xefaa4060, 0xf8b7527b, 0xf5bc5c72, 0xbed50605, 0xb3de080c, 0xa4c31a17, 0xa9c8141e, 0x8af93e21, 0x87f23028, 0x90ef2233, 0x9de42c3a, 0x063d96dd, 0x0b3698d4, 0x1c2b8acf, 0x112084c6, 0x3211aef9, 0x3f1aa0f0, 0x2807b2eb, 0x250cbce2, 0x6e65e695, 0x636ee89c, 0x7473fa87, 0x7978f48e, 0x5a49deb1, 0x5742d0b8, 0x405fc2a3, 0x4d54ccaa, 0xdaf741ec, 0xd7fc4fe5, 0xc0e15dfe, 0xcdea53f7, 0xeedb79c8, 0xe3d077c1, 0xf4cd65da, 0xf9c66bd3, 0xb2af31a4, 0xbfa43fad, 0xa8b92db6, 0xa5b223bf, 0x86830980, 0x8b880789, 0x9c951592, 0x919e1b9b, 0x0a47a17c, 0x074caf75, 0x1051bd6e, 0x1d5ab367, 0x3e6b9958, 0x33609751, 0x247d854a, 0x29768b43, 0x621fd134, 0x6f14df3d, 0x7809cd26, 0x7502c32f, 0x5633e910, 0x5b38e719, 0x4c25f502, 0x412efb0b, 0x618c9ad7, 0x6c8794de, 0x7b9a86c5, 0x769188cc, 0x55a0a2f3, 0x58abacfa, 0x4fb6bee1, 0x42bdb0e8, 0x09d4ea9f, 0x04dfe496, 0x13c2f68d, 0x1ec9f884, 0x3df8d2bb, 0x30f3dcb2, 0x27eecea9, 0x2ae5c0a0, 0xb13c7a47, 0xbc37744e, 0xab2a6655, 0xa621685c, 0x85104263, 0x881b4c6a, 0x9f065e71, 0x920d5078, 0xd9640a0f, 0xd46f0406, 0xc372161d, 0xce791814, 0xed48322b, 0xe0433c22, 0xf75e2e39, 0xfa552030, 0xb701ec9a, 0xba0ae293, 0xad17f088, 0xa01cfe81, 0x832dd4be, 0x8e26dab7, 0x993bc8ac, 0x9430c6a5, 0xdf599cd2, 0xd25292db, 0xc54f80c0, 0xc8448ec9, 0xeb75a4f6, 0xe67eaaff, 0xf163b8e4, 0xfc68b6ed, 0x67b10c0a, 0x6aba0203, 0x7da71018, 0x70ac1e11, 0x539d342e, 0x5e963a27, 0x498b283c, 0x44802635, 0x0fe97c42, 0x02e2724b, 0x15ff6050, 0x18f46e59, 0x3bc54466, 0x36ce4a6f, 0x21d35874, 0x2cd8567d, 0x0c7a37a1, 0x017139a8, 0x166c2bb3, 0x1b6725ba, 0x38560f85, 0x355d018c, 0x22401397, 0x2f4b1d9e, 0x642247e9, 0x692949e0, 0x7e345bfb, 0x733f55f2, 0x500e7fcd, 0x5d0571c4, 0x4a1863df, 0x47136dd6, 0xdccad731, 0xd1c1d938, 0xc6dccb23, 0xcbd7c52a, 0xe8e6ef15, 0xe5ede11c, 0xf2f0f307, 0xfffbfd0e, 0xb492a779, 0xb999a970, 0xae84bb6b, 0xa38fb562, 0x80be9f5d, 0x8db59154, 0x9aa8834f, 0x97a38d46];
var U4 = [0x00000000, 0x090d0b0e, 0x121a161c, 0x1b171d12, 0x24342c38, 0x2d392736, 0x362e3a24, 0x3f23312a, 0x48685870, 0x4165537e, 0x5a724e6c, 0x537f4562, 0x6c5c7448, 0x65517f46, 0x7e466254, 0x774b695a, 0x90d0b0e0, 0x99ddbbee, 0x82caa6fc, 0x8bc7adf2, 0xb4e49cd8, 0xbde997d6, 0xa6fe8ac4, 0xaff381ca, 0xd8b8e890, 0xd1b5e39e, 0xcaa2fe8c, 0xc3aff582, 0xfc8cc4a8, 0xf581cfa6, 0xee96d2b4, 0xe79bd9ba, 0x3bbb7bdb, 0x32b670d5, 0x29a16dc7, 0x20ac66c9, 0x1f8f57e3, 0x16825ced, 0x0d9541ff, 0x04984af1, 0x73d323ab, 0x7ade28a5, 0x61c935b7, 0x68c43eb9, 0x57e70f93, 0x5eea049d, 0x45fd198f, 0x4cf01281, 0xab6bcb3b, 0xa266c035, 0xb971dd27, 0xb07cd629, 0x8f5fe703, 0x8652ec0d, 0x9d45f11f, 0x9448fa11, 0xe303934b, 0xea0e9845, 0xf1198557, 0xf8148e59, 0xc737bf73, 0xce3ab47d, 0xd52da96f, 0xdc20a261, 0x766df6ad, 0x7f60fda3, 0x6477e0b1, 0x6d7aebbf, 0x5259da95, 0x5b54d19b, 0x4043cc89, 0x494ec787, 0x3e05aedd, 0x3708a5d3, 0x2c1fb8c1, 0x2512b3cf, 0x1a3182e5, 0x133c89eb, 0x082b94f9, 0x01269ff7, 0xe6bd464d, 0xefb04d43, 0xf4a75051, 0xfdaa5b5f, 0xc2896a75, 0xcb84617b, 0xd0937c69, 0xd99e7767, 0xaed51e3d, 0xa7d81533, 0xbccf0821, 0xb5c2032f, 0x8ae13205, 0x83ec390b, 0x98fb2419, 0x91f62f17, 0x4dd68d76, 0x44db8678, 0x5fcc9b6a, 0x56c19064, 0x69e2a14e, 0x60efaa40, 0x7bf8b752, 0x72f5bc5c, 0x05bed506, 0x0cb3de08, 0x17a4c31a, 0x1ea9c814, 0x218af93e, 0x2887f230, 0x3390ef22, 0x3a9de42c, 0xdd063d96, 0xd40b3698, 0xcf1c2b8a, 0xc6112084, 0xf93211ae, 0xf03f1aa0, 0xeb2807b2, 0xe2250cbc, 0x956e65e6, 0x9c636ee8, 0x877473fa, 0x8e7978f4, 0xb15a49de, 0xb85742d0, 0xa3405fc2, 0xaa4d54cc, 0xecdaf741, 0xe5d7fc4f, 0xfec0e15d, 0xf7cdea53, 0xc8eedb79, 0xc1e3d077, 0xdaf4cd65, 0xd3f9c66b, 0xa4b2af31, 0xadbfa43f, 0xb6a8b92d, 0xbfa5b223, 0x80868309, 0x898b8807, 0x929c9515, 0x9b919e1b, 0x7c0a47a1, 0x75074caf, 0x6e1051bd, 0x671d5ab3, 0x583e6b99, 0x51336097, 0x4a247d85, 0x4329768b, 0x34621fd1, 0x3d6f14df, 0x267809cd, 0x2f7502c3, 0x105633e9, 0x195b38e7, 0x024c25f5, 0x0b412efb, 0xd7618c9a, 0xde6c8794, 0xc57b9a86, 0xcc769188, 0xf355a0a2, 0xfa58abac, 0xe14fb6be, 0xe842bdb0, 0x9f09d4ea, 0x9604dfe4, 0x8d13c2f6, 0x841ec9f8, 0xbb3df8d2, 0xb230f3dc, 0xa927eece, 0xa02ae5c0, 0x47b13c7a, 0x4ebc3774, 0x55ab2a66, 0x5ca62168, 0x63851042, 0x6a881b4c, 0x719f065e, 0x78920d50, 0x0fd9640a, 0x06d46f04, 0x1dc37216, 0x14ce7918, 0x2bed4832, 0x22e0433c, 0x39f75e2e, 0x30fa5520, 0x9ab701ec, 0x93ba0ae2, 0x88ad17f0, 0x81a01cfe, 0xbe832dd4, 0xb78e26da, 0xac993bc8, 0xa59430c6, 0xd2df599c, 0xdbd25292, 0xc0c54f80, 0xc9c8448e, 0xf6eb75a4, 0xffe67eaa, 0xe4f163b8, 0xedfc68b6, 0x0a67b10c, 0x036aba02, 0x187da710, 0x1170ac1e, 0x2e539d34, 0x275e963a, 0x3c498b28, 0x35448026, 0x420fe97c, 0x4b02e272, 0x5015ff60, 0x5918f46e, 0x663bc544, 0x6f36ce4a, 0x7421d358, 0x7d2cd856, 0xa10c7a37, 0xa8017139, 0xb3166c2b, 0xba1b6725, 0x8538560f, 0x8c355d01, 0x97224013, 0x9e2f4b1d, 0xe9642247, 0xe0692949, 0xfb7e345b, 0xf2733f55, 0xcd500e7f, 0xc45d0571, 0xdf4a1863, 0xd647136d, 0x31dccad7, 0x38d1c1d9, 0x23c6dccb, 0x2acbd7c5, 0x15e8e6ef, 0x1ce5ede1, 0x07f2f0f3, 0x0efffbfd, 0x79b492a7, 0x70b999a9, 0x6bae84bb, 0x62a38fb5, 0x5d80be9f, 0x548db591, 0x4f9aa883, 0x4697a38d];
function convertToInt32(bytes) {
var result = [];
for (var i = 0; i < bytes.length; i += 4) {
result.push(
(bytes[i ] << 24) |
(bytes[i + 1] << 16) |
(bytes[i + 2] << 8) |
bytes[i + 3]
);
}
return result;
}
var AES = function(key) {
if (!(this instanceof AES)) {
throw Error('AES must be instanitated with `new`');
}
Object.defineProperty(this, 'key', {
value: coerceArray(key, true)
});
this._prepare();
}
AES.prototype._prepare = function() {
var rounds = numberOfRounds[this.key.length];
if (rounds == null) {
throw new Error('invalid key size (must be 16, 24 or 32 bytes)');
}
// encryption round keys
this._Ke = [];
// decryption round keys
this._Kd = [];
for (var i = 0; i <= rounds; i++) {
this._Ke.push([0, 0, 0, 0]);
this._Kd.push([0, 0, 0, 0]);
}
var roundKeyCount = (rounds + 1) * 4;
var KC = this.key.length / 4;
// convert the key into ints
var tk = convertToInt32(this.key);
// copy values into round key arrays
var index;
for (var i = 0; i < KC; i++) {
index = i >> 2;
this._Ke[index][i % 4] = tk[i];
this._Kd[rounds - index][i % 4] = tk[i];
}
// key expansion (fips-197 section 5.2)
var rconpointer = 0;
var t = KC, tt;
while (t < roundKeyCount) {
tt = tk[KC - 1];
tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^
(S[(tt >> 8) & 0xFF] << 16) ^
(S[ tt & 0xFF] << 8) ^
S[(tt >> 24) & 0xFF] ^
(rcon[rconpointer] << 24));
rconpointer += 1;
// key expansion (for non-256 bit)
if (KC != 8) {
for (var i = 1; i < KC; i++) {
tk[i] ^= tk[i - 1];
}
// key expansion for 256-bit keys is "slightly different" (fips-197)
} else {
for (var i = 1; i < (KC / 2); i++) {
tk[i] ^= tk[i - 1];
}
tt = tk[(KC / 2) - 1];
tk[KC / 2] ^= (S[ tt & 0xFF] ^
(S[(tt >> 8) & 0xFF] << 8) ^
(S[(tt >> 16) & 0xFF] << 16) ^
(S[(tt >> 24) & 0xFF] << 24));
for (var i = (KC / 2) + 1; i < KC; i++) {
tk[i] ^= tk[i - 1];
}
}
// copy values into round key arrays
var i = 0, r, c;
while (i < KC && t < roundKeyCount) {
r = t >> 2;
c = t % 4;
this._Ke[r][c] = tk[i];
this._Kd[rounds - r][c] = tk[i++];
t++;
}
}
// inverse-cipher-ify the decryption round key (fips-197 section 5.3)
for (var r = 1; r < rounds; r++) {
for (var c = 0; c < 4; c++) {
tt = this._Kd[r][c];
this._Kd[r][c] = (U1[(tt >> 24) & 0xFF] ^
U2[(tt >> 16) & 0xFF] ^
U3[(tt >> 8) & 0xFF] ^
U4[ tt & 0xFF]);
}
}
}
AES.prototype.encrypt = function(plaintext) {
if (plaintext.length != 16) {
throw new Error('invalid plaintext size (must be 16 bytes)');
}
var rounds = this._Ke.length - 1;
var a = [0, 0, 0, 0];
// convert plaintext to (ints ^ key)
var t = convertToInt32(plaintext);
for (var i = 0; i < 4; i++) {
t[i] ^= this._Ke[0][i];
}
// apply round transforms
for (var r = 1; r < rounds; r++) {
for (var i = 0; i < 4; i++) {
a[i] = (T1[(t[ i ] >> 24) & 0xff] ^
T2[(t[(i + 1) % 4] >> 16) & 0xff] ^
T3[(t[(i + 2) % 4] >> 8) & 0xff] ^
T4[ t[(i + 3) % 4] & 0xff] ^
this._Ke[r][i]);
}
t = a.slice();
}
// the last round is special
var result = createArray(16), tt;
for (var i = 0; i < 4; i++) {
tt = this._Ke[rounds][i];
result[4 * i ] = (S[(t[ i ] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;
result[4 * i + 1] = (S[(t[(i + 1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;
result[4 * i + 2] = (S[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;
result[4 * i + 3] = (S[ t[(i + 3) % 4] & 0xff] ^ tt ) & 0xff;
}
return result;
}
AES.prototype.decrypt = function(ciphertext) {
if (ciphertext.length != 16) {
throw new Error('invalid ciphertext size (must be 16 bytes)');
}
var rounds = this._Kd.length - 1;
var a = [0, 0, 0, 0];
// convert plaintext to (ints ^ key)
var t = convertToInt32(ciphertext);
for (var i = 0; i < 4; i++) {
t[i] ^= this._Kd[0][i];
}
// apply round transforms
for (var r = 1; r < rounds; r++) {
for (var i = 0; i < 4; i++) {
a[i] = (T5[(t[ i ] >> 24) & 0xff] ^
T6[(t[(i + 3) % 4] >> 16) & 0xff] ^
T7[(t[(i + 2) % 4] >> 8) & 0xff] ^
T8[ t[(i + 1) % 4] & 0xff] ^
this._Kd[r][i]);
}
t = a.slice();
}
// the last round is special
var result = createArray(16), tt;
for (var i = 0; i < 4; i++) {
tt = this._Kd[rounds][i];
result[4 * i ] = (Si[(t[ i ] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;
result[4 * i + 1] = (Si[(t[(i + 3) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;
result[4 * i + 2] = (Si[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;
result[4 * i + 3] = (Si[ t[(i + 1) % 4] & 0xff] ^ tt ) & 0xff;
}
return result;
}
/**
* Mode Of Operation - Electonic Codebook (ECB)
*/
var ModeOfOperationECB = function(key) {
if (!(this instanceof ModeOfOperationECB)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Electronic Code Block";
this.name = "ecb";
this._aes = new AES(key);
}
ModeOfOperationECB.prototype.encrypt = function(plaintext) {
plaintext = coerceArray(plaintext);
if ((plaintext.length % 16) !== 0) {
throw new Error('invalid plaintext size (must be multiple of 16 bytes)');
}
var ciphertext = createArray(plaintext.length);
var block = createArray(16);
for (var i = 0; i < plaintext.length; i += 16) {
copyArray(plaintext, block, 0, i, i + 16);
block = this._aes.encrypt(block);
copyArray(block, ciphertext, i);
}
return ciphertext;
}
ModeOfOperationECB.prototype.decrypt = function(ciphertext) {
ciphertext = coerceArray(ciphertext);
if ((ciphertext.length % 16) !== 0) {
throw new Error('invalid ciphertext size (must be multiple of 16 bytes)');
}
var plaintext = createArray(ciphertext.length);
var block = createArray(16);
for (var i = 0; i < ciphertext.length; i += 16) {
copyArray(ciphertext, block, 0, i, i + 16);
block = this._aes.decrypt(block);
copyArray(block, plaintext, i);
}
return plaintext;
}
/**
* Mode Of Operation - Cipher Block Chaining (CBC)
*/
var ModeOfOperationCBC = function(key, iv) {
if (!(this instanceof ModeOfOperationCBC)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Cipher Block Chaining";
this.name = "cbc";
if (!iv) {
iv = createArray(16);
} else if (iv.length != 16) {
throw new Error('invalid initialation vector size (must be 16 bytes)');
}
this._lastCipherblock = coerceArray(iv, true);
this._aes = new AES(key);
}
ModeOfOperationCBC.prototype.encrypt = function(plaintext) {
plaintext = coerceArray(plaintext);
if ((plaintext.length % 16) !== 0) {
throw new Error('invalid plaintext size (must be multiple of 16 bytes)');
}
var ciphertext = createArray(plaintext.length);
var block = createArray(16);
for (var i = 0; i < plaintext.length; i += 16) {
copyArray(plaintext, block, 0, i, i + 16);
for (var j = 0; j < 16; j++) {
block[j] ^= this._lastCipherblock[j];
}
this._lastCipherblock = this._aes.encrypt(block);
copyArray(this._lastCipherblock, ciphertext, i);
}
return ciphertext;
}
ModeOfOperationCBC.prototype.decrypt = function(ciphertext) {
ciphertext = coerceArray(ciphertext);
if ((ciphertext.length % 16) !== 0) {
throw new Error('invalid ciphertext size (must be multiple of 16 bytes)');
}
var plaintext = createArray(ciphertext.length);
var block = createArray(16);
for (var i = 0; i < ciphertext.length; i += 16) {
copyArray(ciphertext, block, 0, i, i + 16);
block = this._aes.decrypt(block);
for (var j = 0; j < 16; j++) {
plaintext[i + j] = block[j] ^ this._lastCipherblock[j];
}
copyArray(ciphertext, this._lastCipherblock, 0, i, i + 16);
}
return plaintext;
}
/**
* Mode Of Operation - Cipher Feedback (CFB)
*/
var ModeOfOperationCFB = function(key, iv, segmentSize) {
if (!(this instanceof ModeOfOperationCFB)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Cipher Feedback";
this.name = "cfb";
if (!iv) {
iv = createArray(16);
} else if (iv.length != 16) {
throw new Error('invalid initialation vector size (must be 16 size)');
}
if (!segmentSize) { segmentSize = 1; }
this.segmentSize = segmentSize;
this._shiftRegister = coerceArray(iv, true);
this._aes = new AES(key);
}
ModeOfOperationCFB.prototype.encrypt = function(plaintext) {
if ((plaintext.length % this.segmentSize) != 0) {
throw new Error('invalid plaintext size (must be segmentSize bytes)');
}
var encrypted = coerceArray(plaintext, true);
var xorSegment;
for (var i = 0; i < encrypted.length; i += this.segmentSize) {
xorSegment = this._aes.encrypt(this._shiftRegister);
for (var j = 0; j < this.segmentSize; j++) {
encrypted[i + j] ^= xorSegment[j];
}
// Shift the register
copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize);
copyArray(encrypted, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize);
}
return encrypted;
}
ModeOfOperationCFB.prototype.decrypt = function(ciphertext) {
if ((ciphertext.length % this.segmentSize) != 0) {
throw new Error('invalid ciphertext size (must be segmentSize bytes)');
}
var plaintext = coerceArray(ciphertext, true);
var xorSegment;
for (var i = 0; i < plaintext.length; i += this.segmentSize) {
xorSegment = this._aes.encrypt(this._shiftRegister);
for (var j = 0; j < this.segmentSize; j++) {
plaintext[i + j] ^= xorSegment[j];
}
// Shift the register
copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize);
copyArray(ciphertext, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize);
}
return plaintext;
}
/**
* Mode Of Operation - Output Feedback (OFB)
*/
var ModeOfOperationOFB = function(key, iv) {
if (!(this instanceof ModeOfOperationOFB)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Output Feedback";
this.name = "ofb";
if (!iv) {
iv = createArray(16);
} else if (iv.length != 16) {
throw new Error('invalid initialation vector size (must be 16 bytes)');
}
this._lastPrecipher = coerceArray(iv, true);
this._lastPrecipherIndex = 16;
this._aes = new AES(key);
}
ModeOfOperationOFB.prototype.encrypt = function(plaintext) {
var encrypted = coerceArray(plaintext, true);
for (var i = 0; i < encrypted.length; i++) {
if (this._lastPrecipherIndex === 16) {
this._lastPrecipher = this._aes.encrypt(this._lastPrecipher);
this._lastPrecipherIndex = 0;
}
encrypted[i] ^= this._lastPrecipher[this._lastPrecipherIndex++];
}
return encrypted;
}
// Decryption is symetric
ModeOfOperationOFB.prototype.decrypt = ModeOfOperationOFB.prototype.encrypt;
/**
* Counter object for CTR common mode of operation
*/
var Counter = function(initialValue) {
if (!(this instanceof Counter)) {
throw Error('Counter must be instanitated with `new`');
}
// We allow 0, but anything false-ish uses the default 1
if (initialValue !== 0 && !initialValue) { initialValue = 1; }
if (typeof(initialValue) === 'number') {
this._counter = createArray(16);
this.setValue(initialValue);
} else {
this.setBytes(initialValue);
}
}
Counter.prototype.setValue = function(value) {
if (typeof(value) !== 'number' || parseInt(value) != value) {
throw new Error('invalid counter value (must be an integer)');
}
// We cannot safely handle numbers beyond the safe range for integers
if (value > Number.MAX_SAFE_INTEGER) {
throw new Error('integer value out of safe range');
}
for (var index = 15; index >= 0; --index) {
this._counter[index] = value % 256;
value = parseInt(value / 256);
}
}
Counter.prototype.setBytes = function(bytes) {
bytes = coerceArray(bytes, true);
if (bytes.length != 16) {
throw new Error('invalid counter bytes size (must be 16 bytes)');
}
this._counter = bytes;
};
Counter.prototype.increment = function() {
for (var i = 15; i >= 0; i--) {
if (this._counter[i] === 255) {
this._counter[i] = 0;
} else {
this._counter[i]++;
break;
}
}
}
/**
* Mode Of Operation - Counter (CTR)
*/
var ModeOfOperationCTR = function(key, counter) {
if (!(this instanceof ModeOfOperationCTR)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Counter";
this.name = "ctr";
if (!(counter instanceof Counter)) {
counter = new Counter(counter)
}
this._counter = counter;
this._remainingCounter = null;
this._remainingCounterIndex = 16;
this._aes = new AES(key);
}
ModeOfOperationCTR.prototype.encrypt = function(plaintext) {
var encrypted = coerceArray(plaintext, true);
for (var i = 0; i < encrypted.length; i++) {
if (this._remainingCounterIndex === 16) {
this._remainingCounter = this._aes.encrypt(this._counter._counter);
this._remainingCounterIndex = 0;
this._counter.increment();
}
encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++];
}
return encrypted;
}
// Decryption is symetric
ModeOfOperationCTR.prototype.decrypt = ModeOfOperationCTR.prototype.encrypt;
///////////////////////
// Padding
// See:https://tools.ietf.org/html/rfc2315
function pkcs7pad(data) {
data = coerceArray(data, true);
var padder = 16 - (data.length % 16);
var result = createArray(data.length + padder);
copyArray(data, result);
for (var i = data.length; i < result.length; i++) {
result[i] = padder;
}
return result;
}
function pkcs7strip(data) {
data = coerceArray(data, true);
if (data.length < 16) { throw new Error('PKCS#7 invalid length'); }
var padder = data[data.length - 1];
if (padder > 16) { throw new Error('PKCS#7 padding byte out of range'); }
var length = data.length - padder;
for (var i = 0; i < padder; i++) {
if (data[length + i] !== padder) {
throw new Error('PKCS#7 invalid padding byte');
}
}
var result = createArray(length);
copyArray(data, result, 0, 0, length);
return result;
}
///////////////////////
// Exporting
// The block cipher
var aesjs = {
AES: AES,
Counter: Counter,
ModeOfOperation: {
ecb: ModeOfOperationECB,
cbc: ModeOfOperationCBC,
cfb: ModeOfOperationCFB,
ofb: ModeOfOperationOFB,
ctr: ModeOfOperationCTR
},
utils: {
hex: convertHex,
utf8: convertUtf8
},
padding: {
pkcs7: {
pad: pkcs7pad,
strip: pkcs7strip
}
},
_arrayTest: {
coerceArray: coerceArray,
createArray: createArray,
copyArray: copyArray,
}
};
// node.js
if (typeof exports !== 'undefined') {
module.exports = aesjs
// RequireJS/AMD
// http://www.requirejs.org/docs/api.html
// https://github.com/amdjs/amdjs-api/wiki/AMD
} else if (typeof(define) === 'function' && define.amd) {
define([], function() { return aesjs; });
// Web Browsers
} else {
// If there was an existing library at "aesjs" make sure it's still available
if (root.aesjs) {
aesjs._aesjs = root.aesjs;
}
root.aesjs = aesjs;
}
})(this);
================================================
FILE: docs/libs/noble-ed25519-1.7.3.js
================================================
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.nobleEd25519 = {}));
})(this, (function (exports) { 'use strict';
const _nodeResolve_empty = {};
const nodeCrypto = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': _nodeResolve_empty
});
/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
const _0n = BigInt(0);
const _1n = BigInt(1);
const _2n = BigInt(2);
const _8n = BigInt(8);
const CU_O = BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989');
const CURVE = Object.freeze({
a: BigInt(-1),
d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),
P: BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'),
l: CU_O,
n: CU_O,
h: BigInt(8),
Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
});
const POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');
const SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
BigInt('6853475219497561581579357271197624642482790079785650197046958215289687604742');
const SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');
const INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');
const ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');
const D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');
class ExtendedPoint {
constructor(x, y, z, t) {
this.x = x;
this.y = y;
this.z = z;
this.t = t;
}
static fromAffine(p) {
if (!(p instanceof Point)) {
throw new TypeError('ExtendedPoint#fromAffine: expected Point');
}
if (p.equals(Point.ZERO))
return ExtendedPoint.ZERO;
return new ExtendedPoint(p.x, p.y, _1n, mod(p.x * p.y));
}
static toAffineBatch(points) {
const toInv = invertBatch(points.map((p) => p.z));
return points.map((p, i) => p.toAffine(toInv[i]));
}
static normalizeZ(points) {
return this.toAffineBatch(points).map(this.fromAffine);
}
equals(other) {
assertExtPoint(other);
const { x: X1, y: Y1, z: Z1 } = this;
const { x: X2, y: Y2, z: Z2 } = other;
const X1Z2 = mod(X1 * Z2);
const X2Z1 = mod(X2 * Z1);
const Y1Z2 = mod(Y1 * Z2);
const Y2Z1 = mod(Y2 * Z1);
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
}
negate() {
return new ExtendedPoint(mod(-this.x), this.y, this.z, mod(-this.t));
}
double() {
const { x: X1, y: Y1, z: Z1 } = this;
const { a } = CURVE;
const A = mod(X1 * X1);
const B = mod(Y1 * Y1);
const C = mod(_2n * mod(Z1 * Z1));
const D = mod(a * A);
const x1y1 = X1 + Y1;
const E = mod(mod(x1y1 * x1y1) - A - B);
const G = D + B;
const F = G - C;
const H = D - B;
const X3 = mod(E * F);
const Y3 = mod(G * H);
const T3 = mod(E * H);
const Z3 = mod(F * G);
return new ExtendedPoint(X3, Y3, Z3, T3);
}
add(other) {
assertExtPoint(other);
const { x: X1, y: Y1, z: Z1, t: T1 } = this;
const { x: X2, y: Y2, z: Z2, t: T2 } = other;
const A = mod((Y1 - X1) * (Y2 + X2));
const B = mod((Y1 + X1) * (Y2 - X2));
const F = mod(B - A);
if (F === _0n)
return this.double();
const C = mod(Z1 * _2n * T2);
const D = mod(T1 * _2n * Z2);
const E = D + C;
const G = B + A;
const H = D - C;
const X3 = mod(E * F);
const Y3 = mod(G * H);
const T3 = mod(E * H);
const Z3 = mod(F * G);
return new ExtendedPoint(X3, Y3, Z3, T3);
}
subtract(other) {
return this.add(other.negate());
}
precomputeWindow(W) {
const windows = 1 + 256 / W;
const points = [];
let p = this;
let base = p;
for (let window = 0; window < windows; window++) {
base = p;
points.push(base);
for (let i = 1; i < 2 ** (W - 1); i++) {
base = base.add(p);
points.push(base);
}
p = base.double();
}
return points;
}
wNAF(n, affinePoint) {
if (!affinePoint && this.equals(ExtendedPoint.BASE))
affinePoint = Point.BASE;
const W = (affinePoint && affinePoint._WINDOW_SIZE) || 1;
if (256 % W) {
throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2');
}
let precomputes = affinePoint && pointPrecomputes.get(affinePoint);
if (!precomputes) {
precomputes = this.precomputeWindow(W);
if (affinePoint && W !== 1) {
precomputes = ExtendedPoint.normalizeZ(precomputes);
pointPrecomputes.set(affinePoint, precomputes);
}
}
let p = ExtendedPoint.ZERO;
let f = ExtendedPoint.BASE;
const windows = 1 + 256 / W;
const windowSize = 2 ** (W - 1);
const mask = BigInt(2 ** W - 1);
const maxNumber = 2 ** W;
const shiftBy = BigInt(W);
for (let window = 0; window < windows; window++) {
const offset = window * windowSize;
let wbits = Number(n & mask);
n >>= shiftBy;
if (wbits > windowSize) {
wbits -= maxNumber;
n += _1n;
}
const offset1 = offset;
const offset2 = offset + Math.abs(wbits) - 1;
const cond1 = window % 2 !== 0;
const cond2 = wbits < 0;
if (wbits === 0) {
f = f.add(constTimeNegate(cond1, precomputes[offset1]));
}
else {
p = p.add(constTimeNegate(cond2, precomputes[offset2]));
}
}
return ExtendedPoint.normalizeZ([p, f])[0];
}
multiply(scalar, affinePoint) {
return this.wNAF(normalizeScalar(scalar, CURVE.l), affinePoint);
}
multiplyUnsafe(scalar) {
let n = normalizeScalar(scalar, CURVE.l, false);
const G = ExtendedPoint.BASE;
const P0 = ExtendedPoint.ZERO;
if (n === _0n)
return P0;
if (this.equals(P0) || n === _1n)
return this;
if (this.equals(G))
return this.wNAF(n);
let p = P0;
let d = this;
while (n > _0n) {
if (n & _1n)
p = p.add(d);
d = d.double();
n >>= _1n;
}
return p;
}
isSmallOrder() {
return this.multiplyUnsafe(CURVE.h).equals(ExtendedPoint.ZERO);
}
isTorsionFree() {
let p = this.multiplyUnsafe(CURVE.l / _2n).double();
if (CURVE.l % _2n)
p = p.add(this);
return p.equals(ExtendedPoint.ZERO);
}
toAffine(invZ) {
const { x, y, z } = this;
const is0 = this.equals(ExtendedPoint.ZERO);
if (invZ == null)
invZ = is0 ? _8n : invert(z);
const ax = mod(x * invZ);
const ay = mod(y * invZ);
const zz = mod(z * invZ);
if (is0)
return Point.ZERO;
if (zz !== _1n)
throw new Error('invZ was invalid');
return new Point(ax, ay);
}
fromRistrettoBytes() {
legacyRist();
}
toRistrettoBytes() {
legacyRist();
}
fromRistrettoHash() {
legacyRist();
}
}
ExtendedPoint.BASE = new ExtendedPoint(CURVE.Gx, CURVE.Gy, _1n, mod(CURVE.Gx * CURVE.Gy));
ExtendedPoint.ZERO = new ExtendedPoint(_0n, _1n, _1n, _0n);
function constTimeNegate(condition, item) {
const neg = item.negate();
return condition ? neg : item;
}
function assertExtPoint(other) {
if (!(other instanceof ExtendedPoint))
throw new TypeError('ExtendedPoint expected');
}
function assertRstPoint(other) {
if (!(other instanceof RistrettoPoint))
throw new TypeError('RistrettoPoint expected');
}
function legacyRist() {
throw new Error('Legacy method: switch to RistrettoPoint');
}
class RistrettoPoint {
constructor(ep) {
this.ep = ep;
}
static calcElligatorRistrettoMap(r0) {
const { d } = CURVE;
const r = mod(SQRT_M1 * r0 * r0);
const Ns = mod((r + _1n) * ONE_MINUS_D_SQ);
let c = BigInt(-1);
const D = mod((c - d * r) * mod(r + d));
let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
let s_ = mod(s * r0);
if (!edIsNegative(s_))
s_ = mod(-s_);
if (!Ns_D_is_sq)
s = s_;
if (!Ns_D_is_sq)
c = r;
const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D);
const s2 = s * s;
const W0 = mod((s + s) * D);
const W1 = mod(Nt * SQRT_AD_MINUS_ONE);
const W2 = mod(_1n - s2);
const W3 = mod(_1n + s2);
return new ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));
}
static hashToCurve(hex) {
hex = ensureBytes(hex, 64);
const r1 = bytes255ToNumberLE(hex.slice(0, 32));
const R1 = this.calcElligatorRistrettoMap(r1);
const r2 = bytes255ToNumberLE(hex.slice(32, 64));
const R2 = this.calcElligatorRistrettoMap(r2);
return new RistrettoPoint(R1.add(R2));
}
static fromHex(hex) {
hex = ensureBytes(hex, 32);
const { a, d } = CURVE;
const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';
const s = bytes255ToNumberLE(hex);
if (!equalBytes(numberTo32BytesLE(s), hex) || edIsNegative(s))
throw new Error(emsg);
const s2 = mod(s * s);
const u1 = mod(_1n + a * s2);
const u2 = mod(_1n - a * s2);
const u1_2 = mod(u1 * u1);
const u2_2 = mod(u2 * u2);
const v = mod(a * d * u1_2 - u2_2);
const { isValid, value: I } = invertSqrt(mod(v * u2_2));
const Dx = mod(I * u2);
const Dy = mod(I * Dx * v);
let x = mod((s + s) * Dx);
if (edIsNegative(x))
x = mod(-x);
const y = mod(u1 * Dy);
const t = mod(x * y);
if (!isValid || edIsNegative(t) || y === _0n)
throw new Error(emsg);
return new RistrettoPoint(new ExtendedPoint(x, y, _1n, t));
}
toRawBytes() {
let { x, y, z, t } = this.ep;
const u1 = mod(mod(z + y) * mod(z - y));
const u2 = mod(x * y);
const u2sq = mod(u2 * u2);
const { value: invsqrt } = invertSqrt(mod(u1 * u2sq));
const D1 = mod(invsqrt * u1);
const D2 = mod(invsqrt * u2);
const zInv = mod(D1 * D2 * t);
let D;
if (edIsNegative(t * zInv)) {
let _x = mod(y * SQRT_M1);
let _y = mod(x * SQRT_M1);
x = _x;
y = _y;
D = mod(D1 * INVSQRT_A_MINUS_D);
}
else {
D = D2;
}
if (edIsNegative(x * zInv))
y = mod(-y);
let s = mod((z - y) * D);
if (edIsNegative(s))
s = mod(-s);
return numberTo32BytesLE(s);
}
toHex() {
return bytesToHex(this.toRawBytes());
}
toString() {
return this.toHex();
}
equals(other) {
assertRstPoint(other);
const a = this.ep;
const b = other.ep;
const one = mod(a.x * b.y) === mod(a.y * b.x);
const two = mod(a.y * b.y) === mod(a.x * b.x);
return one || two;
}
add(other) {
assertRstPoint(other);
return new RistrettoPoint(this.ep.add(other.ep));
}
subtract(other) {
assertRstPoint(other);
return new RistrettoPoint(this.ep.subtract(other.ep));
}
multiply(scalar) {
return new RistrettoPoint(this.ep.multiply(scalar));
}
multiplyUnsafe(scalar) {
return new RistrettoPoint(this.ep.multiplyUnsafe(scalar));
}
}
RistrettoPoint.BASE = new RistrettoPoint(ExtendedPoint.BASE);
RistrettoPoint.ZERO = new RistrettoPoint(ExtendedPoint.ZERO);
const pointPrecomputes = new WeakMap();
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
_setWindowSize(windowSize) {
this._WINDOW_SIZE = windowSize;
pointPrecomputes.delete(this);
}
static fromHex(hex, strict = true) {
const { d, P } = CURVE;
hex = ensureBytes(hex, 32);
const normed = hex.slice();
normed[31] = hex[31] & ~0x80;
const y = bytesToNumberLE(normed);
if (strict && y >= P)
throw new Error('Expected 0 < hex < P');
if (!strict && y >= POW_2_256)
throw new Error('Expected 0 < hex < 2**256');
const y2 = mod(y * y);
const u = mod(y2 - _1n);
const v = mod(d * y2 + _1n);
let { isValid, value: x } = uvRatio(u, v);
if (!isValid)
throw new Error('Point.fromHex: invalid y coordinate');
const isXOdd = (x & _1n) === _1n;
const isLastByteOdd = (hex[31] & 0x80) !== 0;
if (isLastByteOdd !== isXOdd) {
x = mod(-x);
}
return new Point(x, y);
}
static async fromPrivateKey(privateKey) {
return (await getExtendedPublicKey(privateKey)).point;
}
toRawBytes() {
const bytes = numberTo32BytesLE(this.y);
bytes[31] |= this.x & _1n ? 0x80 : 0;
return bytes;
}
toHex() {
return bytesToHex(this.toRawBytes());
}
toX25519() {
const { y } = this;
const u = mod((_1n + y) * invert(_1n - y));
return numberTo32BytesLE(u);
}
isTorsionFree() {
return ExtendedPoint.fromAffine(this).isTorsionFree();
}
equals(other) {
return this.x === other.x && this.y === other.y;
}
negate() {
return new Point(mod(-this.x), this.y);
}
add(other) {
return ExtendedPoint.fromAffine(this).add(ExtendedPoint.fromAffine(other)).toAffine();
}
subtract(other) {
return this.add(other.negate());
}
multiply(scalar) {
return ExtendedPoint.fromAffine(this).multiply(scalar, this).toAffine();
}
}
Point.BASE = new Point(CURVE.Gx, CURVE.Gy);
Point.ZERO = new Point(_0n, _1n);
class Signature {
constructor(r, s) {
this.r = r;
this.s = s;
this.assertValidity();
}
static fromHex(hex) {
const bytes = ensureBytes(hex, 64);
const r = Point.fromHex(bytes.slice(0, 32), false);
const s = bytesToNumberLE(bytes.slice(32, 64));
return new Signature(r, s);
}
assertValidity() {
const { r, s } = this;
if (!(r instanceof Point))
throw new Error('Expected Point instance');
normalizeScalar(s, CURVE.l, false);
return this;
}
toRawBytes() {
const u8 = new Uint8Array(64);
u8.set(this.r.toRawBytes());
u8.set(numberTo32BytesLE(this.s), 32);
return u8;
}
toHex() {
return bytesToHex(this.toRawBytes());
}
}
function concatBytes(...arrays) {
if (!arrays.every((a) => a instanceof Uint8Array))
throw new Error('Expected Uint8Array list');
if (arrays.length === 1)
return arrays[0];
const length = arrays.reduce((a, arr) => a + arr.length, 0);
const result = new Uint8Array(length);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const arr = arrays[i];
result.set(arr, pad);
pad += arr.length;
}
return result;
}
const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
function bytesToHex(uint8a) {
if (!(uint8a instanceof Uint8Array))
throw new Error('Uint8Array expected');
let hex = '';
for (let i = 0; i < uint8a.length; i++) {
hex += hexes[uint8a[i]];
}
return hex;
}
function hexToBytes(hex) {
if (typeof hex !== 'string') {
throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
}
if (hex.length % 2)
throw new Error('hexToBytes: received invalid unpadded hex');
const array = new Uint8Array(hex.length / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
const hexByte = hex.slice(j, j + 2);
const byte = Number.parseInt(hexByte, 16);
if (Number.isNaN(byte) || byte < 0)
throw new Error('Invalid byte sequence');
array[i] = byte;
}
return array;
}
function numberTo32BytesBE(num) {
const length = 32;
const hex = num.toString(16).padStart(length * 2, '0');
return hexToBytes(hex);
}
function numberTo32BytesLE(num) {
return numberTo32BytesBE(num).reverse();
}
function edIsNegative(num) {
return (mod(num) & _1n) === _1n;
}
function bytesToNumberLE(uint8a) {
if (!(uint8a instanceof Uint8Array))
throw new Error('Expected Uint8Array');
return BigInt('0x' + bytesToHex(Uint8Array.from(uint8a).reverse()));
}
const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
function bytes255ToNumberLE(bytes) {
return mod(bytesToNumberLE(bytes) & MAX_255B);
}
function mod(a, b = CURVE.P) {
const res = a % b;
return res >= _0n ? res : b + res;
}
function invert(number, modulo = CURVE.P) {
if (number === _0n || modulo <= _0n) {
throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
}
let a = mod(number, modulo);
let b = modulo;
let x = _0n, u = _1n;
while (a !== _0n) {
const q = b / a;
const r = b % a;
const m = x - u * q;
b = a, a = r, x = u, u = m;
}
const gcd = b;
if (gcd !== _1n)
throw new Error('invert: does not exist');
return mod(x, modulo);
}
function invertBatch(nums, p = CURVE.P) {
const tmp = new Array(nums.length);
const lastMultiplied = nums.reduce((acc, num, i) => {
if (num === _0n)
return acc;
tmp[i] = acc;
return mod(acc * num, p);
}, _1n);
const inverted = invert(lastMultiplied, p);
nums.reduceRight((acc, num, i) => {
if (num === _0n)
return acc;
tmp[i] = mod(acc * tmp[i], p);
return mod(acc * num, p);
}, inverted);
return tmp;
}
function pow2(x, power) {
const { P } = CURVE;
let res = x;
while (power-- > _0n) {
res *= res;
res %= P;
}
return res;
}
function pow_2_252_3(x) {
const { P } = CURVE;
const _5n = BigInt(5);
const _10n = BigInt(10);
const _20n = BigInt(20);
const _40n = BigInt(40);
const _80n = BigInt(80);
const x2 = (x * x) % P;
const b2 = (x2 * x) % P;
const b4 = (pow2(b2, _2n) * b2) % P;
const b5 = (pow2(b4, _1n) * x) % P;
const b10 = (pow2(b5, _5n) * b5) % P;
const b20 = (pow2(b10, _10n) * b10) % P;
const b40 = (pow2(b20, _20n) * b20) % P;
const b80 = (pow2(b40, _40n) * b40) % P;
const b160 = (pow2(b80, _80n) * b80) % P;
const b240 = (pow2(b160, _80n) * b80) % P;
const b250 = (pow2(b240, _10n) * b10) % P;
const pow_p_5_8 = (pow2(b250, _2n) * x) % P;
return { pow_p_5_8, b2 };
}
function uvRatio(u, v) {
const v3 = mod(v * v * v);
const v7 = mod(v3 * v3 * v);
const pow = pow_2_252_3(u * v7).pow_p_5_8;
let x = mod(u * v3 * pow);
const vx2 = mod(v * x * x);
const root1 = x;
const root2 = mod(x * SQRT_M1);
const useRoot1 = vx2 === u;
const useRoot2 = vx2 === mod(-u);
const noRoot = vx2 === mod(-u * SQRT_M1);
if (useRoot1)
x = root1;
if (useRoot2 || noRoot)
x = root2;
if (edIsNegative(x))
x = mod(-x);
return { isValid: useRoot1 || useRoot2, value: x };
}
function invertSqrt(number) {
return uvRatio(_1n, number);
}
function modlLE(hash) {
return mod(bytesToNumberLE(hash), CURVE.l);
}
function equalBytes(b1, b2) {
if (b1.length !== b2.length) {
return false;
}
for (let i = 0; i < b1.length; i++) {
if (b1[i] !== b2[i]) {
return false;
}
}
return true;
}
function ensureBytes(hex, expectedLength) {
const bytes = hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex);
if (typeof expectedLength === 'number' && bytes.length !== expectedLength)
throw new Error(`Expected ${expectedLength} bytes`);
return bytes;
}
function normalizeScalar(num, max, strict = true) {
if (!max)
throw new TypeError('Specify max value');
if (typeof num === 'number' && Number.isSafeInteger(num))
num = BigInt(num);
if (typeof num === 'bigint' && num < max) {
if (strict) {
if (_0n < num)
return num;
}
else {
if (_0n <= num)
return num;
}
}
throw new TypeError('Expected valid scalar: 0 < scalar < max');
}
function adjustBytes25519(bytes) {
bytes[0] &= 248;
bytes[31] &= 127;
bytes[31] |= 64;
return bytes;
}
function decodeScalar25519(n) {
return bytesToNumberLE(adjustBytes25519(ensureBytes(n, 32)));
}
function checkPrivateKey(key) {
key =
typeof key === 'bigint' || typeof key === 'number'
? numberTo32BytesBE(normalizeScalar(key, POW_2_256))
: ensureBytes(key);
if (key.length !== 32)
throw new Error(`Expected 32 bytes`);
return key;
}
function getKeyFromHash(hashed) {
const head = adjustBytes25519(hashed.slice(0, 32));
const prefix = hashed.slice(32, 64);
const scalar = modlLE(head);
const point = Point.BASE.multiply(scalar);
const pointBytes = point.toRawBytes();
return { head, prefix, scalar, point, pointBytes };
}
let _sha512Sync;
function sha512s(...m) {
if (typeof _sha512Sync !== 'function')
throw new Error('utils.sha512Sync must be set to use sync methods');
return _sha512Sync(...m);
}
async function getExtendedPublicKey(key) {
return getKeyFromHash(await utils.sha512(checkPrivateKey(key)));
}
function getExtendedPublicKeySync(key) {
return getKeyFromHash(sha512s(checkPrivateKey(key)));
}
async function getPublicKey(privateKey) {
return (await getExtendedPublicKey(privateKey)).pointBytes;
}
function getPublicKeySync(privateKey) {
return getExtendedPublicKeySync(privateKey).pointBytes;
}
async function sign(message, privateKey) {
message = ensureBytes(message);
const { prefix, scalar, pointBytes } = await getExtendedPublicKey(privateKey);
const r = modlLE(await utils.sha512(prefix, message));
const R = Point.BASE.multiply(r);
const k = modlLE(await utils.sha512(R.toRawBytes(), pointBytes, message));
const s = mod(r + k * scalar, CURVE.l);
return new Signature(R, s).toRawBytes();
}
function signSync(message, privateKey) {
message = ensureBytes(message);
const { prefix, scalar, pointBytes } = getExtendedPublicKeySync(privateKey);
const r = modlLE(sha512s(prefix, message));
const R = Point.BASE.multiply(r);
const k = modlLE(sha512s(R.toRawBytes(), pointBytes, message));
const s = mod(r + k * scalar, CURVE.l);
return new Signature(R, s).toRawBytes();
}
function prepareVerification(sig, message, publicKey) {
message = ensureBytes(message);
if (!(publicKey instanceof Point))
publicKey = Point.fromHex(publicKey, false);
const { r, s } = sig instanceof Signature ? sig.assertValidity() : Signature.fromHex(sig);
const SB = ExtendedPoint.BASE.multiplyUnsafe(s);
return { r, s, SB, pub: publicKey, msg: message };
}
function finishVerification(publicKey, r, SB, hashed) {
const k = modlLE(hashed);
const kA = ExtendedPoint.fromAffine(publicKey).multiplyUnsafe(k);
const RkA = ExtendedPoint.fromAffine(r).add(kA);
return RkA.subtract(SB).multiplyUnsafe(CURVE.h).equals(ExtendedPoint.ZERO);
}
async function verify(sig, message, publicKey) {
const { r, SB, msg, pub } = prepareVerification(sig, message, publicKey);
const hashed = await utils.sha512(r.toRawBytes(), pub.toRawBytes(), msg);
return finishVerification(pub, r, SB, hashed);
}
function verifySync(sig, message, publicKey) {
const { r, SB, msg, pub } = prepareVerification(sig, message, publicKey);
const hashed = sha512s(r.toRawBytes(), pub.toRawBytes(), msg);
return finishVerification(pub, r, SB, hashed);
}
const sync = {
getExtendedPublicKey: getExtendedPublicKeySync,
getPublicKey: getPublicKeySync,
sign: signSync,
verify: verifySync,
};
async function getSharedSecret(privateKey, publicKey) {
const { head } = await getExtendedPublicKey(privateKey);
const u = Point.fromHex(publicKey).toX25519();
return curve25519.scalarMult(head, u);
}
Point.BASE._setWindowSize(8);
function cswap(swap, x_2, x_3) {
const dummy = mod(swap * (x_2 - x_3));
x_2 = mod(x_2 - dummy);
x_3 = mod(x_3 + dummy);
return [x_2, x_3];
}
function montgomeryLadder(pointU, scalar) {
const { P } = CURVE;
const u = normalizeScalar(pointU, P);
const k = normalizeScalar(scalar, P);
const a24 = BigInt(121665);
const x_1 = u;
let x_2 = _1n;
let z_2 = _0n;
let x_3 = u;
let z_3 = _1n;
let swap = _0n;
let sw;
for (let t = BigInt(255 - 1); t >= _0n; t--) {
const k_t = (k >> t) & _1n;
swap ^= k_t;
sw = cswap(swap, x_2, x_3);
x_2 = sw[0];
x_3 = sw[1];
sw = cswap(swap, z_2, z_3);
z_2 = sw[0];
z_3 = sw[1];
swap = k_t;
const A = x_2 + z_2;
const AA = mod(A * A);
const B = x_2 - z_2;
const BB = mod(B * B);
const E = AA - BB;
const C = x_3 + z_3;
const D = x_3 - z_3;
const DA = mod(D * A);
const CB = mod(C * B);
const dacb = DA + CB;
const da_cb = DA - CB;
x_3 = mod(dacb * dacb);
z_3 = mod(x_1 * mod(da_cb * da_cb));
x_2 = mod(AA * BB);
z_2 = mod(E * (AA + mod(a24 * E)));
}
sw = cswap(swap, x_2, x_3);
x_2 = sw[0];
x_3 = sw[1];
sw = cswap(swap, z_2, z_3);
z_2 = sw[0];
z_3 = sw[1];
const { pow_p_5_8, b2 } = pow_2_252_3(z_2);
const xp2 = mod(pow2(pow_p_5_8, BigInt(3)) * b2);
return mod(x_2 * xp2);
}
function encodeUCoordinate(u) {
return numberTo32BytesLE(mod(u, CURVE.P));
}
function decodeUCoordinate(uEnc) {
const u = ensureBytes(uEnc, 32);
u[31] &= 127;
return bytesToNumberLE(u);
}
const curve25519 = {
BASE_POINT_U: '0900000000000000000000000000000000000000000000000000000000000000',
scalarMult(privateKey, publicKey) {
const u = decodeUCoordinate(publicKey);
const p = decodeScalar25519(privateKey);
const pu = montgomeryLadder(u, p);
if (pu === _0n)
throw new Error('Invalid private or public key received');
return encodeUCoordinate(pu);
},
scalarMultBase(privateKey) {
return curve25519.scalarMult(privateKey, curve25519.BASE_POINT_U);
},
};
const crypto = {
node: nodeCrypto,
web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined,
};
const utils = {
bytesToHex,
hexToBytes,
concatBytes,
getExtendedPublicKey,
mod,
invert,
TORSION_SUBGROUP: [
'0100000000000000000000000000000000000000000000000000000000000000',
'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',
'0000000000000000000000000000000000000000000000000000000000000080',
'26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',
'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',
'26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',
'0000000000000000000000000000000000000000000000000000000000000000',
'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',
],
hashToPrivateScalar: (hash) => {
hash = ensureBytes(hash);
if (hash.length < 40 || hash.length > 1024)
throw new Error('Expected 40-1024 bytes of private key as per FIPS 186');
return mod(bytesToNumberLE(hash), CURVE.l - _1n) + _1n;
},
randomBytes: (bytesLength = 32) => {
if (crypto.web) {
return crypto.web.getRandomValues(new Uint8Array(bytesLength));
}
else if (crypto.node) {
const { randomBytes } = crypto.node;
return new Uint8Array(randomBytes(bytesLength).buffer);
}
else {
throw new Error("The environment doesn't have randomBytes function");
}
},
randomPrivateKey: () => {
return utils.randomBytes(32);
},
sha512: async (...messages) => {
const message = concatBytes(...messages);
if (crypto.web) {
const buffer = await crypto.web.subtle.digest('SHA-512', message.buffer);
return new Uint8Array(buffer);
}
else if (crypto.node) {
return Uint8Array.from(crypto.node.createHash('sha512').update(message).digest());
}
else {
throw new Error("The environment doesn't have sha512 function");
}
},
precompute(windowSize = 8, point = Point.BASE) {
const cached = point.equals(Point.BASE) ? point : new Point(point.x, point.y);
cached._setWindowSize(windowSize);
cached.multiply(_2n);
return cached;
},
sha512Sync: undefined,
};
Object.defineProperties(utils, {
sha512Sync: {
configurable: false,
get() {
return _sha512Sync;
},
set(val) {
if (!_sha512Sync)
_sha512Sync = val;
},
},
});
exports.CURVE = CURVE;
exports.ExtendedPoint = ExtendedPoint;
exports.Point = Point;
exports.RistrettoPoint = RistrettoPoint;
exports.Signature = Signature;
exports.curve25519 = curve25519;
exports.getPublicKey = getPublicKey;
exports.getSharedSecret = getSharedSecret;
exports.sign = sign;
exports.sync = sync;
exports.utils = utils;
exports.verify = verify;
Object.defineProperty(exports, '__esModule', { value: true });
}));
================================================
FILE: docs/main.css
================================================
@font-face {
font-family: Helvetica, Arial, sans-serif;
/*src: local('Mulish Regular'), local('Mulish-Regular'),*/
/* url('assets/fonts/mulish-regular.woff2') format('woff2');*/
font-weight: 400;
font-style: normal;
font-display: block;
}
@font-face {
font-family: Helvetica, Arial, sans-serif;
/*src: local('Mulish Bold'), local('Mulish-Bold'),*/
/* url('assets/fonts/mulish-bold.woff2') format('woff2');*/
font-weight: 700;
font-style: normal;
font-display: block;
}
html {
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
body, button, input, optgroup, select, textarea {
font-family: Helvetica, Arial, sans-serif;
}
body {
margin: 0;
}
body.plugin {
min-width: 400px;
min-height: 600px;
}
body.disable-animations * {
transition-duration: 0s !important;
animation-duration: 0s !important;
}
.body-container {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: white;
overflow-x: hidden;
overflow-y: scroll;
}
* {
box-sizing: border-box;
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
}
a, a:focus, a:active, a:after {
color: #3CA4DB;
}
input {
width: 100%;
border: none;
border-bottom: 1px solid transparent;
height: 40px;
margin-top: 10px;
margin-bottom: 10px;
font-size: 14px;
outline: none;
border-radius: 0;
padding-left: 0;
padding-right: 0;
user-select: auto;
-webkit-user-select: auto;
-moz-user-select: auto;
background-image: linear-gradient(rgba(215, 77, 77, 0), rgba(215, 77, 77, 0)), linear-gradient(rgba(60, 164, 219, 0), rgba(60, 164, 219, 0)), linear-gradient(#e7e7e7, #e7e7e7);
background-size: 0% 1px, 0% 1px, 100% 1px;
background-position: bottom center;
background-repeat: no-repeat;
transition: 0.2s background-image, 0s 0.2s background-size;
}
input:focus {
background-image: linear-gradient(rgba(215, 77, 77, 0), rgba(215, 77, 77, 0)), linear-gradient(rgba(60, 164, 219, 1), rgba(60, 164, 219, 1)), linear-gradient(#e7e7e7, #e7e7e7);
background-size: 100% 1px, 100% 1px, 100% 1px;
transition: 0.2s background-image, 0.2s background-size;
}
input.error {
background-image: linear-gradient(rgba(215, 77, 77, 1), rgba(215, 77, 77, 1)), linear-gradient(rgba(60, 164, 219, 0), rgba(60, 164, 219, 0)), linear-gradient(#e7e7e7, #e7e7e7);
background-size: 100% 1px, 100% 1px, 100% 1px;
transition: 0.2s background-image, 0.2s background-size;
}
::-webkit-input-placeholder { /* Edge */
color: #999999;
}
::placeholder {
color: #999999;
}
.input-label {
font-weight: 700;
color: #3CA4DB;
}
button {
cursor: pointer;
outline: none;
}
.btn-blue {
border: none;
background: #3CA4DB;
color: white;
border-radius: 2px;
height: 39px;
font-size: 15px;
font-weight: 700;
}
.btn-lite {
border: none;
color: #3CA4DB;
height: 40px;
font-size: 15px;
font-weight: 700;
background: none;
}
.btn-lite-red {
color: #D74D4D;
}
.btn-round {
border: none;
border-radius: 50%;
color: #919191;
width: 40px;
height: 40px;
background-position: center;
background-repeat: no-repeat;
background-size: 50%;
background-color: transparent;
opacity: .5;
}
.btn-round:hover, .btn-round:active {
background-color: #2E2F31;
}
.btn-loader {
pointer-events: none;
}
.btn-loader:after {
content: '';
position: absolute;
transform: translate(8px, 2px);
width: 8px;
height: 8px;
border: 3px solid white;
border-left: 3px solid transparent;
border-radius: 50%;
animation: loading-animation-spin 2s infinite linear;
}
.btn-lite.btn-loader:after {
transform: translate(6px, 3px);
width: 6px;
height: 6px;
border: 2px solid #3CA4DB;
border-left: 2px solid transparent;
animation: loading-animation-spin-small 2s infinite linear;
}
.btn-back {
position: fixed;
top: 10px;
left: 10px;
width: 40px;
height: 40px;
background-position: center;
background-repeat: no-repeat;
background-size: 20px 20px;
border: none;
background-color: transparent;
background-image: url("../assets/ui/arrow.svg");
transform: scaleX(-1);
border-radius: 100%;
background-color: white;
}
.btn-back:hover {
background-color: #F7F7F7;
}
@keyframes loading-animation-spin {
to {
transform: translate(8px, 2px) rotate(1turn);
}
}
@keyframes loading-animation-spin-small {
to {
transform: translate(6px, 3px) rotate(1turn);
}
}
.screen {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: white;
}
.middle {
width: 100%;
min-height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.middle-content {
text-align: center;
}
.screen.faded-show {
opacity: 1;
visibility: inherit !important;
transition: 0.3s opacity, 0.3s visibility step-start;
}
.screen.faded-hide {
opacity: 0;
visibility: hidden;
transition: 0.3s opacity, 0.3s visibility step-end;
animation: 99999999s 0.3s screen-delayed-overflow;
}
.screen.faded-show .middle {
animation: screen-show-left 0.3s ease-out;
}
.screen.faded-hide .middle {
animation: screen-hide-left 0.3s ease-in;
}
.screen.faded-show.isBack .middle {
animation: screen-show-right 0.3s ease-out;
}
.screen.faded-hide.isBack .middle {
animation: screen-hide-right 0.3s ease-in;
}
.screen.faded-show .screen-lottie {
opacity: 1;
transform: scale(1);
transition: 0.2s opacity, transform 0.2s;
}
.screen.faded-hide .screen-lottie {
opacity: 0;
transform: scale(0.3);
transition: 0.2s opacity, transform 0.25s;
}
@keyframes screen-delayed-overflow {
from {
overflow: hidden
}
}
@keyframes screen-hide-left {
from {
transform: translateX(0px)
}
to {
transform: translateX(-25px)
}
}
@keyframes screen-hide-right {
from {
transform: translateX(0px)
}
to {
transform: translateX(25px)
}
}
@keyframes screen-show-left {
from {
transform: translateX(25px)
}
to {
transform: translateX(0px)
}
}
@keyframes screen-show-right {
from {
transform: translateX(-25px)
}
to {
transform: translateX(0px)
}
}
.addr {
min-width: 24ch;
max-width: 24ch;
hyphens: manual;
user-select: text;
-webkit-user-select: text;
-moz-user-select: text;
cursor: text;
}
/* SCREENS */
.screen-lottie {
display: block;
width: 120px;
height: 120px;
margin-left: auto;
margin-right: auto;
margin-top: 15px;
margin-bottom: 13px;
}
.screen-title {
font-size: 20px;
font-weight: 700;
}
.screen-text {
font-size: 15px;
line-height: 19px;
color: #999;
margin-top: 8px;
margin-bottom: 20px
}
.screen-btn {
width: 190px;
}
#notify {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
padding: 10px;
background-color: rgba(0, 0, 0, 0.8);
border-radius: 4px;
color: white;
font-size: 14px;
text-align: center;
opacity: 0;
visibility: hidden;
transition: 0.15s opacity, 0.15s visibility step-end;
}
#notify.faded-show {
opacity: 1;
visibility: inherit !important;
transition: 0.15s opacity, 0.15s visibility step-start;
}
/* SET PASSWORD */
#createPassword input {
width: 200px;
text-align: center;
font-size: 15px;
}
/* IMPORT && BACKUP && CONFIRM */
#import .btn-lite {
font-weight: 400;
font-size: 14px;
margin-bottom: 10px;
}
#importWords,
#confirmWords,
#createWords {
max-width: 276px;
margin-left: auto;
margin-right: auto;
}
#wordsPopup,
#wordsConfirmPopup {
position: absolute;
background: white;
padding-top: 4px;
padding-bottom: 4px;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
width: 92px;
max-height: 100px;
overflow-x: hidden;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
text-align: left;
border: 1px solid #DCDCDC;
}
#wordsConfirmPopup {
width: 190px;
}
.words-popup-item {
font-size: 14px;
line-height: 30px;
cursor: pointer;
padding-left: 20px;
padding-right: 20px;
}
.words-popup-item:hover {
background: #f0f0f0;
}
.words-popup-item.selected {
background: #f0f0f0;
}
.word-item {
float: left;
}
.word-num {
display: inline-block;
width: 20px;
text-align: right;
font-size: 14px;
color: #999;
margin-right: 4px;
}
#import .word-num,
#wordsConfirm .word-num {
margin-right: 8px;
margin-left: 16px;
}
#import input,
#wordsConfirm input {
width: 92px;
height: 32px;
margin-top: 0;
margin-bottom: 0;
}
#wordsConfirm input {
width: 190px;
}
.create-word-item {
float: left;
width: 136px;
margin-top: 8px;
margin-bottom: 8px;
font-size: 14px;
text-align: left;
}
/* MAIN> */
#main {
display: flex;
flex-direction: column;
}
.head {
width: 100%;
background: #000;
color: white;
text-align: center;
padding-bottom: 25px;
}
.head-row {
color: #919191;
display: flex;
align-items: center;
justify-content: center;
padding: 10px;
margin-bottom: 44px
}
#updateLabel {
flex-grow: 1;
font-size: 14px
}
.balance-container {
margin-bottom: 6px;
display: flex;
align-items: center;
justify-content: center;
}
#balance {
font-size: 32px;
}
.balance-symbol {
width: 32px;
height: 32px;
}
@keyframes MoveUpDown {
0%, 100% {
transform: translate(0, -2px);
}
50% {
transform: translate(0, 2px);
}
}
.balance-diamond-container {
position: relative;
width: 48px;
height: 48px;
margin-left: -4px;
}
#diamond {
position: absolute;
left: 0;
top: 0;
width: 48px;
height: 48px;
background-repeat: no-repeat;
background-position: center;
background-size: 110%;
animation: MoveUpDown 3s linear infinite;
}
.your-balance {
font-size: 14px;
margin-bottom: 49px;
color: #eee
}
#main .btn-blue {
width: 140px;
margin-left: 10px;
margin-right: 10px;
}
@media (max-width: 450px) {
#main .btn-blue {
width: 100px;
margin-left: 4px;
margin-right: 4px;
}
}
@media (max-width: 320px) {
#main .btn-blue {
width: 85px;
margin-left: 2px;
margin-right: 2px;
}
}
.btn-icon {
display: inline-block;
width: 10px;
height: 10px;
background-position: center;
background-repeat: no-repeat;
background-size: contain;
margin-right: 4px;
}
#walletCreated {
text-align: center;
position: absolute;
top: 70px;
left: 50%;
margin-left: -75px;
font-weight: 700;
font-size: 20px;
}
#walletCreated tgs-player {
display: block;
width: 150px;
height: 150px;
margin-bottom: 20px;
}
/* menu dropdown */
#menuDropdown {
position: absolute;
right: 50px;
top: 50px;
background: white;
padding-top: 10px;
padding-bottom: 10px;
border-radius: 4px;
min-width: 180px;
}
.dropdown-item {
font-size: 14px;
line-height: 30px;
cursor: pointer;
padding-left: 20px;
padding-right: 20px;
position: relative;
}
.dropdown-item:hover {
background: #f0f0f0;
}
/* menu dropdown toggle */
.dropdown-toggle {
position: absolute;
top: 4px;
right: 8px;
width: 46px;
height: 24px;
background-color: #ddd;
border-radius: 16px;
}
.dropdown-toggle:after {
content: '';
position: absolute;
left: 2px;
top: 2px;
border-radius: 50%;
width: 20px;
height: 20px;
background-color: #fff;
box-shadow: 0 3px 3px rgba(0, 0, 0, 0.2);
transition: left 0.2s cubic-bezier(0, 1, 0.5, 1);
}
.dropdown-toggle.toggle-on {
background-color: #3CA4DB;
}
.toggle-on.dropdown-toggle:after {
left: 24px;
}
/* TRANSACTIONS */
#transactionsContainer {
position: relative;
width: 100%;
flex-grow: 1;
overflow-x: hidden;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
}
#transactionsList {
padding-left: 20px;
padding-right: 20px;
padding-top: 10px;
}
.date-separator {
font-weight: 700;
padding-top: 10px;
padding-bottom: 10px;
font-size: 14px;
width: 100%;
max-width: 480px;
margin-left: auto;
margin-right: auto;
}
.tx-item {
position: relative;
padding-bottom: 10px;
margin-bottom: 10px;
border-bottom: 1px solid #E7E7E7;
cursor: pointer;
width: 100%;
max-width: 480px;
margin-left: auto;
margin-right: auto;
}
.tx-item-encrypted-icon {
position: absolute;
right: 0px;
top: 30px;
width: 32px;
height: 32px;
background-image: url("../assets/ui/encrypted-message.png");
background-size: contain;
background-repeat: no-repeat;
}
.tx-amount {
font-weight: 700;
font-size: 16px;
color: #D74D4D;
}
.tx-amount-green {
color: #39B139;
}
.tx-from {
font-size: 13px;
}
.tx-addr {
font-family: monospace;
font-size: 15px;
margin-top: 4px;
margin-bottom: 4px;
word-break: keep-all;
}
.tx-comment {
color: #000;
font-size: 13px;
margin-top: 8px;
margin-bottom: 8px;
}
.tx-fee {
color: #999999;
font-size: 13px;
}
.tx-item-date {
position: absolute;
top: 0;
right: 0;
color: #999999;
font-size: 13px;
line-height: 26px;
}
/* POPUP */
#modal {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.2);
}
.popup {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
box-shadow: 0px 8px 24px rgba(0, 0, 0, .25);
width: 320px;
background-color: white;
border-radius: 4px;
padding: 20px;
font-size: 14px;
}
.popup#alert {
position: fixed;
}
.popup.faded-show,
#menuDropdown.faded-show,
#modal.faded-show {
opacity: 1;
visibility: inherit !important;
transition: 0.15s opacity, 0.15s visibility step-start;
}
.popup.faded-hide,
#menuDropdown.faded-hide,
#modal.faded-hide {
opacity: 0;
visibility: hidden;
transition: 0.15s opacity, 0.15s visibility step-end;
}
.popup-title {
font-weight: 700;
margin-bottom: 20px;
font-size: 17px;
}
.popup-text {
font-size: 14px;
line-height: 18px;
}
.popup-black-text {
font-size: 14px;
line-height: 18px;
}
.about-magic {
display: none;
text-align: left;
}
.plugin .about-magic {
display: block;
}
.about-magic h4 {
margin-bottom: 12px;
}
.about-magic p {
margin-top: 12px;
}
.popup-grey-text {
line-height: 18px;
color: #999999;
font-size: 14px;
margin-bottom: 20px
}
.popup-close-btn {
position: absolute;
top: 10px;
right: 10px;
width: 32px;
height: 32px;
background-position: center;
background-repeat: no-repeat;
background-size: 40%;
border: none;
background-color: transparent;
background-image: url("../assets/ui/close.svg");
}
.popup-footer {
text-align: right;
margin-top: 10px;
}
.popup .btn-blue {
width: 100%;
}
.popup tgs-player {
display: block;
width: 150px;
height: 150px;
margin-left: auto;
margin-right: auto
}
.popup input {
margin-top: 6px;
margin-bottom: 6px;
height: 36px;
}
/* RECEIVE POPUP */
.qr-container {
text-align: center;
margin: 20px 0px 20px 0px;
}
#qr, #invoiceQrImg {
width: 185px;
height: 185px;
margin-left: auto;
margin-right: auto;
}
#qr img, #invoiceQrImg img, #invoiceQrImg canvas {
width: 185px;
height: 185px;
}
#receive .my-addr {
font-family: monospace;
text-align: center;
font-size: 18px;
margin-top: -4px;
max-width: 280px;
height: 42px;
cursor: pointer;
}
#receive .btn-lite {
text-align: center;
width: 100%;
font-weight: 400;
}
#receive .btn-lite-first {
margin-top: 20px;
}
#receive .btn-blue {
margin-top: 10px;
}
/* SEND POPUP */
#send .btn-blue {
margin-top: 20px;
}
#sendBalance {
position: absolute;
right: 0;
top: 0;
color: #999999;
font-size: 14px;
}
#sendConfirm .addr, #signConfirm .addr {
font-family: monospace;
text-align: center;
font-size: 18px;
margin-top: 10px;
margin-bottom: 10px;
max-width: 280px;
padding: 10px;
background-color: #F1F1F1;
}
#encryptCommentCheckboxContainer {
display: flex;
flex-direction: row;
align-items: center;
margin-top: 12px;
}
#encryptCommentCheckbox {
}
/* INVOICE POPUP */
#invoice .popup-black-text {
margin-top: 10px;
margin-bottom: 10px;
word-break: break-all;
}
#invoice .btn-lite {
text-align: center;
width: 100%;
font-weight: 400;
}
#invoice .btn-blue {
margin-top: 10px;
}
#invoiceQr .btn-blue {
margin-top: 20px;
}
#invoice_link {
user-select: text;
-webkit-user-select: text;
-moz-user-select: text;
cursor: text;
}
/* TRANSACTION POPUP */
#transactionSender {
font-family: monospace;
max-width: 280px;
font-size: 18px;
margin-top: 4px;
margin-bottom: 4px;
}
#transactionComment {
word-break: break-all;
}
#transactionDecryptCommentButton {
margin-top: 10px;
margin-bottom: 10px;
font-weight: normal;
height: auto;
cursor: pointer;
}
#transactionAmount {
font-size: 28px;
text-align: center;
margin-bottom: 8px;
}
#transactionFee {
color: #999;
text-align: center;
}
#transaction .input-label {
margin-top: 20px;
margin-bottom: 10px;
}
/* EXTENSION */
#menu_magic {
display: none;
}
#menu_proxy {
display: none;
pointer-events: none;
}
#menu_telegram {
display: none;
}
.plugin .menu_telegram-show {
display: block !important;
}
#menu_proxy:after {
position: absolute;
top: 4px;
line-height: 8px;
right: 70px;
width: 14px;
height: 8px;
font-size: 10px;
color: #1d98dc;
border-radius: 4px;
padding: 4px;
content: 'Soon';
}
.plugin #menu_magic {
display: block;
}
.plugin #menu_proxy {
display: block;
}
.plugin #menu_extension_chrome {
display: none;
}
#menu_extension_firefox {
display: none;
}
.plugin #start_importLedgerHidBtn {
display: none;
}
#start_importLedgerHidBtn {
display: none;
}
.input-password {
text-align: center;
width: 200px;
margin-left: 40px;
font-size: 15px;
}
.display-none {
display: none;
}
.visibility-hidden {
visibility: hidden;
}
.rotate-180 {
transform: rotate(180deg);
}
.position-relative {
position: relative;
}
.clear-both {
clear: both;
}
.font-weight-normal {
font-weight: 400;
}
.font-weight-bold {
font-weight: 700;
}
.text-danger {
color: #D74D4D;
}
.line-height-24 {
line-height: 24px;
}
.text-align-center {
text-align: center;
}
.bg-down-left {
background-image: url('../assets/ui/down-left.svg')
}
.bg-menu {
background-image: url('../assets/ui/menu.svg')
}
.bg-refresh {
background-image: url('../assets/ui/refresh.svg')
}
.w-100 {
width: 100%;
}
.mb-10 {
margin-bottom: 10px;
}
.mb-18 {
margin-bottom: 18px;
}
.mb-20 {
margin-bottom: 20px;
}
.mt-10 {
margin-top: 10px;
}
.mt-18 {
margin-top: 18px;
}
.mt-20 {
margin-top: 20px;
}
.mt-24 {
margin-top: 24px;
}
.mt-26 {
margin-top: 26px;
}
.mt-30 {
margin-top: 30px;
}
.mt-38 {
margin-top: 38px;
}
.mt-54 {
margin-top: 54px;
}
.mt-80 {
margin-top: 95px;
}
.mt-95 {
margin-top: 95px;
}
.mt-170 {
margin-top: 170px;
}
.pb-10 {
padding-bottom: 10px;
}
/* checkbox */
.checkbox-container {
display: block;
position: relative;
padding-left: 24px;
line-height: 18px;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.checkbox-container input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 18px;
width: 18px;
background-color: #eee;
}
.checkbox-container input:checked ~ .checkmark {
background-color: #3CA4DB;
}
.checkmark:after {
content: "";
position: absolute;
display: none;
}
.checkbox-container input:checked ~ .checkmark:after {
display: block;
}
.checkbox-container .checkmark:after {
left: 6px;
top: 2px;
width: 4px;
height: 8px;
border: solid white;
border-width: 0 3px 3px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
================================================
FILE: license
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: package.json
================================================
{
"name": "ton-wallet",
"version": "1.1.50",
"devDependencies": {
"gulp": "4.0.2",
"gulp-replace": "1.1.3",
"gulp-zip": "5.1.0",
"open": "8.4.0",
"webpack": "5.70.0"
},
"scripts": {
"dev": "gulp dev --gulpfile build/gulpfile.js --cwd . --target",
"watch": "gulp watch --gulpfile build/gulpfile.js --cwd . --target",
"start": "gulp start --gulpfile build/gulpfile.js --cwd . --target",
"build": "gulp build --gulpfile build/gulpfile.js --cwd . --target",
"pack": "gulp pack --gulpfile build/gulpfile.js --cwd . --target"
}
}
================================================
FILE: readme.md
================================================
# ⚠️ Archived
This is the first web wallet in TON. The code may be useful for learning or nostalgia. The actual code of wallet.ton.org is available at https://github.com/ton-blockchain/ton-wallet.
# TON Wallet
TON Wallet is a free client-side interface for interact with The Open Network blockchain.
- [Website (wallet.ton.org)](https://wallet.ton.org)
- [Chrome extension (also available for any Chromium-based browser)](https://chrome.google.com/webstore/detail/ton-wallet/nphplpgoakhhjchkkhmiggakijnkhfnd)
- Firefox Add-on (so far only manual build from source)
- Safari extension (so far only manual build from source)
## Security
Private keys do not leave your device, the keys are stored in the browser memory, encrypted with a password that is entered during transaction generation.
## Issues and proposals
Please, post your issues and proposals as Issues in this repository.
## Switch between mainnet and testnet
- Support from 1.1.35 version
- Open menu in right-top corner and select `About` item
- Click on `Version:` label with Shift key pressed
## Development
See [build](build) project directory.
## Support browsers:
- Chrome (and Chromium-based) 55+ for website version, 88+ for extension
- Firefox 63+
- Safari 11+ (MacOS 10.12+) for website version, 14+ for extension
- Safari iOS 11+
- Edge 79+
- Opera 42+
- Chrome for Android 55+
- Android 5+ browser
- Samsung Internet 6+
- Opera Mobile 64+
- UC Browser 12.12+
- Firefox for Android 63+
================================================
FILE: src/assets/favicon/browserconfig.xml
================================================
#ffffff
================================================
FILE: src/assets/favicon/site.webmanifest
================================================
{
"name": "TON Wallet",
"short_name": "TON Wallet",
"icons": [
{
"src": "36x36.png",
"sizes": "36x36",
"type": "image/png"
},
{
"src": "48x48.png",
"sizes": "48x48",
"type": "image/png"
},
{
"src": "72x72.png",
"sizes": "72x72",
"type": "image/png"
},
{
"src": "96x96.png",
"sizes": "96x96",
"type": "image/png"
},
{
"src": "144x144.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "256x256.png",
"sizes": "256x256",
"type": "image/png"
},
{
"src": "384x384.png",
"sizes": "384x384",
"type": "image/png"
},
{
"src": "512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
}
================================================
FILE: src/css/main.css
================================================
@font-face {
font-family: Helvetica, Arial, sans-serif;
/*src: local('Mulish Regular'), local('Mulish-Regular'),*/
/* url('assets/fonts/mulish-regular.woff2') format('woff2');*/
font-weight: 400;
font-style: normal;
font-display: block;
}
@font-face {
font-family: Helvetica, Arial, sans-serif;
/*src: local('Mulish Bold'), local('Mulish-Bold'),*/
/* url('assets/fonts/mulish-bold.woff2') format('woff2');*/
font-weight: 700;
font-style: normal;
font-display: block;
}
html {
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
body, button, input, optgroup, select, textarea {
font-family: Helvetica, Arial, sans-serif;
}
body {
margin: 0;
}
body.plugin {
min-width: 400px;
min-height: 600px;
}
body.disable-animations * {
transition-duration: 0s !important;
animation-duration: 0s !important;
}
.body-container {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: white;
overflow-x: hidden;
overflow-y: scroll;
}
* {
box-sizing: border-box;
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
}
a, a:focus, a:active, a:after {
color: #3CA4DB;
}
input {
width: 100%;
border: none;
border-bottom: 1px solid transparent;
height: 40px;
margin-top: 10px;
margin-bottom: 10px;
font-size: 14px;
outline: none;
border-radius: 0;
padding-left: 0;
padding-right: 0;
user-select: auto;
-webkit-user-select: auto;
-moz-user-select: auto;
background-image: linear-gradient(rgba(215, 77, 77, 0), rgba(215, 77, 77, 0)), linear-gradient(rgba(60, 164, 219, 0), rgba(60, 164, 219, 0)), linear-gradient(#e7e7e7, #e7e7e7);
background-size: 0% 1px, 0% 1px, 100% 1px;
background-position: bottom center;
background-repeat: no-repeat;
transition: 0.2s background-image, 0s 0.2s background-size;
}
input:focus {
background-image: linear-gradient(rgba(215, 77, 77, 0), rgba(215, 77, 77, 0)), linear-gradient(rgba(60, 164, 219, 1), rgba(60, 164, 219, 1)), linear-gradient(#e7e7e7, #e7e7e7);
background-size: 100% 1px, 100% 1px, 100% 1px;
transition: 0.2s background-image, 0.2s background-size;
}
input.error {
background-image: linear-gradient(rgba(215, 77, 77, 1), rgba(215, 77, 77, 1)), linear-gradient(rgba(60, 164, 219, 0), rgba(60, 164, 219, 0)), linear-gradient(#e7e7e7, #e7e7e7);
background-size: 100% 1px, 100% 1px, 100% 1px;
transition: 0.2s background-image, 0.2s background-size;
}
::-webkit-input-placeholder { /* Edge */
color: #999999;
}
::placeholder {
color: #999999;
}
.input-label {
font-weight: 700;
color: #3CA4DB;
}
button {
cursor: pointer;
outline: none;
}
.btn-blue {
border: none;
background: #3CA4DB;
color: white;
border-radius: 2px;
height: 39px;
font-size: 15px;
font-weight: 700;
}
.btn-lite {
border: none;
color: #3CA4DB;
height: 40px;
font-size: 15px;
font-weight: 700;
background: none;
}
.btn-lite-red {
color: #D74D4D;
}
.btn-round {
border: none;
border-radius: 50%;
color: #919191;
width: 40px;
height: 40px;
background-position: center;
background-repeat: no-repeat;
background-size: 50%;
background-color: transparent;
opacity: .5;
}
.btn-round:hover, .btn-round:active {
background-color: #2E2F31;
}
.btn-loader {
pointer-events: none;
}
.btn-loader:after {
content: '';
position: absolute;
transform: translate(8px, 2px);
width: 8px;
height: 8px;
border: 3px solid white;
border-left: 3px solid transparent;
border-radius: 50%;
animation: loading-animation-spin 2s infinite linear;
}
.btn-lite.btn-loader:after {
transform: translate(6px, 3px);
width: 6px;
height: 6px;
border: 2px solid #3CA4DB;
border-left: 2px solid transparent;
animation: loading-animation-spin-small 2s infinite linear;
}
.btn-back {
position: fixed;
top: 10px;
left: 10px;
width: 40px;
height: 40px;
background-position: center;
background-repeat: no-repeat;
background-size: 20px 20px;
border: none;
background-color: transparent;
background-image: url("../assets/ui/arrow.svg");
transform: scaleX(-1);
border-radius: 100%;
background-color: white;
}
.btn-back:hover {
background-color: #F7F7F7;
}
@keyframes loading-animation-spin {
to {
transform: translate(8px, 2px) rotate(1turn);
}
}
@keyframes loading-animation-spin-small {
to {
transform: translate(6px, 3px) rotate(1turn);
}
}
.screen {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: white;
}
.middle {
width: 100%;
min-height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.middle-content {
text-align: center;
}
.screen.faded-show {
opacity: 1;
visibility: inherit !important;
transition: 0.3s opacity, 0.3s visibility step-start;
}
.screen.faded-hide {
opacity: 0;
visibility: hidden;
transition: 0.3s opacity, 0.3s visibility step-end;
animation: 99999999s 0.3s screen-delayed-overflow;
}
.screen.faded-show .middle {
animation: screen-show-left 0.3s ease-out;
}
.screen.faded-hide .middle {
animation: screen-hide-left 0.3s ease-in;
}
.screen.faded-show.isBack .middle {
animation: screen-show-right 0.3s ease-out;
}
.screen.faded-hide.isBack .middle {
animation: screen-hide-right 0.3s ease-in;
}
.screen.faded-show .screen-lottie {
opacity: 1;
transform: scale(1);
transition: 0.2s opacity, transform 0.2s;
}
.screen.faded-hide .screen-lottie {
opacity: 0;
transform: scale(0.3);
transition: 0.2s opacity, transform 0.25s;
}
@keyframes screen-delayed-overflow {
from {
overflow: hidden
}
}
@keyframes screen-hide-left {
from {
transform: translateX(0px)
}
to {
transform: translateX(-25px)
}
}
@keyframes screen-hide-right {
from {
transform: translateX(0px)
}
to {
transform: translateX(25px)
}
}
@keyframes screen-show-left {
from {
transform: translateX(25px)
}
to {
transform: translateX(0px)
}
}
@keyframes screen-show-right {
from {
transform: translateX(-25px)
}
to {
transform: translateX(0px)
}
}
.addr {
min-width: 24ch;
max-width: 24ch;
hyphens: manual;
user-select: text;
-webkit-user-select: text;
-moz-user-select: text;
cursor: text;
}
/* SCREENS */
.screen-lottie {
display: block;
width: 120px;
height: 120px;
margin-left: auto;
margin-right: auto;
margin-top: 15px;
margin-bottom: 13px;
}
.screen-title {
font-size: 20px;
font-weight: 700;
}
.screen-text {
font-size: 15px;
line-height: 19px;
color: #999;
margin-top: 8px;
margin-bottom: 20px
}
.screen-btn {
width: 190px;
}
#notify {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
padding: 10px;
background-color: rgba(0, 0, 0, 0.8);
border-radius: 4px;
color: white;
font-size: 14px;
text-align: center;
opacity: 0;
visibility: hidden;
transition: 0.15s opacity, 0.15s visibility step-end;
}
#notify.faded-show {
opacity: 1;
visibility: inherit !important;
transition: 0.15s opacity, 0.15s visibility step-start;
}
/* SET PASSWORD */
#createPassword input {
width: 200px;
text-align: center;
font-size: 15px;
}
/* IMPORT && BACKUP && CONFIRM */
#import .btn-lite {
font-weight: 400;
font-size: 14px;
margin-bottom: 10px;
}
#importWords,
#confirmWords,
#createWords {
max-width: 276px;
margin-left: auto;
margin-right: auto;
}
#wordsPopup,
#wordsConfirmPopup {
position: absolute;
background: white;
padding-top: 4px;
padding-bottom: 4px;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
width: 92px;
max-height: 100px;
overflow-x: hidden;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
text-align: left;
border: 1px solid #DCDCDC;
}
#wordsConfirmPopup {
width: 190px;
}
.words-popup-item {
font-size: 14px;
line-height: 30px;
cursor: pointer;
padding-left: 20px;
padding-right: 20px;
}
.words-popup-item:hover {
background: #f0f0f0;
}
.words-popup-item.selected {
background: #f0f0f0;
}
.word-item {
float: left;
}
.word-num {
display: inline-block;
width: 20px;
text-align: right;
font-size: 14px;
color: #999;
margin-right: 4px;
}
#import .word-num,
#wordsConfirm .word-num {
margin-right: 8px;
margin-left: 16px;
}
#import input,
#wordsConfirm input {
width: 92px;
height: 32px;
margin-top: 0;
margin-bottom: 0;
}
#wordsConfirm input {
width: 190px;
}
.create-word-item {
float: left;
width: 136px;
margin-top: 8px;
margin-bottom: 8px;
font-size: 14px;
text-align: left;
}
/* MAIN> */
#main {
display: flex;
flex-direction: column;
}
.head {
width: 100%;
background: #000;
color: white;
text-align: center;
padding-bottom: 25px;
}
.head-row {
color: #919191;
display: flex;
align-items: center;
justify-content: center;
padding: 10px;
margin-bottom: 44px
}
#updateLabel {
flex-grow: 1;
font-size: 14px
}
.balance-container {
margin-bottom: 6px;
display: flex;
align-items: center;
justify-content: center;
}
#balance {
font-size: 32px;
}
.balance-symbol {
width: 32px;
height: 32px;
}
@keyframes MoveUpDown {
0%, 100% {
transform: translate(0, -2px);
}
50% {
transform: translate(0, 2px);
}
}
.balance-diamond-container {
position: relative;
width: 48px;
height: 48px;
margin-left: -4px;
}
#diamond {
position: absolute;
left: 0;
top: 0;
width: 48px;
height: 48px;
background-repeat: no-repeat;
background-position: center;
background-size: 110%;
animation: MoveUpDown 3s linear infinite;
}
.your-balance {
font-size: 14px;
margin-bottom: 49px;
color: #eee
}
#main .btn-blue {
width: 140px;
margin-left: 10px;
margin-right: 10px;
}
@media (max-width: 450px) {
#main .btn-blue {
width: 100px;
margin-left: 4px;
margin-right: 4px;
}
}
@media (max-width: 320px) {
#main .btn-blue {
width: 85px;
margin-left: 2px;
margin-right: 2px;
}
}
.btn-icon {
display: inline-block;
width: 10px;
height: 10px;
background-position: center;
background-repeat: no-repeat;
background-size: contain;
margin-right: 4px;
}
#walletCreated {
text-align: center;
position: absolute;
top: 70px;
left: 50%;
margin-left: -75px;
font-weight: 700;
font-size: 20px;
}
#walletCreated tgs-player {
display: block;
width: 150px;
height: 150px;
margin-bottom: 20px;
}
/* menu dropdown */
#menuDropdown {
position: absolute;
right: 50px;
top: 50px;
background: white;
padding-top: 10px;
padding-bottom: 10px;
border-radius: 4px;
min-width: 180px;
}
.dropdown-item {
font-size: 14px;
line-height: 30px;
cursor: pointer;
padding-left: 20px;
padding-right: 20px;
position: relative;
}
.dropdown-item:hover {
background: #f0f0f0;
}
/* menu dropdown toggle */
.dropdown-toggle {
position: absolute;
top: 4px;
right: 8px;
width: 46px;
height: 24px;
background-color: #ddd;
border-radius: 16px;
}
.dropdown-toggle:after {
content: '';
position: absolute;
left: 2px;
top: 2px;
border-radius: 50%;
width: 20px;
height: 20px;
background-color: #fff;
box-shadow: 0 3px 3px rgba(0, 0, 0, 0.2);
transition: left 0.2s cubic-bezier(0, 1, 0.5, 1);
}
.dropdown-toggle.toggle-on {
background-color: #3CA4DB;
}
.toggle-on.dropdown-toggle:after {
left: 24px;
}
/* TRANSACTIONS */
#transactionsContainer {
position: relative;
width: 100%;
flex-grow: 1;
overflow-x: hidden;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
}
#transactionsList {
padding-left: 20px;
padding-right: 20px;
padding-top: 10px;
}
.date-separator {
font-weight: 700;
padding-top: 10px;
padding-bottom: 10px;
font-size: 14px;
width: 100%;
max-width: 480px;
margin-left: auto;
margin-right: auto;
}
.tx-item {
position: relative;
padding-bottom: 10px;
margin-bottom: 10px;
border-bottom: 1px solid #E7E7E7;
cursor: pointer;
width: 100%;
max-width: 480px;
margin-left: auto;
margin-right: auto;
}
.tx-item-encrypted-icon {
position: absolute;
right: 0px;
top: 30px;
width: 32px;
height: 32px;
background-image: url("../assets/ui/encrypted-message.png");
background-size: contain;
background-repeat: no-repeat;
}
.tx-amount {
font-weight: 700;
font-size: 16px;
color: #D74D4D;
}
.tx-amount-green {
color: #39B139;
}
.tx-from {
font-size: 13px;
}
.tx-addr {
font-family: monospace;
font-size: 15px;
margin-top: 4px;
margin-bottom: 4px;
word-break: keep-all;
}
.tx-comment {
color: #000;
font-size: 13px;
margin-top: 8px;
margin-bottom: 8px;
}
.tx-fee {
color: #999999;
font-size: 13px;
}
.tx-item-date {
position: absolute;
top: 0;
right: 0;
color: #999999;
font-size: 13px;
line-height: 26px;
}
/* POPUP */
#modal {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.2);
}
.popup {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
box-shadow: 0px 8px 24px rgba(0, 0, 0, .25);
width: 320px;
background-color: white;
border-radius: 4px;
padding: 20px;
font-size: 14px;
}
.popup#alert {
position: fixed;
}
.popup.faded-show,
#menuDropdown.faded-show,
#modal.faded-show {
opacity: 1;
visibility: inherit !important;
transition: 0.15s opacity, 0.15s visibility step-start;
}
.popup.faded-hide,
#menuDropdown.faded-hide,
#modal.faded-hide {
opacity: 0;
visibility: hidden;
transition: 0.15s opacity, 0.15s visibility step-end;
}
.popup-title {
font-weight: 700;
margin-bottom: 20px;
font-size: 17px;
}
.popup-text {
font-size: 14px;
line-height: 18px;
}
.popup-black-text {
font-size: 14px;
line-height: 18px;
}
.about-magic {
display: none;
text-align: left;
}
.plugin .about-magic {
display: block;
}
.about-magic h4 {
margin-bottom: 12px;
}
.about-magic p {
margin-top: 12px;
}
.popup-grey-text {
line-height: 18px;
color: #999999;
font-size: 14px;
margin-bottom: 20px
}
.popup-close-btn {
position: absolute;
top: 10px;
right: 10px;
width: 32px;
height: 32px;
background-position: center;
background-repeat: no-repeat;
background-size: 40%;
border: none;
background-color: transparent;
background-image: url("../assets/ui/close.svg");
}
.popup-footer {
text-align: right;
margin-top: 10px;
}
.popup .btn-blue {
width: 100%;
}
.popup tgs-player {
display: block;
width: 150px;
height: 150px;
margin-left: auto;
margin-right: auto
}
.popup input {
margin-top: 6px;
margin-bottom: 6px;
height: 36px;
}
/* RECEIVE POPUP */
.qr-container {
text-align: center;
margin: 20px 0px 20px 0px;
}
#qr, #invoiceQrImg {
width: 185px;
height: 185px;
margin-left: auto;
margin-right: auto;
}
#qr img, #invoiceQrImg img, #invoiceQrImg canvas {
width: 185px;
height: 185px;
}
#receive .my-addr {
font-family: monospace;
text-align: center;
font-size: 18px;
margin-top: -4px;
max-width: 280px;
height: 42px;
cursor: pointer;
}
#receive .btn-lite {
text-align: center;
width: 100%;
font-weight: 400;
}
#receive .btn-lite-first {
margin-top: 20px;
}
#receive .btn-blue {
margin-top: 10px;
}
/* SEND POPUP */
#send .btn-blue {
margin-top: 20px;
}
#sendBalance {
position: absolute;
right: 0;
top: 0;
color: #999999;
font-size: 14px;
}
#sendConfirm .addr, #signConfirm .addr {
font-family: monospace;
text-align: center;
font-size: 18px;
margin-top: 10px;
margin-bottom: 10px;
max-width: 280px;
padding: 10px;
background-color: #F1F1F1;
}
#encryptCommentCheckboxContainer {
display: flex;
flex-direction: row;
align-items: center;
margin-top: 12px;
}
#encryptCommentCheckbox {
}
/* INVOICE POPUP */
#invoice .popup-black-text {
margin-top: 10px;
margin-bottom: 10px;
word-break: break-all;
}
#invoice .btn-lite {
text-align: center;
width: 100%;
font-weight: 400;
}
#invoice .btn-blue {
margin-top: 10px;
}
#invoiceQr .btn-blue {
margin-top: 20px;
}
#invoice_link {
user-select: text;
-webkit-user-select: text;
-moz-user-select: text;
cursor: text;
}
/* TRANSACTION POPUP */
#transactionSender {
font-family: monospace;
max-width: 280px;
font-size: 18px;
margin-top: 4px;
margin-bottom: 4px;
}
#transactionComment {
word-break: break-all;
}
#transactionDecryptCommentButton {
margin-top: 10px;
margin-bottom: 10px;
font-weight: normal;
height: auto;
cursor: pointer;
}
#transactionAmount {
font-size: 28px;
text-align: center;
margin-bottom: 8px;
}
#transactionFee {
color: #999;
text-align: center;
}
#transaction .input-label {
margin-top: 20px;
margin-bottom: 10px;
}
/* EXTENSION */
#menu_magic {
display: none;
}
#menu_proxy {
display: none;
pointer-events: none;
}
#menu_telegram {
display: none;
}
.plugin .menu_telegram-show {
display: block !important;
}
#menu_proxy:after {
position: absolute;
top: 4px;
line-height: 8px;
right: 70px;
width: 14px;
height: 8px;
font-size: 10px;
color: #1d98dc;
border-radius: 4px;
padding: 4px;
content: 'Soon';
}
.plugin #menu_magic {
display: block;
}
.plugin #menu_proxy {
display: block;
}
.plugin #menu_extension_chrome {
display: none;
}
#menu_extension_firefox {
display: none;
}
.plugin #start_importLedgerHidBtn {
display: none;
}
#start_importLedgerHidBtn {
display: none;
}
.input-password {
text-align: center;
width: 200px;
margin-left: 40px;
font-size: 15px;
}
.display-none {
display: none;
}
.visibility-hidden {
visibility: hidden;
}
.rotate-180 {
transform: rotate(180deg);
}
.position-relative {
position: relative;
}
.clear-both {
clear: both;
}
.font-weight-normal {
font-weight: 400;
}
.font-weight-bold {
font-weight: 700;
}
.text-danger {
color: #D74D4D;
}
.line-height-24 {
line-height: 24px;
}
.text-align-center {
text-align: center;
}
.bg-down-left {
background-image: url('../assets/ui/down-left.svg')
}
.bg-menu {
background-image: url('../assets/ui/menu.svg')
}
.bg-refresh {
background-image: url('../assets/ui/refresh.svg')
}
.w-100 {
width: 100%;
}
.mb-10 {
margin-bottom: 10px;
}
.mb-18 {
margin-bottom: 18px;
}
.mb-20 {
margin-bottom: 20px;
}
.mt-10 {
margin-top: 10px;
}
.mt-18 {
margin-top: 18px;
}
.mt-20 {
margin-top: 20px;
}
.mt-24 {
margin-top: 24px;
}
.mt-26 {
margin-top: 26px;
}
.mt-30 {
margin-top: 30px;
}
.mt-38 {
margin-top: 38px;
}
.mt-54 {
margin-top: 54px;
}
.mt-80 {
margin-top: 95px;
}
.mt-95 {
margin-top: 95px;
}
.mt-170 {
margin-top: 170px;
}
.pb-10 {
padding-bottom: 10px;
}
/* checkbox */
.checkbox-container {
display: block;
position: relative;
padding-left: 24px;
line-height: 18px;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.checkbox-container input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 18px;
width: 18px;
background-color: #eee;
}
.checkbox-container input:checked ~ .checkmark {
background-color: #3CA4DB;
}
.checkmark:after {
content: "";
position: absolute;
display: none;
}
.checkbox-container input:checked ~ .checkmark:after {
display: block;
}
.checkbox-container .checkmark:after {
left: 6px;
top: 2px;
width: 4px;
height: 8px;
border: solid white;
border-width: 0 3px 3px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
================================================
FILE: src/index.html
================================================
TON Wallet
TON Wallet
TON wallet allows you to make fast and
secure blockchain-based payments
without intermediaries.
24 Secret Words
Please restore access to your non-hardware wallet by
entering the 24 secret words you wrote
down when creating the wallet.
Congratulations
Your TON wallet has just been created.
Only you control it.
To be able to always have access to it,
please set up a secure password and write
down secret words.
24 secret words
Write down these 24 words in the correct
order and store them in secret place.
Use these secret words to restore access to
your wallet if you lose your password or
access to this device.
Test Time!
Now let's check that you wrote your secret words correctly.
Please enter the words , and below:
Ready to go!
You're all set. Now you have a wallet that
only you control - directly, without
middlemen or bankers.
Your balance
================================================
FILE: src/js/Controller.js
================================================
import storage from './util/storage.js';
import {decryptMessageComment, encryptMessageComment, makeSnakeCells, parseSnakeCells} from "./util/encryption.js";
const TONCONNECT_MAINNET = '-239';
const TONCONNECT_TESTNET = '-3';
let extensionWindowId = -1;
let contentScriptPorts = new Set();
let popupPort = null;
const queueToPopup = [];
/**
* @type {Promise | null}
*/
let dAppPromise = null;
const createDappPromise = () => {
if (dAppPromise) dAppPromise.resolve(false);
let resolve;
let reject;
dAppPromise = new Promise((localResolve, localReject) => {
resolve = localResolve;
reject = localReject;
});
dAppPromise.resolve = (...args) => {
resolve(...args);
dAppPromise = null;
};
dAppPromise.reject = (...args) => {
reject(...args);
dAppPromise = null;
};
};
const showExtensionWindow = () => {
return new Promise(async resolve => {
if (extensionWindowId > -1) {
chrome.windows.update(extensionWindowId, {focused: true});
return resolve();
}
const windowState = (await storage.getItem('windowState')) || {};
windowState.top = windowState.top || 0;
windowState.left = windowState.left || 0;
windowState.height = windowState.height || 800;
windowState.width = windowState.width || 480;
chrome.windows.create(Object.assign(windowState, {
url: 'index.html',
type: 'popup',
focused: true
}), window => {
extensionWindowId = window.id;
resolve();
});
});
};
const BN = TonWeb.utils.BN;
const nacl = TonWeb.utils.nacl;
const Address = TonWeb.utils.Address;
const formatNanograms = TonWeb.utils.fromNano;
// ENCRYPTION
/**
* @param plaintext {string}
* @param password {string}
* @return {Promise}
*/
async function encrypt(plaintext, password) {
const pwUtf8 = new TextEncoder().encode(password); // encode password as UTF-8
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8); // hash the password
const iv = crypto.getRandomValues(new Uint8Array(12)); // get 96-bit random iv
const alg = {name: 'AES-GCM', iv: iv}; // specify algorithm to use
const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt']); // generate key from pw
const ptUint8 = new TextEncoder().encode(plaintext); // encode plaintext as UTF-8
const ctBuffer = await crypto.subtle.encrypt(alg, key, ptUint8); // encrypt plaintext using key
const ctArray = Array.from(new Uint8Array(ctBuffer)); // ciphertext as byte array
const ctStr = ctArray.map(byte => String.fromCharCode(byte)).join(''); // ciphertext as string
const ctBase64 = btoa(ctStr); // encode ciphertext as base64
const ivHex = Array.from(iv).map(b => ('00' + b.toString(16)).slice(-2)).join(''); // iv as hex string
return ivHex + ctBase64; // return iv+ciphertext
}
/**
* @param ciphertext {string}
* @param password {string}
* @return {Promise}
*/
async function decrypt(ciphertext, password) {
const pwUtf8 = new TextEncoder().encode(password); // encode password as UTF-8
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8); // hash the password
const iv = ciphertext.slice(0, 24).match(/.{2}/g).map(byte => parseInt(byte, 16)); // get iv from ciphertext
const alg = {name: 'AES-GCM', iv: new Uint8Array(iv)}; // specify algorithm to use
const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['decrypt']); // use pw to generate key
const ctStr = atob(ciphertext.slice(24)); // decode base64 ciphertext
const ctUint8 = new Uint8Array(ctStr.match(/[\s\S]/g).map(ch => ch.charCodeAt(0))); // ciphertext as Uint8Array
// note: why doesn't ctUint8 = new TextEncoder().encode(ctStr) work?
const plainBuffer = await crypto.subtle.decrypt(alg, key, ctUint8); // decrypt ciphertext using key
const plaintext = new TextDecoder().decode(plainBuffer); // decode password from UTF-8
return plaintext; // return the plaintext
}
// CONTROLLER
const IS_EXTENSION = !!(self.chrome && chrome.runtime && chrome.runtime.onConnect);
const ACCOUNT_NUMBER = 0;
const DEFAULT_WALLET_VERSION = 'v3R2';
const DEFAULT_LEDGER_WALLET_VERSION = 'v3R1';
class Controller {
constructor() {
/** @type {boolean} */
this.isTestnet = false;
/** @type {boolean} */
this.isDebug = false;
/** @type {string} */
this.myAddress = null;
/** @type {string} */
this.publicKeyHex = null;
/** @type {string[]} */
this.myMnemonicWords = null;
/** @type {BN | null} */
this.balance = null;
/** @type {WalletContract} */
this.walletContract = null;
this.transactions = [];
/** @type {number} */
this.updateIntervalId = 0;
/** @type {null | {totalAmount: BN, bodyHashBase64: string }} */
this.sendingData = null;
/** @type {boolean} */
this.processingVisible = false;
this.ledgerApp = null;
/** @type {boolean} */
this.isLedger = false;
/** @type {(words: string[]) => Promise | null} */
this.afterEnterPassword = null;
if (self.view) {
self.view.controller = this;
}
this.pendingMessageResolvers = new Map();
this._lastMsgId = 1;
if (IS_EXTENSION) {
setInterval(() => storage.setItem('__time', Date.now()), 5 * 1000);
}
this.whenReady = this._init();
}
debug(...args) {
if (!this.isDebug) return;
console.log(...args);
}
/**
* @param words {string[]}
* @return {Promise} base64
*/
static async wordsToPrivateKey(words) {
const keyPair = await TonWeb.mnemonic.mnemonicToKeyPair(words);
return TonWeb.utils.bytesToBase64(keyPair.secretKey.slice(0, 32));
}
/**
* @param words {string[]}
* @param password {string}
* @return {Promise}
*/
static async saveWords(words, password) {
await storage.setItem('words', await encrypt(words.join(','), password));
}
/**
* @param password {string}
* @return {Promise}
*/
static async loadWords(password) {
return (await decrypt(await storage.getItem('words'), password)).split(',');
}
/**
* @param isTestnet {boolean}
* @return {string}
*/
getApiKey(isTestnet) {
const webApiKey = isTestnet
? TONCENTER_API_KEY_WEB_TEST
: TONCENTER_API_KEY_WEB_MAIN;
const extensionApiKey = isTestnet
? TONCENTER_API_KEY_EXT_TEST
: TONCENTER_API_KEY_EXT_MAIN;
return IS_EXTENSION ? extensionApiKey : webApiKey;
}
async _init() {
return new Promise(async (resolve) => {
await storage.removeItem('pwdHash');
this.isTestnet = IS_EXTENSION ? (await storage.getItem('isTestnet')) : (self.location.href.indexOf('testnet') > -1);
this.isDebug = IS_EXTENSION ? (await storage.getItem('isDebug')) : (self.location.href.indexOf('debug') > -1);
const mainnetRpc = 'https://toncenter.com/api/v2/jsonRPC';
const testnetRpc = 'https://testnet.toncenter.com/api/v2/jsonRPC';
if (IS_EXTENSION && !(await storage.getItem('address'))) {
await this._restoreDeprecatedStorage();
}
this.ton = new TonWeb(new TonWeb.HttpProvider(this.isTestnet ? testnetRpc : mainnetRpc, {apiKey: this.getApiKey(this.isTestnet)}));
this.myAddress = await storage.getItem('address');
if (this.myAddress) {
this.myAddress = new TonWeb.utils.Address(this.myAddress).toString(true, true, false, this.isTestnet);
}
this.publicKeyHex = await storage.getItem('publicKey');
if (!this.myAddress || !(await storage.getItem('words'))) {
await storage.clear();
this.sendToView('showScreen', {name: 'start', noAnimation: true});
} else {
if ((await storage.getItem('isLedger')) === 'true') {
this.isLedger = true;
this.sendToView('setIsLedger', this.isLedger);
}
await this.showMain();
}
this.sendToView('setIsTestnet', this.isTestnet);
resolve();
});
}
async _restoreDeprecatedStorage() {
const {
address, words, walletVersion, magic, proxy,
} = await this.sendToView('restoreDeprecatedStorage', undefined, true, true);
if (!address || !words) {
return;
}
await Promise.all([
storage.setItem('address', address),
storage.setItem('words', words),
storage.setItem('walletVersion', walletVersion),
storage.setItem('magic', magic),
storage.setItem('proxy', proxy),
]);
}
async toggleTestnet() {
this.isTestnet = !this.isTestnet;
if (this.isTestnet) {
await storage.setItem('isTestnet', 'true');
} else {
await storage.removeItem('isTestnet');
}
this.clearVars();
await this._init();
await this.sendToView('setIsTestnet', this.isTestnet);
}
async toggleDebug() {
this.isDebug = !this.isDebug;
if (this.isDebug) {
await storage.setItem('isDebug', 'true');
} else {
await storage.removeItem('isDebug');
}
}
// INDEXED API
/**
* @private
* @param method {string}
* @param params {any}
* @return {Promise}
*/
async sendToIndex(method, params) {
const mainnetRpc = 'https://toncenter.com/api/v3/';
const testnetRpc = 'https://testnet.toncenter.com/api/v3/';
const rpc = this.isTestnet ? testnetRpc : mainnetRpc;
const headers = {
'Content-Type': 'application/json',
'X-API-Key': this.getApiKey(this.isTestnet)
};
const response = await fetch(rpc + method + '?' + new URLSearchParams(params), {
method: 'GET',
headers: headers,
});
return await response.json();
}
/**
* @private
* @param address {string}
* @return {Promise<{seqno: number | null}>}
*/
async getWalletInfoFromIndex(address) {
return this.sendToIndex('wallet', {
address: address
});
}
/**
* @private
* @param address {string}
* @return {Promise<{balance: string, status: string}>}
*/
async getAccountInfoFromIndex(address) {
return this.sendToIndex('account', {
address: address
});
}
/**
* @return {Promise} seqno
*/
async getMySeqno() {
const walletInfo = await this.getWalletInfoFromIndex(this.myAddress);
return walletInfo.seqno || 0;
}
/**
* @param address {string}
* @return {Promise} in nanotons
*/
async getBalance(address) {
const accountInfo = await this.getAccountInfoFromIndex(address);
return new BN(accountInfo.balance);
}
/**
* @param address {string}
* @return {Promise}
*/
async checkContractInitialized(address) {
const accountInfo = await this.getAccountInfoFromIndex(address);
return accountInfo.status === "active";
}
/**
* @private
* @param address {string}
* @param limit {number}
* @return {Promise}
*/
async getTransactionsFromIndex(address, limit) {
return this.sendToIndex('transactions', {
account: address,
limit: limit
});
}
/**
* @param limit? {number}
* @return {Promise} transactions
*/
async getTransactions(limit = 10) {
/**
* @param msg {any} raw.message
* @return {string}
*/
function getComment(msg) {
if (!msg.message_content) return '';
if (!msg.message_content.decoded) return '';
if (msg.message_content.decoded['type'] !== 'text_comment') return '';
return msg.message_content.decoded.comment;
}
/**
* @param msg {any} raw.message
* @return {string} '' or base64
*/
function getEncryptedComment(msg) {
if (!msg.message_content) return '';
if (!msg.message_content.body) return '';
if (msg.opcode !== "0x2167da4b") return '';
/** @type {string} */
const cellBase64 = msg.message_content.body;
/** @type {Cell} */
const cell = TonWeb.boc.Cell.oneFromBoc(TonWeb.utils.base64ToBytes(cellBase64));
return TonWeb.utils.bytesToBase64(parseSnakeCells(cell).slice(4)); // skip 4 bytes of prefix 0x2167da4b
}
const arr = [];
const transactionsResponse= await this.getTransactionsFromIndex(this.myAddress, limit);
const transactions = transactionsResponse.transactions; // index.transaction[]
const addressBook = transactionsResponse.address_book;
/**
* @param rawAddress {string}
* @return {string}
*/
const formatTxAddress = (rawAddress) => {
return addressBook[rawAddress].user_friendly;
}
for (const t of transactions) {
let amount = new BN(t.in_msg.value);
for (const outMsg of t.out_msgs) {
amount = amount.sub(new BN(outMsg.value));
}
let from_addr = "";
let to_addr = "";
let comment = "";
let encryptedComment = "";
let inbound = false;
if (t.in_msg.source) { // internal message with Toncoins, set source
inbound = true;
from_addr = formatTxAddress(t.in_msg.source);
to_addr = formatTxAddress(t.in_msg.destination);
comment = getComment(t.in_msg);
encryptedComment = getEncryptedComment(t.in_msg);
} else if (t.out_msgs.length) { // external message, we sending Toncoins
inbound = false;
from_addr = formatTxAddress(t.out_msgs[0].source);
to_addr = formatTxAddress(t.out_msgs[0].destination);
comment = getComment(t.out_msgs[0]);
encryptedComment = getEncryptedComment(t.out_msgs[0]);
//TODO support many out messages. We need to show separate outgoing payment for each? How to show fees?
} else {
// Deploying wallet contract onchain
}
/** @type {BN} */
let fee = new BN(t.total_fees);
for (let outMsg of t.out_msgs) {
fee = fee.add(new BN(outMsg.fwd_fee));
fee = fee.add(new BN(outMsg.ihr_fee));
}
if (to_addr) {
arr.push({
bodyHashBase64: t.in_msg.message_content.hash, // base64
inbound,
hash: t.hash, // base64
amount: amount.toString(),
from_addr: from_addr,
to_addr: to_addr,
fee: fee.toString(), // string BN
comment: comment,
encryptedComment: encryptedComment,
date: t.now * 1000
});
}
}
return arr;
}
/**
* @param request {{expireAt?: number, messages: [{amount: BN, toAddress: string, comment?: string | Uint8Array | Cell, needEncryptComment: boolean, stateInit?: Cell}]}}
* @param keyPair {nacl.KeyPair | null} null if estimates fee, keyPair if real sending
* @return Promise<{{send: () => Promise<*>, getQuery: () => Promise, estimateFee: () => Promise<*>}}> transfer object
*/
async sign(request, keyPair) {
/** @type {number} */
const seqno = await this.getMySeqno();
/** @type {Uint8Array | null} */
const secretKey = keyPair ? keyPair.secretKey : null;
return this.walletContract.methods.transfers({
secretKey: secretKey,
seqno: seqno,
expireAt: request.expireAt,
messages: request.messages.map(message => {
return {
toAddress: message.toAddress,
amount: message.amount,
payload: message.comment,
sendMode: 3,
stateInit: message.stateInit
}
})
});
}
// CREATE WALLET
async showCreated() {
this.sendToView('showScreen', {name: 'created'});
this.sendToView('disableCreated', true);
this.myMnemonicWords = await TonWeb.mnemonic.generateMnemonic();
const privateKey = await Controller.wordsToPrivateKey(this.myMnemonicWords);
const keyPair = nacl.sign.keyPair.fromSeed(TonWeb.utils.base64ToBytes(privateKey));
const walletVersion = DEFAULT_WALLET_VERSION;
const WalletClass = this.ton.wallet.all[walletVersion];
this.walletContract = new WalletClass(this.ton.provider, {
publicKey: keyPair.publicKey,
wc: 0
});
this.myAddress = (await this.walletContract.getAddress()).toString(true, true, false, this.isTestnet);
this.publicKeyHex = TonWeb.utils.bytesToHex(keyPair.publicKey);
await storage.setItem('publicKey', this.publicKeyHex);
await storage.setItem('walletVersion', walletVersion);
this.sendToView('disableCreated', false);
}
async createPrivateKey() {
this.showBackup(this.myMnemonicWords, true);
}
// BACKUP WALLET
onBackupWalletClick() {
this.afterEnterPassword = async mnemonicWords => {
this.showBackup(mnemonicWords);
};
this.sendToView('showPopup', {name: 'enterPassword'});
}
showBackup(words, isFirst) {
this.sendToView('showScreen', {name: 'backup', words, isFirst});
}
async onBackupDone() {
if (await storage.getItem('words')) {
this.sendToView('showScreen', {name: 'main'});
} else {
this.sendToView('showScreen', {name: 'wordsConfirm', words: this.myMnemonicWords});
}
}
onConfirmDone(words) {
if (words) {
let isValid = true;
Object.keys(words).forEach(index => {
if (this.myMnemonicWords[index] !== words[index]) {
isValid = false;
}
});
if (!isValid) {
return;
}
this.showCreatePassword();
}
}
// IMPORT LEDGER
async createLedger(transportType) {
let transport;
switch (transportType) {
case 'hid':
transport = await TonWeb.ledger.TransportWebHID.create();
break;
case 'ble':
transport = await TonWeb.ledger.BluetoothTransport.create();
break;
default:
throw new Error('unknown transportType' + transportType);
}
transport.setDebugMode(true);
this.isLedger = true;
this.ledgerApp = new TonWeb.ledger.AppTon(transport, this.ton);
const ledgerVersion = (await this.ledgerApp.getAppConfiguration()).version;
this.debug('ledgerAppConfig=', ledgerVersion);
if (!ledgerVersion.startsWith('2')) {
alert('Please update your Ledger TON-app to v2.0.1 or upper or use old wallet version https://tonwallet.me/prev/');
throw new Error('outdated ledger ton-app version');
}
const {publicKey} = await this.ledgerApp.getPublicKey(ACCOUNT_NUMBER, false); // todo: можно сохранять publicKey и не запрашивать это
const WalletClass = this.ton.wallet.all[DEFAULT_LEDGER_WALLET_VERSION];
const wallet = new WalletClass(this.ton.provider, {
publicKey: publicKey,
wc: 0
});
this.walletContract = wallet;
const address = await wallet.getAddress();
this.myAddress = address.toString(true, true, false, this.isTestnet);
this.publicKeyHex = TonWeb.utils.bytesToHex(publicKey);
}
async importLedger(transportType) {
await this.createLedger(transportType);
await storage.setItem('walletVersion', this.walletContract.getName());
await storage.setItem('address', this.myAddress);
await storage.setItem('isLedger', 'true');
await storage.setItem('ledgerTransportType', transportType);
await storage.setItem('words', 'ledger');
await storage.setItem('publicKey', this.publicKeyHex);
this.sendToView('setIsLedger', this.isLedger);
this.sendToView('showScreen', {name: 'readyToGo'});
}
// IMPORT WALLET
showImport() {
this.sendToView('showScreen', {name: 'import'});
}
async import(words) {
this.myMnemonicWords = words;
if (this.myMnemonicWords) {
try {
const privateKey = await Controller.wordsToPrivateKey(this.myMnemonicWords);
const keyPair = nacl.sign.keyPair.fromSeed(TonWeb.utils.base64ToBytes(privateKey));
let hasBalance = [];
for (let WalletClass of this.ton.wallet.list) {
const wallet = new WalletClass(this.ton.provider, {
publicKey: keyPair.publicKey,
wc: 0
});
const walletAddress = (await wallet.getAddress()).toString(true, true, false, this.isTestnet);
const walletBalance = await this.getBalance(walletAddress);
if (walletBalance.gt(new BN(0))) {
hasBalance.push({balance: walletBalance, clazz: WalletClass});
}
this.debug(wallet.getName(), walletAddress, walletBalance.toString());
}
let walletClass = this.ton.wallet.all[DEFAULT_WALLET_VERSION];
if (hasBalance.length > 0) {
hasBalance.sort((a, b) => {
return a.balance.cmp(b.balance);
});
walletClass = hasBalance[hasBalance.length - 1].clazz;
}
await this.importImpl(keyPair, walletClass);
this.sendToView('importCompleted', {state: 'success'});
} catch (e) {
this.debug(e);
this.sendToView('importCompleted', {state: 'failure'});
}
} else {
this.sendToView('importCompleted', {state: 'failure'});
}
}
async importImpl(keyPair, WalletClass) {
this.walletContract = new WalletClass(this.ton.provider, {
publicKey: keyPair.publicKey,
wc: 0
});
this.myAddress = (await this.walletContract.getAddress()).toString(true, true, false, this.isTestnet);
this.publicKeyHex = TonWeb.utils.bytesToHex(keyPair.publicKey);
await storage.setItem('publicKey', this.publicKeyHex);
await storage.setItem('walletVersion', this.walletContract.getName());
this.showCreatePassword();
}
// PASSWORD
showCreatePassword() {
this.sendToView('showScreen', {name: 'createPassword'});
}
/**
* @param password {string}
* @return {Promise}
*/
async savePrivateKey(password) {
this.isLedger = false;
await storage.setItem('isLedger', 'false');
await storage.setItem('address', this.myAddress);
await Controller.saveWords(this.myMnemonicWords, password);
this.myMnemonicWords = null;
this.sendToView('setIsLedger', this.isLedger);
this.sendToView('showScreen', {name: 'readyToGo'});
this.sendToView('privateKeySaved');
}
/**
* @param oldPassword {string}
* @param newPassword {string}
* @return {Promise}
*/
async onChangePassword(oldPassword, newPassword) {
let words;
try {
words = await Controller.loadWords(oldPassword);
} catch (e) {
this.sendToView('showChangePasswordError');
return;
}
await Controller.saveWords(words, newPassword);
this.sendToView('closePopup');
this.sendToView('passwordChanged');
}
/**
* @param password {string}
* @return {Promise}
*/
async onEnterPassword(password) {
let words;
try {
words = await Controller.loadWords(password);
} catch (e) {
this.sendToView('showEnterPasswordError');
return;
}
this.afterEnterPassword(words);
this.sendToView('passwordEntered');
}
// MAIN
/**
* @return {Promise}
*/
async showMain() {
this.sendToView('showScreen', {name: 'main', myAddress: this.myAddress});
if (!this.walletContract) {
const walletVersion = await storage.getItem('walletVersion');
const walletClass = walletVersion ? this.ton.wallet.all[walletVersion] : this.ton.wallet.default;
this.walletContract = new walletClass(this.ton.provider, {
address: this.myAddress,
publicKey: this.publicKeyHex ? TonWeb.utils.hexToBytes(this.publicKeyHex) : undefined,
wc: 0
});
}
this.updateIntervalId = setInterval(() => this.update(false), 5000);
this.update(true);
this.sendToDapp('ton_accounts', [this.myAddress]);
}
/**
* @return {Promise}
*/
async initDapp() {
this.sendToDapp('ton_accounts', this.myAddress ? [this.myAddress] : []);
this.doMagic((await storage.getItem('magic')) === 'true');
this.doProxy((await storage.getItem('proxy')) === 'true');
}
/**
* @return {Promise}
*/
async initView() {
if (!this.myAddress || !(await storage.getItem('words'))) {
this.sendToView('showScreen', {name: 'start', noAnimation: true});
} else {
this.sendToView('showScreen', {name: 'main', myAddress: this.myAddress});
if (this.balance !== null) {
this.sendToView('setBalance', {balance: this.balance.toString(), txs: this.transactions});
}
}
this.sendToView('setIsMagic', (await storage.getItem('magic')) === 'true');
this.sendToView('setIsProxy', (await storage.getItem('proxy')) === 'true');
this.sendToView('setIsTestnet', this.isTestnet);
}
/**
* @return {Promise} successfully updated
*/
async updateBalance() {
try {
this.balance = await this.getBalance(this.myAddress);
return true;
} catch (e) {
console.error(e);
return false;
}
}
/**
* @param force {boolean}
* @return {Promise} successfully updated
*/
async update(force) {
try {
// if (!document.hasFocus()) {
// return true;
// }
const needUpdate = (this.processingVisible && this.sendingData) || (this.balance === null) || force;
if (!needUpdate) return true;
if (!(await this.updateBalance())) return false;
const txs = await this.getTransactions();
if (txs.length > 0) {
this.transactions = txs;
if (this.processingVisible && this.sendingData) {
for (let tx of txs) {
if (tx.bodyHashBase64 === this.sendingData.bodyHashBase64) {
this.sendToView('showPopup', {
name: 'done',
message: formatNanograms(this.sendingData.totalAmount) + ' TON have been sent'
});
this.processingVisible = false;
this.sendingData = null;
break;
}
}
}
}
this.sendToView('setBalance', {balance: this.balance.toString(), txs: this.transactions});
return true;
} catch (e) {
console.error(e);
return false;
}
}
async showAddressOnDevice() {
if (!this.ledgerApp) {
await this.createLedger((await storage.getItem('ledgerTransportType')) || 'hid');
}
const {address} = await this.ledgerApp.getAddress(ACCOUNT_NUMBER, true, this.ledgerApp.ADDRESS_FORMAT_USER_FRIENDLY + this.ledgerApp.ADDRESS_FORMAT_URL_SAFE + this.ledgerApp.ADDRESS_FORMAT_BOUNCEABLE);
this.debug(address.toString(true, true, true));
}
// DECRYPT MESSAGE COMMENT
/**
* @param hash {string}
* @param encryptedComment {string} base64
* @param senderAddress {string | Address}
*/
onDecryptComment(hash, encryptedComment, senderAddress) {
this.afterEnterPassword = async mnemonicWords => {
const keyPair = await TonWeb.mnemonic.mnemonicToKeyPair(mnemonicWords);
let decryptedComment = ''
try {
decryptedComment = await decryptMessageComment(TonWeb.utils.base64ToBytes(encryptedComment), keyPair.publicKey, keyPair.secretKey, senderAddress);
} catch (e) {
console.error(e);
}
this.sendToView('decryptedComment', {hash, decryptedComment});
};
this.sendToView('showPopup', {name: 'enterPassword'});
}
// SEND TONCOIN
/**
* @param request {{expireAt?: number, messages: [{amount: BN, toAddress: string, comment?: string | Uint8Array | Cell, needEncryptComment: boolean, stateInit?: Cell}]}}
* @return {Promise} total fees in nanotons
*/
async getFees(request) {
/** @type {{expireAt?: number, messages: [{amount: BN, toAddress: string, comment?: string | Uint8Array | Cell, needEncryptComment: boolean, stateInit?: Cell}]}} */
const tempRequest = {
expireAt: request.expireAt,
messages: []
};
for (const message of request.messages) {
let tempComment = message.comment
if (message.needEncryptComment) {
const tempKeyPair = TonWeb.utils.newKeyPair(); // encrypt with random key just to get estimage fees
const tempEncryptedCommentCell = await encryptMessageComment(message.comment, tempKeyPair.publicKey, tempKeyPair.publicKey, tempKeyPair.secretKey, this.myAddress);
tempComment = tempEncryptedCommentCell;
}
tempRequest.messages.push({
amount: message.amount,
toAddress: message.toAddress,
comment: tempComment,
needEncryptComment: message.needEncryptComment,
stateInit: message.stateInit
});
}
const query = await this.sign(tempRequest, null);
const all_fees = await query.estimateFee();
const fees = all_fees.source_fees;
const in_fwd_fee = new BN(fees.in_fwd_fee); // External processing fee
const storage_fee = new BN(fees.storage_fee);
const gas_fee = new BN(fees.gas_fee);
const fwd_fee = new BN(fees.fwd_fee);
return in_fwd_fee.add(storage_fee).add(gas_fee).add(fwd_fee);
};
/**
* @param request {{expireAt?: number, messages: [{amount: BN, toAddress: string, comment?: string | Uint8Array | Cell, needEncryptComment: boolean, stateInit?: Cell}]}}
* @param needQueue? {boolean}
* @return {Promise} successfully sent BoC
*/
async showSendConfirm(request, needQueue) {
createDappPromise();
if (!request.messages) throw new Error('no messages');
if (!request.messages.length) throw new Error('no messages to send');
if (request.messages.length > 4) throw new Error('maximum 4 message at once');
/** @type {BN} */
let totalAmount = new BN(0);
for (const message of request.messages) {
// message.address
if (!message.amount) throw new Error('no amount');
if (!message.amount.gte(new BN(0))) {
this.sendToView('sendCheckFailed', {message: 'Amount must be positive'});
return null;
}
if (message.amount.eq(new BN(0)) && !message.comment) {
this.sendToView('sendCheckFailed', {message: 'You can send 0 TON only with comment'});
return null;
}
totalAmount = totalAmount.add(message.amount);
// message.toAddress
if (!message.toAddress) throw new Error('no toAddress');
if (!Address.isValid(message.toAddress)) {
try {
message.toAddress = message.toAddress.toLowerCase();
if (!message.toAddress.endsWith('.ton') && !message.toAddress.endsWith('.t.me')) {
throw new Error();
}
message.toAddress = await this.ton.dns.getWalletAddress(message.toAddress);
if (!message.toAddress) {
throw new Error();
}
if (!Address.isValid(message.toAddress)) {
throw new Error();
}
message.toAddress = message.toAddress.toString(true, true, true, this.isTestnet);
} catch (e) {
this.sendToView('sendCheckFailed', {message: 'Invalid address or domain'});
return null;
}
}
// make toAddress non-bounceable if destination contract uninitialized
if (!(await this.checkContractInitialized(message.toAddress))) {
message.toAddress = (new Address(message.toAddress)).toString(true, true, false);
}
// message.payload
if (!message.comment) {
message.needEncryptComment = false;
}
// serialize long text comment
if (!message.needEncryptComment && (typeof message.comment === 'string')) {
if (message.comment.length > 0) {
const commentBytes = new TextEncoder().encode(message.comment);
const payloadBytes = new Uint8Array(4 + commentBytes.length);
payloadBytes[0] = 0; // zero uint32 means simple text message
payloadBytes[1] = 0;
payloadBytes[2] = 0;
payloadBytes[3] = 0;
payloadBytes.set(commentBytes, 4);
message.comment = makeSnakeCells(payloadBytes);
}
}
// get destination public key for encryption
if (message.needEncryptComment) {
let toPublicKey = null;
try {
const toPublicKeyBN = await this.ton.provider.call2(message.toAddress, 'get_public_key');
let toPublicKeyHex = toPublicKeyBN.toString(16);
if (toPublicKeyHex.length % 2 !== 0) {
toPublicKeyHex = '0' + toPublicKeyHex;
}
toPublicKey = TonWeb.utils.hexToBytes(toPublicKeyHex);
} catch (e) {
console.error(e);
}
if (!toPublicKey) {
this.sendToView('sendCheckCantPublicKey', {});
return null;
}
message.toPublicKey = toPublicKey;
}
}
// check balance
if (!(await this.updateBalance())) {
this.sendToView('sendCheckFailed', {message: 'API request error'});
return null;
}
if (this.balance.lt(totalAmount)) {
this.sendToView('sendCheckFailed', {
message: 'Not enough balance'
});
return null;
}
let fee;
try {
fee = await this.getFees(request);
} catch (e) {
console.error(e);
this.sendToView('sendCheckFailed', {message: 'API request error'});
return null;
}
if (this.balance.sub(fee).lt(totalAmount)) {
this.sendToView('sendCheckCantPayFee', {fee});
return null;
}
// start
if (this.isLedger) {
const message = request.messages[0];
this.sendToView('showPopup', {
name: 'sendConfirm',
amount: message.amount.toString(),
toAddress: message.toAddress,
needEncryptComment: false,
fee: fee.toString()
}, needQueue);
const sentBoc = await this.send(request, null, totalAmount);
if (sentBoc) {
dAppPromise.resolve(sentBoc);
} else {
this.sendToView('sendCheckFailed', {message: 'API request error'});
dAppPromise.resolve(null);
}
} else {
this.afterEnterPassword = async words => {
this.processingVisible = true;
this.sendToView('showPopup', {name: 'processing'});
const keyPair = await TonWeb.mnemonic.mnemonicToKeyPair(words);
for (const message of request.messages) {
if (message.needEncryptComment) {
const encryptedCommentCell = await encryptMessageComment(message.comment, keyPair.publicKey, message.toPublicKey, keyPair.secretKey, this.myAddress);
message.comment = encryptedCommentCell;
}
}
const privateKeyBase64 = await Controller.wordsToPrivateKey(words);
const sentBoc = await this.send(request, privateKeyBase64, totalAmount);
this.onCancelAction = null;
if (sentBoc) {
dAppPromise.resolve(sentBoc);
} else {
this.sendToView('sendCheckFailed', {message: 'API request error'});
dAppPromise.resolve(null);
}
};
this.onCancelAction = () => {
dAppPromise.resolve(null);
};
this.sendToView('showPopup', {
name: 'sendConfirm',
amount: totalAmount.toString(),
toAddress: request.messages.length === 1 ? request.messages[0].toAddress : `${request.messages.length} addresses`,
fee: fee.toString(),
needEncryptComment: request.messages[0].needEncryptComment // todo
}, needQueue);
}
this.sendToView('sendCheckSucceeded');
return dAppPromise;
}
/**
* @param request {{expireAt?: number, messages: [{amount: BN, toAddress: string, comment?: string | Uint8Array | Cell, needEncryptComment: boolean, stateInit?: Cell}]}}
* @param privateKeyBase64 {string | null} null if Ledger
* @param totalAmount {BN}
* @return {Promise} successfully sent BoC
*/
async send(request, privateKeyBase64, totalAmount) {
try {
let query;
if (this.isLedger) {
if (request.messages.length !== 1) {
throw new Error('Ledger support only 1 message at once');
}
const message = request.messages[0];
if (message.needEncryptComment) {
throw new Error('encrypted comment dont supported by Ledger');
}
if (message.stateInit) {
throw new Error('stateInit dont supported by Ledger');
}
if (!this.ledgerApp) {
await this.createLedger((await storage.getItem('ledgerTransportType')) || 'hid');
}
let addressFormat = 0;
const toAddress = new Address(message.toAddress);
if (toAddress.isUserFriendly) {
addressFormat += this.ledgerApp.ADDRESS_FORMAT_USER_FRIENDLY;
if (toAddress.isUrlSafe) {
addressFormat += this.ledgerApp.ADDRESS_FORMAT_URL_SAFE;
}
if (toAddress.isBounceable) {
addressFormat += this.ledgerApp.ADDRESS_FORMAT_BOUNCEABLE;
}
if (toAddress.isTestOnly) {
addressFormat += this.ledgerApp.ADDRESS_FORMAT_TEST_ONLY;
}
}
const seqno = await this.getMySeqno();
query = await this.ledgerApp.transfer(ACCOUNT_NUMBER, this.walletContract, message.toAddress, message.amount, seqno, addressFormat);
this.sendToView('showPopup', {name: 'processing'});
this.processingVisible = true;
} else {
const keyPair = nacl.sign.keyPair.fromSeed(TonWeb.utils.base64ToBytes(privateKeyBase64));
query = await this.sign(request, keyPair);
}
/** @type {Cell | null} */
const sentBoc = await this.sendQuery(query);
if (!sentBoc) return null;
/** @type {Cell} */
const bodyCell = await query.getBody();
/** @type {Uint8Array} */
const bodyHash = await bodyCell.hash();
this.sendingData = {
bodyHashBase64: TonWeb.utils.bytesToBase64(bodyHash),
totalAmount: totalAmount
};
return sentBoc;
} catch (e) {
this.debug(e);
this.sendToView('closePopup');
alert('Error sending');
return null;
}
}
/**
* @param hexToSign {string} hex to sign
* @param privateKey {string}
* @returns {Promise} signature in hex
*/
rawSign(hexToSign, privateKey) {
const keyPair = nacl.sign.keyPair.fromSeed(TonWeb.utils.base64ToBytes(privateKey));
const signature = nacl.sign.detached(TonWeb.utils.hexToBytes(hexToSign), keyPair.secretKey);
return TonWeb.utils.bytesToHex(signature);
}
/**
* @param query {{send: () => Promise<*>, getQuery: () => Promise}}
* @return {Promise} successfully sent BoC
*/
async sendQuery(query) {
const sendResponse = await query.send();
if (sendResponse["@type"] === "ok") { // response from ton-http-api
// wait for transaction, then show Done popup
return query.getQuery();
} else {
this.sendToView('closePopup');
alert('Send error');
return null;
}
}
// RAW SIGN
/**
* @param hexToSign {string} hex data to sign
* @param isConnect {boolean}
* @param needQueue {boolean}
* @returns {Promise} signature in hex
*/
showSignConfirm(hexToSign, isConnect, needQueue) {
return new Promise((resolve, reject) => {
if (this.isLedger) {
alert('sign not supported by Ledger');
reject();
} else {
this.onCancelAction = () => {
reject('User cancel');
};
this.afterEnterPassword = async words => {
this.sendToView('closePopup');
const privateKeyBase64 = await Controller.wordsToPrivateKey(words);
const signature = this.rawSign(hexToSign, privateKeyBase64);
resolve(signature);
};
this.sendToView('showPopup', {
name: 'signConfirm',
data: hexToSign,
isConnect: isConnect
}, needQueue);
}
});
}
/**
* Ask user for password and set `this.publicKeyHex`
* @param needQueue {boolean}
* @return {Promise}
*/
requestPublicKey(needQueue) {
return new Promise(async (resolve, reject) => {
await showExtensionWindow();
this.onCancelAction = () => {
reject('User cancel');
};
this.afterEnterPassword = async words => {
const privateKey = await Controller.wordsToPrivateKey(words);
const keyPair = nacl.sign.keyPair.fromSeed(TonWeb.utils.base64ToBytes(privateKey));
this.publicKeyHex = TonWeb.utils.bytesToHex(keyPair.publicKey);
await storage.setItem('publicKey', this.publicKeyHex);
resolve();
};
this.sendToView('showPopup', {name: 'enterPassword'}, needQueue);
});
}
/**
* @param needQueue {boolean}
* @returns {Promise}
*/
showConnectConfirm(needQueue) {
return new Promise((resolve, reject) => {
this.onCancelAction = () => {
reject({
message: 'Reject request',
code: 300 // USER_REJECTS_ERROR
});
};
this.onConnectConfirmed = async () => {
this.sendToView('closePopup');
resolve();
};
this.sendToView('showPopup', {
name: 'connectConfirm',
}, needQueue);
});
}
// DISCONNECT WALLET
clearVars() {
this.myAddress = null;
this.publicKeyHex = null;
this.balance = null;
this.walletContract = null;
this.transactions = [];
this.sendingData = null;
this.processingVisible = false;
this.isLedger = false;
this.ledgerApp = null;
clearInterval(this.updateIntervalId);
}
async onDisconnectClick() {
this.clearVars();
await storage.clear();
this.sendToView('showScreen', {name: 'start'});
this.sendToDapp('ton_accounts', []);
}
// MAGIC
doMagic(enabled) {
try {
this.sendToDapp('ton_doMagic', enabled);
} catch (e) {
}
}
// PROXY
doProxy(enabled) {
}
// TRANSPORT WITH VIEW
/**
* @param method {string}
* @param params? {any} boolean or object, not array
* @param needQueue? {boolean}
* @param needResult? {boolean}
* @return {void | Promise<{magic: (string|null), proxy: (string|null), address: (string|null), words: (string|null), walletVersion: (string|null)}>}
*/
sendToView(method, params, needQueue, needResult) {
if (self.view) {
const result = self.view.onMessage(method, params);
if (needResult) {
return result;
}
} else {
const msg = {method, params};
const exec = () => {
if (popupPort) {
popupPort.postMessage(msg);
} else if (needQueue) {
queueToPopup.push(msg);
}
};
if (!needResult) {
exec();
return;
}
return new Promise((resolve) => {
msg.id = this._lastMsgId++;
this.pendingMessageResolvers.set(msg.id, resolve);
exec();
});
}
}
/**
* @param method {string}
* @param params? {any} boolean or object, not array
* @return {Promise}
*/
async onViewMessage(method, params) {
switch (method) {
case 'showScreen':
switch (params.name) {
case 'created':
await this.showCreated();
break;
case 'import':
this.showImport();
break;
case 'importLedger':
await this.importLedger(params.transportType);
break;
}
break;
case 'import':
await this.import(params.words);
break;
case 'createPrivateKey':
await this.createPrivateKey();
break;
case 'passwordCreated':
await this.savePrivateKey(params.password);
break;
case 'update':
this.update(true);
break;
case 'showAddressOnDevice':
await this.showAddressOnDevice();
break;
case 'onCancelAction':
if (this.onCancelAction) {
await this.onCancelAction();
this.onCancelAction = null;
}
break;
case 'onConnectConfirmed':
if (this.onConnectConfirmed) {
this.onConnectConfirmed();
this.onConnectConfirmed = null;
}
break;
case 'onEnterPassword':
await this.onEnterPassword(params.password);
break;
case 'decryptComment':
await this.onDecryptComment(params.hash, params.encryptedComment, params.senderAddress);
break;
case 'onChangePassword':
await this.onChangePassword(params.oldPassword, params.newPassword);
break;
case 'onSend':
await this.showSendConfirm({
messages: [
{
amount: new BN(params.amount),
toAddress: params.toAddress,
comment: params.comment,
needEncryptComment: params.needEncryptComment
}
]
}, false);
break;
case 'onBackupDone':
await this.onBackupDone();
break;
case 'onConfirmBack':
this.showBackup(this.myMnemonicWords);
break;
case 'onImportBack':
this.sendToView('showScreen', {name: 'start'});
break;
case 'onConfirmDone':
this.onConfirmDone(params.words);
break;
case 'showMain':
await this.showMain();
break;
case 'onBackupWalletClick':
this.onBackupWalletClick();
break;
case 'disconnect':
await this.onDisconnectClick();
break;
case 'onClosePopup':
this.processingVisible = false;
break;
case 'onMagicClick':
await storage.setItem('magic', params ? 'true' : 'false');
this.doMagic(params);
break;
case 'onProxyClick':
await storage.setItem('proxy', params ? 'true' : 'false');
this.doProxy(params);
break;
case 'toggleTestnet':
await this.toggleTestnet();
break;
case 'toggleDebug':
await this.toggleDebug();
break;
case 'onWindowUpdate':
await storage.setItem('windowState', {
top: params.top,
left: params.left,
// -2 need for remove frames size
// TODO: check in linux and macos
height: params.height - 2,
width: params.width - 2
});
break;
}
}
// TRANSPORT WITH DAPP
/**
* @param method {string}
* @param params {any | any[]}
*/
sendToDapp(method, params) {
contentScriptPorts.forEach(port => {
port.postMessage(JSON.stringify({
type: 'gramWalletAPI',
message: {jsonrpc: '2.0', method: method, params: params}
}));
});
}
/**
* @param needQueue {boolean}
* @return {Promise<{name: 'ton_addr', address: string, network: string, walletStateInit: string, publicKey: string }>}
*/
async createTonAddrItemReply(needQueue) {
if (!this.myAddress) {
throw {
message: 'Missing connection',
code: 1 // BAD_REQUEST_ERROR
};
}
if (!this.publicKeyHex) {
await this.requestPublicKey(needQueue);
}
const walletVersion = await storage.getItem('walletVersion');
const rawAddressString = new TonWeb.utils.Address(this.myAddress).toString(false);
const WalletClass = walletVersion ? this.ton.wallet.all[walletVersion] : this.ton.wallet.default;
const wallet = new WalletClass(this.ton.provider, {
publicKey: TonWeb.utils.hexToBytes(this.publicKeyHex),
wc: 0
});
const {stateInit} = await wallet.createStateInit();
const stateInitBase64 = TonWeb.utils.bytesToBase64(await stateInit.toBoc(false));
return {
name: 'ton_addr',
address: rawAddressString,
network: this.isTestnet ? TONCONNECT_TESTNET : TONCONNECT_MAINNET,
walletStateInit: stateInitBase64,
publicKey: this.publicKeyHex
};
}
/**
* @param origin {string}
* @param payload {string}
* @param needQueue {boolean}
* @return {any} ton_proof item
*/
async createTonProofItemReply(origin, payload, needQueue) {
if (!this.myAddress) {
throw {
message: 'Missing connection',
code: 1 // BAD_REQUEST_ERROR
};
}
const timestamp = Math.round(Date.now() / 1000);
const timestampBuffer = new BigInt64Array(1);
timestampBuffer[0] = BigInt(timestamp);
const domain = new URL(origin).host;
const domainBuffer = new TextEncoder().encode(domain);
const domainLengthBuffer = new Int32Array(1);
domainLengthBuffer[0] = domainBuffer.byteLength;
const address = new TonWeb.utils.Address(this.myAddress);
const addressWorkchainBuffer = new Int32Array(1);
addressWorkchainBuffer[0] = address.wc;
const addressBuffer = new Uint8Array(4 + address.hashPart.length);
addressBuffer.set(addressWorkchainBuffer, 0);
addressBuffer.set(address.hashPart, 4);
const prefixBuffer = new TextEncoder().encode('ton-proof-item-v2/');
const payloadBuffer = new TextEncoder().encode(payload);
const messageBuffer = new Uint8Array(prefixBuffer.byteLength + addressBuffer.byteLength + domainLengthBuffer.byteLength + domainBuffer.byteLength + timestampBuffer.byteLength + payloadBuffer.byteLength);
let offset = 0;
messageBuffer.set(prefixBuffer, offset);
offset += prefixBuffer.byteLength;
messageBuffer.set(addressBuffer, offset);
offset += addressBuffer.byteLength;
messageBuffer.set(domainLengthBuffer, offset);
offset += domainLengthBuffer.byteLength;
messageBuffer.set(domainBuffer, offset);
offset += domainBuffer.byteLength;
messageBuffer.set(new Uint8Array(timestampBuffer.buffer), offset);
offset += 8;
messageBuffer.set(payloadBuffer, offset);
const ffffPrefix = new Uint8Array([0xff, 0xff]);
const tonconnectPrefix = new TextEncoder().encode('ton-connect')
const messageBufferHash = new Uint8Array(await TonWeb.utils.sha256(messageBuffer));
const bufferToSign = new Uint8Array(ffffPrefix.byteLength + tonconnectPrefix.byteLength + messageBufferHash.byteLength);
offset = 0;
bufferToSign.set(ffffPrefix, offset);
offset += ffffPrefix.byteLength;
bufferToSign.set(tonconnectPrefix, offset);
offset += tonconnectPrefix.byteLength;
bufferToSign.set(messageBufferHash, offset);
const hexToSign = TonWeb.utils.bytesToHex(new Uint8Array(await TonWeb.utils.sha256(bufferToSign)));
const signatureHex = await this.showSignConfirm(hexToSign, true, needQueue);
console.log({signatureHex});
const signatureBase64 = TonWeb.utils.bytesToBase64(TonWeb.utils.hexToBytes(signatureHex));
console.log({signatureBase64});
return {
name: 'ton_proof',
proof: {
timestamp: timestamp, // 64-bit unix epoch time of the signing operation (seconds)
domain: {
lengthBytes: domainBuffer.byteLength, // AppDomain Length
value: domain, // app domain name (as url part, without encoding)
},
signature: signatureBase64, // base64-encoded signature
payload: payload, // payload from the request
},
}
}
async onDappMessage(method, params, origin) {
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1102.md
await this.whenReady;
const needQueue = !popupPort;
switch (method) {
case 'tonConnect_connect':
await showExtensionWindow();
if (!this.myAddress) {
throw {
message: 'Missing connection',
code: 1 // BAD_REQUEST_ERROR
}
}
const data = params[0];
const tonProof = data.items.find((item) => item.name === 'ton_proof');
if (!tonProof &&
!(await storage.getItem('tonconnect_' + this.myAddress + '_' + (this.isTestnet ? 'testnet' : 'mainnet') + '_' + origin))) {
await this.showConnectConfirm(needQueue);
}
await storage.setItem('tonconnect_' + this.myAddress + '_' + (this.isTestnet ? 'testnet' : 'mainnet') + '_' + origin, 'true');
const connectResult = [
await this.createTonAddrItemReply(needQueue),
];
if (tonProof) {
connectResult.push(await this.createTonProofItemReply(origin, tonProof.payload, needQueue))
}
return connectResult;
case 'tonConnect_reconnect':
if (!this.myAddress ||
!(await storage.getItem('tonconnect_' + this.myAddress + '_' + (this.isTestnet ? 'testnet' : 'mainnet') + '_' + origin))) {
throw {
message: 'Missing connection',
code: 1 // BAD_REQUEST_ERROR
}
}
return [
await this.createTonAddrItemReply(needQueue)
];
case 'tonConnect_disconnect':
await storage.removeItem('tonconnect_' + this.myAddress + '_' + (this.isTestnet ? 'testnet' : 'mainnet') + '_' + origin);
return;
case 'tonConnect_sendTransaction':
await showExtensionWindow();
const tx = params[0];
console.log('tonConnect_sendTransaction', params, origin, tx);
// check is dapp connected to wallet
if (!this.myAddress) {
throw {
message: 'Missing connection',
code: 1 // BAD_REQUEST_ERROR
}
}
if (!(await storage.getItem('tonconnect_' + this.myAddress + '_' + (this.isTestnet ? 'testnet' : 'mainnet') + '_' + origin))) {
throw {
message: 'dApp don\'t have an access to wallet',
code: 1 // BAD_REQUEST_ERROR
}
}
// check tonConnect_sendTransaction request
/** @type {number | undefined} */
let expireAt = undefined;
if (tx.valid_until) {
expireAt = Number(tx.valid_until);
if (isNaN(expireAt)) {
throw {
message: 'invalid validUntil',
code: 1 // BAD_REQUEST_ERROR
}
}
if (expireAt > 9999999999) {
expireAt = expireAt / 1000; // convert millis to seconds, todo: it's not good
}
if (expireAt < Date.now() / 1000) {
throw {
message: 'expired',
code: 1 // BAD_REQUEST_ERROR
}
}
}
if (tx.from) {
if (!Address.isValid(tx.from)) {
throw {
message: 'Invalid source address',
code: 1 // BAD_REQUEST_ERROR
}
}
if (new TonWeb.utils.Address(tx.from).toString(false) !== new TonWeb.utils.Address(this.myAddress).toString(false)) {
throw {
message: 'Different source address',
code: 1 // BAD_REQUEST_ERROR
}
}
}
if (tx.network) {
if (tx.network !== TONCONNECT_TESTNET && tx.network !== TONCONNECT_MAINNET) {
throw {
message: 'Invalid network',
code: 1 // BAD_REQUEST_ERROR
}
}
if ((tx.network === TONCONNECT_TESTNET) !== !!this.isTestnet) {
throw {
message: 'Different network',
code: 1 // BAD_REQUEST_ERROR
}
}
}
if (!tx.messages || !tx.messages.length) {
throw {
message: 'no messages',
code: 1 // BAD_REQUEST_ERROR
}
}
const convertTonconnectMessage = (message) => {
try {
if (!message.address) {
throw new Error('no address')
}
if (!Address.isValid(message.address)) {
throw new Error('invalid address');
}
if (!message.amount) {
throw new Error('no amount')
}
message.amount = new BN(message.amount);
if (message.payload) {
message.payload = TonWeb.boc.Cell.oneFromBoc(TonWeb.utils.base64ToBytes(message.payload));
}
if (message.stateInit) {
message.stateInit = TonWeb.boc.Cell.oneFromBoc(TonWeb.utils.base64ToBytes(message.stateInit));
}
return {
amount: message.amount,
toAddress: message.address,
comment: message.payload,
needEncryptComment: false,
stateInit: message.stateInit
}
} catch (e) {
throw {
message: e.message,
code: 1 // BAD_REQUEST_ERROR
}
}
}
const messages = [];
for (const message of tx.messages) {
messages.push(convertTonconnectMessage(message));
}
this.sendToView('showPopup', {
name: 'loader',
});
/** @type {Cell | null} */
const sentBoc = await this.showSendConfirm(
{
expireAt: expireAt,
messages
},
needQueue
);
if (!sentBoc) {
this.sendToView('closePopup');
throw {
message: 'Reject request',
code: 300 // USER_REJECTS_ERROR
}
}
return TonWeb.utils.bytesToBase64(await sentBoc.toBoc(false));
case 'ton_requestAccounts':
return (this.myAddress ? [this.myAddress] : []);
case 'ton_requestWallets':
if (!this.myAddress) {
return [];
}
if (!this.publicKeyHex) {
await this.requestPublicKey(needQueue);
}
const walletVersion = await storage.getItem('walletVersion');
return [{
address: this.myAddress,
publicKey: this.publicKeyHex,
walletVersion: walletVersion
}];
case 'ton_getBalance':
await this.updateBalance();
return (this.balance ? this.balance.toString() : '');
case 'ton_sendTransaction':
const param = params[0];
await showExtensionWindow();
if (param.data) {
if (param.dataType === 'hex') {
param.data = TonWeb.utils.hexToBytes(param.data);
} else if (param.dataType === 'base64') {
param.data = TonWeb.utils.base64ToBytes(param.data);
} else if (param.dataType === 'boc') {
param.data = TonWeb.boc.Cell.oneFromBoc(TonWeb.utils.base64ToBytes(param.data));
}
}
if (param.stateInit) {
param.stateInit = TonWeb.boc.Cell.oneFromBoc(TonWeb.utils.base64ToBytes(param.stateInit));
}
this.sendToView('showPopup', {
name: 'loader',
});
const result = await this.showSendConfirm(
{
messages: [{
amount: new BN(param.value),
toAddress: param.to,
comment: param.data,
needEncryptComment: false,
stateInit: param.stateInit,
}]
},
needQueue
);
if (!result) {
this.sendToView('closePopup');
}
return !!result;
case 'ton_rawSign':
const signParam = params[0];
await showExtensionWindow();
return this.showSignConfirm(signParam.data, false, needQueue);
case 'flushMemoryCache':
await chrome.webRequest.handlerBehaviorChanged();
return true;
default:
throw {
message: `Method "${method}" not implemented`,
code: 400 // METHOD_NOT_SUPPORTED
};
}
}
}
const controller = new Controller();
if (IS_EXTENSION) {
chrome.runtime.onConnect.addListener(port => {
if (port.name === 'gramWalletContentScript') { // dapp
contentScriptPorts.add(port)
port.onMessage.addListener(async (msg, port) => {
if (msg.type === 'gramWalletAPI_ton_provider_connect') {
controller.whenReady.then(() => {
controller.initDapp();
});
}
if (!msg.message) return;
const origin = decodeURIComponent(msg.message.origin);
let result = undefined;
let error = undefined;
try {
result = await controller.onDappMessage(msg.message.method, msg.message.params, origin);
} catch (e) {
console.error(e);
error = {
message: e.message,
code: e.code || 0
};
}
if (port) {
port.postMessage(JSON.stringify({
type: 'gramWalletAPI',
message: {jsonrpc: '2.0', id: msg.message.id, method: msg.message.method, result, error}
}));
}
});
port.onDisconnect.addListener(port => {
contentScriptPorts.delete(port)
})
} else if (port.name === 'gramWalletPopup') { // view
popupPort = port;
popupPort.onMessage.addListener(function (msg) {
if (msg.method === 'response') {
const resolver = controller.pendingMessageResolvers.get(msg.id);
if (resolver) {
resolver(msg.result);
controller.pendingMessageResolvers.delete(msg.id);
}
} else {
controller.onViewMessage(msg.method, msg.params);
}
});
popupPort.onDisconnect.addListener(() => {
popupPort = null;
});
const runQueueToPopup = () => {
queueToPopup.forEach(msg => popupPort.postMessage(msg));
queueToPopup.length = 0;
};
if (!controller.myAddress) { // if controller not initialized yet
runQueueToPopup();
}
controller.whenReady.then(async () => {
await controller.initView();
runQueueToPopup();
});
}
});
let actionApiName = 'action';
if (chrome.runtime.getManifest().manifest_version === 2) actionApiName = 'browserAction';
chrome[actionApiName].onClicked.addListener(showExtensionWindow);
chrome.windows.onRemoved.addListener(removedWindowId => {
if (dAppPromise) dAppPromise.resolve(false);
if (removedWindowId !== extensionWindowId) return;
extensionWindowId = -1;
});
}
================================================
FILE: src/js/extension/background.js
================================================
if(typeof importScripts !== 'function') {
const injectScript = path => {
return new Promise(resolve => {
const scriptTag = document.createElement('script');
scriptTag.setAttribute('src', path);
scriptTag.addEventListener('load', resolve);
document.body.appendChild(scriptTag);
});
};
window.importScripts = async (...scripts) => {
for (const path of scripts) {
await injectScript(path);
}
};
}
importScripts(
'/libs/aes-js-3.1.2.js',
'/libs/noble-ed25519-1.7.3.js',
'/libs/tonweb.min.js',
'/libs/tonweb-mnemonic.min.js',
'/js/Controller.js',
);
================================================
FILE: src/js/extension/content.js
================================================
const container = document.head || document.documentElement;
const scriptTag = document.createElement('script');
scriptTag.async = false;
scriptTag.src = chrome.runtime.getURL('/js/extension/provider.js');
container.insertBefore(scriptTag, container.children[0]);
container.removeChild(scriptTag);
const onPortMessage = data => {
self.postMessage(data, '*'); // todo: origin
};
const onPageMessage = e => {
if (!e.data) return;
if (e.data.type !== 'gramWalletAPI_ton_provider_write' &&
e.data.type !== 'gramWalletAPI_ton_provider_connect') return;
sendMessageToActivePort(e.data);
};
const PORT_NAME = 'gramWalletContentScript'
let port = chrome.runtime.connect({ name: PORT_NAME });
port.onMessage.addListener(onPortMessage);
const sendMessageToActivePort = (payload, isRepeat = false) => {
try {
port.postMessage(payload);
} catch (err) {
const isInvalidated = err.message.toString().includes('Extension context invalidated');
if (isInvalidated) {
self.removeEventListener('message', onPageMessage);
return;
}
const isDisconnected = err.message.toString().includes('disconnected port');
if (!isRepeat && isDisconnected) {
port = chrome.runtime.connect({name: PORT_NAME});
port.onMessage.addListener(onPortMessage);
sendMessageToActivePort(payload, true);
} else {
onPortMessage(JSON.stringify({
type: 'gramWalletAPI',
message: {
id: payload?.message?.id,
method: payload?.message?.method,
error: { message: err.message },
jsonrpc: true,
}
}));
}
}
}
self.addEventListener('message', onPageMessage);
================================================
FILE: src/js/extension/provider.js
================================================
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1193.md#sample-class-implementation
(() => {
class TonProvider {
constructor() {
this.listeners = window.ton ? window.ton.listeners : {};
this.isTonWallet = true;
this.targetOrigin = '*'; // todo
// Init storage
this._nextJsonRpcId = window.ton ? window.ton._nextJsonRpcId : 0;
this._promises = window.ton ? window.ton._promises : {};
// todo: take `listeners` from previous window.ton ?
// Fire the connect
this._connect();
if (window.ton) window.ton._destroy();
// Listen for jsonrpc responses
this._onMessage = this._handleJsonRpcMessage.bind(this);
window.addEventListener('message', this._onMessage);
}
/* EventEmitter */
on(method, listener) {
let methodListeners = this.listeners[method];
if (!methodListeners) {
methodListeners = [];
this.listeners[method] = methodListeners;
}
if (methodListeners.indexOf(listener) === -1) {
methodListeners.push(listener);
}
return this;
}
removeListener(method, listener) {
const methodListeners = this.listeners[method];
if (!methodListeners) return;
const index = methodListeners.indexOf(listener);
if (index > -1) {
methodListeners.splice(index, 1);
}
}
emit(method, ...args) {
const methodListeners = this.listeners[method];
if (!methodListeners || !methodListeners.length) return false;
methodListeners.forEach(listener => listener(...args));
return true;
}
/* Methods */
send(method, params = []) {
if (!method || typeof method !== 'string') {
return new Error('Method is not a valid string.');
}
if (!(params instanceof Array)) {
return new Error('Params is not a valid array.');
}
const id = this._nextJsonRpcId++;
const jsonrpc = '2.0';
const payload = {
jsonrpc,
id,
method,
params,
origin: window.origin
};
const promise = new Promise((resolve, reject) => {
this._promises[payload.id] = {
resolve,
reject,
};
});
// Send jsonrpc request to TON Wallet
window.postMessage(
{
type: 'gramWalletAPI_ton_provider_write',
message: payload,
},
this.targetOrigin,
);
return promise;
}
/* Internal methods */
async _handleJsonRpcMessage(event) {
// Return if no data to parse
if (!event || !event.data) {
return;
}
let data;
try {
data = JSON.parse(event.data);
} catch (error) {
// Return if we can't parse a valid object
return;
}
if (data.type !== 'gramWalletAPI') return;
// Return if not a jsonrpc response
if (!data || !data.message || !data.message.jsonrpc) {
return;
}
const message = data.message;
const {
id,
method,
error,
result,
} = message;
if (typeof id !== 'undefined') {
const promise = this._promises[id];
if (promise) {
// Handle pending promise
if (data.type === 'error') {
promise.reject(message);
} else if (message.error) {
promise.reject(error);
} else {
promise.resolve(result);
}
delete this._promises[id];
}
} else {
if (method) {
if (method.indexOf('_subscription') > -1) {
// Emit subscription notification
this._emitNotification(message.params);
} else if (method === 'ton_accounts') { // todo
this._emitAccountsChanged(message.params);
} else if (method === 'ton_doMagic') {
const isTurnedOn = message.params;
if (!location.href.startsWith('https://web.telegram.org/z/')) {
if (location.href.startsWith('https://web.telegram.org/k/')) {
toggleMagicBadge(isTurnedOn);
}
return;
}
if (isTurnedOn) {
const scriptEl = document.querySelector('script[src^="main."]');
const localRevision = scriptEl.getAttribute('src');
const filesToInjectResponse = await fetch('https://ton.org/app/magic-sources.json?' + Date.now());
const filesToInject = await filesToInjectResponse.json();
const magicRevision = filesToInject.find(f => f.startsWith('main.') && f.endsWith('.js'));
const assetCache = await window.caches.open('tt-assets');
const cachedResponse = await assetCache.match(localRevision);
if (cachedResponse) {
const cachedText = await cachedResponse.text();
// we leverage the fact that the file has its name as part of the sourcemaps appendix
const isMagicInjected = cachedText?.endsWith(magicRevision + '.map');
if (isMagicInjected) {
return;
}
}
addBadge('Loading TON magic...');
const responses = await Promise.all(filesToInject.map(async (fileName) => {
const res = await fetch('https://ton.org/app/' + fileName);
if (res.status !== 200) {
throw new Error('[TON Wallet] Failed to load magic: ' + res.statusText + '. File: ' + fileName);
}
return [
fileName,
new Response(await res.blob(), {
headers: res.headers,
status: res.status,
statusText: res.statusText,
}),
];
}));
await Promise.all(responses.map(async ([fileName, response]) => {
if (fileName.startsWith('main.')) {
if (fileName.endsWith('.js')) {
await assetCache.put('https://web.telegram.org/z/' + localRevision, response.clone());
} else if (fileName.endsWith('.css')) {
const linkEl = document.querySelector('link[rel=stylesheet]');
const currentCssRevision = linkEl.getAttribute('href');
await assetCache.put('https://web.telegram.org/z/' + currentCssRevision, response.clone());
}
} else {
await assetCache.put('https://web.telegram.org/z/' + fileName, response.clone());
}
}));
localStorage.setItem('ton:magicRevision', magicRevision);
await this.send('flushMemoryCache');
window.location.reload();
} else {
const prevMagicRevision = localStorage.getItem('ton:magicRevision');
if (!prevMagicRevision) {
return;
}
localStorage.removeItem('ton:magicRevision');
await window.caches.delete('tt-assets');
await this.send('flushMemoryCache');
window.location.reload();
}
}
}
}
}
/* Connection handling */
_connect() {
// Send to TON Wallet
window.postMessage(
{type: 'gramWalletAPI_ton_provider_connect'},
this.targetOrigin,
);
// Reconnect on close
// this.once('close', this._connect.bind(this)); todo
}
_destroy() {
window.removeEventListener('message', this._onMessage);
}
/* Events */
_emitNotification(result) {
this.emit('notification', result);
}
_emitConnect() {
this.emit('connect');
}
_emitClose(code, reason) {
this.emit('close', code, reason);
}
_emitChainChanged(chainId) {
this.emit('chainChanged', chainId);
}
_emitAccountsChanged(accounts) {
this.emit('accountsChanged', accounts);
}
};
// TONCONNECT
function tonConnectEventError(message, code) {
return {
event: 'connect_error',
id: Date.now(),
payload: {
code: code,
message: message
}
}
}
class TonConnectBridge {
constructor(provider, prevBridge) {
this.provider = provider;
provider.on('chainChanged', () => {
this.notify({
event: 'disconnect',
id: Date.now(),
payload: {}
})
});
this.callbacks = prevBridge?.tonconnect ? prevBridge?.tonconnect.callbacks : [];
this.deviceInfo = {
platform: 'web',
appName: 'tonwallet',
appVersion: '1.1.50',
maxProtocolVersion: 2,
features: [
'SendTransaction',
{
name: 'SendTransaction',
maxMessages: 4,
},
],
};
this.walletInfo = {
name: 'TON Wallet',
image: 'https://wallet.ton.org/assets/ui/qr-logo.png',
about_url: 'https://wallet.ton.org',
}
this.protocolVersion = 2;
this.isWalletBrowser = false;
}
async connect(protocolVersion, message) {
if (protocolVersion > this.protocolVersion) {
return this.notify(
tonConnectEventError('Unsupported protocol version', 1)
);
}
try {
const items = await this.provider.send(
'tonConnect_connect',
[message]
);
return this.notify({
event: 'connect',
id: Date.now(),
payload: {
items: items,
device: this.deviceInfo
}
});
} catch (e) {
return this.notify(
tonConnectEventError(e?.message || 'Unknown error', 0)
);
}
}
async disconnect() {
await this.provider.send('tonConnect_disconnect', []);
return this.notify({
event: 'disconnect',
id: Date.now(),
payload: {}
})
}
async restoreConnection() {
try {
const items = await this.provider.send('tonConnect_reconnect', [{name: 'ton_addr'}]);
return this.notify({
event: 'connect',
id: Date.now(),
payload: {
items: items,
device: this.deviceInfo
}
})
} catch (e) {
return this.notify(
tonConnectEventError(e?.message || 'Unknown error', 0)
);
}
}
async send(message) {
try {
const result = await this.provider.send(
'tonConnect_' + message.method,
message.params.map(param => JSON.parse(param))
);
return {
result,
id: String(message.id)
}
} catch (e) {
return {
error: {
message: e?.message || 'Unknown error',
code: 0 // unknown error
},
id: String(message.id)
}
}
}
listen(callback) {
this.callbacks.push(callback);
const callbacks = this.callbacks;
return () => {
const index = callbacks.indexOf(callback);
if (index > -1) {
callbacks.splice(index, 1);
}
}
}
async notify(event) {
this.callbacks.forEach(callback => callback(event));
return event;
}
}
// START
const havePrevInstance = !!window.ton;
window.tonProtocolVersion = 1;
window.ton = new TonProvider();
if (!havePrevInstance) window.dispatchEvent(new Event('tonready'));
window.tonwallet = {
provider: window.ton,
tonconnect: new TonConnectBridge(window.ton, window.tonwallet)
}
function toggleMagicBadge(isTurnedOn) {
if (isTurnedOn) {
addBadge('Switch to Z version in the menu to take advantage of TON magic.');
// handle shallow screen layout
document.getElementById('column-left').style.top = '28px';
document.getElementById('column-center').style.top = '28px';
} else {
const badge = document.getElementById('ton-magic-badge');
if (badge) {
badge.remove();
document.getElementById('column-left').style.top = '';
document.getElementById('column-center').style.top = '';
}
}
}
function addBadge(html) {
const badge = document.createElement('div');
badge.id = 'ton-magic-badge';
badge.style.position = 'fixed';
badge.style.zIndex = '999';
badge.style.top = '0';
badge.style.background = '#0072ab';
badge.style.width = '100%';
badge.style.height = '28px';
badge.style.lineHeight = '28px';
badge.style.textAlign = 'center';
badge.style.fontSize = '14px';
badge.style.color = 'white';
badge.innerHTML = html;
document.body.prepend(badge);
}
})();
================================================
FILE: src/js/util/encryption.js
================================================
// This JS library implements TON message comment encryption and decryption for Web
// Reference C++ code - SimpleEncryptionV2 - https://github.com/ton-blockchain/ton/blob/cc0eb453cb3bf69f92693160103d33112856c056/tonlib/tonlib/keys/SimpleEncryption.cpp#L110
// Dependencies:
// - TonWeb 0.0.60
// - aes-js - 3.1.2 - https://github.com/ricmoo/aes-js/releases/tag/v3.1.2 - for aes-cbc without padding
// - noble-ed25519 - 1.7.3 - // https://github.com/paulmillr/noble-ed25519/releases/tag/1.7.3 - for getSharedKey
const ed25519 = self.nobleEd25519;
/**
* @param key {Uint8Array}
* @param data {Uint8Array}
* @return {Promise}
*/
const hmac_sha512 = async (key, data) => {
const hmacAlgo = {name: "HMAC", hash: "SHA-512"};
/** @type {CryptoKey} */
const hmacKey = await self.crypto.subtle.importKey("raw", key, hmacAlgo, false, ["sign"]);
/** @type {ArrayBuffer} */
const signature = await self.crypto.subtle.sign(hmacAlgo, hmacKey, data);
const result = new Uint8Array(signature);
if (result.length !== 512 / 8) throw new Error();
return result;
}
/**
* @param hash {Uint8Array}
* @return {Promise} aesjs.ModeOfOperation.cbc
*/
const getAesCbcState = async (hash) => {
if (hash.length < 48) throw new Error();
const key = hash.slice(0, 32);
const iv = hash.slice(32, 32 + 16);
// Note that native crypto.subtle AES-CBC not suitable here because
// even if the data IS a multiple of 16 bytes, padding will still be added
// So we use aes-js
return new aesjs.ModeOfOperation.cbc(key, iv);
}
/**
* @param dataLength {number}
* @param minPadding {number}
* @return {Uint8Array}
*/
const getRandomPrefix = (dataLength, minPadding) => {
const prefixLength = ((minPadding + 15 + dataLength) & -16) - dataLength;
/** @type {Uint8Array} */
const prefix = self.crypto.getRandomValues(new Uint8Array(prefixLength));
prefix[0] = prefixLength;
if ((prefixLength + dataLength) % 16 !== 0) throw new Error();
return prefix;
}
/**
* @param a {Uint8Array}
* @param b {Uint8Array}
* @return {Promise}
*/
const combineSecrets = async (a, b) => {
return hmac_sha512(a, b);
}
/**
* @param data {Uint8Array}
* @param sharedSecret {Uint8Array}
* @param salt {Uint8Array}
* @return {Promise}
*/
const encryptDataWithPrefix = async (data, sharedSecret, salt) => {
if (data.length % 16 !== 0) throw new Error();
/** @type {Uint8Array} */
const dataHash = await combineSecrets(salt, data);
/** @type {Uint8Array} */
const msgKey = dataHash.slice(0, 16);
const res = new Uint8Array(data.length + 16);
res.set(msgKey, 0);
/** @type {Uint8Array} */
const cbcStateSecret = await combineSecrets(sharedSecret, msgKey);
/** @type {Uint8Array} */
const encrypted = (await getAesCbcState(cbcStateSecret)).encrypt(data);
res.set(encrypted, 16);
return res;
}
/**
* @param data {Uint8Array}
* @param sharedSecret {Uint8Array}
* @param salt {Uint8Array}
* @return {Promise}
*/
const encryptDataImpl = async (data, sharedSecret, salt) => {
/** @type {Uint8Array} */
const prefix = await getRandomPrefix(data.length, 16);
const combined = new Uint8Array(prefix.length + data.length);
combined.set(prefix, 0);
combined.set(data, prefix.length);
return encryptDataWithPrefix(combined, sharedSecret, salt);
}
/**
* @param data {Uint8Array}
* @param myPublicKey {Uint8Array}
* @param theirPublicKey {Uint8Array}
* @param privateKey {Uint8Array}
* @param salt {Uint8Array}
* @return {Promise}
*/
export const encryptData = async (data, myPublicKey, theirPublicKey, privateKey, salt) => {
/** @type {Uint8Array} */
const sharedSecret = await ed25519.getSharedSecret(privateKey, theirPublicKey);
/** @type {Uint8Array} */
const encrypted = await encryptDataImpl(data, sharedSecret, salt);
const prefixedEncrypted = new Uint8Array(myPublicKey.length + encrypted.length);
for (let i = 0; i < myPublicKey.length; i++) {
prefixedEncrypted[i] = theirPublicKey[i] ^ myPublicKey[i];
}
prefixedEncrypted.set(encrypted, myPublicKey.length);
return prefixedEncrypted;
}
/**
* @param bytes {Uint8Array}
* @return {Cell}
*/
export const makeSnakeCells = (bytes) => {
const ROOT_CELL_BYTE_LENGTH = 35 + 4;
const CELL_BYTE_LENGTH = 127;
/** @type {Cell} */
const root = new TonWeb.boc.Cell();
root.bits.writeBytes(bytes.slice(0, Math.min(bytes.length, ROOT_CELL_BYTE_LENGTH)));
const cellCount = Math.ceil((bytes.length - ROOT_CELL_BYTE_LENGTH) / CELL_BYTE_LENGTH);
if (cellCount > 16) {
throw new Error('Text too long');
}
/** @type {Cell} */
let cell = root;
for (let i = 0; i < cellCount; i++) {
/** @type {Cell} */
const prevCell = cell;
cell = new TonWeb.boc.Cell();
const cursor = ROOT_CELL_BYTE_LENGTH + i * CELL_BYTE_LENGTH;
cell.bits.writeBytes(bytes.slice(cursor, Math.min(bytes.length, cursor + CELL_BYTE_LENGTH)));
prevCell.refs[0] = cell;
}
return root;
}
/**
* @param cell {Cell}
* @return {Uint8Array}
*/
export const parseSnakeCells = (cell) => {
/** @type {Cell} */
let c = cell;
/** @type {Uint8Array} */
let result = new Uint8Array(0);
while (c) {
/** @type {Uint8Array} */
const newResult = new Uint8Array(result.length + c.bits.array.length);
newResult.set(result);
newResult.set(c.bits.array, result.length);
result = newResult;
c = c.refs[0];
}
return result;
}
/**
* @param comment {string}
* @param myPublicKey {Uint8Array}
* @param theirPublicKey {Uint8Array}
* @param myPrivateKey {Uint8Array}
* @param senderAddress {string | Address}
* @return {Promise| } full message binary payload with 0x2167da4b prefix
*/
export const encryptMessageComment = async (comment, myPublicKey, theirPublicKey, myPrivateKey, senderAddress) => {
if (!comment || !comment.length) throw new Error('empty comment');
if (myPrivateKey.length === 64) {
myPrivateKey = myPrivateKey.slice(0, 32); // convert nacl private key
}
/** @type {Uint8Array} */
const commentBytes = new TextEncoder().encode(comment);
/** @type {Uint8Array} */
const salt = new TextEncoder().encode(new TonWeb.utils.Address(senderAddress).toString(true, true, true, false));
/** @type {Uint8Array} */
const encryptedBytes = await encryptData(commentBytes, myPublicKey, theirPublicKey, myPrivateKey, salt);
const payload = new Uint8Array(encryptedBytes.length + 4);
payload[0] = 0x21; // encrypted text prefix
payload[1] = 0x67;
payload[2] = 0xda;
payload[3] = 0x4b;
payload.set(encryptedBytes, 4);
return makeSnakeCells(payload);
}
/**
* @param cbcStateSecret {Uint8Array}
* @param msgKey {Uint8Array}
* @param encryptedData {Uint8Array}
* @param salt {Uint8Array}
* @return {Promise}
*/
const doDecrypt = async (cbcStateSecret, msgKey, encryptedData, salt) => {
/** @type {Uint8Array} */
const decryptedData = (await getAesCbcState(cbcStateSecret)).decrypt(encryptedData);
/** @type {Uint8Array} */
const dataHash = await combineSecrets(salt, decryptedData);
/** @type {Uint8Array} */
const gotMsgKey = dataHash.slice(0, 16);
if (msgKey.join(',') !== gotMsgKey.join(',')) {
throw new Error('Failed to decrypt: hash mismatch')
}
const prefixLength = decryptedData[0];
if (prefixLength > decryptedData.length || prefixLength < 16) {
throw new Error('Failed to decrypt: invalid prefix size');
}
return decryptedData.slice(prefixLength);
}
/**
* @param encryptedData {Uint8Array}
* @param sharedSecret {Uint8Array}
* @param salt {Uint8Array}
* @return {Promise}
*/
const decryptDataImpl = async (encryptedData, sharedSecret, salt) => {
if (encryptedData.length < 16) throw new Error('Failed to decrypt: data is too small');
if (encryptedData.length % 16 !== 0) throw new Error('Failed to decrypt: data size is not divisible by 16');
/** @type {Uint8Array} */
const msgKey = encryptedData.slice(0, 16);
/** @type {Uint8Array} */
const data = encryptedData.slice(16);
/** @type {Uint8Array} */
const cbcStateSecret = await combineSecrets(sharedSecret, msgKey);
/** @type {Uint8Array} */
const res = await doDecrypt(cbcStateSecret, msgKey, data, salt);
return res;
}
/**
* @param data {Uint8Array}
* @param publicKey {Uint8Array}
* @param privateKey {Uint8Array}
* @param salt {Uint8Array}
* @return {Promise}
*/
export const decryptData = async (data, publicKey, privateKey, salt) => {
if (data.length < publicKey.length) {
throw new Error('Failed to decrypt: data is too small');
}
const theirPublicKey = new Uint8Array(publicKey.length);
for (let i = 0; i < publicKey.length; i++) {
theirPublicKey[i] = data[i] ^ publicKey[i];
}
/** @type {Uint8Array} */
const sharedSecret = await ed25519.getSharedSecret(privateKey, theirPublicKey);
/** @type {Uint8Array} */
const decrypted = await decryptDataImpl(data.slice(publicKey.length), sharedSecret, salt);
return decrypted;
}
/**
* @param encryptedData {Uint8Array} encrypted data without 0x2167da4b prefix
* @param myPublicKey {Uint8Array}
* @param myPrivateKey {Uint8Array}
* @param senderAddress {string | Address}
* @return {Promise} decrypted text comment
*/
export const decryptMessageComment = async (encryptedData, myPublicKey, myPrivateKey, senderAddress) => {
if (myPrivateKey.length === 64) {
myPrivateKey = myPrivateKey.slice(0, 32); // convert nacl private key
}
/** @type {Uint8Array} */
const salt = new TextEncoder().encode(new TonWeb.utils.Address(senderAddress).toString(true, true, true, false));
/** @type {Uint8Array} */
const decryptedBytes = await decryptData(encryptedData, myPublicKey, myPrivateKey, salt);
return new TextDecoder().decode(decryptedBytes);
}
================================================
FILE: src/js/util/storage.js
================================================
/**
* `localStorage` polyfill for Chrome Extension environment
*/
export default self.localStorage || {
/**
* @param key {string}
* @param value {string}
* @return {Promise}
*/
setItem(key, value) {
return chrome.storage.local.set({[key]: value});
},
/**
* @param key {string}
* @return {Promise}
*/
getItem(key) {
return chrome.storage.local.get(key)
.then(({[key]: value}) => value);
},
/**
* @param key {string}
* @return {Promise}
*/
removeItem(key) {
return chrome.storage.local.remove(key);
},
/**
* @return {Promise}
*/
clear() {
return chrome.storage.local.clear();
},
};
================================================
FILE: src/js/view/DropDown.js
================================================
import {clearElement, createElement, toggle} from "./Utils.js";
export default class DropDown {
/**
* @param container {HTMLElement}
* @param onEnter {(input: HTMLInputElement) => void}
* @param mnemonicWords {string[]}
*/
constructor(container, onEnter, mnemonicWords) {
/** @type {HTMLElement} */
this.container = container;
/** @type {(input: HTMLInputElement) => void} */
this.onEnter = onEnter;
/** @type {string[]} */
this.mnemonicWords = mnemonicWords;
/** @type {number} */
this.selectedI = -1;
}
/**
* @param input {HTMLInputElement}
* @param text {string}
*/
show(input, text) {
clearElement(this.container);
/**
* @param e {MouseEvent}
*/
const onMouseDown = e => {
input.value = e.target.innerText;
input.classList.remove('error');
this.hide();
e.preventDefault();
this.onEnter(input);
};
this.mnemonicWords
.filter(w => w.indexOf(text) === 0)
.forEach(w => {
const item = createElement({tag: 'div', clazz: 'words-popup-item', text: w});
item.addEventListener('mousedown', onMouseDown);
this.container.appendChild(item);
});
this.selectedI = -1;
if (this.container.children.length > 0) this.select(0);
this.container.style.left = input.offsetLeft + 'px';
this.container.style.top = (input.offsetTop + input.offsetHeight) + 'px';
toggle(this.container, true);
};
hide() {
toggle(this.container, false);
clearElement(this.container);
this.selectedI = -1;
}
/**
* @param i {number}
*/
select(i) {
if (this.selectedI > -1) {
this.container.children[this.selectedI].classList.remove('selected');
}
this.selectedI = i;
if (this.selectedI > -1) {
this.container.children[this.selectedI].classList.add('selected');
const ITEM_HEIGHT = 30;
this.container.scrollTo(0, ITEM_HEIGHT * this.selectedI);
}
}
/**
* @return {null | string}
*/
getSelectedText() {
if (this.selectedI === -1) return null;
return this.container.children[this.selectedI].innerText;
}
up() {
if (this.selectedI === -1) return;
if (this.selectedI > 0) {
this.select(this.selectedI - 1);
}
}
down() {
if (this.selectedI === -1) return;
if (this.selectedI < this.container.children.length - 1) {
this.select(this.selectedI + 1);
}
}
}
================================================
FILE: src/js/view/Lottie.js
================================================
import {$$} from "./Utils.js";
/**
* @type {Object} lottie name -> lottie element
*/
const lotties = {};
/**
* @param div {HTMLElement}
* @return {Promise}
*/
function initLottie(div) {
return new Promise((resolve, reject) => {
const url = div.getAttribute('src');
const name = div.getAttribute('data-name');
const w = Number(div.getAttribute('width'));
const h = Number(div.getAttribute('height'));
const xmlHttp = new XMLHttpRequest();
xmlHttp.responseType = 'arraybuffer';
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
const canvas = document.createElement('canvas');
canvas.setAttribute('width', w * window.devicePixelRatio);
canvas.setAttribute('height', h * window.devicePixelRatio);
canvas.style.width = w + 'px';
canvas.style.height = h + 'px';
div.appendChild(canvas);
const ctx = canvas.getContext('2d');
const animationData = JSON.parse(new TextDecoder('utf-8').decode(pako.inflate(xmlHttp.response)));
lotties[name] = {
ctx: ctx,
player: lottie.loadAnimation({
renderer: 'canvas',
loop: name === 'processing' || name === 'start' || name === 'about' || name === 'symbol',
autoplay: false,
animationData,
rendererSettings: {
context: ctx,
scaleMode: 'noScale',
clearCanvas: true
},
})
};
ctx.clearRect(0, 0, 1000, 1000);
resolve();
} else {
reject();
}
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
});
}
/**
* @return {Promise}
*/
async function initLotties() {
const divs = $$('tgs-player');
for (let i = 0; i < divs.length; i++) {
try {
await initLottie(divs[i]);
} catch (e) {
}
}
}
/**
* @param lottie? {any}
* @param visible {boolean}
* @param params? {{hideDelay?: number}}
*/
function toggleLottie(lottie, visible, params) {
if (!lottie) return;
params = params || {};
clearTimeout(lottie.hideTimeout);
if (visible) {
lottie.player.play();
} else {
lottie.player.stop();
if (params.hideDelay) {
lottie.hideTimeout = setTimeout(() => {
lottie.ctx.clearRect(0, 0, 1000, 1000);
}, params.hideDelay);
} else {
lottie.ctx.clearRect(0, 0, 1000, 1000);
}
}
}
export {initLotties, toggleLottie, lotties};
================================================
FILE: src/js/view/Utils.js
================================================
// UI Utils
/**
* @param selector {string}
* @return {HTMLElement | null}
*/
function $(selector) {
return document.querySelector(selector);
}
/**
* @param selector {string}
* @return {NodeListOf}
*/
function $$(selector) {
return document.querySelectorAll(selector);
}
/**
* @param div {HTMLElement}
* @param visible {boolean | 'none' | 'block' | 'flex' | 'inline-block'}
*/
function toggle(div, visible) {
let d = visible;
if (visible === true) d = 'block';
if (visible === false) d = 'none';
div.style.display = d;
}
/**
* @param div {HTMLElement}
* @param isVisible {boolean}
* @param params? {{isBack?: boolean}}
*/
function toggleFaded(div, isVisible, params) {
params = params || {};
if (params.isBack) {
div.classList.add('isBack');
} else {
div.classList.remove('isBack');
}
if (isVisible) {
div.classList.add('faded-show');
div.classList.remove('faded-hide');
} else {
div.classList.remove('faded-show');
div.classList.add('faded-hide');
}
}
/**
* @param div {HTMLElement}
* @param className {string}
* @param duration {number}
*/
function triggerClass(div, className, duration) {
div.classList.add(className);
setTimeout(() => {
div.classList.remove(className);
}, duration);
}
/**
* @param params {{tag: string, clazz?: string | (string | undefined)[], text?: string, child?: (HTMLElement | undefined)[], style?: Object}}
* @return {HTMLElement}
*/
function createElement(params) {
const item = document.createElement(params.tag);
if (params.clazz) {
if (Array.isArray(params.clazz)) {
for (let c of params.clazz) {
if (c) {
item.classList.add(c);
}
}
} else {
item.classList.add(params.clazz);
}
}
if (params.text) item.innerText = params.text;
if (params.child) {
for (let c of params.child) {
if (c) {
item.appendChild(c);
}
}
}
if (params.style) {
for (let key in params.style) {
item.style[key] = params.style[key];
}
}
return item;
}
/**
* @param el {HTMLElement}
* @param s {string}
* @return {HTMLElement}
*/
function setAddr(el, s) {
el.innerHTML = '';
el.appendChild(document.createTextNode(s.substring(0, s.length / 2)));
el.appendChild(document.createElement('wbr'));
el.appendChild(document.createTextNode(s.substring(s.length / 2)));
return el;
}
/**
* @param el {HTMLElement}
*/
function clearElement(el) {
el.innerHTML = '';
}
/**
* @param input {HTMLElement}
* @param handler {(e: Event) => void}
*/
function onInput(input, handler) {
input.addEventListener('change', handler);
input.addEventListener('input', handler);
input.addEventListener('cut', handler);
input.addEventListener('paste', handler);
}
/**
* @param n {number}
* @return {string}
*/
function doubleZero(n) {
if (n < 10) return '0' + n;
return n.toString();
}
/**
* @param date {Date}
* @return {string}
*/
function formatTime(date) {
return doubleZero(date.getHours()) + ':' + doubleZero(date.getMinutes());
}
const MONTH_NAMES = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
/**
* @param date {Date}
* @return {string}
*/
function formatDate(date) {
return MONTH_NAMES[date.getMonth()] + ' ' + date.getDate();
}
/**
* @param date {Date}
* @return {string}
*/
function formatDateFull(date) {
return date.toString();
}
/**
* @param text {string}
* @return {boolean}
*/
function copyToClipboard(text) {
/** @type {HTMLTextAreaElement} */
const textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.position = "fixed"; //avoid scrolling to bottom
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
/** @type {boolean} */
let result = false;
try {
result = document.execCommand('copy');
} catch (err) {
}
document.body.removeChild(textArea);
return result;
}
const IMPORT_WORDS_COUNT = 24;
const CONFIRM_WORDS_COUNT = 3;
export {
$,
$$,
toggle,
toggleFaded,
triggerClass,
createElement,
clearElement,
onInput,
setAddr,
doubleZero,
formatTime,
formatDate,
formatDateFull,
copyToClipboard,
IMPORT_WORDS_COUNT,
CONFIRM_WORDS_COUNT
};
================================================
FILE: src/js/view/View.js
================================================
import {
$,
$$,
clearElement,
CONFIRM_WORDS_COUNT,
copyToClipboard,
createElement,
formatDate,
formatDateFull,
formatTime,
IMPORT_WORDS_COUNT,
onInput,
setAddr,
toggle,
toggleFaded,
triggerClass
} from "./Utils.js";
import {initLotties, lotties, toggleLottie} from "./Lottie.js";
import DropDown from "./DropDown.js";
const toNano = TonWeb.utils.toNano;
const fromNano = TonWeb.utils.fromNano;
const BN = TonWeb.utils.BN;
const IS_EXTENSION = !!(self.chrome && chrome.runtime && chrome.runtime.onConnect);
const IS_FIREFOX = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
/**
* @param text {string}
* @param containerSelector {string}
*/
const drawQRCode = (text, containerSelector) => {
const $container = $(containerSelector);
clearElement($container);
new QRCode($container, {
text: text,
width: 185 * window.devicePixelRatio,
height: 185 * window.devicePixelRatio,
colorDark: '#303757',
logo: "assets/ui/qr-logo.png",
logoBackgroundTransparent: false,
logoWidth: 44 * window.devicePixelRatio,
logoHeight: 44 * window.devicePixelRatio,
correctLevel: QRCode.CorrectLevel.L
});
const canvas = $container.querySelector('canvas');
canvas.style.width = '185px';
canvas.style.height = '185px';
};
class View {
/**
* @param mnemonicWords {string[]}
*/
constructor(mnemonicWords) {
/** @type {string[]} */
this.mnemonicWords = mnemonicWords;
/** @type {Controller | null} */
this.controller = null;
/** @type {any | null} */
this.port = null;
/** @type {string | null} */
this.myAddress = null;
/** @type {string | null} */
this.address = null;
/** @type {BN | null} */
this.balance = null;
/** @type {string | null} */
this.currentScreenName = null;
/** @type {boolean} */
this.isTestnet = false;
/** @type {string} */
this.popup = ''; // current opened popup name
/** @type {boolean} */
this.isBack = false;
/** @type {number} */
this.backupShownTime = 0;
/** @type {any | null} */
this.currentOpenTransaction = null;
/** @type {string | null} */
this.currentTransactionAddr = null;
this.createWordInputs({
count: IMPORT_WORDS_COUNT,
dropdownId: '#wordsPopup',
inputId: '#importsInput',
containerId: '#importWords',
multiColumns: true
});
this.createWordInputs({
count: CONFIRM_WORDS_COUNT,
dropdownId: '#wordsConfirmPopup',
inputId: '#confirmInput',
containerId: '#confirmWords',
multiColumns: false
});
/** @type {Promise} */
this._initLotties = initLotties().then(() => {
if (this.currentScreenName) {
toggleLottie(lotties[this.currentScreenName], true);
toggleLottie(lotties['symbol'], this.currentScreenName === 'main');
}
});
/**
* @param e {Event}
*/
function resetErrors(e) {
const input = e.target;
input.classList.remove('error');
}
onInput($('#amountInput'), resetErrors);
onInput($('#toWalletInput'), resetErrors);
onInput($('#commentInput'), resetErrors);
onInput($('#createPassword_repeatInput'), resetErrors);
onInput($('#enterPassword_input'), resetErrors);
onInput($('#changePassword_oldInput'), resetErrors);
onInput($('#changePassword_newInput'), resetErrors);
onInput($('#changePassword_repeatInput'), resetErrors);
/**
* @param e {ClipboardEvent}
* @return {string}
*/
function getClipboardData(e) {
const s = (e.clipboardData || window.clipboardData).getData('text');
try {
return decodeURI(s).replaceAll(/%23/g, '#');
} catch (e) { // URIError
return s;
}
}
$('#toWalletInput').addEventListener('paste', e => {
const urlString = getClipboardData(e);
if (!urlString.startsWith('ton://')) return;
/** @type {{address: string, amount?: string, text?: string} | null } */
let parsedTransferUrl = null;
try {
parsedTransferUrl = TonWeb.utils.parseTransferUrl(urlString);
} catch (e) {
$('#notify').innerText = 'Parse transfer URL error';
triggerClass($('#notify'), 'faded-show', 2000);
return;
}
$('#toWalletInput').value = parsedTransferUrl.address;
if (parsedTransferUrl.amount) {
$('#amountInput').value = fromNano(new BN(parsedTransferUrl.amount));
}
if (parsedTransferUrl.text) {
$('#commentInput').value = parsedTransferUrl.text;
}
e.preventDefault();
});
onInput($('#invoice_amountInput'), () => this.updateInvoiceLink());
onInput($('#invoice_commentInput'), () => this.updateInvoiceLink());
$("#start_createBtn").addEventListener('click', () => this.sendMessage('showScreen', {name: 'created'}));
$("#start_importBtn").addEventListener('click', () => this.sendMessage('showScreen', {name: 'import'}));
/** @type {boolean} */
let needShowLedger = false;
try {
needShowLedger = window.location.href.indexOf('ledgerReview') > -1;
} catch (e) {
}
if (needShowLedger) {
toggle($("#start_importLedgerHidBtn"), 'inline-block');
}
$("#start_importLedgerHidBtn").addEventListener('click', () => {
this.showPopup('connectLedger');
this.sendMessage('showScreen', {name: 'importLedger', transportType: 'hid'});
});
// $("#start_importLedgerBleBtn").addEventListener('click', () => this.sendMessage('showScreen', {name: 'importLedger', transportType: 'ble'}));
// $('#main_buyBtn').addEventListener('click', () => {
// window.open('https://exchange.mercuryo.io/?currency=TONCOIN&address=' + this.myAddress, '_blank');
// });
$('#import_backBtn').addEventListener('click', () => {
this.isBack = true;
this.sendMessage('onImportBack');
});
$('#import_alertBtn').addEventListener('click', () => {
this.showAlert({
title: 'Too Bad',
message: 'Without the secret words, you can\'t restore access to your wallet.',
buttons: [
{
label: 'CANCEL',
callback: () => {
this.isBack = true;
this.sendMessage('onImportBack');
}
},
{
label: 'ENTER WORDS',
callback: () => {
this.closePopup();
}
},
]
});
});
$('#import_continueBtn').addEventListener('click', async (e) => {
this.toggleButtonLoader(e.currentTarget, true);
this.sendMessage('import', {words: await this.getImportWords()});
});
$('#createdContinueButton').addEventListener('click', () => this.sendMessage('createPrivateKey'));
$('#backup_continueBtn').addEventListener('click', () => {
const currentTime = Date.now();
if (currentTime - this.backupShownTime < 60000) { // 1 minute
this.showAlert({
title: 'Sure done?',
message: 'You didn\'t have enough time to write these words down.',
buttons: [
{
label: 'I\'M SURE',
callback: () => {
this.sendMessage('onBackupDone');
}
},
{
label: 'OK, SORRY',
callback: () => {
this.closePopup();
}
},
]
});
} else {
this.sendMessage('onBackupDone');
}
});
$('#wordsConfirm_backBtn').addEventListener('click', () => {
this.isBack = true;
this.sendMessage('onConfirmBack');
});
$('#wordsConfirm_continueBtn').addEventListener('click', () => {
const confirmWords = this.getConfirmWords();
if (!confirmWords.isWordsFromList) {
return;
}
if (!confirmWords.isRightWords) {
this.showAlert({
title: 'Incorrect words',
message: 'The secret words you have entered do not match the ones in the list.',
buttons: [
{
label: 'SEE WORDS',
callback: () => {
this.isBack = true;
this.sendMessage('onConfirmBack');
}
},
{
label: 'TRY AGAIN',
callback: () => {
this.closePopup();
}
},
]
});
} else {
this.sendMessage('onConfirmDone', {words: confirmWords.words});
}
});
$('#createPassword_continueBtn').addEventListener('click', (e) => {
/** @type {string} */
const password = $('#createPassword_input').value;
/** @type {string} */
const passwordRepeat = $('#createPassword_repeatInput').value;
const isEmpty = password.length === 0 && !this.isTestnet;
if (isEmpty) {
$('#createPassword_input').classList.add('error');
} else if (password !== passwordRepeat) {
$('#createPassword_repeatInput').classList.add('error');
} else {
this.toggleButtonLoader(e.currentTarget, true);
this.sendMessage('passwordCreated', {password});
}
});
$('#readyToGo_continueBtn').addEventListener('click', () => this.sendMessage('showMain'));
$('#main_refreshBtn').addEventListener('click', () => {
this.setUpdating(true);
this.sendMessage('update');
});
$('#main_settingsButton').addEventListener('click', () => this.onSettingsClick());
$('#main_receiveBtn').addEventListener('click', () => {
toggle($('#receive_showAddressOnDeviceBtn'), !!this.isLedger);
this.showPopup('receive');
});
$('#sendButton').addEventListener('click', () => this.onMessage('showPopup', {name: 'send'}));
$('#modal').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup();
});
if (IS_FIREFOX) {
toggle($('#menu_magic'), false);
toggle($('.about-magic'), false);
}
$('#menu_magic').addEventListener('click', () => {
$('#menu_magic .dropdown-toggle').classList.toggle('toggle-on');
const isTurnedOn = $('#menu_magic .dropdown-toggle').classList.contains('toggle-on');
$('#menu_telegram').classList.toggle('menu_telegram-show', isTurnedOn);
this.sendMessage('onMagicClick', isTurnedOn);
});
$('#menu_telegram').addEventListener('click', () => {
window.open('https://web.telegram.org/z', '_blank');
});
$('#menu_proxy').addEventListener('click', () => {
$('#menu_proxy .dropdown-toggle').classList.toggle('toggle-on');
this.sendMessage('onProxyClick', $('#menu_proxy .dropdown-toggle').classList.contains('toggle-on'));
});
$('#menu_extension_chrome').addEventListener('click', () => window.open('https://chrome.google.com/webstore/detail/ton-wallet/nphplpgoakhhjchkkhmiggakijnkhfnd', '_blank'));
$('#menu_extension_firefox').addEventListener('click', () => window.open('https://addons.mozilla.org/ru/firefox/addon/', '_blank'));
$('#menu_about').addEventListener('click', () => this.showPopup('about'));
$('#menu_changePassword').addEventListener('click', () => this.onMessage('showPopup', {name: 'changePassword'}));
$('#menu_backupWallet').addEventListener('click', () => this.sendMessage('onBackupWalletClick'));
$('#menu_delete').addEventListener('click', () => this.showPopup('delete'));
$('#receive_showAddressOnDeviceBtn').addEventListener('click', () => this.onShowAddressOnDevice());
$('#receive_invoiceBtn').addEventListener('click', () => this.onCreateInvoiceClick());
$('#receive_shareBtn').addEventListener('click', () => this.onShareAddressClick(false));
$('#receive .addr').addEventListener('click', () => this.onShareAddressClick(true));
$('#receive_closeBtn').addEventListener('click', () => this.closePopup());
$('#invoice_qrBtn').addEventListener('click', () => this.onCreateInvoiceQrClick());
$('#invoice_shareBtn').addEventListener('click', () => this.onShareInvoiceClick());
$('#invoice_closeBtn').addEventListener('click', () => this.showPopup('receive'));
$('#invoiceQr_shareBtn').addEventListener('click', () => this.onShareInvoiceClick());
$('#invoiceQr_closeBtn').addEventListener('click', () => this.showPopup('invoice'));
$('#transaction_sendBtn').addEventListener('click', () => this.onTransactionButtonClick());
$('#transaction_closeBtn').addEventListener('click', () => this.closePopup());
$('#connectLedger_cancelBtn').addEventListener('click', () => this.closePopup());
$('#send_btn').addEventListener('click', (e) => {
/** @type {string} */
const amount = $('#amountInput').value;
/** @type {BN} */
const amountNano = toNano(amount);
if (!amountNano.gt(new BN(0)) || this.balance.lt(amountNano)) {
$('#amountInput').classList.add('error');
return;
}
/** @type {string} */
const toAddressString = $('#toWalletInput').value;
/** @type {Address | null} */
let toAddress = null;
try {
toAddress = new TonWeb.utils.Address(toAddressString);
} catch (e) {
}
if (!toAddressString.toLowerCase().endsWith('.ton') && !toAddressString.toLowerCase().endsWith('.t.me') && !toAddress) {
$('#toWalletInput').classList.add('error');
return;
}
/** @type {string} */
const comment = $('#commentInput').value;
/** @type {boolean} */
const needEncryptComment = $('#encryptCommentCheckbox').checked;
if (comment.length > 1024) {
$('#commentInput').classList.add('error');
$('#notify').innerText = 'Maximum 1024 symbols';
triggerClass($('#notify'), 'faded-show', 2000);
return;
}
// from https://github.com/tonkeeper/ton-assets/blob/main/accounts.json with "require_memo": true
const exchangeAddresses = [
'0:5f00decb7da51881764dc3959cec60609045f6ca1b89e646bde49d492705d77f', // OKX
'0:b31535e934db05bbc220267467903c8108bdabcbc2a06588838b726ddf589ef0', // FTX
'0:57eb74407604a19f7e04005315ef70aeb7b675e6551977586756f6baf12125ee', // MEXC
'0:7994848c1fcbcbc57a6a5a987b66eb424b8b54e10759b6b514a66b600c2b0eef', // EXMO
'0:8d195793baad9a08c46dc353aebe999341dabd07721b9725f19e18abc3d10d92', // EXMO Cold Storage 1
'0:26ab8ae763a3a7c3067d882b7b01cd5d37254cb8768f57b6a47c00028effc7b8', // EXMO Cold Storage 2
'0:0130c77346e9ed82df677d107ad6a775c11f9c18f6a05c0dd17906b355850dad', // EXMO Deposit
'0:342a359e38357c083968129fddddf049ef5c47315bfbef27505a356bf9f02d65', // CoinEx
'0:555f3053e257130374bb831ae0e219e5e5f9ec0ca8f8a0d133369d3d690c64c2', // Huobi Deposit
'0:85af78e8d035e920117cda654615cdf371d464480b629e110d3c5310d85ab362', // Huobi
'0:80d4123841167ca989ac912443cc99a4b9c1a87584536427ff6fd85c92395ae9', // Kucoin
'0:a14b1f452385b2bb984ad2c4441e1d23cae071fdfc096dfba53ebba3b6ff1d10', // Lbank.info
'0:c3f1da8ecda8f8cd42bace224ea3f1b6971eaa7f54c492d4d190527b4f573f7c', // Bybit
'0:008bb088e81e38d583826901093567027cc1575ec744ac354fa4eeec302d166d', // bit.com
]
const isExchange = toAddress && (exchangeAddresses.indexOf(toAddress.toString(false)) > -1);
if (isExchange) {
if (!comment) {
$('#notify').innerText = 'Exchange require text comment (MEMO) for deposit';
triggerClass($('#notify'), 'faded-show', 2000);
return;
}
if (comment && needEncryptComment) {
$('#notify').innerText = `Can't encrypt comment when depositing on exchange`;
triggerClass($('#notify'), 'faded-show', 2000);
return;
}
}
this.toggleButtonLoader(e.currentTarget, true);
this.sendMessage('onSend', {
amount: amountNano.toString(),
toAddress: toAddressString,
comment,
needEncryptComment
});
});
$('#send_closeBtn').addEventListener('click', () => this.closePopup());
$('#sendConfirm_closeBtn').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup();
});
$('#sendConfirm_cancelBtn').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup();
});
$('#sendConfirm_okBtn').addEventListener('click', () => this.onMessage('showPopup', {name: 'enterPassword'}));
$('#signConfirm_closeBtn').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup()
});
$('#signConfirm_cancelBtn').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup()
});
$('#signConfirm_okBtn').addEventListener('click', () => this.onMessage('showPopup', {name: 'enterPassword'}));
$('#connectConfirm_closeBtn').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup()
});
$('#connectConfirm_cancelBtn').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup()
});
$('#connectConfirm_okBtn').addEventListener('click', () => {
this.sendMessage('onConnectConfirmed', {});
});
$('#processing_closeBtn').addEventListener('click', () => this.closePopup());
$('#done_closeBtn').addEventListener('click', () => this.closePopup());
$('#about_closeBtn').addEventListener('click', () => this.closePopup());
$('#about_version').addEventListener('click', (e) => {
if (e.shiftKey) {
this.showAlert({
title: 'Are you sure you want to switch between mainnet/testnet?',
message: 'You can switch back the network by clicking on the version with the Shift key pressed',
buttons: [
{
label: 'I\'M SURE',
callback: () => {
this.sendMessage('toggleTestnet');
}
},
{
label: 'BACK',
callback: () => {
this.closePopup();
}
},
]
});
} else if (e.altKey) {
this.showAlert({
title: 'Are you sure you want to switch between clear console/debug mode?',
message: 'You can switch back the clear console by clicking on the version with the Alt key pressed',
buttons: [
{
label: 'I\'M SURE',
callback: () => {
this.sendMessage('toggleDebug');
}
},
{
label: 'BACK',
callback: () => {
this.closePopup();
}
},
]
});
}
});
$('#changePassword_cancelBtn').addEventListener('click', () => this.closePopup());
$('#changePassword_okBtn').addEventListener('click', async (e) => {
/** @type {string} */
const oldPassword = $('#changePassword_oldInput').value;
/** @type {string} */
const newPassword = $('#changePassword_newInput').value;
/** @type {string} */
const passwordRepeat = $('#changePassword_repeatInput').value;
const isEmpty = newPassword.length === 0 && !this.isTestnet;
if (isEmpty) {
$('#changePassword_newInput').classList.add('error');
return;
}
if (newPassword !== passwordRepeat) {
$('#changePassword_repeatInput').classList.add('error');
return;
}
this.toggleButtonLoader(e.currentTarget, true);
this.sendMessage('onChangePassword', {oldPassword, newPassword});
});
$('#enterPassword_cancelBtn').addEventListener('click', () => {
this.sendMessage('onCancelAction');
this.closePopup();
});
$('#enterPassword_okBtn').addEventListener('click', async (e) => {
/** @type {string} */
const password = $('#enterPassword_input').value;
this.toggleButtonLoader(e.currentTarget, true);
this.sendMessage('onEnterPassword', {password});
});
$('#delete_cancelBtn').addEventListener('click', () => this.closePopup());
$('#delete_okBtn').addEventListener('click', () => this.sendMessage('disconnect'));
$('#transactionDecryptCommentButton').addEventListener('click', () => {
if (!this.currentOpenTransaction) return;
this.sendMessage('decryptComment', {
hash: this.currentOpenTransaction.hash,
senderAddress: this.currentOpenTransaction.from_addr,
encryptedComment: this.currentOpenTransaction.encryptedComment,
});
});
}
// COMMON
/**
* @param name {string}
*/
showScreen(name) {
this.closePopup();
const screens = ['start', 'created', 'backup', 'wordsConfirm', 'import', 'createPassword', 'readyToGo', 'main'];
screens.forEach(screen => {
toggleFaded($('#' + screen), name === screen, {
isBack: this.isBack,
});
toggleLottie(lotties[screen], name === screen, {hideDelay: 300}); // 300ms, as for screen show/hide animation duration in CSS
});
toggleLottie(lotties['symbol'], name === 'main', {hideDelay: 300});
this.currentScreenName = name;
this.isBack = false;
window.scrollTo(0, 0);
}
/**
* @param el {HTMLElement}
* @param enable {boolean}
*/
toggleButtonLoader(el, enable) {
el.disabled = enable;
enable ? el.classList.add('btn-loader') : el.classList.remove('btn-loader');
}
/**
* @param params {{title: string, message: string, buttons?: {label: string, callback: () => void}[]}}
*/
showAlert(params) {
$('#alert .popup-title').innerText = params.title;
$('#alert .popup-black-text').innerText = params.message;
$('#alert .popup-footer').innerHTML = '';
if (params.buttons) {
params.buttons.forEach(button => {
const el = createElement({
tag: 'button',
clazz: 'btn-lite',
text: button.label
});
$('#alert .popup-footer').appendChild(el);
el.addEventListener('click', button.callback);
});
}
this.showPopup('alert');
}
/**
* @param name {string}
*/
showPopup(name) {
this.popup = name;
$('#enterPassword_input').value = '';
//popups switching without animations
if (this.popup && name) {
triggerClass(document.body, 'disable-animations', 20);
}
toggleFaded($('#modal'), name !== '');
const popups = ['alert', 'receive', 'invoice', 'invoiceQr', 'send', 'sendConfirm', 'signConfirm', 'connectConfirm', 'processing', 'done', 'menuDropdown', 'about', 'delete', 'changePassword', 'enterPassword', 'transaction', 'connectLedger', 'loader'];
popups.forEach(popup => {
toggleFaded($('#' + popup), name === popup);
toggleLottie(lotties[popup], name === popup);
});
}
closePopup() {
this.currentOpenTransaction = null;
this.showPopup('');
this.sendMessage('onClosePopup');
}
// BACKUP SCREEN
/**
* @param words {string[]}
*/
setBackupWords(words) {
/**
* @param n {number}
*/
const createBackupWord = n => {
$('#createWords').appendChild(
createElement({
tag: 'div',
clazz: 'create-word-item',
child: [
createElement({
tag: 'span',
clazz: 'word-num',
text: (n + 1) + '.'
}),
createElement({
tag: 'span',
style: {
'font-weight': 'bold'
},
text: words[n]
})
]
})
);
};
clearElement($('#createWords'));
for (let i = 0; i < words.length / 2; i++) {
createBackupWord(i);
createBackupWord(i + 12);
}
}
clearBackupWords() {
clearElement($('#createWords'));
}
// IMPORT && CONFIRM SCREENS
/**
* @param params {{count: number, containerId: string, inputId: string, dropdownId: string, multiColumns: boolean}}
*/
createWordInputs(params) {
/**
* @param input {HTMLInputElement}
*/
const onEnter = input => {
const i = Number(input.getAttribute('tabindex'));
if (i === params.count) {
} else {
$(params.inputId + i).focus();
}
};
const dropdown = new DropDown($(params.dropdownId), onEnter, this.mnemonicWords);
/** @type {HTMLInputElement | null} */
let lastInput = null;
/**
* @param input {HTMLInputElement}
*/
const showWordsPopup = input => {
const text = input.value;
if (text === null || text.length === 0) {
toggle($(params.dropdownId), false);
return;
}
dropdown.show(input, text.toLowerCase());
};
/**
* @param e {Event}
*/
function onWordInput(e) {
/** @type {HTMLInputElement} */
const input = e.target;
input.classList.remove('error');
showWordsPopup(input);
}
/**
* @param e {Event}
*/
const onFocusIn = (e) => {
/** @type {HTMLInputElement} */
const input = e.target;
lastInput = input;
showWordsPopup(input);
};
/**
* @param e {Event}
*/
const onFocusOut = (e) => {
toggle($(params.dropdownId), false);
if (lastInput) {
const value = lastInput.value.toLowerCase().trim();
if (value.length > 0 && this.mnemonicWords.indexOf(value) === -1) {
lastInput.classList.add('error');
} else {
lastInput.classList.remove('error');
}
}
};
/**
* @param e {KeyboardEvent}
*/
const onKeyDown = (e) => {
/** @type {HTMLInputElement} */
const input = e.target;
switch (e.key) {
case 'Enter':
const selectedText = dropdown.getSelectedText();
if (selectedText) {
input.value = selectedText;
input.classList.remove('error');
dropdown.hide();
}
onEnter(input);
break;
case 'ArrowUp':
dropdown.up();
break;
case 'ArrowDown':
dropdown.down();
break;
}
};
/**
* @param event {ClipboardEvent}
*/
const onPaste = (event) => {
const text = (event.clipboardData || window.clipboardData).getData('text');
let arr = text.split(' ');
if (arr.length !== params.count) {
arr = text.split(',');
}
if (arr.length === params.count) {
for (let i = 0; i < params.count; i++) {
/** @type {HTMLInputElement} */
const input = $(params.inputId + i);
const value = arr[i].toLowerCase().trim();
if (!value || this.mnemonicWords.indexOf(value) === -1) {
input.classList.add('error');
} else {
input.classList.remove('error');
}
input.value = value;
}
event.preventDefault();
}
};
/**
* @param n {number}
*/
const createInput = (n) => {
const inputContainer = createElement({tag: 'div', clazz: 'word-item'});
const span = createElement({tag: 'span', clazz: 'word-num', text: (n + 1) + '.'});
inputContainer.appendChild(span);
/** @type {HTMLInputElement} */
const input = createElement({tag: 'input'});
input.id = params.inputId.slice(1) + n;
input.type = 'text';
input.tabIndex = n + 1;
input.autocomplete = 'off';
inputContainer.appendChild(input);
input.addEventListener('focusin', onFocusIn);
input.addEventListener('focusout', onFocusOut);
input.addEventListener('keydown', onKeyDown);
input.addEventListener('paste', onPaste);
onInput(input, onWordInput);
$(params.containerId).appendChild(inputContainer);
};
if (params.multiColumns) {
for (let i = 0; i < params.count / 2; i++) {
createInput(i);
createInput(i + params.count / 2);
}
} else {
for (let i = 0; i < params.count; i++) {
createInput(i);
}
}
}
clearImportWords() {
toggle($('#wordsPopup'), false);
for (let i = 0; i < IMPORT_WORDS_COUNT; i++) {
/** @type {HTMLInputElement} */
const input = $('#importsInput' + i);
input.value = '';
input.classList.remove('error');
}
}
clearConfirmWords() {
toggle($('#wordsConfirmPopup'), false);
for (let i = 0; i < CONFIRM_WORDS_COUNT; i++) {
/** @type {HTMLInputElement} */
const input = $('#confirmInput' + i);
input.value = '';
input.setAttribute('data-word', '');
input.classList.remove('error');
}
}
/**
* @param words {string[]}
*/
setConfirmWords(words) {
/** @type {number[]} */
const nums = Array(IMPORT_WORDS_COUNT)
.fill(0)
.map((_, index) => ({index, rnd: Math.random()}))
.sort((a, b) => a.rnd - b.rnd)
.map(item => item.index)
.slice(0, CONFIRM_WORDS_COUNT)
.sort((a, b) => a - b);
const spans = $$('#confirmWordsNums span');
for (let i = 0; i < CONFIRM_WORDS_COUNT; i++) {
/** @type {HTMLInputElement} */
const input = $('#confirmInput' + i);
input.setAttribute('data-index', nums[i].toString());
input.setAttribute('data-word', words[nums[i]]);
spans[i].innerText = (nums[i] + 1).toString();
input.parentNode.children[0].innerText = (nums[i] + 1) + '.';
}
}
/**
* @return {Promise}
*/
async getImportWords() {
/** @type {boolean} */
let isValid = true;
/** @type {string[]} */
const words = [];
for (let i = 0; i < IMPORT_WORDS_COUNT; i++) {
/** @type {HTMLInputElement} */
const input = $('#importsInput' + i);
/** @type {string} */
const value = input.value.toLowerCase().trim();
if (!value || this.mnemonicWords.indexOf(value) === -1) {
input.classList.add('error');
isValid = false;
}
words.push(value);
}
if (isValid) {
isValid = await TonWeb.mnemonic.validateMnemonic(words);
if (!isValid) {
for (let i = 0; i < IMPORT_WORDS_COUNT; i++) {
const input = $('#importsInput' + i);
input.classList.add('error');
}
}
}
return isValid ? words : null;
}
/**
* @return {{isWordsFromList: boolean, isRightWords: boolean, words: null | Object}} words - index to word
*/
getConfirmWords() {
/** @type {boolean} */
let isWordsFromList = true;
/** @type {boolean} */
let isRightWords = true;
/** @type {Object} */
const words = {};
for (let i = 0; i < CONFIRM_WORDS_COUNT; i++) {
/** @type {HTMLInputElement} */
const input = $('#confirmInput' + i);
/** @type {string} */
const value = input.value.toLowerCase().trim();
/** @type {string} */
const index = input.getAttribute('data-index');
/** @type {string} */
const validValue = input.getAttribute('data-word');
if (!value || this.mnemonicWords.indexOf(value) === -1) {
input.classList.add('error');
isWordsFromList = false;
}
if (value !== validValue) {
isRightWords = false;
}
words[index] = value;
}
return {
isWordsFromList,
isRightWords,
words: isWordsFromList && isRightWords ? words : null
};
}
// CREATE PASSWORD SCREEN
clearCreatePassword() {
$('#createPassword_input').value = '';
$('#createPassword_repeatInput').value = '';
}
// CHANGE PASSWORD POPUP
clearChangePassword() {
$('#changePassword_oldInput').value = '';
$('#changePassword_newInput').value = '';
$('#changePassword_repeatInput').value = '';
}
// MAIN SCREEN
/**
* @param updating {boolean}
*/
setUpdating(updating) {
$('#updateLabel').innerText = updating ? 'updating..' : 'updated just now';
}
onSettingsClick() {
toggleFaded($('#modal'), true);
toggleFaded($('#menuDropdown'), true);
toggle($('#menu_changePassword'), !this.isLedger);
toggle($('#menu_backupWallet'), !this.isLedger);
}
clearBalance() {
clearElement($('#balance'));
clearElement($('#transactionsList'));
toggle($('#walletCreated'), false);
}
/**
* @param balance {BN}
* @param txs {any[]}
*/
setBalance(balance, txs) {
this.balance = balance;
/** @type {string} */
let s = fromNano(balance);
if (s === '0') s = '0.00';
const i = s.indexOf('.');
const first = s.substring(0, i);
const last = s.substring(i);
clearElement($('#balance'));
$('#balance').appendChild(createElement({tag: 'span', text: first}));
$('#balance').appendChild(createElement({tag: 'span', style: {'font-size': '24px'}, text: last}));
$('#sendBalance').innerText = 'Balance: ' + s + ' 💎';
toggle($('#sendButton'), balance.gt(new BN(0)) ? 'inline-block' : 'none');
this.setTransactions(txs);
this.setUpdating(false);
}
/**
* @param txs {any[]}
*/
setTransactions(txs) {
clearElement($('#transactionsList'));
/** @type {string} */
let date = '';
toggle($('#walletCreated'), txs.length === 0);
txs.forEach(tx => {
tx.amount = new BN(tx.amount);
tx.fee = new BN(tx.fee);
tx.date = new Date(tx.date);
/** @type {string} */
const txDate = formatDate(tx.date);
if (date !== txDate) {
this.addDateSeparator(txDate);
date = txDate;
}
this.addTx(tx);
});
}
/**
* @param dateString {string}
*/
addDateSeparator(dateString) {
$('#transactionsList').appendChild(createElement({tag: 'div', clazz: 'date-separator', text: dateString}));
}
/**
* @param tx {any}
*/
addTx(tx) {
/** @type {boolean} */
const isReceive = tx.inbound;
/** @type {string} */
const amountFormatted = fromNano(tx.amount);
/** @type {string} */
const addr = isReceive ? tx.from_addr : tx.to_addr;
const item = createElement({
tag: 'div',
clazz: 'tx-item',
child: [
createElement({
tag: 'div',
child: isReceive ? [
createElement({
tag: 'span',
clazz: ['tx-amount', 'tx-amount-green'],
text: '+' + amountFormatted
}),
createElement({tag: 'span', text: ' 💎'}),
createElement({tag: 'span', clazz: 'tx-from', text: ' from:'})
] : [
createElement({tag: 'span', clazz: 'tx-amount', text: amountFormatted}),
createElement({tag: 'span', text: ' 💎'}),
createElement({tag: 'span', clazz: 'tx-from', text: ' to:'})
]
}),
setAddr(createElement({tag: 'div', clazz: ['tx-addr', 'addr']}), addr),
tx.encryptedComment ? createElement({tag: 'div', clazz: 'tx-item-encrypted-icon'}) : undefined,
tx.comment ? createElement({tag: 'div', clazz: 'tx-comment', text: tx.comment}) : undefined,
createElement({tag: 'div', clazz: 'tx-fee', text: `blockchain fees: ${fromNano(tx.fee)}`}),
createElement({tag: 'div', clazz: 'tx-item-date', text: formatTime(tx.date)})
]
});
item.addEventListener('click', () => this.onTransactionClick(tx));
$('#transactionsList').appendChild(item);
}
// TRANSACTION POPUP
/**
* @param tx {any}
*/
onTransactionClick(tx) {
this.currentOpenTransaction = tx;
this.showPopup('transaction');
/** @type {boolean} */
const isReceive = tx.inbound;
/** @type {string} */
const amountFormatted = fromNano(tx.amount);
/** @type {string} */
const addr = isReceive ? tx.from_addr : tx.to_addr;
this.currentTransactionAddr = addr;
$('#transactionAmount').innerText = (isReceive ? '+' + amountFormatted : amountFormatted) + ' 💎';
$('#transactionFee').innerText = fromNano(tx.fee) + ' transaction fee';
$('#transactionSenderLabel').innerText = isReceive ? 'Sender' : 'Recipient';
setAddr($('#transactionSender'), addr);
toggle($('#transactionCommentLabel'), !!tx.comment || !!tx.encryptedComment);
toggle($('#transactionDecryptCommentButton'), !!tx.encryptedComment);
toggle($('#transactionComment'), !!tx.comment);
$('#transactionComment').innerText = tx.comment;
$('#transactionDate').innerText = formatDateFull(tx.date);
}
onTransactionButtonClick() {
this.onMessage('showPopup', {name: 'send', toAddr: this.currentTransactionAddr});
}
// SEND POPUP
clearSend() {
$('#toWalletInput').value = '';
$('#amountInput').value = '';
$('#commentInput').value = '';
$('#encryptCommentCheckbox').checked = false;
}
// RECEIVE POPUP
/**
* @param address {string}
*/
setMyAddress(address) {
setAddr($('#receive .addr'), address);
drawQRCode(TonWeb.utils.formatTransferUrl(address), '#qr');
this.address = address;
this.loadDiamond(address);
}
/**
* @param address {string}
* @return {Promise}
*/
async loadDiamond(address) {
toggle($('.balance-symbol'), true);
toggle($('.balance-diamond-container'), false);
toggle($('#diamond'), false);
try {
if (this.isTestnet) return;
const res = await fetch('https://ton.diamonds/api/wallet/diamond_nfts?address=' + address + '&perPage=1¤t=1');
if (res.status !== 200) return;
const json = await res.json();
if (json.ok !== true) return;
if (json.result.total < 1) return;
const nftNumber = json.result.rows[0].nftNumber;
const diamondImageUrl = 'https://nft.ton.diamonds/nft/' + nftNumber + '/' + nftNumber + '_diamond.svg';
if (address === this.address) {
toggle($('.balance-symbol'), false);
$('#diamond').style.backgroundImage = 'url("' + diamondImageUrl + '")';
toggle($('.balance-diamond-container'), true);
toggle($('#diamond'), true);
}
} catch (e) {
console.error('Diamonds Error', e);
}
}
/**
* @param onyAddress {boolean} share address or transfer link
*/
onShareAddressClick(onyAddress) {
const data = onyAddress ? this.myAddress : TonWeb.utils.formatTransferUrl(this.myAddress);
const text = onyAddress ? 'Wallet address copied to clipboard' : 'Transfer link copied to clipboard';
$('#notify').innerText = copyToClipboard(data) ? text : 'Can\'t copy link';
triggerClass($('#notify'), 'faded-show', 2000);
}
onShowAddressOnDevice() {
this.sendMessage('showAddressOnDevice');
$('#notify').innerText = 'Please check the address on your device';
triggerClass($('#notify'), 'faded-show', 2000);
}
// RECEIVE INVOICE POPUP
onCreateInvoiceClick() {
this.onMessage('showPopup', {name: 'invoice'});
}
updateInvoiceLink() {
$('#invoice_link').innerText = this.getInvoiceLink();
};
/**
* @return {string}
*/
getInvoiceLink() {
const amountString = $('#invoice_amountInput').value;
/** @type {string | undefined} */
const amount = amountString ? toNano(amountString).toString() : undefined;
return TonWeb.utils.formatTransferUrl(this.myAddress, amount, $('#invoice_commentInput').value);
}
onShareInvoiceClick() {
$('#notify').innerText = copyToClipboard(this.getInvoiceLink()) ? 'Transfer link copied to clipboard' : 'Can\'t copy link';
triggerClass($('#notify'), 'faded-show', 2000);
}
// RECEIVE INVOICE QR POPUP
onCreateInvoiceQrClick() {
this.onMessage('showPopup', {name: 'invoiceQr'});
}
/**
* @param link {string}
*/
drawInvoiceQr(link) {
drawQRCode(link, '#invoiceQrImg');
}
// TRANSPORT WITH CONTROLLER
/**
* Send message to Controller.js
* @param method {string}
* @param params? {any} boolean or object, not array
*/
sendMessage(method, params) {
if (this.controller) {
this.controller.onViewMessage(method, params);
} else {
this.port.postMessage({method, params});
}
}
/**
* Receive message from Controller.js
* @param method {string}
* @param params? {any} boolean or object, not array
* @return {undefined | {magic: string | null, proxy: string | null, address: string | null, words: string | null, walletVersion: string | null}}
*/
onMessage(method, params) {
switch (method) {
case 'disableCreated':
$('#createdContinueButton').disabled = params;
break;
case 'setIsTestnet':
this.isTestnet = params;
$('.your-balance').innerText = params ? 'Your testnet balance' : 'Your mainnet balance';
break;
case 'setBalance':
this.setBalance(new BN(params.balance), params.txs);
break;
case 'setIsLedger':
this.isLedger = params;
break;
case 'setIsMagic':
const isTurnedOn = params;
$('#menu_magic .dropdown-toggle').classList.toggle('toggle-on', isTurnedOn && !IS_FIREFOX);
$('#menu_telegram').classList.toggle('menu_telegram-show', isTurnedOn && !IS_FIREFOX);
break;
case 'setIsProxy':
if (params) {
$('#menu_proxy .dropdown-toggle').classList.add('toggle-on');
} else {
$('#menu_proxy .dropdown-toggle').classList.remove('toggle-on');
}
break;
case 'privateKeySaved':
this.toggleButtonLoader($('#createPassword_continueBtn'), false);
break;
case 'passwordChanged':
this.toggleButtonLoader($('#changePassword_okBtn'), false);
break;
case 'showChangePasswordError':
this.toggleButtonLoader($('#changePassword_okBtn'), false);
$('#changePassword_oldInput').classList.add('error');
break;
case 'passwordEntered':
this.toggleButtonLoader($('#enterPassword_okBtn'), false);
break;
case 'showEnterPasswordError':
this.toggleButtonLoader($('#enterPassword_okBtn'), false);
$('#enterPassword_input').classList.add('error');
break;
case 'importCompleted':
this.toggleButtonLoader($('#import_continueBtn'), false);
break;
case 'sendCheckFailed':
if (params && params.message) {
$('#notify').innerText = params.message;
triggerClass($('#notify'), 'faded-show', 3000);
}
this.toggleButtonLoader($('#send_btn'), false);
break;
case 'sendCheckSucceeded':
this.toggleButtonLoader($('#send_btn'), false);
break;
case 'sendCheckCantPublicKey':
this.toggleButtonLoader($('#send_btn'), false);
$('#notify').innerText = `To encrypt a message, the destination wallet must have at least one outgoing transfer`;
triggerClass($('#notify'), 'faded-show', 3000);
break;
case 'sendCheckCantPayFee':
this.toggleButtonLoader($('#send_btn'), false);
$('#amountInput').classList.add('error');
$('#notify').innerText = `Estimated fee is ~${fromNano(params.fee)} TON`;
triggerClass($('#notify'), 'faded-show', 3000);
break;
case 'decryptedComment':
if (this.currentOpenTransaction && this.currentOpenTransaction.hash === params.hash) {
this.currentOpenTransaction.encryptedComment = null;
this.currentOpenTransaction.comment = params.decryptedComment;
this.onTransactionClick(this.currentOpenTransaction);
}
break;
case 'showScreen':
if (params.noAnimation) {
triggerClass(document.body, 'disable-animations', 300);
}
this.showScreen(params.name);
switch (params.name) {
case 'start':
this.clearBalance();
this.clearImportWords();
break;
case 'created':
break;
case 'import':
this.clearImportWords();
$('#importsInput0').focus();
break;
case 'backup':
this.clearConfirmWords();
this.setBackupWords(params.words);
this.backupShownTime = params.isFirst ? (+new Date()) : 0;
break;
case 'wordsConfirm':
this.clearConfirmWords();
this.clearBackupWords();
$('#confirmInput0').focus();
this.setConfirmWords(params.words);
break;
case 'createPassword':
this.clearImportWords();
this.clearConfirmWords();
this.clearCreatePassword();
$('#createPassword_input').focus();
break;
case 'readyToGo':
this.clearCreatePassword();
break;
case 'main':
this.clearBackupWords();
if (params.myAddress) {
this.myAddress = params.myAddress;
this.setMyAddress(params.myAddress);
}
break;
}
break;
case 'showPopup':
this.showPopup(params.name);
switch (params.name) {
case 'changePassword':
this.clearChangePassword();
$('#changePassword_oldInput').focus();
break;
case 'enterPassword':
$('#enterPassword_input').focus();
break;
case 'done':
$('#done .popup-grey-text').innerText = params.message;
break;
case 'invoice':
$('#invoice_amountInput').value = '';
$('#invoice_commentInput').value = '';
this.updateInvoiceLink();
$('#invoice_amountInput').focus();
break;
case 'invoiceQr':
this.drawInvoiceQr(this.getInvoiceLink());
$('#invoiceQrAmount').innerText = $('#invoice_amountInput').value;
break;
case 'send':
this.clearSend();
if (params.toAddr) {
$('#toWalletInput').value = params.toAddr;
}
toggle($('#commentInput'), !this.isLedger);
toggle($('#encryptCommentCheckboxContainer'), !this.isLedger ? 'flex' : false);
$('#toWalletInput').focus();
break;
case 'sendConfirm':
$('#sendConfirmAmount').innerText = fromNano(new BN(params.amount)) + ' TON';
setAddr($('#sendConfirmAddr'), params.toAddress);
$('#sendConfirmFee').innerText = params.fee ? 'Fee: ~' + fromNano(new BN(params.fee)) + ' TON' : '';
toggle($('#sendConfirmNotEncryptedNote'), !params.needEncryptComment);
toggle($('#sendConfirm .popup-footer'), !this.isLedger);
toggle($('#sendConfirm_closeBtn'), !this.isLedger);
// todo: show label 'Please approve on device'
break;
case 'signConfirm':
$('#signConfirmText').innerText = params.isConnect ? 'Do you want to connect your wallet to this page?' : 'Do you want to sign:';
toggle($('#signConfirmData'), !params.isConnect);
toggle($('#signConfirmAlert'), !params.isConnect);
const hex = params.data.length > 48 ? params.data.substring(0, 47) + '…' : params.data;
setAddr($('#signConfirmData'), hex);
break;
case 'connectConfirm':
break;
}
break;
case 'closePopup':
this.closePopup();
break;
case 'restoreDeprecatedStorage':
const address = localStorage.getItem('address');
const words = localStorage.getItem('words');
const walletVersion = localStorage.getItem('walletVersion');
const magic = localStorage.getItem('magic');
const proxy = localStorage.getItem('proxy');
localStorage.clear();
return {address, words, walletVersion, magic, proxy};
}
}
}
window.view = new View(TonWeb.mnemonic.wordlists.EN);
if (IS_EXTENSION) {
// connect to background process
const connectToBackground = () => {
const port = chrome.runtime.connect({name: 'gramWalletPopup'});
window.view.port = port;
port.onMessage.addListener(data => {
const result = window.view.onMessage(data.method, data.params);
if (result && data.id) {
port.postMessage({method: 'response', id: data.id, result});
}
});
port.onDisconnect.addListener(() => {
connectToBackground();
});
}
connectToBackground();
// remember extension position and size
const startTrackWindowPositionAndSize = async () => {
let prevWindow = await chrome.windows.getCurrent();
setInterval(async () => {
const currentWindow = await chrome.windows.getCurrent();
if (
currentWindow.top !== prevWindow.top ||
currentWindow.left !== prevWindow.left ||
currentWindow.height !== prevWindow.height ||
currentWindow.width !== prevWindow.width
) {
prevWindow = currentWindow;
window.view.sendMessage('onWindowUpdate', {
top: currentWindow.top,
left: currentWindow.left,
height: currentWindow.height,
width: currentWindow.width
});
}
}, 3000);
}
startTrackWindowPositionAndSize();
}
// show attention message in browser console
if (window.top == window && window.console) {
/** @type {Object} */
const selfXssAttentions = {
'ru-RU': ['Внимание!', 'Используя эту консоль, вы можете подвергнуться атаке Self-XSS, что позволит злоумышленникам завладеть вашим кошельком.\nНе вводите и не вставляйте программный код, который не понимаете.'],
'*': ['Attention!', 'Using this console, you can be exposed to a Self-XSS attack, allowing attackers to take over your wallet.\nDo not enter or paste program code that you do not understand.']
};
/** @type {string} */
const userLanguage = navigator.language || navigator.userLanguage;
/** @type {string[]} */
let localizedSelfXssAttention = selfXssAttentions[userLanguage];
if (!localizedSelfXssAttention) localizedSelfXssAttention = selfXssAttentions['*'];
console.log(
'%c%s', 'color: red; background: yellow; font-size: 24px;', localizedSelfXssAttention[0]
);
console.log('%c%s', 'font-size: 18px;', localizedSelfXssAttention[1]);
}
================================================
FILE: src/libs/aes-js-3.1.2.js
================================================
/*! MIT License. Copyright 2015-2018 Richard Moore . See LICENSE.txt. */
(function(root) {
"use strict";
function checkInt(value) {
return (parseInt(value) === value);
}
function checkInts(arrayish) {
if (!checkInt(arrayish.length)) { return false; }
for (var i = 0; i < arrayish.length; i++) {
if (!checkInt(arrayish[i]) || arrayish[i] < 0 || arrayish[i] > 255) {
return false;
}
}
return true;
}
function coerceArray(arg, copy) {
// ArrayBuffer view
if (arg.buffer && arg.name === 'Uint8Array') {
if (copy) {
if (arg.slice) {
arg = arg.slice();
} else {
arg = Array.prototype.slice.call(arg);
}
}
return arg;
}
// It's an array; check it is a valid representation of a byte
if (Array.isArray(arg)) {
if (!checkInts(arg)) {
throw new Error('Array contains invalid value: ' + arg);
}
return new Uint8Array(arg);
}
// Something else, but behaves like an array (maybe a Buffer? Arguments?)
if (checkInt(arg.length) && checkInts(arg)) {
return new Uint8Array(arg);
}
throw new Error('unsupported array-like object');
}
function createArray(length) {
return new Uint8Array(length);
}
function copyArray(sourceArray, targetArray, targetStart, sourceStart, sourceEnd) {
if (sourceStart != null || sourceEnd != null) {
if (sourceArray.slice) {
sourceArray = sourceArray.slice(sourceStart, sourceEnd);
} else {
sourceArray = Array.prototype.slice.call(sourceArray, sourceStart, sourceEnd);
}
}
targetArray.set(sourceArray, targetStart);
}
var convertUtf8 = (function() {
function toBytes(text) {
var result = [], i = 0;
text = encodeURI(text);
while (i < text.length) {
var c = text.charCodeAt(i++);
// if it is a % sign, encode the following 2 bytes as a hex value
if (c === 37) {
result.push(parseInt(text.substr(i, 2), 16))
i += 2;
// otherwise, just the actual byte
} else {
result.push(c)
}
}
return coerceArray(result);
}
function fromBytes(bytes) {
var result = [], i = 0;
while (i < bytes.length) {
var c = bytes[i];
if (c < 128) {
result.push(String.fromCharCode(c));
i++;
} else if (c > 191 && c < 224) {
result.push(String.fromCharCode(((c & 0x1f) << 6) | (bytes[i + 1] & 0x3f)));
i += 2;
} else {
result.push(String.fromCharCode(((c & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f)));
i += 3;
}
}
return result.join('');
}
return {
toBytes: toBytes,
fromBytes: fromBytes,
}
})();
var convertHex = (function() {
function toBytes(text) {
var result = [];
for (var i = 0; i < text.length; i += 2) {
result.push(parseInt(text.substr(i, 2), 16));
}
return result;
}
// http://ixti.net/development/javascript/2011/11/11/base64-encodedecode-of-utf8-in-browser-with-js.html
var Hex = '0123456789abcdef';
function fromBytes(bytes) {
var result = [];
for (var i = 0; i < bytes.length; i++) {
var v = bytes[i];
result.push(Hex[(v & 0xf0) >> 4] + Hex[v & 0x0f]);
}
return result.join('');
}
return {
toBytes: toBytes,
fromBytes: fromBytes,
}
})();
// Number of rounds by keysize
var numberOfRounds = {16: 10, 24: 12, 32: 14}
// Round constant words
var rcon = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91];
// S-box and Inverse S-box (S is for Substitution)
var S = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16];
var Si =[0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d];
// Transformations for encryption
var T1 = [0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a];
var T2 = [0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616];
var T3 = [0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16];
var T4 = [0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c];
// Transformations for decryption
var T5 = [0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742];
var T6 = [0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, 0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10, 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015, 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, 0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, 0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, 0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, 0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8, 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6, 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, 0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95, 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857];
var T7 = [0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3, 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, 0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655, 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, 0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, 0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, 0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, 0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, 0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, 0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8];
var T8 = [0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, 0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9, 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced, 0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4, 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60, 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, 0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, 0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, 0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff, 0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0];
// Transformations for decryption key expansion
var U1 = [0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3];
var U2 = [0x00000000, 0x0b0e090d, 0x161c121a, 0x1d121b17, 0x2c382434, 0x27362d39, 0x3a24362e, 0x312a3f23, 0x58704868, 0x537e4165, 0x4e6c5a72, 0x4562537f, 0x74486c5c, 0x7f466551, 0x62547e46, 0x695a774b, 0xb0e090d0, 0xbbee99dd, 0xa6fc82ca, 0xadf28bc7, 0x9cd8b4e4, 0x97d6bde9, 0x8ac4a6fe, 0x81caaff3, 0xe890d8b8, 0xe39ed1b5, 0xfe8ccaa2, 0xf582c3af, 0xc4a8fc8c, 0xcfa6f581, 0xd2b4ee96, 0xd9bae79b, 0x7bdb3bbb, 0x70d532b6, 0x6dc729a1, 0x66c920ac, 0x57e31f8f, 0x5ced1682, 0x41ff0d95, 0x4af10498, 0x23ab73d3, 0x28a57ade, 0x35b761c9, 0x3eb968c4, 0x0f9357e7, 0x049d5eea, 0x198f45fd, 0x12814cf0, 0xcb3bab6b, 0xc035a266, 0xdd27b971, 0xd629b07c, 0xe7038f5f, 0xec0d8652, 0xf11f9d45, 0xfa119448, 0x934be303, 0x9845ea0e, 0x8557f119, 0x8e59f814, 0xbf73c737, 0xb47dce3a, 0xa96fd52d, 0xa261dc20, 0xf6ad766d, 0xfda37f60, 0xe0b16477, 0xebbf6d7a, 0xda955259, 0xd19b5b54, 0xcc894043, 0xc787494e, 0xaedd3e05, 0xa5d33708, 0xb8c12c1f, 0xb3cf2512, 0x82e51a31, 0x89eb133c, 0x94f9082b, 0x9ff70126, 0x464de6bd, 0x4d43efb0, 0x5051f4a7, 0x5b5ffdaa, 0x6a75c289, 0x617bcb84, 0x7c69d093, 0x7767d99e, 0x1e3daed5, 0x1533a7d8, 0x0821bccf, 0x032fb5c2, 0x32058ae1, 0x390b83ec, 0x241998fb, 0x2f1791f6, 0x8d764dd6, 0x867844db, 0x9b6a5fcc, 0x906456c1, 0xa14e69e2, 0xaa4060ef, 0xb7527bf8, 0xbc5c72f5, 0xd50605be, 0xde080cb3, 0xc31a17a4, 0xc8141ea9, 0xf93e218a, 0xf2302887, 0xef223390, 0xe42c3a9d, 0x3d96dd06, 0x3698d40b, 0x2b8acf1c, 0x2084c611, 0x11aef932, 0x1aa0f03f, 0x07b2eb28, 0x0cbce225, 0x65e6956e, 0x6ee89c63, 0x73fa8774, 0x78f48e79, 0x49deb15a, 0x42d0b857, 0x5fc2a340, 0x54ccaa4d, 0xf741ecda, 0xfc4fe5d7, 0xe15dfec0, 0xea53f7cd, 0xdb79c8ee, 0xd077c1e3, 0xcd65daf4, 0xc66bd3f9, 0xaf31a4b2, 0xa43fadbf, 0xb92db6a8, 0xb223bfa5, 0x83098086, 0x8807898b, 0x9515929c, 0x9e1b9b91, 0x47a17c0a, 0x4caf7507, 0x51bd6e10, 0x5ab3671d, 0x6b99583e, 0x60975133, 0x7d854a24, 0x768b4329, 0x1fd13462, 0x14df3d6f, 0x09cd2678, 0x02c32f75, 0x33e91056, 0x38e7195b, 0x25f5024c, 0x2efb0b41, 0x8c9ad761, 0x8794de6c, 0x9a86c57b, 0x9188cc76, 0xa0a2f355, 0xabacfa58, 0xb6bee14f, 0xbdb0e842, 0xd4ea9f09, 0xdfe49604, 0xc2f68d13, 0xc9f8841e, 0xf8d2bb3d, 0xf3dcb230, 0xeecea927, 0xe5c0a02a, 0x3c7a47b1, 0x37744ebc, 0x2a6655ab, 0x21685ca6, 0x10426385, 0x1b4c6a88, 0x065e719f, 0x0d507892, 0x640a0fd9, 0x6f0406d4, 0x72161dc3, 0x791814ce, 0x48322bed, 0x433c22e0, 0x5e2e39f7, 0x552030fa, 0x01ec9ab7, 0x0ae293ba, 0x17f088ad, 0x1cfe81a0, 0x2dd4be83, 0x26dab78e, 0x3bc8ac99, 0x30c6a594, 0x599cd2df, 0x5292dbd2, 0x4f80c0c5, 0x448ec9c8, 0x75a4f6eb, 0x7eaaffe6, 0x63b8e4f1, 0x68b6edfc, 0xb10c0a67, 0xba02036a, 0xa710187d, 0xac1e1170, 0x9d342e53, 0x963a275e, 0x8b283c49, 0x80263544, 0xe97c420f, 0xe2724b02, 0xff605015, 0xf46e5918, 0xc544663b, 0xce4a6f36, 0xd3587421, 0xd8567d2c, 0x7a37a10c, 0x7139a801, 0x6c2bb316, 0x6725ba1b, 0x560f8538, 0x5d018c35, 0x40139722, 0x4b1d9e2f, 0x2247e964, 0x2949e069, 0x345bfb7e, 0x3f55f273, 0x0e7fcd50, 0x0571c45d, 0x1863df4a, 0x136dd647, 0xcad731dc, 0xc1d938d1, 0xdccb23c6, 0xd7c52acb, 0xe6ef15e8, 0xede11ce5, 0xf0f307f2, 0xfbfd0eff, 0x92a779b4, 0x99a970b9, 0x84bb6bae, 0x8fb562a3, 0xbe9f5d80, 0xb591548d, 0xa8834f9a, 0xa38d4697];
var U3 = [0x00000000, 0x0d0b0e09, 0x1a161c12, 0x171d121b, 0x342c3824, 0x3927362d, 0x2e3a2436, 0x23312a3f, 0x68587048, 0x65537e41, 0x724e6c5a, 0x7f456253, 0x5c74486c, 0x517f4665, 0x4662547e, 0x4b695a77, 0xd0b0e090, 0xddbbee99, 0xcaa6fc82, 0xc7adf28b, 0xe49cd8b4, 0xe997d6bd, 0xfe8ac4a6, 0xf381caaf, 0xb8e890d8, 0xb5e39ed1, 0xa2fe8cca, 0xaff582c3, 0x8cc4a8fc, 0x81cfa6f5, 0x96d2b4ee, 0x9bd9bae7, 0xbb7bdb3b, 0xb670d532, 0xa16dc729, 0xac66c920, 0x8f57e31f, 0x825ced16, 0x9541ff0d, 0x984af104, 0xd323ab73, 0xde28a57a, 0xc935b761, 0xc43eb968, 0xe70f9357, 0xea049d5e, 0xfd198f45, 0xf012814c, 0x6bcb3bab, 0x66c035a2, 0x71dd27b9, 0x7cd629b0, 0x5fe7038f, 0x52ec0d86, 0x45f11f9d, 0x48fa1194, 0x03934be3, 0x0e9845ea, 0x198557f1, 0x148e59f8, 0x37bf73c7, 0x3ab47dce, 0x2da96fd5, 0x20a261dc, 0x6df6ad76, 0x60fda37f, 0x77e0b164, 0x7aebbf6d, 0x59da9552, 0x54d19b5b, 0x43cc8940, 0x4ec78749, 0x05aedd3e, 0x08a5d337, 0x1fb8c12c, 0x12b3cf25, 0x3182e51a, 0x3c89eb13, 0x2b94f908, 0x269ff701, 0xbd464de6, 0xb04d43ef, 0xa75051f4, 0xaa5b5ffd, 0x896a75c2, 0x84617bcb, 0x937c69d0, 0x9e7767d9, 0xd51e3dae, 0xd81533a7, 0xcf0821bc, 0xc2032fb5, 0xe132058a, 0xec390b83, 0xfb241998, 0xf62f1791, 0xd68d764d, 0xdb867844, 0xcc9b6a5f, 0xc1906456, 0xe2a14e69, 0xefaa4060, 0xf8b7527b, 0xf5bc5c72, 0xbed50605, 0xb3de080c, 0xa4c31a17, 0xa9c8141e, 0x8af93e21, 0x87f23028, 0x90ef2233, 0x9de42c3a, 0x063d96dd, 0x0b3698d4, 0x1c2b8acf, 0x112084c6, 0x3211aef9, 0x3f1aa0f0, 0x2807b2eb, 0x250cbce2, 0x6e65e695, 0x636ee89c, 0x7473fa87, 0x7978f48e, 0x5a49deb1, 0x5742d0b8, 0x405fc2a3, 0x4d54ccaa, 0xdaf741ec, 0xd7fc4fe5, 0xc0e15dfe, 0xcdea53f7, 0xeedb79c8, 0xe3d077c1, 0xf4cd65da, 0xf9c66bd3, 0xb2af31a4, 0xbfa43fad, 0xa8b92db6, 0xa5b223bf, 0x86830980, 0x8b880789, 0x9c951592, 0x919e1b9b, 0x0a47a17c, 0x074caf75, 0x1051bd6e, 0x1d5ab367, 0x3e6b9958, 0x33609751, 0x247d854a, 0x29768b43, 0x621fd134, 0x6f14df3d, 0x7809cd26, 0x7502c32f, 0x5633e910, 0x5b38e719, 0x4c25f502, 0x412efb0b, 0x618c9ad7, 0x6c8794de, 0x7b9a86c5, 0x769188cc, 0x55a0a2f3, 0x58abacfa, 0x4fb6bee1, 0x42bdb0e8, 0x09d4ea9f, 0x04dfe496, 0x13c2f68d, 0x1ec9f884, 0x3df8d2bb, 0x30f3dcb2, 0x27eecea9, 0x2ae5c0a0, 0xb13c7a47, 0xbc37744e, 0xab2a6655, 0xa621685c, 0x85104263, 0x881b4c6a, 0x9f065e71, 0x920d5078, 0xd9640a0f, 0xd46f0406, 0xc372161d, 0xce791814, 0xed48322b, 0xe0433c22, 0xf75e2e39, 0xfa552030, 0xb701ec9a, 0xba0ae293, 0xad17f088, 0xa01cfe81, 0x832dd4be, 0x8e26dab7, 0x993bc8ac, 0x9430c6a5, 0xdf599cd2, 0xd25292db, 0xc54f80c0, 0xc8448ec9, 0xeb75a4f6, 0xe67eaaff, 0xf163b8e4, 0xfc68b6ed, 0x67b10c0a, 0x6aba0203, 0x7da71018, 0x70ac1e11, 0x539d342e, 0x5e963a27, 0x498b283c, 0x44802635, 0x0fe97c42, 0x02e2724b, 0x15ff6050, 0x18f46e59, 0x3bc54466, 0x36ce4a6f, 0x21d35874, 0x2cd8567d, 0x0c7a37a1, 0x017139a8, 0x166c2bb3, 0x1b6725ba, 0x38560f85, 0x355d018c, 0x22401397, 0x2f4b1d9e, 0x642247e9, 0x692949e0, 0x7e345bfb, 0x733f55f2, 0x500e7fcd, 0x5d0571c4, 0x4a1863df, 0x47136dd6, 0xdccad731, 0xd1c1d938, 0xc6dccb23, 0xcbd7c52a, 0xe8e6ef15, 0xe5ede11c, 0xf2f0f307, 0xfffbfd0e, 0xb492a779, 0xb999a970, 0xae84bb6b, 0xa38fb562, 0x80be9f5d, 0x8db59154, 0x9aa8834f, 0x97a38d46];
var U4 = [0x00000000, 0x090d0b0e, 0x121a161c, 0x1b171d12, 0x24342c38, 0x2d392736, 0x362e3a24, 0x3f23312a, 0x48685870, 0x4165537e, 0x5a724e6c, 0x537f4562, 0x6c5c7448, 0x65517f46, 0x7e466254, 0x774b695a, 0x90d0b0e0, 0x99ddbbee, 0x82caa6fc, 0x8bc7adf2, 0xb4e49cd8, 0xbde997d6, 0xa6fe8ac4, 0xaff381ca, 0xd8b8e890, 0xd1b5e39e, 0xcaa2fe8c, 0xc3aff582, 0xfc8cc4a8, 0xf581cfa6, 0xee96d2b4, 0xe79bd9ba, 0x3bbb7bdb, 0x32b670d5, 0x29a16dc7, 0x20ac66c9, 0x1f8f57e3, 0x16825ced, 0x0d9541ff, 0x04984af1, 0x73d323ab, 0x7ade28a5, 0x61c935b7, 0x68c43eb9, 0x57e70f93, 0x5eea049d, 0x45fd198f, 0x4cf01281, 0xab6bcb3b, 0xa266c035, 0xb971dd27, 0xb07cd629, 0x8f5fe703, 0x8652ec0d, 0x9d45f11f, 0x9448fa11, 0xe303934b, 0xea0e9845, 0xf1198557, 0xf8148e59, 0xc737bf73, 0xce3ab47d, 0xd52da96f, 0xdc20a261, 0x766df6ad, 0x7f60fda3, 0x6477e0b1, 0x6d7aebbf, 0x5259da95, 0x5b54d19b, 0x4043cc89, 0x494ec787, 0x3e05aedd, 0x3708a5d3, 0x2c1fb8c1, 0x2512b3cf, 0x1a3182e5, 0x133c89eb, 0x082b94f9, 0x01269ff7, 0xe6bd464d, 0xefb04d43, 0xf4a75051, 0xfdaa5b5f, 0xc2896a75, 0xcb84617b, 0xd0937c69, 0xd99e7767, 0xaed51e3d, 0xa7d81533, 0xbccf0821, 0xb5c2032f, 0x8ae13205, 0x83ec390b, 0x98fb2419, 0x91f62f17, 0x4dd68d76, 0x44db8678, 0x5fcc9b6a, 0x56c19064, 0x69e2a14e, 0x60efaa40, 0x7bf8b752, 0x72f5bc5c, 0x05bed506, 0x0cb3de08, 0x17a4c31a, 0x1ea9c814, 0x218af93e, 0x2887f230, 0x3390ef22, 0x3a9de42c, 0xdd063d96, 0xd40b3698, 0xcf1c2b8a, 0xc6112084, 0xf93211ae, 0xf03f1aa0, 0xeb2807b2, 0xe2250cbc, 0x956e65e6, 0x9c636ee8, 0x877473fa, 0x8e7978f4, 0xb15a49de, 0xb85742d0, 0xa3405fc2, 0xaa4d54cc, 0xecdaf741, 0xe5d7fc4f, 0xfec0e15d, 0xf7cdea53, 0xc8eedb79, 0xc1e3d077, 0xdaf4cd65, 0xd3f9c66b, 0xa4b2af31, 0xadbfa43f, 0xb6a8b92d, 0xbfa5b223, 0x80868309, 0x898b8807, 0x929c9515, 0x9b919e1b, 0x7c0a47a1, 0x75074caf, 0x6e1051bd, 0x671d5ab3, 0x583e6b99, 0x51336097, 0x4a247d85, 0x4329768b, 0x34621fd1, 0x3d6f14df, 0x267809cd, 0x2f7502c3, 0x105633e9, 0x195b38e7, 0x024c25f5, 0x0b412efb, 0xd7618c9a, 0xde6c8794, 0xc57b9a86, 0xcc769188, 0xf355a0a2, 0xfa58abac, 0xe14fb6be, 0xe842bdb0, 0x9f09d4ea, 0x9604dfe4, 0x8d13c2f6, 0x841ec9f8, 0xbb3df8d2, 0xb230f3dc, 0xa927eece, 0xa02ae5c0, 0x47b13c7a, 0x4ebc3774, 0x55ab2a66, 0x5ca62168, 0x63851042, 0x6a881b4c, 0x719f065e, 0x78920d50, 0x0fd9640a, 0x06d46f04, 0x1dc37216, 0x14ce7918, 0x2bed4832, 0x22e0433c, 0x39f75e2e, 0x30fa5520, 0x9ab701ec, 0x93ba0ae2, 0x88ad17f0, 0x81a01cfe, 0xbe832dd4, 0xb78e26da, 0xac993bc8, 0xa59430c6, 0xd2df599c, 0xdbd25292, 0xc0c54f80, 0xc9c8448e, 0xf6eb75a4, 0xffe67eaa, 0xe4f163b8, 0xedfc68b6, 0x0a67b10c, 0x036aba02, 0x187da710, 0x1170ac1e, 0x2e539d34, 0x275e963a, 0x3c498b28, 0x35448026, 0x420fe97c, 0x4b02e272, 0x5015ff60, 0x5918f46e, 0x663bc544, 0x6f36ce4a, 0x7421d358, 0x7d2cd856, 0xa10c7a37, 0xa8017139, 0xb3166c2b, 0xba1b6725, 0x8538560f, 0x8c355d01, 0x97224013, 0x9e2f4b1d, 0xe9642247, 0xe0692949, 0xfb7e345b, 0xf2733f55, 0xcd500e7f, 0xc45d0571, 0xdf4a1863, 0xd647136d, 0x31dccad7, 0x38d1c1d9, 0x23c6dccb, 0x2acbd7c5, 0x15e8e6ef, 0x1ce5ede1, 0x07f2f0f3, 0x0efffbfd, 0x79b492a7, 0x70b999a9, 0x6bae84bb, 0x62a38fb5, 0x5d80be9f, 0x548db591, 0x4f9aa883, 0x4697a38d];
function convertToInt32(bytes) {
var result = [];
for (var i = 0; i < bytes.length; i += 4) {
result.push(
(bytes[i ] << 24) |
(bytes[i + 1] << 16) |
(bytes[i + 2] << 8) |
bytes[i + 3]
);
}
return result;
}
var AES = function(key) {
if (!(this instanceof AES)) {
throw Error('AES must be instanitated with `new`');
}
Object.defineProperty(this, 'key', {
value: coerceArray(key, true)
});
this._prepare();
}
AES.prototype._prepare = function() {
var rounds = numberOfRounds[this.key.length];
if (rounds == null) {
throw new Error('invalid key size (must be 16, 24 or 32 bytes)');
}
// encryption round keys
this._Ke = [];
// decryption round keys
this._Kd = [];
for (var i = 0; i <= rounds; i++) {
this._Ke.push([0, 0, 0, 0]);
this._Kd.push([0, 0, 0, 0]);
}
var roundKeyCount = (rounds + 1) * 4;
var KC = this.key.length / 4;
// convert the key into ints
var tk = convertToInt32(this.key);
// copy values into round key arrays
var index;
for (var i = 0; i < KC; i++) {
index = i >> 2;
this._Ke[index][i % 4] = tk[i];
this._Kd[rounds - index][i % 4] = tk[i];
}
// key expansion (fips-197 section 5.2)
var rconpointer = 0;
var t = KC, tt;
while (t < roundKeyCount) {
tt = tk[KC - 1];
tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^
(S[(tt >> 8) & 0xFF] << 16) ^
(S[ tt & 0xFF] << 8) ^
S[(tt >> 24) & 0xFF] ^
(rcon[rconpointer] << 24));
rconpointer += 1;
// key expansion (for non-256 bit)
if (KC != 8) {
for (var i = 1; i < KC; i++) {
tk[i] ^= tk[i - 1];
}
// key expansion for 256-bit keys is "slightly different" (fips-197)
} else {
for (var i = 1; i < (KC / 2); i++) {
tk[i] ^= tk[i - 1];
}
tt = tk[(KC / 2) - 1];
tk[KC / 2] ^= (S[ tt & 0xFF] ^
(S[(tt >> 8) & 0xFF] << 8) ^
(S[(tt >> 16) & 0xFF] << 16) ^
(S[(tt >> 24) & 0xFF] << 24));
for (var i = (KC / 2) + 1; i < KC; i++) {
tk[i] ^= tk[i - 1];
}
}
// copy values into round key arrays
var i = 0, r, c;
while (i < KC && t < roundKeyCount) {
r = t >> 2;
c = t % 4;
this._Ke[r][c] = tk[i];
this._Kd[rounds - r][c] = tk[i++];
t++;
}
}
// inverse-cipher-ify the decryption round key (fips-197 section 5.3)
for (var r = 1; r < rounds; r++) {
for (var c = 0; c < 4; c++) {
tt = this._Kd[r][c];
this._Kd[r][c] = (U1[(tt >> 24) & 0xFF] ^
U2[(tt >> 16) & 0xFF] ^
U3[(tt >> 8) & 0xFF] ^
U4[ tt & 0xFF]);
}
}
}
AES.prototype.encrypt = function(plaintext) {
if (plaintext.length != 16) {
throw new Error('invalid plaintext size (must be 16 bytes)');
}
var rounds = this._Ke.length - 1;
var a = [0, 0, 0, 0];
// convert plaintext to (ints ^ key)
var t = convertToInt32(plaintext);
for (var i = 0; i < 4; i++) {
t[i] ^= this._Ke[0][i];
}
// apply round transforms
for (var r = 1; r < rounds; r++) {
for (var i = 0; i < 4; i++) {
a[i] = (T1[(t[ i ] >> 24) & 0xff] ^
T2[(t[(i + 1) % 4] >> 16) & 0xff] ^
T3[(t[(i + 2) % 4] >> 8) & 0xff] ^
T4[ t[(i + 3) % 4] & 0xff] ^
this._Ke[r][i]);
}
t = a.slice();
}
// the last round is special
var result = createArray(16), tt;
for (var i = 0; i < 4; i++) {
tt = this._Ke[rounds][i];
result[4 * i ] = (S[(t[ i ] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;
result[4 * i + 1] = (S[(t[(i + 1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;
result[4 * i + 2] = (S[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;
result[4 * i + 3] = (S[ t[(i + 3) % 4] & 0xff] ^ tt ) & 0xff;
}
return result;
}
AES.prototype.decrypt = function(ciphertext) {
if (ciphertext.length != 16) {
throw new Error('invalid ciphertext size (must be 16 bytes)');
}
var rounds = this._Kd.length - 1;
var a = [0, 0, 0, 0];
// convert plaintext to (ints ^ key)
var t = convertToInt32(ciphertext);
for (var i = 0; i < 4; i++) {
t[i] ^= this._Kd[0][i];
}
// apply round transforms
for (var r = 1; r < rounds; r++) {
for (var i = 0; i < 4; i++) {
a[i] = (T5[(t[ i ] >> 24) & 0xff] ^
T6[(t[(i + 3) % 4] >> 16) & 0xff] ^
T7[(t[(i + 2) % 4] >> 8) & 0xff] ^
T8[ t[(i + 1) % 4] & 0xff] ^
this._Kd[r][i]);
}
t = a.slice();
}
// the last round is special
var result = createArray(16), tt;
for (var i = 0; i < 4; i++) {
tt = this._Kd[rounds][i];
result[4 * i ] = (Si[(t[ i ] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;
result[4 * i + 1] = (Si[(t[(i + 3) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;
result[4 * i + 2] = (Si[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;
result[4 * i + 3] = (Si[ t[(i + 1) % 4] & 0xff] ^ tt ) & 0xff;
}
return result;
}
/**
* Mode Of Operation - Electonic Codebook (ECB)
*/
var ModeOfOperationECB = function(key) {
if (!(this instanceof ModeOfOperationECB)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Electronic Code Block";
this.name = "ecb";
this._aes = new AES(key);
}
ModeOfOperationECB.prototype.encrypt = function(plaintext) {
plaintext = coerceArray(plaintext);
if ((plaintext.length % 16) !== 0) {
throw new Error('invalid plaintext size (must be multiple of 16 bytes)');
}
var ciphertext = createArray(plaintext.length);
var block = createArray(16);
for (var i = 0; i < plaintext.length; i += 16) {
copyArray(plaintext, block, 0, i, i + 16);
block = this._aes.encrypt(block);
copyArray(block, ciphertext, i);
}
return ciphertext;
}
ModeOfOperationECB.prototype.decrypt = function(ciphertext) {
ciphertext = coerceArray(ciphertext);
if ((ciphertext.length % 16) !== 0) {
throw new Error('invalid ciphertext size (must be multiple of 16 bytes)');
}
var plaintext = createArray(ciphertext.length);
var block = createArray(16);
for (var i = 0; i < ciphertext.length; i += 16) {
copyArray(ciphertext, block, 0, i, i + 16);
block = this._aes.decrypt(block);
copyArray(block, plaintext, i);
}
return plaintext;
}
/**
* Mode Of Operation - Cipher Block Chaining (CBC)
*/
var ModeOfOperationCBC = function(key, iv) {
if (!(this instanceof ModeOfOperationCBC)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Cipher Block Chaining";
this.name = "cbc";
if (!iv) {
iv = createArray(16);
} else if (iv.length != 16) {
throw new Error('invalid initialation vector size (must be 16 bytes)');
}
this._lastCipherblock = coerceArray(iv, true);
this._aes = new AES(key);
}
ModeOfOperationCBC.prototype.encrypt = function(plaintext) {
plaintext = coerceArray(plaintext);
if ((plaintext.length % 16) !== 0) {
throw new Error('invalid plaintext size (must be multiple of 16 bytes)');
}
var ciphertext = createArray(plaintext.length);
var block = createArray(16);
for (var i = 0; i < plaintext.length; i += 16) {
copyArray(plaintext, block, 0, i, i + 16);
for (var j = 0; j < 16; j++) {
block[j] ^= this._lastCipherblock[j];
}
this._lastCipherblock = this._aes.encrypt(block);
copyArray(this._lastCipherblock, ciphertext, i);
}
return ciphertext;
}
ModeOfOperationCBC.prototype.decrypt = function(ciphertext) {
ciphertext = coerceArray(ciphertext);
if ((ciphertext.length % 16) !== 0) {
throw new Error('invalid ciphertext size (must be multiple of 16 bytes)');
}
var plaintext = createArray(ciphertext.length);
var block = createArray(16);
for (var i = 0; i < ciphertext.length; i += 16) {
copyArray(ciphertext, block, 0, i, i + 16);
block = this._aes.decrypt(block);
for (var j = 0; j < 16; j++) {
plaintext[i + j] = block[j] ^ this._lastCipherblock[j];
}
copyArray(ciphertext, this._lastCipherblock, 0, i, i + 16);
}
return plaintext;
}
/**
* Mode Of Operation - Cipher Feedback (CFB)
*/
var ModeOfOperationCFB = function(key, iv, segmentSize) {
if (!(this instanceof ModeOfOperationCFB)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Cipher Feedback";
this.name = "cfb";
if (!iv) {
iv = createArray(16);
} else if (iv.length != 16) {
throw new Error('invalid initialation vector size (must be 16 size)');
}
if (!segmentSize) { segmentSize = 1; }
this.segmentSize = segmentSize;
this._shiftRegister = coerceArray(iv, true);
this._aes = new AES(key);
}
ModeOfOperationCFB.prototype.encrypt = function(plaintext) {
if ((plaintext.length % this.segmentSize) != 0) {
throw new Error('invalid plaintext size (must be segmentSize bytes)');
}
var encrypted = coerceArray(plaintext, true);
var xorSegment;
for (var i = 0; i < encrypted.length; i += this.segmentSize) {
xorSegment = this._aes.encrypt(this._shiftRegister);
for (var j = 0; j < this.segmentSize; j++) {
encrypted[i + j] ^= xorSegment[j];
}
// Shift the register
copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize);
copyArray(encrypted, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize);
}
return encrypted;
}
ModeOfOperationCFB.prototype.decrypt = function(ciphertext) {
if ((ciphertext.length % this.segmentSize) != 0) {
throw new Error('invalid ciphertext size (must be segmentSize bytes)');
}
var plaintext = coerceArray(ciphertext, true);
var xorSegment;
for (var i = 0; i < plaintext.length; i += this.segmentSize) {
xorSegment = this._aes.encrypt(this._shiftRegister);
for (var j = 0; j < this.segmentSize; j++) {
plaintext[i + j] ^= xorSegment[j];
}
// Shift the register
copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize);
copyArray(ciphertext, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize);
}
return plaintext;
}
/**
* Mode Of Operation - Output Feedback (OFB)
*/
var ModeOfOperationOFB = function(key, iv) {
if (!(this instanceof ModeOfOperationOFB)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Output Feedback";
this.name = "ofb";
if (!iv) {
iv = createArray(16);
} else if (iv.length != 16) {
throw new Error('invalid initialation vector size (must be 16 bytes)');
}
this._lastPrecipher = coerceArray(iv, true);
this._lastPrecipherIndex = 16;
this._aes = new AES(key);
}
ModeOfOperationOFB.prototype.encrypt = function(plaintext) {
var encrypted = coerceArray(plaintext, true);
for (var i = 0; i < encrypted.length; i++) {
if (this._lastPrecipherIndex === 16) {
this._lastPrecipher = this._aes.encrypt(this._lastPrecipher);
this._lastPrecipherIndex = 0;
}
encrypted[i] ^= this._lastPrecipher[this._lastPrecipherIndex++];
}
return encrypted;
}
// Decryption is symetric
ModeOfOperationOFB.prototype.decrypt = ModeOfOperationOFB.prototype.encrypt;
/**
* Counter object for CTR common mode of operation
*/
var Counter = function(initialValue) {
if (!(this instanceof Counter)) {
throw Error('Counter must be instanitated with `new`');
}
// We allow 0, but anything false-ish uses the default 1
if (initialValue !== 0 && !initialValue) { initialValue = 1; }
if (typeof(initialValue) === 'number') {
this._counter = createArray(16);
this.setValue(initialValue);
} else {
this.setBytes(initialValue);
}
}
Counter.prototype.setValue = function(value) {
if (typeof(value) !== 'number' || parseInt(value) != value) {
throw new Error('invalid counter value (must be an integer)');
}
// We cannot safely handle numbers beyond the safe range for integers
if (value > Number.MAX_SAFE_INTEGER) {
throw new Error('integer value out of safe range');
}
for (var index = 15; index >= 0; --index) {
this._counter[index] = value % 256;
value = parseInt(value / 256);
}
}
Counter.prototype.setBytes = function(bytes) {
bytes = coerceArray(bytes, true);
if (bytes.length != 16) {
throw new Error('invalid counter bytes size (must be 16 bytes)');
}
this._counter = bytes;
};
Counter.prototype.increment = function() {
for (var i = 15; i >= 0; i--) {
if (this._counter[i] === 255) {
this._counter[i] = 0;
} else {
this._counter[i]++;
break;
}
}
}
/**
* Mode Of Operation - Counter (CTR)
*/
var ModeOfOperationCTR = function(key, counter) {
if (!(this instanceof ModeOfOperationCTR)) {
throw Error('AES must be instanitated with `new`');
}
this.description = "Counter";
this.name = "ctr";
if (!(counter instanceof Counter)) {
counter = new Counter(counter)
}
this._counter = counter;
this._remainingCounter = null;
this._remainingCounterIndex = 16;
this._aes = new AES(key);
}
ModeOfOperationCTR.prototype.encrypt = function(plaintext) {
var encrypted = coerceArray(plaintext, true);
for (var i = 0; i < encrypted.length; i++) {
if (this._remainingCounterIndex === 16) {
this._remainingCounter = this._aes.encrypt(this._counter._counter);
this._remainingCounterIndex = 0;
this._counter.increment();
}
encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++];
}
return encrypted;
}
// Decryption is symetric
ModeOfOperationCTR.prototype.decrypt = ModeOfOperationCTR.prototype.encrypt;
///////////////////////
// Padding
// See:https://tools.ietf.org/html/rfc2315
function pkcs7pad(data) {
data = coerceArray(data, true);
var padder = 16 - (data.length % 16);
var result = createArray(data.length + padder);
copyArray(data, result);
for (var i = data.length; i < result.length; i++) {
result[i] = padder;
}
return result;
}
function pkcs7strip(data) {
data = coerceArray(data, true);
if (data.length < 16) { throw new Error('PKCS#7 invalid length'); }
var padder = data[data.length - 1];
if (padder > 16) { throw new Error('PKCS#7 padding byte out of range'); }
var length = data.length - padder;
for (var i = 0; i < padder; i++) {
if (data[length + i] !== padder) {
throw new Error('PKCS#7 invalid padding byte');
}
}
var result = createArray(length);
copyArray(data, result, 0, 0, length);
return result;
}
///////////////////////
// Exporting
// The block cipher
var aesjs = {
AES: AES,
Counter: Counter,
ModeOfOperation: {
ecb: ModeOfOperationECB,
cbc: ModeOfOperationCBC,
cfb: ModeOfOperationCFB,
ofb: ModeOfOperationOFB,
ctr: ModeOfOperationCTR
},
utils: {
hex: convertHex,
utf8: convertUtf8
},
padding: {
pkcs7: {
pad: pkcs7pad,
strip: pkcs7strip
}
},
_arrayTest: {
coerceArray: coerceArray,
createArray: createArray,
copyArray: copyArray,
}
};
// node.js
if (typeof exports !== 'undefined') {
module.exports = aesjs
// RequireJS/AMD
// http://www.requirejs.org/docs/api.html
// https://github.com/amdjs/amdjs-api/wiki/AMD
} else if (typeof(define) === 'function' && define.amd) {
define([], function() { return aesjs; });
// Web Browsers
} else {
// If there was an existing library at "aesjs" make sure it's still available
if (root.aesjs) {
aesjs._aesjs = root.aesjs;
}
root.aesjs = aesjs;
}
})(this);
================================================
FILE: src/libs/noble-ed25519-1.7.3.js
================================================
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.nobleEd25519 = {}));
})(this, (function (exports) { 'use strict';
const _nodeResolve_empty = {};
const nodeCrypto = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': _nodeResolve_empty
});
/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
const _0n = BigInt(0);
const _1n = BigInt(1);
const _2n = BigInt(2);
const _8n = BigInt(8);
const CU_O = BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989');
const CURVE = Object.freeze({
a: BigInt(-1),
d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),
P: BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'),
l: CU_O,
n: CU_O,
h: BigInt(8),
Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
});
const POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');
const SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
BigInt('6853475219497561581579357271197624642482790079785650197046958215289687604742');
const SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');
const INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');
const ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');
const D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');
class ExtendedPoint {
constructor(x, y, z, t) {
this.x = x;
this.y = y;
this.z = z;
this.t = t;
}
static fromAffine(p) {
if (!(p instanceof Point)) {
throw new TypeError('ExtendedPoint#fromAffine: expected Point');
}
if (p.equals(Point.ZERO))
return ExtendedPoint.ZERO;
return new ExtendedPoint(p.x, p.y, _1n, mod(p.x * p.y));
}
static toAffineBatch(points) {
const toInv = invertBatch(points.map((p) => p.z));
return points.map((p, i) => p.toAffine(toInv[i]));
}
static normalizeZ(points) {
return this.toAffineBatch(points).map(this.fromAffine);
}
equals(other) {
assertExtPoint(other);
const { x: X1, y: Y1, z: Z1 } = this;
const { x: X2, y: Y2, z: Z2 } = other;
const X1Z2 = mod(X1 * Z2);
const X2Z1 = mod(X2 * Z1);
const Y1Z2 = mod(Y1 * Z2);
const Y2Z1 = mod(Y2 * Z1);
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
}
negate() {
return new ExtendedPoint(mod(-this.x), this.y, this.z, mod(-this.t));
}
double() {
const { x: X1, y: Y1, z: Z1 } = this;
const { a } = CURVE;
const A = mod(X1 * X1);
const B = mod(Y1 * Y1);
const C = mod(_2n * mod(Z1 * Z1));
const D = mod(a * A);
const x1y1 = X1 + Y1;
const E = mod(mod(x1y1 * x1y1) - A - B);
const G = D + B;
const F = G - C;
const H = D - B;
const X3 = mod(E * F);
const Y3 = mod(G * H);
const T3 = mod(E * H);
const Z3 = mod(F * G);
return new ExtendedPoint(X3, Y3, Z3, T3);
}
add(other) {
assertExtPoint(other);
const { x: X1, y: Y1, z: Z1, t: T1 } = this;
const { x: X2, y: Y2, z: Z2, t: T2 } = other;
const A = mod((Y1 - X1) * (Y2 + X2));
const B = mod((Y1 + X1) * (Y2 - X2));
const F = mod(B - A);
if (F === _0n)
return this.double();
const C = mod(Z1 * _2n * T2);
const D = mod(T1 * _2n * Z2);
const E = D + C;
const G = B + A;
const H = D - C;
const X3 = mod(E * F);
const Y3 = mod(G * H);
const T3 = mod(E * H);
const Z3 = mod(F * G);
return new ExtendedPoint(X3, Y3, Z3, T3);
}
subtract(other) {
return this.add(other.negate());
}
precomputeWindow(W) {
const windows = 1 + 256 / W;
const points = [];
let p = this;
let base = p;
for (let window = 0; window < windows; window++) {
base = p;
points.push(base);
for (let i = 1; i < 2 ** (W - 1); i++) {
base = base.add(p);
points.push(base);
}
p = base.double();
}
return points;
}
wNAF(n, affinePoint) {
if (!affinePoint && this.equals(ExtendedPoint.BASE))
affinePoint = Point.BASE;
const W = (affinePoint && affinePoint._WINDOW_SIZE) || 1;
if (256 % W) {
throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2');
}
let precomputes = affinePoint && pointPrecomputes.get(affinePoint);
if (!precomputes) {
precomputes = this.precomputeWindow(W);
if (affinePoint && W !== 1) {
precomputes = ExtendedPoint.normalizeZ(precomputes);
pointPrecomputes.set(affinePoint, precomputes);
}
}
let p = ExtendedPoint.ZERO;
let f = ExtendedPoint.BASE;
const windows = 1 + 256 / W;
const windowSize = 2 ** (W - 1);
const mask = BigInt(2 ** W - 1);
const maxNumber = 2 ** W;
const shiftBy = BigInt(W);
for (let window = 0; window < windows; window++) {
const offset = window * windowSize;
let wbits = Number(n & mask);
n >>= shiftBy;
if (wbits > windowSize) {
wbits -= maxNumber;
n += _1n;
}
const offset1 = offset;
const offset2 = offset + Math.abs(wbits) - 1;
const cond1 = window % 2 !== 0;
const cond2 = wbits < 0;
if (wbits === 0) {
f = f.add(constTimeNegate(cond1, precomputes[offset1]));
}
else {
p = p.add(constTimeNegate(cond2, precomputes[offset2]));
}
}
return ExtendedPoint.normalizeZ([p, f])[0];
}
multiply(scalar, affinePoint) {
return this.wNAF(normalizeScalar(scalar, CURVE.l), affinePoint);
}
multiplyUnsafe(scalar) {
let n = normalizeScalar(scalar, CURVE.l, false);
const G = ExtendedPoint.BASE;
const P0 = ExtendedPoint.ZERO;
if (n === _0n)
return P0;
if (this.equals(P0) || n === _1n)
return this;
if (this.equals(G))
return this.wNAF(n);
let p = P0;
let d = this;
while (n > _0n) {
if (n & _1n)
p = p.add(d);
d = d.double();
n >>= _1n;
}
return p;
}
isSmallOrder() {
return this.multiplyUnsafe(CURVE.h).equals(ExtendedPoint.ZERO);
}
isTorsionFree() {
let p = this.multiplyUnsafe(CURVE.l / _2n).double();
if (CURVE.l % _2n)
p = p.add(this);
return p.equals(ExtendedPoint.ZERO);
}
toAffine(invZ) {
const { x, y, z } = this;
const is0 = this.equals(ExtendedPoint.ZERO);
if (invZ == null)
invZ = is0 ? _8n : invert(z);
const ax = mod(x * invZ);
const ay = mod(y * invZ);
const zz = mod(z * invZ);
if (is0)
return Point.ZERO;
if (zz !== _1n)
throw new Error('invZ was invalid');
return new Point(ax, ay);
}
fromRistrettoBytes() {
legacyRist();
}
toRistrettoBytes() {
legacyRist();
}
fromRistrettoHash() {
legacyRist();
}
}
ExtendedPoint.BASE = new ExtendedPoint(CURVE.Gx, CURVE.Gy, _1n, mod(CURVE.Gx * CURVE.Gy));
ExtendedPoint.ZERO = new ExtendedPoint(_0n, _1n, _1n, _0n);
function constTimeNegate(condition, item) {
const neg = item.negate();
return condition ? neg : item;
}
function assertExtPoint(other) {
if (!(other instanceof ExtendedPoint))
throw new TypeError('ExtendedPoint expected');
}
function assertRstPoint(other) {
if (!(other instanceof RistrettoPoint))
throw new TypeError('RistrettoPoint expected');
}
function legacyRist() {
throw new Error('Legacy method: switch to RistrettoPoint');
}
class RistrettoPoint {
constructor(ep) {
this.ep = ep;
}
static calcElligatorRistrettoMap(r0) {
const { d } = CURVE;
const r = mod(SQRT_M1 * r0 * r0);
const Ns = mod((r + _1n) * ONE_MINUS_D_SQ);
let c = BigInt(-1);
const D = mod((c - d * r) * mod(r + d));
let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
let s_ = mod(s * r0);
if (!edIsNegative(s_))
s_ = mod(-s_);
if (!Ns_D_is_sq)
s = s_;
if (!Ns_D_is_sq)
c = r;
const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D);
const s2 = s * s;
const W0 = mod((s + s) * D);
const W1 = mod(Nt * SQRT_AD_MINUS_ONE);
const W2 = mod(_1n - s2);
const W3 = mod(_1n + s2);
return new ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));
}
static hashToCurve(hex) {
hex = ensureBytes(hex, 64);
const r1 = bytes255ToNumberLE(hex.slice(0, 32));
const R1 = this.calcElligatorRistrettoMap(r1);
const r2 = bytes255ToNumberLE(hex.slice(32, 64));
const R2 = this.calcElligatorRistrettoMap(r2);
return new RistrettoPoint(R1.add(R2));
}
static fromHex(hex) {
hex = ensureBytes(hex, 32);
const { a, d } = CURVE;
const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';
const s = bytes255ToNumberLE(hex);
if (!equalBytes(numberTo32BytesLE(s), hex) || edIsNegative(s))
throw new Error(emsg);
const s2 = mod(s * s);
const u1 = mod(_1n + a * s2);
const u2 = mod(_1n - a * s2);
const u1_2 = mod(u1 * u1);
const u2_2 = mod(u2 * u2);
const v = mod(a * d * u1_2 - u2_2);
const { isValid, value: I } = invertSqrt(mod(v * u2_2));
const Dx = mod(I * u2);
const Dy = mod(I * Dx * v);
let x = mod((s + s) * Dx);
if (edIsNegative(x))
x = mod(-x);
const y = mod(u1 * Dy);
const t = mod(x * y);
if (!isValid || edIsNegative(t) || y === _0n)
throw new Error(emsg);
return new RistrettoPoint(new ExtendedPoint(x, y, _1n, t));
}
toRawBytes() {
let { x, y, z, t } = this.ep;
const u1 = mod(mod(z + y) * mod(z - y));
const u2 = mod(x * y);
const u2sq = mod(u2 * u2);
const { value: invsqrt } = invertSqrt(mod(u1 * u2sq));
const D1 = mod(invsqrt * u1);
const D2 = mod(invsqrt * u2);
const zInv = mod(D1 * D2 * t);
let D;
if (edIsNegative(t * zInv)) {
let _x = mod(y * SQRT_M1);
let _y = mod(x * SQRT_M1);
x = _x;
y = _y;
D = mod(D1 * INVSQRT_A_MINUS_D);
}
else {
D = D2;
}
if (edIsNegative(x * zInv))
y = mod(-y);
let s = mod((z - y) * D);
if (edIsNegative(s))
s = mod(-s);
return numberTo32BytesLE(s);
}
toHex() {
return bytesToHex(this.toRawBytes());
}
toString() {
return this.toHex();
}
equals(other) {
assertRstPoint(other);
const a = this.ep;
const b = other.ep;
const one = mod(a.x * b.y) === mod(a.y * b.x);
const two = mod(a.y * b.y) === mod(a.x * b.x);
return one || two;
}
add(other) {
assertRstPoint(other);
return new RistrettoPoint(this.ep.add(other.ep));
}
subtract(other) {
assertRstPoint(other);
return new RistrettoPoint(this.ep.subtract(other.ep));
}
multiply(scalar) {
return new RistrettoPoint(this.ep.multiply(scalar));
}
multiplyUnsafe(scalar) {
return new RistrettoPoint(this.ep.multiplyUnsafe(scalar));
}
}
RistrettoPoint.BASE = new RistrettoPoint(ExtendedPoint.BASE);
RistrettoPoint.ZERO = new RistrettoPoint(ExtendedPoint.ZERO);
const pointPrecomputes = new WeakMap();
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
_setWindowSize(windowSize) {
this._WINDOW_SIZE = windowSize;
pointPrecomputes.delete(this);
}
static fromHex(hex, strict = true) {
const { d, P } = CURVE;
hex = ensureBytes(hex, 32);
const normed = hex.slice();
normed[31] = hex[31] & ~0x80;
const y = bytesToNumberLE(normed);
if (strict && y >= P)
throw new Error('Expected 0 < hex < P');
if (!strict && y >= POW_2_256)
throw new Error('Expected 0 < hex < 2**256');
const y2 = mod(y * y);
const u = mod(y2 - _1n);
const v = mod(d * y2 + _1n);
let { isValid, value: x } = uvRatio(u, v);
if (!isValid)
throw new Error('Point.fromHex: invalid y coordinate');
const isXOdd = (x & _1n) === _1n;
const isLastByteOdd = (hex[31] & 0x80) !== 0;
if (isLastByteOdd !== isXOdd) {
x = mod(-x);
}
return new Point(x, y);
}
static async fromPrivateKey(privateKey) {
return (await getExtendedPublicKey(privateKey)).point;
}
toRawBytes() {
const bytes = numberTo32BytesLE(this.y);
bytes[31] |= this.x & _1n ? 0x80 : 0;
return bytes;
}
toHex() {
return bytesToHex(this.toRawBytes());
}
toX25519() {
const { y } = this;
const u = mod((_1n + y) * invert(_1n - y));
return numberTo32BytesLE(u);
}
isTorsionFree() {
return ExtendedPoint.fromAffine(this).isTorsionFree();
}
equals(other) {
return this.x === other.x && this.y === other.y;
}
negate() {
return new Point(mod(-this.x), this.y);
}
add(other) {
return ExtendedPoint.fromAffine(this).add(ExtendedPoint.fromAffine(other)).toAffine();
}
subtract(other) {
return this.add(other.negate());
}
multiply(scalar) {
return ExtendedPoint.fromAffine(this).multiply(scalar, this).toAffine();
}
}
Point.BASE = new Point(CURVE.Gx, CURVE.Gy);
Point.ZERO = new Point(_0n, _1n);
class Signature {
constructor(r, s) {
this.r = r;
this.s = s;
this.assertValidity();
}
static fromHex(hex) {
const bytes = ensureBytes(hex, 64);
const r = Point.fromHex(bytes.slice(0, 32), false);
const s = bytesToNumberLE(bytes.slice(32, 64));
return new Signature(r, s);
}
assertValidity() {
const { r, s } = this;
if (!(r instanceof Point))
throw new Error('Expected Point instance');
normalizeScalar(s, CURVE.l, false);
return this;
}
toRawBytes() {
const u8 = new Uint8Array(64);
u8.set(this.r.toRawBytes());
u8.set(numberTo32BytesLE(this.s), 32);
return u8;
}
toHex() {
return bytesToHex(this.toRawBytes());
}
}
function concatBytes(...arrays) {
if (!arrays.every((a) => a instanceof Uint8Array))
throw new Error('Expected Uint8Array list');
if (arrays.length === 1)
return arrays[0];
const length = arrays.reduce((a, arr) => a + arr.length, 0);
const result = new Uint8Array(length);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const arr = arrays[i];
result.set(arr, pad);
pad += arr.length;
}
return result;
}
const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
function bytesToHex(uint8a) {
if (!(uint8a instanceof Uint8Array))
throw new Error('Uint8Array expected');
let hex = '';
for (let i = 0; i < uint8a.length; i++) {
hex += hexes[uint8a[i]];
}
return hex;
}
function hexToBytes(hex) {
if (typeof hex !== 'string') {
throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
}
if (hex.length % 2)
throw new Error('hexToBytes: received invalid unpadded hex');
const array = new Uint8Array(hex.length / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
const hexByte = hex.slice(j, j + 2);
const byte = Number.parseInt(hexByte, 16);
if (Number.isNaN(byte) || byte < 0)
throw new Error('Invalid byte sequence');
array[i] = byte;
}
return array;
}
function numberTo32BytesBE(num) {
const length = 32;
const hex = num.toString(16).padStart(length * 2, '0');
return hexToBytes(hex);
}
function numberTo32BytesLE(num) {
return numberTo32BytesBE(num).reverse();
}
function edIsNegative(num) {
return (mod(num) & _1n) === _1n;
}
function bytesToNumberLE(uint8a) {
if (!(uint8a instanceof Uint8Array))
throw new Error('Expected Uint8Array');
return BigInt('0x' + bytesToHex(Uint8Array.from(uint8a).reverse()));
}
const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
function bytes255ToNumberLE(bytes) {
return mod(bytesToNumberLE(bytes) & MAX_255B);
}
function mod(a, b = CURVE.P) {
const res = a % b;
return res >= _0n ? res : b + res;
}
function invert(number, modulo = CURVE.P) {
if (number === _0n || modulo <= _0n) {
throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
}
let a = mod(number, modulo);
let b = modulo;
let x = _0n, u = _1n;
while (a !== _0n) {
const q = b / a;
const r = b % a;
const m = x - u * q;
b = a, a = r, x = u, u = m;
}
const gcd = b;
if (gcd !== _1n)
throw new Error('invert: does not exist');
return mod(x, modulo);
}
function invertBatch(nums, p = CURVE.P) {
const tmp = new Array(nums.length);
const lastMultiplied = nums.reduce((acc, num, i) => {
if (num === _0n)
return acc;
tmp[i] = acc;
return mod(acc * num, p);
}, _1n);
const inverted = invert(lastMultiplied, p);
nums.reduceRight((acc, num, i) => {
if (num === _0n)
return acc;
tmp[i] = mod(acc * tmp[i], p);
return mod(acc * num, p);
}, inverted);
return tmp;
}
function pow2(x, power) {
const { P } = CURVE;
let res = x;
while (power-- > _0n) {
res *= res;
res %= P;
}
return res;
}
function pow_2_252_3(x) {
const { P } = CURVE;
const _5n = BigInt(5);
const _10n = BigInt(10);
const _20n = BigInt(20);
const _40n = BigInt(40);
const _80n = BigInt(80);
const x2 = (x * x) % P;
const b2 = (x2 * x) % P;
const b4 = (pow2(b2, _2n) * b2) % P;
const b5 = (pow2(b4, _1n) * x) % P;
const b10 = (pow2(b5, _5n) * b5) % P;
const b20 = (pow2(b10, _10n) * b10) % P;
const b40 = (pow2(b20, _20n) * b20) % P;
const b80 = (pow2(b40, _40n) * b40) % P;
const b160 = (pow2(b80, _80n) * b80) % P;
const b240 = (pow2(b160, _80n) * b80) % P;
const b250 = (pow2(b240, _10n) * b10) % P;
const pow_p_5_8 = (pow2(b250, _2n) * x) % P;
return { pow_p_5_8, b2 };
}
function uvRatio(u, v) {
const v3 = mod(v * v * v);
const v7 = mod(v3 * v3 * v);
const pow = pow_2_252_3(u * v7).pow_p_5_8;
let x = mod(u * v3 * pow);
const vx2 = mod(v * x * x);
const root1 = x;
const root2 = mod(x * SQRT_M1);
const useRoot1 = vx2 === u;
const useRoot2 = vx2 === mod(-u);
const noRoot = vx2 === mod(-u * SQRT_M1);
if (useRoot1)
x = root1;
if (useRoot2 || noRoot)
x = root2;
if (edIsNegative(x))
x = mod(-x);
return { isValid: useRoot1 || useRoot2, value: x };
}
function invertSqrt(number) {
return uvRatio(_1n, number);
}
function modlLE(hash) {
return mod(bytesToNumberLE(hash), CURVE.l);
}
function equalBytes(b1, b2) {
if (b1.length !== b2.length) {
return false;
}
for (let i = 0; i < b1.length; i++) {
if (b1[i] !== b2[i]) {
return false;
}
}
return true;
}
function ensureBytes(hex, expectedLength) {
const bytes = hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex);
if (typeof expectedLength === 'number' && bytes.length !== expectedLength)
throw new Error(`Expected ${expectedLength} bytes`);
return bytes;
}
function normalizeScalar(num, max, strict = true) {
if (!max)
throw new TypeError('Specify max value');
if (typeof num === 'number' && Number.isSafeInteger(num))
num = BigInt(num);
if (typeof num === 'bigint' && num < max) {
if (strict) {
if (_0n < num)
return num;
}
else {
if (_0n <= num)
return num;
}
}
throw new TypeError('Expected valid scalar: 0 < scalar < max');
}
function adjustBytes25519(bytes) {
bytes[0] &= 248;
bytes[31] &= 127;
bytes[31] |= 64;
return bytes;
}
function decodeScalar25519(n) {
return bytesToNumberLE(adjustBytes25519(ensureBytes(n, 32)));
}
function checkPrivateKey(key) {
key =
typeof key === 'bigint' || typeof key === 'number'
? numberTo32BytesBE(normalizeScalar(key, POW_2_256))
: ensureBytes(key);
if (key.length !== 32)
throw new Error(`Expected 32 bytes`);
return key;
}
function getKeyFromHash(hashed) {
const head = adjustBytes25519(hashed.slice(0, 32));
const prefix = hashed.slice(32, 64);
const scalar = modlLE(head);
const point = Point.BASE.multiply(scalar);
const pointBytes = point.toRawBytes();
return { head, prefix, scalar, point, pointBytes };
}
let _sha512Sync;
function sha512s(...m) {
if (typeof _sha512Sync !== 'function')
throw new Error('utils.sha512Sync must be set to use sync methods');
return _sha512Sync(...m);
}
async function getExtendedPublicKey(key) {
return getKeyFromHash(await utils.sha512(checkPrivateKey(key)));
}
function getExtendedPublicKeySync(key) {
return getKeyFromHash(sha512s(checkPrivateKey(key)));
}
async function getPublicKey(privateKey) {
return (await getExtendedPublicKey(privateKey)).pointBytes;
}
function getPublicKeySync(privateKey) {
return getExtendedPublicKeySync(privateKey).pointBytes;
}
async function sign(message, privateKey) {
message = ensureBytes(message);
const { prefix, scalar, pointBytes } = await getExtendedPublicKey(privateKey);
const r = modlLE(await utils.sha512(prefix, message));
const R = Point.BASE.multiply(r);
const k = modlLE(await utils.sha512(R.toRawBytes(), pointBytes, message));
const s = mod(r + k * scalar, CURVE.l);
return new Signature(R, s).toRawBytes();
}
function signSync(message, privateKey) {
message = ensureBytes(message);
const { prefix, scalar, pointBytes } = getExtendedPublicKeySync(privateKey);
const r = modlLE(sha512s(prefix, message));
const R = Point.BASE.multiply(r);
const k = modlLE(sha512s(R.toRawBytes(), pointBytes, message));
const s = mod(r + k * scalar, CURVE.l);
return new Signature(R, s).toRawBytes();
}
function prepareVerification(sig, message, publicKey) {
message = ensureBytes(message);
if (!(publicKey instanceof Point))
publicKey = Point.fromHex(publicKey, false);
const { r, s } = sig instanceof Signature ? sig.assertValidity() : Signature.fromHex(sig);
const SB = ExtendedPoint.BASE.multiplyUnsafe(s);
return { r, s, SB, pub: publicKey, msg: message };
}
function finishVerification(publicKey, r, SB, hashed) {
const k = modlLE(hashed);
const kA = ExtendedPoint.fromAffine(publicKey).multiplyUnsafe(k);
const RkA = ExtendedPoint.fromAffine(r).add(kA);
return RkA.subtract(SB).multiplyUnsafe(CURVE.h).equals(ExtendedPoint.ZERO);
}
async function verify(sig, message, publicKey) {
const { r, SB, msg, pub } = prepareVerification(sig, message, publicKey);
const hashed = await utils.sha512(r.toRawBytes(), pub.toRawBytes(), msg);
return finishVerification(pub, r, SB, hashed);
}
function verifySync(sig, message, publicKey) {
const { r, SB, msg, pub } = prepareVerification(sig, message, publicKey);
const hashed = sha512s(r.toRawBytes(), pub.toRawBytes(), msg);
return finishVerification(pub, r, SB, hashed);
}
const sync = {
getExtendedPublicKey: getExtendedPublicKeySync,
getPublicKey: getPublicKeySync,
sign: signSync,
verify: verifySync,
};
async function getSharedSecret(privateKey, publicKey) {
const { head } = await getExtendedPublicKey(privateKey);
const u = Point.fromHex(publicKey).toX25519();
return curve25519.scalarMult(head, u);
}
Point.BASE._setWindowSize(8);
function cswap(swap, x_2, x_3) {
const dummy = mod(swap * (x_2 - x_3));
x_2 = mod(x_2 - dummy);
x_3 = mod(x_3 + dummy);
return [x_2, x_3];
}
function montgomeryLadder(pointU, scalar) {
const { P } = CURVE;
const u = normalizeScalar(pointU, P);
const k = normalizeScalar(scalar, P);
const a24 = BigInt(121665);
const x_1 = u;
let x_2 = _1n;
let z_2 = _0n;
let x_3 = u;
let z_3 = _1n;
let swap = _0n;
let sw;
for (let t = BigInt(255 - 1); t >= _0n; t--) {
const k_t = (k >> t) & _1n;
swap ^= k_t;
sw = cswap(swap, x_2, x_3);
x_2 = sw[0];
x_3 = sw[1];
sw = cswap(swap, z_2, z_3);
z_2 = sw[0];
z_3 = sw[1];
swap = k_t;
const A = x_2 + z_2;
const AA = mod(A * A);
const B = x_2 - z_2;
const BB = mod(B * B);
const E = AA - BB;
const C = x_3 + z_3;
const D = x_3 - z_3;
const DA = mod(D * A);
const CB = mod(C * B);
const dacb = DA + CB;
const da_cb = DA - CB;
x_3 = mod(dacb * dacb);
z_3 = mod(x_1 * mod(da_cb * da_cb));
x_2 = mod(AA * BB);
z_2 = mod(E * (AA + mod(a24 * E)));
}
sw = cswap(swap, x_2, x_3);
x_2 = sw[0];
x_3 = sw[1];
sw = cswap(swap, z_2, z_3);
z_2 = sw[0];
z_3 = sw[1];
const { pow_p_5_8, b2 } = pow_2_252_3(z_2);
const xp2 = mod(pow2(pow_p_5_8, BigInt(3)) * b2);
return mod(x_2 * xp2);
}
function encodeUCoordinate(u) {
return numberTo32BytesLE(mod(u, CURVE.P));
}
function decodeUCoordinate(uEnc) {
const u = ensureBytes(uEnc, 32);
u[31] &= 127;
return bytesToNumberLE(u);
}
const curve25519 = {
BASE_POINT_U: '0900000000000000000000000000000000000000000000000000000000000000',
scalarMult(privateKey, publicKey) {
const u = decodeUCoordinate(publicKey);
const p = decodeScalar25519(privateKey);
const pu = montgomeryLadder(u, p);
if (pu === _0n)
throw new Error('Invalid private or public key received');
return encodeUCoordinate(pu);
},
scalarMultBase(privateKey) {
return curve25519.scalarMult(privateKey, curve25519.BASE_POINT_U);
},
};
const crypto = {
node: nodeCrypto,
web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined,
};
const utils = {
bytesToHex,
hexToBytes,
concatBytes,
getExtendedPublicKey,
mod,
invert,
TORSION_SUBGROUP: [
'0100000000000000000000000000000000000000000000000000000000000000',
'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',
'0000000000000000000000000000000000000000000000000000000000000080',
'26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',
'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',
'26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',
'0000000000000000000000000000000000000000000000000000000000000000',
'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',
],
hashToPrivateScalar: (hash) => {
hash = ensureBytes(hash);
if (hash.length < 40 || hash.length > 1024)
throw new Error('Expected 40-1024 bytes of private key as per FIPS 186');
return mod(bytesToNumberLE(hash), CURVE.l - _1n) + _1n;
},
randomBytes: (bytesLength = 32) => {
if (crypto.web) {
return crypto.web.getRandomValues(new Uint8Array(bytesLength));
}
else if (crypto.node) {
const { randomBytes } = crypto.node;
return new Uint8Array(randomBytes(bytesLength).buffer);
}
else {
throw new Error("The environment doesn't have randomBytes function");
}
},
randomPrivateKey: () => {
return utils.randomBytes(32);
},
sha512: async (...messages) => {
const message = concatBytes(...messages);
if (crypto.web) {
const buffer = await crypto.web.subtle.digest('SHA-512', message.buffer);
return new Uint8Array(buffer);
}
else if (crypto.node) {
return Uint8Array.from(crypto.node.createHash('sha512').update(message).digest());
}
else {
throw new Error("The environment doesn't have sha512 function");
}
},
precompute(windowSize = 8, point = Point.BASE) {
const cached = point.equals(Point.BASE) ? point : new Point(point.x, point.y);
cached._setWindowSize(windowSize);
cached.multiply(_2n);
return cached;
},
sha512Sync: undefined,
};
Object.defineProperties(utils, {
sha512Sync: {
configurable: false,
get() {
return _sha512Sync;
},
set(val) {
if (!_sha512Sync)
_sha512Sync = val;
},
},
});
exports.CURVE = CURVE;
exports.ExtendedPoint = ExtendedPoint;
exports.Point = Point;
exports.RistrettoPoint = RistrettoPoint;
exports.Signature = Signature;
exports.curve25519 = curve25519;
exports.getPublicKey = getPublicKey;
exports.getSharedSecret = getSharedSecret;
exports.sign = sign;
exports.sync = sync;
exports.utils = utils;
exports.verify = verify;
Object.defineProperty(exports, '__esModule', { value: true });
}));
| | | | | | | | | | | |