From cec429c691634bec9db781437198bdbf78817106 Mon Sep 17 00:00:00 2001 From: Nicola Benaglia Date: Sat, 24 May 2025 11:53:08 +0200 Subject: [PATCH] Create encryption folder and move files --- src/App.tsx | 4 +- src/Wallets.tsx | 6 +- src/{ => background}/background-cases.ts | 16 +- src/{ => background}/background.ts | 41 +- src/components/Apps/AppPublish.tsx | 2 +- src/components/Apps/AppRating.tsx | 2 +- src/components/Apps/AppsDevModeHome.tsx | 2 +- src/components/Apps/AppsPrivate.tsx | 2 +- src/components/Chat/AdminSpaceInner.tsx | 4 +- .../Chat/AnnouncementDiscussion.tsx | 2 +- src/components/Chat/ChatDirect.tsx | 2 +- src/components/Chat/ChatGroup.tsx | 2 +- src/components/Chat/CreateCommonSecret.tsx | 4 +- src/components/Chat/GroupAnnouncements.tsx | 4 +- src/components/Chat/GroupAvatar.tsx | 2 +- src/components/Embeds/PollEmbed.tsx | 2 +- src/components/GlobalActions/JoinGroup.tsx | 2 +- src/components/Group/AddGroup.tsx | 2 +- src/components/Group/AddGroupList.tsx | 2 +- src/components/Group/Forum/NewThread.tsx | 2 +- src/components/Group/Group.tsx | 2 +- src/components/Group/InviteMember.tsx | 2 +- src/components/Group/ListOfBans.tsx | 2 +- .../Group/ListOfGroupPromotions.tsx | 2 +- src/components/Group/ListOfInvites.tsx | 2 +- src/components/Group/ListOfJoinRequests.tsx | 2 +- src/components/Group/ListOfMembers.tsx | 2 +- src/components/Group/ManageMembers.tsx | 2 +- src/components/Group/Settings.tsx | 4 +- src/components/Group/UserListOfInvites.tsx | 2 +- src/components/MainAvatar.tsx | 2 +- src/components/Minting/Minting.tsx | 2 +- src/components/NotAuthenticated.tsx | 2 +- src/components/QortPayment.tsx | 2 +- src/components/RegisterName.tsx | 2 +- src/components/Save/Save.tsx | 4 +- src/components/UserLookup.tsx/UserLookup.tsx | 5 +- src/deps/AltcoinHDWallet.ts | 864 ----------------- src/encryption/AltcoinHDWallet.ts | 881 ++++++++++++++++++ src/{deps => encryption}/Base58.ts | 0 .../bcryptworker.worker.js | 0 .../bcryptworkerwasm.worker.js | 0 src/{deps => encryption}/broken-ripemd160.ts | 0 src/{deps => encryption}/ecbn.ts | 0 src/{deps => encryption}/ed2curve.ts | 0 .../encryption.ts | 12 +- src/{deps => encryption}/kdf.ts | 0 src/{deps => encryption}/nacl-fast.ts | 0 src/{deps => encryption}/ripemd160.ts | 0 src/hooks/useHandlePaymentNotification.tsx | 5 +- src/hooks/useHandlePrivateApps.tsx | 4 +- src/hooks/useQortalGetSaveSettings.tsx | 2 +- src/qdn/encryption/group-encryption.ts | 6 +- src/qdn/publish/pubish.ts | 90 +- src/qortalRequests/get.ts | 13 +- src/{ => qortalRequests}/qortalRequests.ts | 10 +- src/transactions/ChatBase.ts | 4 +- src/transactions/ChatTransaction.ts | 4 +- .../RemoveRewardShareTransaction.ts | 2 +- src/transactions/RewardShareTransaction.ts | 4 +- src/transactions/TransactionBase.ts | 4 +- src/transactions/signChat.ts | 2 +- src/transactions/signTradeBotTransaction.ts | 4 +- src/utils/decryptChatMessage.ts | 6 +- src/utils/decryptWallet.ts | 4 +- src/utils/generateWallet/generateWallet.ts | 2 +- src/utils/generateWallet/phrase-wallet.ts | 346 ++++--- .../generateWallet/publicKeyToAddress.ts | 6 +- src/utils/generateWallet/storeWallet.ts | 4 +- src/utils/validateAddress.ts | 2 +- 70 files changed, 1272 insertions(+), 1155 deletions(-) rename src/{ => background}/background-cases.ts (99%) rename src/{ => background}/background.ts (98%) delete mode 100644 src/deps/AltcoinHDWallet.ts create mode 100644 src/encryption/AltcoinHDWallet.ts rename src/{deps => encryption}/Base58.ts (100%) rename src/{deps => encryption}/bcryptworker.worker.js (100%) rename src/{deps => encryption}/bcryptworkerwasm.worker.js (100%) rename src/{deps => encryption}/broken-ripemd160.ts (100%) rename src/{deps => encryption}/ecbn.ts (100%) rename src/{deps => encryption}/ed2curve.ts (100%) rename src/{backgroundFunctions => encryption}/encryption.ts (96%) rename src/{deps => encryption}/kdf.ts (100%) rename src/{deps => encryption}/nacl-fast.ts (100%) rename src/{deps => encryption}/ripemd160.ts (100%) rename src/{ => qortalRequests}/qortalRequests.ts (99%) diff --git a/src/App.tsx b/src/App.tsx index 777454d..fe721a7 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -76,7 +76,7 @@ import { groupApi, groupApiSocket, storeWallets, -} from './background'; +} from './background/background.ts'; import { executeEvent, subscribeToEvent, @@ -124,7 +124,7 @@ import { Tutorials } from './components/Tutorials/Tutorials'; import { useHandleTutorials } from './hooks/useHandleTutorials.tsx'; import { useHandleUserInfo } from './hooks/useHandleUserInfo.tsx'; import { Minting } from './components/Minting/Minting'; -import { isRunningGateway } from './qortalRequests'; +import { isRunningGateway } from './qortalRequests/qortalRequests.ts'; import { QMailStatus } from './components/QMailStatus'; import { GlobalActions } from './components/GlobalActions/GlobalActions'; import { useBlockedAddresses } from './hooks/useBlockUsers.tsx'; diff --git a/src/Wallets.tsx b/src/Wallets.tsx index ef259fc..e6e4906 100644 --- a/src/Wallets.tsx +++ b/src/Wallets.tsx @@ -23,7 +23,11 @@ import { useDropzone } from 'react-dropzone'; import EditIcon from '@mui/icons-material/Edit'; import { Label } from './components/Group/AddGroup'; import { Spacer } from './common/Spacer'; -import { getWallets, storeWallets, walletVersion } from './background'; +import { + getWallets, + storeWallets, + walletVersion, +} from './background/background.ts'; import { useModal } from './common/useModal'; import PhraseWallet from './utils/generateWallet/phrase-wallet'; import { decryptStoredWalletFromSeedPhrase } from './utils/decryptWallet'; diff --git a/src/background-cases.ts b/src/background/background-cases.ts similarity index 99% rename from src/background-cases.ts rename to src/background/background-cases.ts index 29dab32..f6c0158 100644 --- a/src/background-cases.ts +++ b/src/background/background-cases.ts @@ -55,20 +55,20 @@ import { setGroupData, updateThreadActivity, walletVersion, -} from './background'; +} from '../background/background.ts'; import { decryptGroupEncryption, encryptAndPublishSymmetricKeyGroupChat, encryptAndPublishSymmetricKeyGroupChatForAdmins, publishGroupEncryptedResource, publishOnQDN, -} from './backgroundFunctions/encryption'; -import { PUBLIC_NOTIFICATION_CODE_FIRST_SECRET_KEY } from './constants/constants'; -import Base58 from './deps/Base58'; -import { encryptSingle } from './qdn/encryption/group-encryption'; -import { _createPoll, _voteOnPoll } from './qortalRequests/get'; -import { createTransaction } from './transactions/transactions'; -import { getData, storeData } from './utils/chromeStorage'; +} from '../encryption/encryption.ts'; +import { PUBLIC_NOTIFICATION_CODE_FIRST_SECRET_KEY } from '../constants/constants'; +import Base58 from '../encryption/Base58.ts'; +import { encryptSingle } from '../qdn/encryption/group-encryption'; +import { _createPoll, _voteOnPoll } from '../qortalRequests/get'; +import { createTransaction } from '../transactions/transactions'; +import { getData, storeData } from '../utils/chromeStorage'; export function versionCase(request, event) { event.source.postMessage( diff --git a/src/background.ts b/src/background/background.ts similarity index 98% rename from src/background.ts rename to src/background/background.ts index cbc96b3..ec55028 100644 --- a/src/background.ts +++ b/src/background/background.ts @@ -1,27 +1,27 @@ // @ts-nocheck -import './qortalRequests'; +import '../qortalRequests/qortalRequests'; import { isArray } from 'lodash'; -import { uint8ArrayToObject } from './backgroundFunctions/encryption'; -import Base58 from './deps/Base58'; +import { uint8ArrayToObject } from '../encryption/encryption.ts'; +import Base58 from '../encryption/Base58'; import axios from 'axios'; import { base64ToUint8Array, decryptSingle, encryptSingle, objectToBase64, -} from './qdn/encryption/group-encryption'; -import ChatComputePowWorker from './chatComputePow.worker.js?worker'; -import { reusableGet } from './qdn/publish/pubish'; -import { signChat } from './transactions/signChat'; -import { createTransaction } from './transactions/transactions'; -import { decryptChatMessage } from './utils/decryptChatMessage'; -import { decryptStoredWallet } from './utils/decryptWallet'; -import PhraseWallet from './utils/generateWallet/phrase-wallet'; -import { RequestQueueWithPromise } from './utils/queue/queue'; -import { validateAddress } from './utils/validateAddress'; +} from '../qdn/encryption/group-encryption'; +import ChatComputePowWorker from '../chatComputePow.worker.js?worker'; +import { reusableGet } from '../qdn/publish/pubish'; +import { signChat } from '../transactions/signChat'; +import { createTransaction } from '../transactions/transactions'; +import { decryptChatMessage } from '../utils/decryptChatMessage'; +import { decryptStoredWallet } from '../utils/decryptWallet'; +import PhraseWallet from '../utils/generateWallet/phrase-wallet'; +import { RequestQueueWithPromise } from '../utils/queue/queue'; +import { validateAddress } from '../utils/validateAddress'; import { Sha256 } from 'asmcrypto.js'; -import { TradeBotRespondMultipleRequest } from './transactions/TradeBotRespondMultipleRequest'; -import { RESOURCE_TYPE_NUMBER_GROUP_CHAT_REACTIONS } from './constants/constants'; +import { TradeBotRespondMultipleRequest } from '../transactions/TradeBotRespondMultipleRequest'; +import { RESOURCE_TYPE_NUMBER_GROUP_CHAT_REACTIONS } from '../constants/constants'; import { addDataPublishesCase, addEnteredQmailTimestampCase, @@ -68,7 +68,6 @@ import { ltcBalanceCase, makeAdminCase, nameCase, - notificationCase, notifyAdminRegenerateSecretKeyCase, pauseAllQueuesCase, publishGroupEncryptedResourceCase, @@ -90,9 +89,13 @@ import { validApiCase, versionCase, voteOnPollCase, -} from './background-cases'; -import { getData, removeKeysAndLogout, storeData } from './utils/chromeStorage'; -import TradeBotRespondRequest from './transactions/TradeBotRespondRequest'; +} from '../background/background-cases'; +import { + getData, + removeKeysAndLogout, + storeData, +} from '../utils/chromeStorage'; +import TradeBotRespondRequest from '../transactions/TradeBotRespondRequest'; export let groupSecretkeys = {}; diff --git a/src/components/Apps/AppPublish.tsx b/src/components/Apps/AppPublish.tsx index 1e102ee..da58cc9 100644 --- a/src/components/Apps/AppPublish.tsx +++ b/src/components/Apps/AppPublish.tsx @@ -22,7 +22,7 @@ import { executeEvent } from '../../utils/events'; import { useDropzone } from 'react-dropzone'; import { LoadingSnackbar } from '../Snackbar/LoadingSnackbar'; import { CustomizedSnackbars } from '../Snackbar/Snackbar'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { fileToBase64 } from '../../utils/fileReading'; import { useTranslation } from 'react-i18next'; import { useSortedMyNames } from '../../hooks/useSortedMyNames'; diff --git a/src/components/Apps/AppRating.tsx b/src/components/Apps/AppRating.tsx index 9d63213..edd628a 100644 --- a/src/components/Apps/AppRating.tsx +++ b/src/components/Apps/AppRating.tsx @@ -1,6 +1,6 @@ import { Box, Rating } from '@mui/material'; import { useCallback, useContext, useEffect, useRef, useState } from 'react'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { QORTAL_APP_CONTEXT, getBaseApiReact } from '../../App'; import { CustomizedSnackbars } from '../Snackbar/Snackbar'; import { StarFilledIcon } from '../../assets/Icons/StarFilled'; diff --git a/src/components/Apps/AppsDevModeHome.tsx b/src/components/Apps/AppsDevModeHome.tsx index d21618b..f9ade5d 100644 --- a/src/components/Apps/AppsDevModeHome.tsx +++ b/src/components/Apps/AppsDevModeHome.tsx @@ -23,7 +23,7 @@ import { QORTAL_APP_CONTEXT, getBaseApiReact } from '../../App'; import { executeEvent } from '../../utils/events'; import { Spacer } from '../../common/Spacer'; import { useModal } from '../../common/useModal'; -import { createEndpoint, isUsingLocal } from '../../background'; +import { createEndpoint, isUsingLocal } from '../../background/background.ts'; import { Label } from '../Group/AddGroup'; import ShortUniqueId from 'short-unique-id'; import swaggerSVG from '../../assets/svgs/swagger.svg'; diff --git a/src/components/Apps/AppsPrivate.tsx b/src/components/Apps/AppsPrivate.tsx index 298fc6a..f24d15a 100644 --- a/src/components/Apps/AppsPrivate.tsx +++ b/src/components/Apps/AppsPrivate.tsx @@ -40,7 +40,7 @@ import ImageUploader from '../../common/ImageUploader'; import { QORTAL_APP_CONTEXT } from '../../App'; import { fileToBase64 } from '../../utils/fileReading'; import { objectToBase64 } from '../../qdn/encryption/group-encryption'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { useAtom } from 'jotai'; import { useTranslation } from 'react-i18next'; import { useSortedMyNames } from '../../hooks/useSortedMyNames'; diff --git a/src/components/Chat/AdminSpaceInner.tsx b/src/components/Chat/AdminSpaceInner.tsx index 0a68048..97e3fd1 100644 --- a/src/components/Chat/AdminSpaceInner.tsx +++ b/src/components/Chat/AdminSpaceInner.tsx @@ -10,9 +10,9 @@ import { getPublishesFromAdmins, validateSecretKey, } from '../Group/Group'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { base64ToUint8Array } from '../../qdn/encryption/group-encryption'; -import { uint8ArrayToObject } from '../../backgroundFunctions/encryption'; +import { uint8ArrayToObject } from '../../encryption/encryption.ts'; import { formatTimestampForum } from '../../utils/time'; import { Spacer } from '../../common/Spacer'; import { GroupAvatar } from './GroupAvatar'; diff --git a/src/components/Chat/AnnouncementDiscussion.tsx b/src/components/Chat/AnnouncementDiscussion.tsx index 8959a9f..e0da144 100644 --- a/src/components/Chat/AnnouncementDiscussion.tsx +++ b/src/components/Chat/AnnouncementDiscussion.tsx @@ -8,7 +8,7 @@ import { Box, CircularProgress, useTheme } from '@mui/material'; import { objectToBase64 } from '../../qdn/encryption/group-encryption'; import ShortUniqueId from 'short-unique-id'; import { LoadingSnackbar } from '../Snackbar/LoadingSnackbar'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { decryptPublishes, getTempPublish, diff --git a/src/components/Chat/ChatDirect.tsx b/src/components/Chat/ChatDirect.tsx index 35370ad..36681e9 100644 --- a/src/components/Chat/ChatDirect.tsx +++ b/src/components/Chat/ChatDirect.tsx @@ -14,7 +14,7 @@ import { pauseAllQueues, resumeAllQueues, } from '../../App'; -import { getPublicKey } from '../../background'; +import { getPublicKey } from '../../background/background.ts'; import { useMessageQueue } from '../../MessageQueueContext'; import { executeEvent, diff --git a/src/components/Chat/ChatGroup.tsx b/src/components/Chat/ChatGroup.tsx index 0b2ede3..e6b75d0 100644 --- a/src/components/Chat/ChatGroup.tsx +++ b/src/components/Chat/ChatGroup.tsx @@ -44,7 +44,7 @@ import ShortUniqueId from 'short-unique-id'; import { ReplyPreview } from './MessageItem'; import { ExitIcon } from '../../assets/Icons/ExitIcon'; import { RESOURCE_TYPE_NUMBER_GROUP_CHAT_REACTIONS } from '../../constants/constants'; -import { getFee, isExtMsg } from '../../background'; +import { getFee, isExtMsg } from '../../background/background.ts'; import AppViewerContainer from '../Apps/AppViewerContainer'; import CloseIcon from '@mui/icons-material/Close'; import { throttle } from 'lodash'; diff --git a/src/components/Chat/CreateCommonSecret.tsx b/src/components/Chat/CreateCommonSecret.tsx index e7472f6..46f76d6 100644 --- a/src/components/Chat/CreateCommonSecret.tsx +++ b/src/components/Chat/CreateCommonSecret.tsx @@ -8,14 +8,14 @@ import { getBaseApiReact, pauseAllQueues, } from '../../App'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { decryptResource, getGroupAdmins, validateSecretKey, } from '../Group/Group'; import { base64ToUint8Array } from '../../qdn/encryption/group-encryption'; -import { uint8ArrayToObject } from '../../backgroundFunctions/encryption'; +import { uint8ArrayToObject } from '../../encryption/encryption.ts'; import { useSetAtom } from 'jotai'; import { txListAtom } from '../../atoms/global'; import { useTranslation } from 'react-i18next'; diff --git a/src/components/Chat/GroupAnnouncements.tsx b/src/components/Chat/GroupAnnouncements.tsx index a9d1e0a..18170cd 100644 --- a/src/components/Chat/GroupAnnouncements.tsx +++ b/src/components/Chat/GroupAnnouncements.tsx @@ -7,7 +7,7 @@ import { useRef, useState, } from 'react'; -import { uint8ArrayToObject } from '../../backgroundFunctions/encryption'; +import { uint8ArrayToObject } from '../../encryption/encryption.ts'; import { base64ToUint8Array, objectToBase64, @@ -15,7 +15,7 @@ import { import Tiptap from './TipTap'; import { CustomButton } from '../../styles/App-styles'; import CircularProgress from '@mui/material/CircularProgress'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { LoadingSnackbar } from '../Snackbar/LoadingSnackbar'; import { Box, Typography, useTheme } from '@mui/material'; import { Spacer } from '../../common/Spacer'; diff --git a/src/components/Chat/GroupAvatar.tsx b/src/components/Chat/GroupAvatar.tsx index 17bf99b..ecc7c86 100644 --- a/src/components/Chat/GroupAvatar.tsx +++ b/src/components/Chat/GroupAvatar.tsx @@ -16,7 +16,7 @@ import { } from '@mui/material'; import { Spacer } from '../../common/Spacer'; import ImageUploader from '../../common/ImageUploader'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { fileToBase64 } from '../../utils/fileReading'; import { LoadingButton } from '@mui/lab'; import ErrorIcon from '@mui/icons-material/Error'; diff --git a/src/components/Embeds/PollEmbed.tsx b/src/components/Embeds/PollEmbed.tsx index bc246ba..6d7a510 100644 --- a/src/components/Embeds/PollEmbed.tsx +++ b/src/components/Embeds/PollEmbed.tsx @@ -16,7 +16,7 @@ import { } from '@mui/material'; import { getNameInfo } from '../Group/Group'; import PollIcon from '@mui/icons-material/Poll'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import RefreshIcon from '@mui/icons-material/Refresh'; import { Spacer } from '../../common/Spacer'; import OpenInNewIcon from '@mui/icons-material/OpenInNew'; diff --git a/src/components/GlobalActions/JoinGroup.tsx b/src/components/GlobalActions/JoinGroup.tsx index 48ea442..95e95e6 100644 --- a/src/components/GlobalActions/JoinGroup.tsx +++ b/src/components/GlobalActions/JoinGroup.tsx @@ -12,7 +12,7 @@ import { } from '@mui/material'; import { CustomButtonAccept } from '../../styles/App-styles'; import { getBaseApiReact, QORTAL_APP_CONTEXT } from '../../App'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { CustomizedSnackbars } from '../Snackbar/Snackbar'; import { FidgetSpinner } from 'react-loader-spinner'; import { useAtom, useSetAtom } from 'jotai'; diff --git a/src/components/Group/AddGroup.tsx b/src/components/Group/AddGroup.tsx index 2e0ca92..ec01443 100644 --- a/src/components/Group/AddGroup.tsx +++ b/src/components/Group/AddGroup.tsx @@ -34,7 +34,7 @@ import { import { AddGroupList } from './AddGroupList'; import { UserListOfInvites } from './UserListOfInvites'; import { CustomizedSnackbars } from '../Snackbar/Snackbar'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { QORTAL_APP_CONTEXT } from '../../App'; import { subscribeToEvent, unsubscribeFromEvent } from '../../utils/events'; import { useTranslation } from 'react-i18next'; diff --git a/src/components/Group/AddGroupList.tsx b/src/components/Group/AddGroupList.tsx index e9316d8..8cad787 100644 --- a/src/components/Group/AddGroupList.tsx +++ b/src/components/Group/AddGroupList.tsx @@ -25,7 +25,7 @@ import { import _ from 'lodash'; import { QORTAL_APP_CONTEXT, getBaseApiReact } from '../../App'; import { LoadingButton } from '@mui/lab'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import LockIcon from '@mui/icons-material/Lock'; import NoEncryptionGmailerrorredIcon from '@mui/icons-material/NoEncryptionGmailerrorred'; import { Spacer } from '../../common/Spacer'; diff --git a/src/components/Group/Forum/NewThread.tsx b/src/components/Group/Forum/NewThread.tsx index b9d8048..9749480 100644 --- a/src/components/Group/Forum/NewThread.tsx +++ b/src/components/Group/Forum/NewThread.tsx @@ -22,7 +22,7 @@ import { pauseAllQueues, resumeAllQueues, } from '../../../App'; -import { getFee } from '../../../background'; +import { getFee } from '../../../background/background'; import TipTap from '../../Chat/TipTap'; import { MessageDisplay } from '../../Chat/MessageDisplay'; import { CustomizedSnackbars } from '../../Snackbar/Snackbar'; diff --git a/src/components/Group/Group.tsx b/src/components/Group/Group.tsx index 13a807b..368dd15 100644 --- a/src/components/Group/Group.tsx +++ b/src/components/Group/Group.tsx @@ -13,7 +13,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { ChatGroup } from '../Chat/ChatGroup'; import { CreateCommonSecret } from '../Chat/CreateCommonSecret'; import { base64ToUint8Array } from '../../qdn/encryption/group-encryption'; -import { uint8ArrayToObject } from '../../backgroundFunctions/encryption'; +import { uint8ArrayToObject } from '../../encryption/encryption'; import { AddGroup } from './AddGroup'; import CreateIcon from '@mui/icons-material/Create'; import { diff --git a/src/components/Group/InviteMember.tsx b/src/components/Group/InviteMember.tsx index 07ee3a7..8a562d0 100644 --- a/src/components/Group/InviteMember.tsx +++ b/src/components/Group/InviteMember.tsx @@ -3,7 +3,7 @@ import { Box, Input, MenuItem, Select, SelectChangeEvent } from '@mui/material'; import { useState } from 'react'; import { Spacer } from '../../common/Spacer'; import { Label } from './AddGroup'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { useTranslation } from 'react-i18next'; export const InviteMember = ({ groupId, setInfoSnack, setOpenSnack, show }) => { diff --git a/src/components/Group/ListOfBans.tsx b/src/components/Group/ListOfBans.tsx index 9399b7d..122ce27 100644 --- a/src/components/Group/ListOfBans.tsx +++ b/src/components/Group/ListOfBans.tsx @@ -15,7 +15,7 @@ import { List, } from 'react-virtualized'; import { getNameInfo } from './Group'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { LoadingButton } from '@mui/lab'; import { getBaseApiReact } from '../../App'; import { useTranslation } from 'react-i18next'; diff --git a/src/components/Group/ListOfGroupPromotions.tsx b/src/components/Group/ListOfGroupPromotions.tsx index 75fe480..01fbed3 100644 --- a/src/components/Group/ListOfGroupPromotions.tsx +++ b/src/components/Group/ListOfGroupPromotions.tsx @@ -42,7 +42,7 @@ import { useVirtualizer } from '@tanstack/react-virtual'; import ErrorBoundary from '../../common/ErrorBoundary'; import ExpandMoreIcon from '@mui/icons-material/ExpandMore'; import ExpandLessIcon from '@mui/icons-material/ExpandLess'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { useAtom, useSetAtom } from 'jotai'; import { useTranslation } from 'react-i18next'; diff --git a/src/components/Group/ListOfInvites.tsx b/src/components/Group/ListOfInvites.tsx index 8c4fe9b..037dddc 100644 --- a/src/components/Group/ListOfInvites.tsx +++ b/src/components/Group/ListOfInvites.tsx @@ -15,7 +15,7 @@ import { List, } from 'react-virtualized'; import { getNameInfo } from './Group'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { LoadingButton } from '@mui/lab'; import { getBaseApiReact } from '../../App'; import { useTranslation } from 'react-i18next'; diff --git a/src/components/Group/ListOfJoinRequests.tsx b/src/components/Group/ListOfJoinRequests.tsx index 1805733..5fbfe9e 100644 --- a/src/components/Group/ListOfJoinRequests.tsx +++ b/src/components/Group/ListOfJoinRequests.tsx @@ -15,7 +15,7 @@ import { List, } from 'react-virtualized'; import { getNameInfo } from './Group'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { LoadingButton } from '@mui/lab'; import { getBaseApiReact } from '../../App'; import { txListAtom } from '../../atoms/global'; diff --git a/src/components/Group/ListOfMembers.tsx b/src/components/Group/ListOfMembers.tsx index 7a0048f..c57e501 100644 --- a/src/components/Group/ListOfMembers.tsx +++ b/src/components/Group/ListOfMembers.tsx @@ -17,7 +17,7 @@ import { List, } from 'react-virtualized'; import { LoadingButton } from '@mui/lab'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { getBaseApiReact } from '../../App'; import { useTranslation } from 'react-i18next'; diff --git a/src/components/Group/ManageMembers.tsx b/src/components/Group/ManageMembers.tsx index 9fd3150..e87b002 100644 --- a/src/components/Group/ManageMembers.tsx +++ b/src/components/Group/ManageMembers.tsx @@ -28,7 +28,7 @@ import { CustomizedSnackbars } from '../Snackbar/Snackbar'; import { QORTAL_APP_CONTEXT, getBaseApiReact } from '../../App'; import { getGroupMembers, getNames } from './Group'; import { LoadingSnackbar } from '../Snackbar/LoadingSnackbar'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { LoadingButton } from '@mui/lab'; import { subscribeToEvent, unsubscribeFromEvent } from '../../utils/events'; import { Spacer } from '../../common/Spacer'; diff --git a/src/components/Group/Settings.tsx b/src/components/Group/Settings.tsx index 058adde..78db9bc 100644 --- a/src/components/Group/Settings.tsx +++ b/src/components/Group/Settings.tsx @@ -36,8 +36,8 @@ import { useAtom } from 'jotai'; import { decryptStoredWallet } from '../../utils/decryptWallet'; import { Spacer } from '../../common/Spacer'; import PhraseWallet from '../../utils/generateWallet/phrase-wallet'; -import { walletVersion } from '../../background'; -import Base58 from '../../deps/Base58'; +import { walletVersion } from '../../background/background.ts'; +import Base58 from '../../encryption/Base58.ts'; import { QORTAL_APP_CONTEXT } from '../../App'; import { useTranslation } from 'react-i18next'; diff --git a/src/components/Group/UserListOfInvites.tsx b/src/components/Group/UserListOfInvites.tsx index 064296a..2717af9 100644 --- a/src/components/Group/UserListOfInvites.tsx +++ b/src/components/Group/UserListOfInvites.tsx @@ -16,7 +16,7 @@ import { } from 'react-virtualized'; import { QORTAL_APP_CONTEXT, getBaseApiReact } from '../../App'; import { LoadingButton } from '@mui/lab'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import LockIcon from '@mui/icons-material/Lock'; import NoEncryptionGmailerrorredIcon from '@mui/icons-material/NoEncryptionGmailerrorred'; import { Spacer } from '../../common/Spacer'; diff --git a/src/components/MainAvatar.tsx b/src/components/MainAvatar.tsx index 47c985c..b458145 100644 --- a/src/components/MainAvatar.tsx +++ b/src/components/MainAvatar.tsx @@ -16,7 +16,7 @@ import { } from '@mui/material'; import { Spacer } from '../common/Spacer'; import ImageUploader from '../common/ImageUploader'; -import { getFee } from '../background'; +import { getFee } from '../background/background.ts'; import { fileToBase64 } from '../utils/fileReading'; import { LoadingButton } from '@mui/lab'; import ErrorIcon from '@mui/icons-material/Error'; diff --git a/src/components/Minting/Minting.tsx b/src/components/Minting/Minting.tsx index 114d521..2c2d877 100644 --- a/src/components/Minting/Minting.tsx +++ b/src/components/Minting/Minting.tsx @@ -21,7 +21,7 @@ import { subscribeToEvent, unsubscribeFromEvent, } from '../../utils/events'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { Spacer } from '../../common/Spacer'; import { FidgetSpinner } from 'react-loader-spinner'; import { useModal } from '../../common/useModal'; diff --git a/src/components/NotAuthenticated.tsx b/src/components/NotAuthenticated.tsx index c9be445..0d2949c 100644 --- a/src/components/NotAuthenticated.tsx +++ b/src/components/NotAuthenticated.tsx @@ -27,7 +27,7 @@ import { import Logo1Dark from '../assets/svgs/Logo1Dark.svg'; import HelpIcon from '@mui/icons-material/Help'; import { CustomizedSnackbars } from './Snackbar/Snackbar'; -import { cleanUrl, gateways } from '../background'; +import { cleanUrl, gateways } from '../background/background.ts'; import Tooltip, { TooltipProps, tooltipClasses } from '@mui/material/Tooltip'; import ThemeSelector from './Theme/ThemeSelector'; import { useTranslation } from 'react-i18next'; diff --git a/src/components/QortPayment.tsx b/src/components/QortPayment.tsx index c031914..1907686 100644 --- a/src/components/QortPayment.tsx +++ b/src/components/QortPayment.tsx @@ -2,7 +2,7 @@ import { Box, useTheme } from '@mui/material'; import { useState } from 'react'; import { TextP } from '../styles/App-styles'; import { Spacer } from '../common/Spacer'; -import { getFee } from '../background'; +import { getFee } from '../background/background.ts'; import { useTranslation } from 'react-i18next'; export const QortPayment = ({ balance, show, onSuccess, defaultPaymentTo }) => { diff --git a/src/components/RegisterName.tsx b/src/components/RegisterName.tsx index 6e2bfe3..2b5b224 100644 --- a/src/components/RegisterName.tsx +++ b/src/components/RegisterName.tsx @@ -17,7 +17,7 @@ import { import { Label } from './Group/AddGroup'; import { Spacer } from '../common/Spacer'; import { getBaseApiReact } from '../App'; -import { getFee } from '../background'; +import { getFee } from '../background/background.ts'; import RadioButtonCheckedIcon from '@mui/icons-material/RadioButtonChecked'; import { subscribeToEvent, unsubscribeFromEvent } from '../utils/events'; import { BarSpinner } from '../common/Spinners/BarSpinner/BarSpinner'; diff --git a/src/components/Save/Save.tsx b/src/components/Save/Save.tsx index 67950e6..e213174 100644 --- a/src/components/Save/Save.tsx +++ b/src/components/Save/Save.tsx @@ -19,7 +19,7 @@ import { } from '@mui/material'; import { objectToBase64 } from '../../qdn/encryption/group-encryption'; import { QORTAL_APP_CONTEXT } from '../../App'; -import { getFee } from '../../background'; +import { getFee } from '../../background/background.ts'; import { CustomizedSnackbars } from '../Snackbar/Snackbar'; import { SaveIcon } from '../../assets/Icons/SaveIcon'; import { IconWrapper } from '../Desktop/DesktopFooter'; @@ -31,7 +31,7 @@ import { saveFileToDiskGeneric } from '../../utils/generateWallet/generateWallet import { base64ToUint8Array, uint8ArrayToObject, -} from '../../backgroundFunctions/encryption'; +} from '../../encryption/encryption.ts'; import { useTranslation } from 'react-i18next'; import { useAtom, useSetAtom } from 'jotai'; diff --git a/src/components/UserLookup.tsx/UserLookup.tsx b/src/components/UserLookup.tsx/UserLookup.tsx index 675d661..3be4ef6 100644 --- a/src/components/UserLookup.tsx/UserLookup.tsx +++ b/src/components/UserLookup.tsx/UserLookup.tsx @@ -19,7 +19,10 @@ import { useTheme, Autocomplete, } from '@mui/material'; -import { getAddressInfo, getNameOrAddress } from '../../background'; +import { + getAddressInfo, + getNameOrAddress, +} from '../../background/background.ts'; import { getBaseApiReact } from '../../App'; import { getNameInfo } from '../Group/Group'; import AccountCircleIcon from '@mui/icons-material/AccountCircle'; diff --git a/src/deps/AltcoinHDWallet.ts b/src/deps/AltcoinHDWallet.ts deleted file mode 100644 index cd4a10b..0000000 --- a/src/deps/AltcoinHDWallet.ts +++ /dev/null @@ -1,864 +0,0 @@ -// @ts-nocheck -; -import Base58 from '../deps/Base58.js' -import {Sha256, Sha512} from 'asmcrypto.js' -import jsSHA from 'jssha' -import RIPEMD160 from '../deps/ripemd160.js' -import utils from '../utils/utils' -import {BigInteger, EllipticCurve} from './ecbn' -import {Buffer} from 'buffer' - -export default class AltcoinHDWallet { - - constructor(addressParams) { - - /** - * Seed - 32 bytes - */ - - this.seed = new Uint8Array(32) - - /** - * Version Bytes - 4 byte - */ - - this.versionBytes = addressParams - - /** - * Depth - 1 byte - */ - - this.depth = 0 - - /** - * Parent Fingerprint - 4 bytes - */ - - this.parentFingerprint = '0x00000000' // master key - - /** - * Child Index - 4 bytes - */ - - this.childIndex = '0x00000000' // master key - - /** - * Chain Code - 32 bytes - */ - - this.chainCode = new Uint8Array(32) - - /** - * Key Data - 33 bytes - */ - - this.keyData = new Uint8Array(33) - - /** - * Seed Hash - 64 bytes - */ - - this.seedHash = new Uint8Array(64) - - /** - * Private Key - 32 bytes - */ - - this.privateKey = new Uint8Array(32) - - /** - * Public Key - 33 bytes (compressed) - */ - - this.publicKey = new Uint8Array(33) - - /** - * Public Key Hash160 (used to derive the parent fingerprint for derived) - */ - - this.publicKeyHash = new Uint8Array(20) - - /** - * Master Private Key (Base58 encoded) - */ - - this.masterPrivateKey = '' - - /** - * Master Public Key (Base58 encoded) - */ - - this.masterPublicKey = '' - - /** - * Testnet Master Private Key (Base58 encoded) - THIS IS TESTNET - */ - - this._tMasterPrivateKey = '' - - /** - * Testnet Master Public Key (Base58 encoded) - THIS IS TESTNET - */ - - this._tmasterPublicKey = '' - - /** - * Child Keys Derivation from the Parent Keys - */ - - /** - * Child Private Key - 32 bytes - */ - - this.childPrivateKey = new Uint8Array(32) - - /** - * Child Chain Code - 32 bytes - */ - - this.childChainCode = new Uint8Array(32) - - /** - * Child Public Key - 33 bytes (compressed) - */ - - this.childPublicKey = new Uint8Array(33) - - /** - * Child Public Key Hash160 (used to derive the parent fingerprint for derived) - */ - - this.childPublicKeyHash = new Uint8Array(20) - - /** - * Extended Private Child Key - Base58 encoded - */ - - this.xPrivateChildKey = '' - - /** - * Extended Public Child Key - Base58 encoded - */ - - this.xPublicChildKey = '' - - /** - * Grand Child Keys Derivation from the Child Keys - */ - - /** - * Grand Child Private Key - 32 bytes - */ - - this.grandChildPrivateKey = new Uint8Array(32) - - /** - * Grand Child Chain Code - 32 bytes - */ - - this.grandChildChainCode = new Uint8Array(32) - - /** - * Grand Child Public Key - 33 bytes (compressed) - */ - - this.grandChildPublicKey = new Uint8Array(33) - - /** - * Grand Public Key Hash160 (used to derive the parent fingerprint for derived) - */ - - this.grandChildPublicKeyHash = new Uint8Array(20) - - /** - * Extended Private Grand Child Key - Base58 encoded - */ - - this.xPrivateGrandChildKey = '' - - /** - * Extended Public Grand Child Key - Base58 encoded - */ - - this.xPublicGrandChildKey = '' - - /** - * Litecoin Legacy Address - Derived from the Grand Child Public Key Hash - */ - - this.litecoinLegacyAddress = '' - - /** - * TESTNET Litecoin Legacy Address (Derived from the Grand Child Public Key Hash) - THIS IS TESTNET - */ - - this._tlitecoinLegacyAddress = '' - - /** - * Wallet - Wallet Object (keys...) - */ - - this.wallet = {} - } - - setSeed(seed) { - this.seed = seed - } - - createWallet(seed, isBIP44, indicator = null) { - - // Set Seeed - this.setSeed(seed) - - // Generate Seed Hash - this.generateSeedHash(this.seed, isBIP44, indicator) - - // Generate Private Key - this.generatePrivateKey(this.seedHash) - - // Generate Chain Code - this.generateChainCode(this.seedHash) - - // Generate Public Key from Private Key - this.generatePublicKey(this.privateKey) - - // Generate Mainnet Master Private Key - this.generateMainnetMasterPrivateKey() - - // Generate Mainnet Master Public Key - this.generateMainnetMasterPublicKey() - - // Generate Testnet Master Private Key - this.generateTestnetMasterPrivateKey() - - // Generate Testnet Master Public Key - this.generateTestnetMasterPublicKey() - - // Generate Child and Grand Child Keys - this.generateDerivedChildKeys() - - // Return Wallet Object Specification - return this.returnWallet() - } - - - generateSeedHash(seed, isBIP44, indicator = null) { - let buffer - - if (isBIP44) { - buffer = utils.appendBuffer(seed.reverse(), utils.int32ToBytes(indicator)) - } else { - if(indicator !== null) { - const indicatorString = utils.stringtoUTF8Array(indicator) - buffer = utils.appendBuffer(seed.reverse(), indicatorString) - } - else - { - buffer = seed.reverse() - } - } - - const _reverseSeedHash = new Sha256().process(buffer).finish().result - this.seedHash = new Sha512().process(utils.appendBuffer(seed, _reverseSeedHash)).finish().result - } - - generatePrivateKey(seedHash) { - const SECP256K1_CURVE_ORDER = new BigInteger("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141") - - const privateKeyHash = seedHash.slice(0, 32) - - this.seed58 = Base58.encode(privateKeyHash) - - const _privateKeyHash = [...privateKeyHash] - let privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKeyHash) - - const privateKey = (privateKeyBigInt.mod(SECP256K1_CURVE_ORDER.subtract(BigInteger.ONE))).add(BigInteger.ONE) - this.privateKey = privateKey.toByteArrayUnsigned() - } - - generateChainCode(seedHash) { - this.chainCode = new Sha256().process(seedHash.slice(32, 64)).finish().result - } - - generatePublicKey(privateKey) { - const _privateKey = [...privateKey] - const privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKey) - - const epCurve = EllipticCurve.getSECCurveByName("secp256k1") - const curvePoints = epCurve.getG().multiply(privateKeyBigInt) - - - const x = curvePoints.getX().toBigInteger() - const y = curvePoints.getY().toBigInteger() - - /** - * Deriving Uncompressed Public Key (65 bytes) - * - * const publicKeyBytes = EllipticCurve.integerToBytes(x, 32) - * this.publicKey = publicKeyBytes.concat(EllipticCurve.integerToBytes(y, 32)) - * this.publicKey.unshift(0x04) // append point indicator - */ - - // Compressed Public Key (33 bytes) - this.publicKey = EllipticCurve.integerToBytes(x, 32) - - - if (y.isEven()) { - this.publicKey.unshift(0x02) // append point indicator - } else { - this.publicKey.unshift(0x03) // append point indicator - } - - // PublicKey Hash - const publicKeySHA256 = new Sha256().process(new Uint8Array(this.publicKey)).finish().result - const _publicKeyHash = new RIPEMD160().update(Buffer.from(publicKeySHA256)).digest('hex') - this.publicKeyHash = _publicKeyHash - } - - generateMainnetMasterPrivateKey() { - // Serialization Variable - const s = [] - - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.private))) - - // Append Depth - s.push(this.depth) - - // Append Parent Fingerprint - s.push(...(utils.int32ToBytes(this.parentFingerprint))) - - // Append Child Number - s.push(...(utils.int32ToBytes(this.childIndex))) - - // Append Chain Code - s.push(...this.chainCode) - - // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) - s.push(0) - - //if the private key length is less than 32 let's add leading zeros - if(this.privateKey.length<32){ - for(let i=this.privateKey.length;i<32;i++){ - s.push(0) - } - } - - // Append Private Key - s.push(...this.privateKey) - - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) - - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... - - // Save to Private Key as Base58 encoded - this.masterPrivateKey = Base58.encode(s) - } - - generateMainnetMasterPublicKey() { - // Serialization Variable - const s = [] - - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.public))) - - // Append Depth - s.push(this.depth) - - // Append Parent Fingerprint - s.push(...(utils.int32ToBytes(this.parentFingerprint))) - - // Append Child Number - s.push(...(utils.int32ToBytes(this.childIndex))) - - // Append Chain Code - s.push(...this.chainCode) - - // Append Public Key - s.push(...this.publicKey) - - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) - - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... - - // Save to Public Key as Base58 encoded - this.masterPublicKey = Base58.encode(s) - } - - generateTestnetMasterPrivateKey() { - - // To be Used ONLY in Testnet... - - // Serialization Variable - const s = [] - - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.testnet.private))) - - // Append Depth - s.push(this.depth) - - // Append Parent Fingerprint - s.push(...(utils.int32ToBytes(this.parentFingerprint))) - - // Append Child Number - s.push(...(utils.int32ToBytes(this.childIndex))) - - // Append Chain Code - s.push(...this.chainCode) - - // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) - s.push(0) - - // Append Private Key - s.push(...this.privateKey) - - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) - - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... - - // Save to Private Key as Base58 encoded - this._tMasterPrivateKey = Base58.encode(s) - } - - generateTestnetMasterPublicKey() { - - // To be Used ONLY in Testnet... - - // Serialization Variable - const s = [] - - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.testnet.public))) - - // Append Depth - s.push(this.depth) - - // Append Parent Fingerprint - s.push(...(utils.int32ToBytes(this.parentFingerprint))) - - // Append Child Number - s.push(...(utils.int32ToBytes(this.childIndex))) - - // Append Chain Code - s.push(...this.chainCode) - - // Append Private Key - s.push(...this.publicKey) - - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) - - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... - - // Save to Private Key as Base58 encoded - this._tmasterPublicKey = Base58.encode(s) - } - - generateDerivedChildKeys() { - - // SPEC INFO: https://en.bitcoin.it/wiki/BIP_0032#Child_key_derivation_.28CKD.29_functions - // NOTE: will not be using some of derivations func as the value is known. (So I'd rather shove in the values and rewrite out the derivations later ?) - - // NOTE: I "re-wrote" and "reduplicate" the code for child and grandChild keys derivations inorder to get the child and grandchild from the child - // TODO: Make this more better in the future - - const path = 'm/0/0' - // let p = path.split('/') - - // Get Public kEY - const derivePublicChildKey = () => { - - const _privateKey = [...this.childPrivateKey] - const privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKey) - - const epCurve = EllipticCurve.getSECCurveByName("secp256k1") - const curvePoints = epCurve.getG().multiply(privateKeyBigInt) - - const x = curvePoints.getX().toBigInteger() - const y = curvePoints.getY().toBigInteger() - - // Compressed Public Key (33 bytes) - this.childPublicKey = EllipticCurve.integerToBytes(x, 32) - - - if (y.isEven()) { - - this.childPublicKey.unshift(0x02) // append point indicator - } else { - - this.childPublicKey.unshift(0x03) // append point indicator - } - - // PublicKey Hash - const childPublicKeySHA256 = new Sha256().process(new Uint8Array(this.childPublicKey)).finish().result - const _childPublicKeyHash = new RIPEMD160().update(Buffer.from(childPublicKeySHA256)).digest('hex') - this.childPublicKeyHash = _childPublicKeyHash - - - // Call deriveExtendedPublicChildKey // WIll be hardcoding the values... - deriveExtendedPublicChildKey(1, 0) - } - - const derivePrivateChildKey = (cI) => { - - let ib = [] - ib.push((cI >> 24) & 0xff) - ib.push((cI >> 16) & 0xff) - ib.push((cI >> 8) & 0xff) - ib.push(cI & 0xff) - - const s = [...this.publicKey].concat(ib) - - const _hmacSha512 = new jsSHA("SHA-512", "UINT8ARRAY", { numRounds: 1, hmacKey: { value: this.chainCode, format: "UINT8ARRAY" } }) - _hmacSha512.update(new Uint8Array(s)) - - - const IL = BigInteger.fromByteArrayUnsigned([..._hmacSha512.getHMAC('UINT8ARRAY').slice(0, 32)]) - this.childChainCode = _hmacSha512.getHMAC('UINT8ARRAY').slice(32, 64) // IR according to the SPEC - - - // SECP256k1 init - const epCurve = EllipticCurve.getSECCurveByName("secp256k1") - - - const ki = IL.add(BigInteger.fromByteArrayUnsigned(this.privateKey)).mod(epCurve.getN()) // parse256(IL) + kpar (mod n) ==> ki - this.childPrivateKey = ki.toByteArrayUnsigned() - - // Call deriveExtendedPrivateChildKey - deriveExtendedPrivateChildKey(1, 0) - } - - - const deriveExtendedPrivateChildKey = (i, childIndex) => { - - // Serialization Variable - const s = [] - - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.private))) - - // Append Depth (using the index as depth) - i = parseInt(i) - s.push(i) - - // Append Parent Fingerprint - s.push(...(this.publicKeyHash.slice(0, 4))) - - // Append Child Index - s.push(childIndex >>> 24) - s.push((childIndex >>> 16) & 0xff) - s.push((childIndex >>> 8) & 0xff) - s.push(childIndex & 0xff) - - // Append Chain Code - s.push(...this.childChainCode) - - // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) - s.push(0) - - // Append Private Key - s.push(...this.childPrivateKey) - - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) - - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... - - // Save to Private Key as Base58 encoded - this.xPrivateChildKey = Base58.encode(s) - } - - const deriveExtendedPublicChildKey = (i, childIndex) => { - - // Serialization Variable - const s = [] - - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.public))) - - // Append Depth - i = parseInt(i) - s.push(i) - - // Append Parent Fingerprint - s.push(...(this.publicKeyHash.slice(0, 4))) - - // Append Child Index - s.push(childIndex >>> 24) - s.push((childIndex >>> 16) & 0xff) - s.push((childIndex >>> 8) & 0xff) - s.push(childIndex & 0xff) - - // Append Chain Code - s.push(...this.childChainCode) - - // Append Public Key - s.push(...this.childPublicKey) - - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) - - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... - - - // Save to Public Key as Base58 encoded - this.xPublicChildKey = Base58.encode(s) - } - - - /** - * GRAND CHILD KEYS - * - * NOTE: I know this is not the best way to generate this (even though it works the way it ought) - * Things to rewrite will be and not limited to deriving this through a for loop, removing hard code values, etc... - */ - - const derivePublicGrandChildKey = () => { - - const _privateKey = [...this.grandChildPrivateKey] - const privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKey) - - - const epCurve = EllipticCurve.getSECCurveByName("secp256k1") - const curvePoints = epCurve.getG().multiply(privateKeyBigInt) - - const x = curvePoints.getX().toBigInteger() - const y = curvePoints.getY().toBigInteger() - - // Compressed Public Key (33 bytes) - this.grandChildPublicKey = EllipticCurve.integerToBytes(x, 32) - - - if (y.isEven()) { - this.grandChildPublicKey.unshift(0x02) // append point indicator - } else { - this.grandChildPublicKey.unshift(0x03) // append point indicator - } - - - // PublicKey Hash - const grandChildPublicKeySHA256 = new Sha256().process(new Uint8Array(this.grandChildPublicKey)).finish().result - const _grandChildPublicKeyHash = new RIPEMD160().update(Buffer.from(grandChildPublicKeySHA256)).digest('hex') - this.grandChildPublicKeyHash = _grandChildPublicKeyHash - - - // Call deriveExtendedPublicChildKey // WIll be hardcoding the values... - deriveExtendedPublicGrandChildKey(2, 0) - - /** - * Derive Litecoin Legacy Address - */ - - // Append Address Prefix - let prefix = [this.versionBytes.mainnet.prefix] - if (2 == this.versionBytes.mainnet.prefix.length) { - prefix = [this.versionBytes.mainnet.prefix[0]] - prefix.push([this.versionBytes.mainnet.prefix[1]]) - } - - const k = prefix.concat(...this.grandChildPublicKeyHash) - - // Derive Checksum - const _addressCheckSum = new Sha256().process(new Sha256().process(new Uint8Array(k)).finish().result).finish().result - const addressCheckSum = _addressCheckSum.slice(0, 4) - - // Append CheckSum - const _litecoinLegacyAddress = k.concat(...addressCheckSum) - - // Convert to Base58 - this.litecoinLegacyAddress = Base58.encode(_litecoinLegacyAddress) - - - /** - * Derive TESTNET Litecoin Legacy Address - */ - - // Append Version Byte - const tK = [this.versionBytes.testnet.prefix].concat(...this.grandChildPublicKeyHash) - - // Derive Checksum - const _tAddressCheckSum = new Sha256().process(new Sha256().process(new Uint8Array(tK)).finish().result).finish().result - const tAddressCheckSum = _tAddressCheckSum.slice(0, 4) - - // Append CheckSum - const _tlitecoinLegacyAddress = tK.concat(...tAddressCheckSum) - - // Convert to Base58 - this._tlitecoinLegacyAddress = Base58.encode(_tlitecoinLegacyAddress) - } - - const derivePrivateGrandChildKey = (cI, i) => { - - let ib = [] - ib.push((cI >> 24) & 0xff) - ib.push((cI >> 16) & 0xff) - ib.push((cI >> 8) & 0xff) - ib.push(cI & 0xff) - - const s = [...this.childPublicKey].concat(ib) - - - const _hmacSha512 = new jsSHA("SHA-512", "UINT8ARRAY", { numRounds: 1, hmacKey: { value: this.childChainCode, format: "UINT8ARRAY" } }) - _hmacSha512.update(new Uint8Array(s)) - - - const IL = BigInteger.fromByteArrayUnsigned([..._hmacSha512.getHMAC('UINT8ARRAY').slice(0, 32)]) - this.grandChildChainCode = _hmacSha512.getHMAC('UINT8ARRAY').slice(32, 64) // IR according to the SPEC - - // SECP256k1 init - const epCurve = EllipticCurve.getSECCurveByName("secp256k1") - - - const ki = IL.add(BigInteger.fromByteArrayUnsigned(this.childPrivateKey)).mod(epCurve.getN()) // parse256(IL) + kpar (mod n) ==> ki - this.grandChildPrivateKey = ki.toByteArrayUnsigned() - - - // Call deriveExtendedPrivateChildKey - deriveExtendedPrivateGrandChildKey(2, 0) - } - - - const deriveExtendedPrivateGrandChildKey = (i, childIndex) => { - - // Serialization Variable - const s = [] - - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.private))) - - // Append Depth (using the index as depth) - i = parseInt(i) - s.push(i) - - // Append Parent Fingerprint - s.push(...(this.childPublicKeyHash.slice(0, 4))) - - // Append Child Index - s.push(childIndex >>> 24) - s.push((childIndex >>> 16) & 0xff) - s.push((childIndex >>> 8) & 0xff) - s.push(childIndex & 0xff) - - // Append Chain Code - s.push(...this.grandChildChainCode) - - // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) - s.push(0) - - // Append Private Key - s.push(...this.grandChildPrivateKey) - - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) - - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... - - // Save to Private Key as Base58 encoded - this.xPrivateGrandChildKey = Base58.encode(s) - } - - const deriveExtendedPublicGrandChildKey = (i, childIndex) => { - - // Serialization Variable - const s = [] - - // Append Version Byte - s.push(...(utils.int32ToBytes(this.versionBytes.mainnet.public))) - - // Append Depth - i = parseInt(i) - s.push(i) - - // Append Parent Fingerprint - s.push(...(this.childPublicKeyHash.slice(0, 4))) - - // Append Child Index - s.push(childIndex >>> 24) - s.push((childIndex >>> 16) & 0xff) - s.push((childIndex >>> 8) & 0xff) - s.push(childIndex & 0xff) - - // Append Chain Code - s.push(...this.grandChildChainCode) - - // Append Public Key - s.push(...this.grandChildPublicKey) - - // Generate CheckSum - const _s = new Uint8Array(s) - const _checkSum = new Sha256().process(new Sha256().process(_s).finish().result).finish().result - const checkSum = _checkSum.slice(0, 4) - - // Append CheckSum - s.push(...checkSum) // And this brings us to the end of the serialization... - - // Save to Public Key as Base58 encoded - this.xPublicGrandChildKey = Base58.encode(s) - } - - - - // Hard Code value.. - let childIndex = 0 - - // Call derivePrivateChildKey //Hard code value - derivePrivateChildKey(childIndex) - - // Call derivePublicChildKey - derivePublicChildKey() - - - // Call derivePrivateGrandChildKey // Hard Code value... - derivePrivateGrandChildKey(0, 2) - - // Call derivePublicGrandChildKey - derivePublicGrandChildKey() - } - - returnWallet() { - - // Will be limiting the exported Wallet Object to just the Master keys and Legacy Addresses - - const wallet = { - derivedMasterPrivateKey: this.masterPrivateKey, - derivedMasterPublicKey: this.masterPublicKey, - _tDerivedMasterPrivateKey: this._tMasterPrivateKey, - _tDerivedmasterPublicKey: this._tmasterPublicKey, - seed58: this.seed58, - // derivedPrivateChildKey: this.xPrivateChildKey, - // derivedPublicChildKey: this.xPublicChildKey, - // derivedPrivateGrandChildKey: this.xPrivateGrandChildKey, - // derivedPublicGrandChildKey: this.xPublicGrandChildKey, - address: this.litecoinLegacyAddress, - _taddress: this._tlitecoinLegacyAddress - } - - this.wallet = wallet - return wallet - } -} diff --git a/src/encryption/AltcoinHDWallet.ts b/src/encryption/AltcoinHDWallet.ts new file mode 100644 index 0000000..0af6875 --- /dev/null +++ b/src/encryption/AltcoinHDWallet.ts @@ -0,0 +1,881 @@ +// @ts-nocheck +import Base58 from './Base58.js'; +import { Sha256, Sha512 } from 'asmcrypto.js'; +import jsSHA from 'jssha'; +import RIPEMD160 from './ripemd160.js'; +import utils from '../utils/utils.js'; +import { BigInteger, EllipticCurve } from './ecbn'; +import { Buffer } from 'buffer'; + +export default class AltcoinHDWallet { + constructor(addressParams) { + /** + * Seed - 32 bytes + */ + + this.seed = new Uint8Array(32); + + /** + * Version Bytes - 4 byte + */ + + this.versionBytes = addressParams; + + /** + * Depth - 1 byte + */ + + this.depth = 0; + + /** + * Parent Fingerprint - 4 bytes + */ + + this.parentFingerprint = '0x00000000'; // master key + + /** + * Child Index - 4 bytes + */ + + this.childIndex = '0x00000000'; // master key + + /** + * Chain Code - 32 bytes + */ + + this.chainCode = new Uint8Array(32); + + /** + * Key Data - 33 bytes + */ + + this.keyData = new Uint8Array(33); + + /** + * Seed Hash - 64 bytes + */ + + this.seedHash = new Uint8Array(64); + + /** + * Private Key - 32 bytes + */ + + this.privateKey = new Uint8Array(32); + + /** + * Public Key - 33 bytes (compressed) + */ + + this.publicKey = new Uint8Array(33); + + /** + * Public Key Hash160 (used to derive the parent fingerprint for derived) + */ + + this.publicKeyHash = new Uint8Array(20); + + /** + * Master Private Key (Base58 encoded) + */ + + this.masterPrivateKey = ''; + + /** + * Master Public Key (Base58 encoded) + */ + + this.masterPublicKey = ''; + + /** + * Testnet Master Private Key (Base58 encoded) - THIS IS TESTNET + */ + + this._tMasterPrivateKey = ''; + + /** + * Testnet Master Public Key (Base58 encoded) - THIS IS TESTNET + */ + + this._tmasterPublicKey = ''; + + /** + * Child Keys Derivation from the Parent Keys + */ + + /** + * Child Private Key - 32 bytes + */ + + this.childPrivateKey = new Uint8Array(32); + + /** + * Child Chain Code - 32 bytes + */ + + this.childChainCode = new Uint8Array(32); + + /** + * Child Public Key - 33 bytes (compressed) + */ + + this.childPublicKey = new Uint8Array(33); + + /** + * Child Public Key Hash160 (used to derive the parent fingerprint for derived) + */ + + this.childPublicKeyHash = new Uint8Array(20); + + /** + * Extended Private Child Key - Base58 encoded + */ + + this.xPrivateChildKey = ''; + + /** + * Extended Public Child Key - Base58 encoded + */ + + this.xPublicChildKey = ''; + + /** + * Grand Child Keys Derivation from the Child Keys + */ + + /** + * Grand Child Private Key - 32 bytes + */ + + this.grandChildPrivateKey = new Uint8Array(32); + + /** + * Grand Child Chain Code - 32 bytes + */ + + this.grandChildChainCode = new Uint8Array(32); + + /** + * Grand Child Public Key - 33 bytes (compressed) + */ + + this.grandChildPublicKey = new Uint8Array(33); + + /** + * Grand Public Key Hash160 (used to derive the parent fingerprint for derived) + */ + + this.grandChildPublicKeyHash = new Uint8Array(20); + + /** + * Extended Private Grand Child Key - Base58 encoded + */ + + this.xPrivateGrandChildKey = ''; + + /** + * Extended Public Grand Child Key - Base58 encoded + */ + + this.xPublicGrandChildKey = ''; + + /** + * Litecoin Legacy Address - Derived from the Grand Child Public Key Hash + */ + + this.litecoinLegacyAddress = ''; + + /** + * TESTNET Litecoin Legacy Address (Derived from the Grand Child Public Key Hash) - THIS IS TESTNET + */ + + this._tlitecoinLegacyAddress = ''; + + /** + * Wallet - Wallet Object (keys...) + */ + + this.wallet = {}; + } + + setSeed(seed) { + this.seed = seed; + } + + createWallet(seed, isBIP44, indicator = null) { + // Set Seeed + this.setSeed(seed); + + // Generate Seed Hash + this.generateSeedHash(this.seed, isBIP44, indicator); + + // Generate Private Key + this.generatePrivateKey(this.seedHash); + + // Generate Chain Code + this.generateChainCode(this.seedHash); + + // Generate Public Key from Private Key + this.generatePublicKey(this.privateKey); + + // Generate Mainnet Master Private Key + this.generateMainnetMasterPrivateKey(); + + // Generate Mainnet Master Public Key + this.generateMainnetMasterPublicKey(); + + // Generate Testnet Master Private Key + this.generateTestnetMasterPrivateKey(); + + // Generate Testnet Master Public Key + this.generateTestnetMasterPublicKey(); + + // Generate Child and Grand Child Keys + this.generateDerivedChildKeys(); + + // Return Wallet Object Specification + return this.returnWallet(); + } + + generateSeedHash(seed, isBIP44, indicator = null) { + let buffer; + + if (isBIP44) { + buffer = utils.appendBuffer( + seed.reverse(), + utils.int32ToBytes(indicator) + ); + } else { + if (indicator !== null) { + const indicatorString = utils.stringtoUTF8Array(indicator); + buffer = utils.appendBuffer(seed.reverse(), indicatorString); + } else { + buffer = seed.reverse(); + } + } + + const _reverseSeedHash = new Sha256().process(buffer).finish().result; + this.seedHash = new Sha512() + .process(utils.appendBuffer(seed, _reverseSeedHash)) + .finish().result; + } + + generatePrivateKey(seedHash) { + const SECP256K1_CURVE_ORDER = new BigInteger( + '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141' + ); + + const privateKeyHash = seedHash.slice(0, 32); + + this.seed58 = Base58.encode(privateKeyHash); + + const _privateKeyHash = [...privateKeyHash]; + let privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKeyHash); + + const privateKey = privateKeyBigInt + .mod(SECP256K1_CURVE_ORDER.subtract(BigInteger.ONE)) + .add(BigInteger.ONE); + this.privateKey = privateKey.toByteArrayUnsigned(); + } + + generateChainCode(seedHash) { + this.chainCode = new Sha256() + .process(seedHash.slice(32, 64)) + .finish().result; + } + + generatePublicKey(privateKey) { + const _privateKey = [...privateKey]; + const privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKey); + + const epCurve = EllipticCurve.getSECCurveByName('secp256k1'); + const curvePoints = epCurve.getG().multiply(privateKeyBigInt); + + const x = curvePoints.getX().toBigInteger(); + const y = curvePoints.getY().toBigInteger(); + + /** + * Deriving Uncompressed Public Key (65 bytes) + * + * const publicKeyBytes = EllipticCurve.integerToBytes(x, 32) + * this.publicKey = publicKeyBytes.concat(EllipticCurve.integerToBytes(y, 32)) + * this.publicKey.unshift(0x04) // append point indicator + */ + + // Compressed Public Key (33 bytes) + this.publicKey = EllipticCurve.integerToBytes(x, 32); + + if (y.isEven()) { + this.publicKey.unshift(0x02); // append point indicator + } else { + this.publicKey.unshift(0x03); // append point indicator + } + + // PublicKey Hash + const publicKeySHA256 = new Sha256() + .process(new Uint8Array(this.publicKey)) + .finish().result; + const _publicKeyHash = new RIPEMD160() + .update(Buffer.from(publicKeySHA256)) + .digest('hex'); + this.publicKeyHash = _publicKeyHash; + } + + generateMainnetMasterPrivateKey() { + // Serialization Variable + const s = []; + + // Append Version Byte + s.push(...utils.int32ToBytes(this.versionBytes.mainnet.private)); + + // Append Depth + s.push(this.depth); + + // Append Parent Fingerprint + s.push(...utils.int32ToBytes(this.parentFingerprint)); + + // Append Child Number + s.push(...utils.int32ToBytes(this.childIndex)); + + // Append Chain Code + s.push(...this.chainCode); + + // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) + s.push(0); + + //if the private key length is less than 32 let's add leading zeros + if (this.privateKey.length < 32) { + for (let i = this.privateKey.length; i < 32; i++) { + s.push(0); + } + } + + // Append Private Key + s.push(...this.privateKey); + + // Generate CheckSum + const _s = new Uint8Array(s); + const _checkSum = new Sha256() + .process(new Sha256().process(_s).finish().result) + .finish().result; + const checkSum = _checkSum.slice(0, 4); + + // Append CheckSum + s.push(...checkSum); // And this brings us to the end of the serialization... + + // Save to Private Key as Base58 encoded + this.masterPrivateKey = Base58.encode(s); + } + + generateMainnetMasterPublicKey() { + // Serialization Variable + const s = []; + + // Append Version Byte + s.push(...utils.int32ToBytes(this.versionBytes.mainnet.public)); + + // Append Depth + s.push(this.depth); + + // Append Parent Fingerprint + s.push(...utils.int32ToBytes(this.parentFingerprint)); + + // Append Child Number + s.push(...utils.int32ToBytes(this.childIndex)); + + // Append Chain Code + s.push(...this.chainCode); + + // Append Public Key + s.push(...this.publicKey); + + // Generate CheckSum + const _s = new Uint8Array(s); + const _checkSum = new Sha256() + .process(new Sha256().process(_s).finish().result) + .finish().result; + const checkSum = _checkSum.slice(0, 4); + + // Append CheckSum + s.push(...checkSum); // And this brings us to the end of the serialization... + + // Save to Public Key as Base58 encoded + this.masterPublicKey = Base58.encode(s); + } + + generateTestnetMasterPrivateKey() { + // To be Used ONLY in Testnet... + + // Serialization Variable + const s = []; + + // Append Version Byte + s.push(...utils.int32ToBytes(this.versionBytes.testnet.private)); + + // Append Depth + s.push(this.depth); + + // Append Parent Fingerprint + s.push(...utils.int32ToBytes(this.parentFingerprint)); + + // Append Child Number + s.push(...utils.int32ToBytes(this.childIndex)); + + // Append Chain Code + s.push(...this.chainCode); + + // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) + s.push(0); + + // Append Private Key + s.push(...this.privateKey); + + // Generate CheckSum + const _s = new Uint8Array(s); + const _checkSum = new Sha256() + .process(new Sha256().process(_s).finish().result) + .finish().result; + const checkSum = _checkSum.slice(0, 4); + + // Append CheckSum + s.push(...checkSum); // And this brings us to the end of the serialization... + + // Save to Private Key as Base58 encoded + this._tMasterPrivateKey = Base58.encode(s); + } + + generateTestnetMasterPublicKey() { + // To be Used ONLY in Testnet... + + // Serialization Variable + const s = []; + + // Append Version Byte + s.push(...utils.int32ToBytes(this.versionBytes.testnet.public)); + + // Append Depth + s.push(this.depth); + + // Append Parent Fingerprint + s.push(...utils.int32ToBytes(this.parentFingerprint)); + + // Append Child Number + s.push(...utils.int32ToBytes(this.childIndex)); + + // Append Chain Code + s.push(...this.chainCode); + + // Append Private Key + s.push(...this.publicKey); + + // Generate CheckSum + const _s = new Uint8Array(s); + const _checkSum = new Sha256() + .process(new Sha256().process(_s).finish().result) + .finish().result; + const checkSum = _checkSum.slice(0, 4); + + // Append CheckSum + s.push(...checkSum); // And this brings us to the end of the serialization... + + // Save to Private Key as Base58 encoded + this._tmasterPublicKey = Base58.encode(s); + } + + generateDerivedChildKeys() { + // SPEC INFO: https://en.bitcoin.it/wiki/BIP_0032#Child_key_derivation_.28CKD.29_functions + // NOTE: will not be using some of derivations func as the value is known. (So I'd rather shove in the values and rewrite out the derivations later ?) + + // NOTE: I "re-wrote" and "reduplicate" the code for child and grandChild keys derivations inorder to get the child and grandchild from the child + // TODO: Make this more better in the future + + const path = 'm/0/0'; + // let p = path.split('/') + + // Get Public kEY + const derivePublicChildKey = () => { + const _privateKey = [...this.childPrivateKey]; + const privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKey); + + const epCurve = EllipticCurve.getSECCurveByName('secp256k1'); + const curvePoints = epCurve.getG().multiply(privateKeyBigInt); + + const x = curvePoints.getX().toBigInteger(); + const y = curvePoints.getY().toBigInteger(); + + // Compressed Public Key (33 bytes) + this.childPublicKey = EllipticCurve.integerToBytes(x, 32); + + if (y.isEven()) { + this.childPublicKey.unshift(0x02); // append point indicator + } else { + this.childPublicKey.unshift(0x03); // append point indicator + } + + // PublicKey Hash + const childPublicKeySHA256 = new Sha256() + .process(new Uint8Array(this.childPublicKey)) + .finish().result; + const _childPublicKeyHash = new RIPEMD160() + .update(Buffer.from(childPublicKeySHA256)) + .digest('hex'); + this.childPublicKeyHash = _childPublicKeyHash; + + // Call deriveExtendedPublicChildKey // WIll be hardcoding the values... + deriveExtendedPublicChildKey(1, 0); + }; + + const derivePrivateChildKey = (cI) => { + let ib = []; + ib.push((cI >> 24) & 0xff); + ib.push((cI >> 16) & 0xff); + ib.push((cI >> 8) & 0xff); + ib.push(cI & 0xff); + + const s = [...this.publicKey].concat(ib); + + const _hmacSha512 = new jsSHA('SHA-512', 'UINT8ARRAY', { + numRounds: 1, + hmacKey: { value: this.chainCode, format: 'UINT8ARRAY' }, + }); + _hmacSha512.update(new Uint8Array(s)); + + const IL = BigInteger.fromByteArrayUnsigned([ + ..._hmacSha512.getHMAC('UINT8ARRAY').slice(0, 32), + ]); + this.childChainCode = _hmacSha512.getHMAC('UINT8ARRAY').slice(32, 64); // IR according to the SPEC + + // SECP256k1 init + const epCurve = EllipticCurve.getSECCurveByName('secp256k1'); + + const ki = IL.add(BigInteger.fromByteArrayUnsigned(this.privateKey)).mod( + epCurve.getN() + ); // parse256(IL) + kpar (mod n) ==> ki + this.childPrivateKey = ki.toByteArrayUnsigned(); + + // Call deriveExtendedPrivateChildKey + deriveExtendedPrivateChildKey(1, 0); + }; + + const deriveExtendedPrivateChildKey = (i, childIndex) => { + // Serialization Variable + const s = []; + + // Append Version Byte + s.push(...utils.int32ToBytes(this.versionBytes.mainnet.private)); + + // Append Depth (using the index as depth) + i = parseInt(i); + s.push(i); + + // Append Parent Fingerprint + s.push(...this.publicKeyHash.slice(0, 4)); + + // Append Child Index + s.push(childIndex >>> 24); + s.push((childIndex >>> 16) & 0xff); + s.push((childIndex >>> 8) & 0xff); + s.push(childIndex & 0xff); + + // Append Chain Code + s.push(...this.childChainCode); + + // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) + s.push(0); + + // Append Private Key + s.push(...this.childPrivateKey); + + // Generate CheckSum + const _s = new Uint8Array(s); + const _checkSum = new Sha256() + .process(new Sha256().process(_s).finish().result) + .finish().result; + const checkSum = _checkSum.slice(0, 4); + + // Append CheckSum + s.push(...checkSum); // And this brings us to the end of the serialization... + + // Save to Private Key as Base58 encoded + this.xPrivateChildKey = Base58.encode(s); + }; + + const deriveExtendedPublicChildKey = (i, childIndex) => { + // Serialization Variable + const s = []; + + // Append Version Byte + s.push(...utils.int32ToBytes(this.versionBytes.mainnet.public)); + + // Append Depth + i = parseInt(i); + s.push(i); + + // Append Parent Fingerprint + s.push(...this.publicKeyHash.slice(0, 4)); + + // Append Child Index + s.push(childIndex >>> 24); + s.push((childIndex >>> 16) & 0xff); + s.push((childIndex >>> 8) & 0xff); + s.push(childIndex & 0xff); + + // Append Chain Code + s.push(...this.childChainCode); + + // Append Public Key + s.push(...this.childPublicKey); + + // Generate CheckSum + const _s = new Uint8Array(s); + const _checkSum = new Sha256() + .process(new Sha256().process(_s).finish().result) + .finish().result; + const checkSum = _checkSum.slice(0, 4); + + // Append CheckSum + s.push(...checkSum); // And this brings us to the end of the serialization... + + // Save to Public Key as Base58 encoded + this.xPublicChildKey = Base58.encode(s); + }; + + /** + * GRAND CHILD KEYS + * + * NOTE: I know this is not the best way to generate this (even though it works the way it ought) + * Things to rewrite will be and not limited to deriving this through a for loop, removing hard code values, etc... + */ + + const derivePublicGrandChildKey = () => { + const _privateKey = [...this.grandChildPrivateKey]; + const privateKeyBigInt = BigInteger.fromByteArrayUnsigned(_privateKey); + + const epCurve = EllipticCurve.getSECCurveByName('secp256k1'); + const curvePoints = epCurve.getG().multiply(privateKeyBigInt); + + const x = curvePoints.getX().toBigInteger(); + const y = curvePoints.getY().toBigInteger(); + + // Compressed Public Key (33 bytes) + this.grandChildPublicKey = EllipticCurve.integerToBytes(x, 32); + + if (y.isEven()) { + this.grandChildPublicKey.unshift(0x02); // append point indicator + } else { + this.grandChildPublicKey.unshift(0x03); // append point indicator + } + + // PublicKey Hash + const grandChildPublicKeySHA256 = new Sha256() + .process(new Uint8Array(this.grandChildPublicKey)) + .finish().result; + const _grandChildPublicKeyHash = new RIPEMD160() + .update(Buffer.from(grandChildPublicKeySHA256)) + .digest('hex'); + this.grandChildPublicKeyHash = _grandChildPublicKeyHash; + + // Call deriveExtendedPublicChildKey // WIll be hardcoding the values... + deriveExtendedPublicGrandChildKey(2, 0); + + /** + * Derive Litecoin Legacy Address + */ + + // Append Address Prefix + let prefix = [this.versionBytes.mainnet.prefix]; + if (2 == this.versionBytes.mainnet.prefix.length) { + prefix = [this.versionBytes.mainnet.prefix[0]]; + prefix.push([this.versionBytes.mainnet.prefix[1]]); + } + + const k = prefix.concat(...this.grandChildPublicKeyHash); + + // Derive Checksum + const _addressCheckSum = new Sha256() + .process(new Sha256().process(new Uint8Array(k)).finish().result) + .finish().result; + const addressCheckSum = _addressCheckSum.slice(0, 4); + + // Append CheckSum + const _litecoinLegacyAddress = k.concat(...addressCheckSum); + + // Convert to Base58 + this.litecoinLegacyAddress = Base58.encode(_litecoinLegacyAddress); + + /** + * Derive TESTNET Litecoin Legacy Address + */ + + // Append Version Byte + const tK = [this.versionBytes.testnet.prefix].concat( + ...this.grandChildPublicKeyHash + ); + + // Derive Checksum + const _tAddressCheckSum = new Sha256() + .process(new Sha256().process(new Uint8Array(tK)).finish().result) + .finish().result; + const tAddressCheckSum = _tAddressCheckSum.slice(0, 4); + + // Append CheckSum + const _tlitecoinLegacyAddress = tK.concat(...tAddressCheckSum); + + // Convert to Base58 + this._tlitecoinLegacyAddress = Base58.encode(_tlitecoinLegacyAddress); + }; + + const derivePrivateGrandChildKey = (cI, i) => { + let ib = []; + ib.push((cI >> 24) & 0xff); + ib.push((cI >> 16) & 0xff); + ib.push((cI >> 8) & 0xff); + ib.push(cI & 0xff); + + const s = [...this.childPublicKey].concat(ib); + + const _hmacSha512 = new jsSHA('SHA-512', 'UINT8ARRAY', { + numRounds: 1, + hmacKey: { value: this.childChainCode, format: 'UINT8ARRAY' }, + }); + _hmacSha512.update(new Uint8Array(s)); + + const IL = BigInteger.fromByteArrayUnsigned([ + ..._hmacSha512.getHMAC('UINT8ARRAY').slice(0, 32), + ]); + this.grandChildChainCode = _hmacSha512 + .getHMAC('UINT8ARRAY') + .slice(32, 64); // IR according to the SPEC + + // SECP256k1 init + const epCurve = EllipticCurve.getSECCurveByName('secp256k1'); + + const ki = IL.add( + BigInteger.fromByteArrayUnsigned(this.childPrivateKey) + ).mod(epCurve.getN()); // parse256(IL) + kpar (mod n) ==> ki + this.grandChildPrivateKey = ki.toByteArrayUnsigned(); + + // Call deriveExtendedPrivateChildKey + deriveExtendedPrivateGrandChildKey(2, 0); + }; + + const deriveExtendedPrivateGrandChildKey = (i, childIndex) => { + // Serialization Variable + const s = []; + + // Append Version Byte + s.push(...utils.int32ToBytes(this.versionBytes.mainnet.private)); + + // Append Depth (using the index as depth) + i = parseInt(i); + s.push(i); + + // Append Parent Fingerprint + s.push(...this.childPublicKeyHash.slice(0, 4)); + + // Append Child Index + s.push(childIndex >>> 24); + s.push((childIndex >>> 16) & 0xff); + s.push((childIndex >>> 8) & 0xff); + s.push(childIndex & 0xff); + + // Append Chain Code + s.push(...this.grandChildChainCode); + + // Append 1 byte '0x00' (to make the key data 33 bytes, DO THIS ONLY FOR PRIVATE KEYS ) + s.push(0); + + // Append Private Key + s.push(...this.grandChildPrivateKey); + + // Generate CheckSum + const _s = new Uint8Array(s); + const _checkSum = new Sha256() + .process(new Sha256().process(_s).finish().result) + .finish().result; + const checkSum = _checkSum.slice(0, 4); + + // Append CheckSum + s.push(...checkSum); // And this brings us to the end of the serialization... + + // Save to Private Key as Base58 encoded + this.xPrivateGrandChildKey = Base58.encode(s); + }; + + const deriveExtendedPublicGrandChildKey = (i, childIndex) => { + // Serialization Variable + const s = []; + + // Append Version Byte + s.push(...utils.int32ToBytes(this.versionBytes.mainnet.public)); + + // Append Depth + i = parseInt(i); + s.push(i); + + // Append Parent Fingerprint + s.push(...this.childPublicKeyHash.slice(0, 4)); + + // Append Child Index + s.push(childIndex >>> 24); + s.push((childIndex >>> 16) & 0xff); + s.push((childIndex >>> 8) & 0xff); + s.push(childIndex & 0xff); + + // Append Chain Code + s.push(...this.grandChildChainCode); + + // Append Public Key + s.push(...this.grandChildPublicKey); + + // Generate CheckSum + const _s = new Uint8Array(s); + const _checkSum = new Sha256() + .process(new Sha256().process(_s).finish().result) + .finish().result; + const checkSum = _checkSum.slice(0, 4); + + // Append CheckSum + s.push(...checkSum); // And this brings us to the end of the serialization... + + // Save to Public Key as Base58 encoded + this.xPublicGrandChildKey = Base58.encode(s); + }; + + // Hard Code value.. + let childIndex = 0; + + // Call derivePrivateChildKey //Hard code value + derivePrivateChildKey(childIndex); + + // Call derivePublicChildKey + derivePublicChildKey(); + + // Call derivePrivateGrandChildKey // Hard Code value... + derivePrivateGrandChildKey(0, 2); + + // Call derivePublicGrandChildKey + derivePublicGrandChildKey(); + } + + returnWallet() { + // Will be limiting the exported Wallet Object to just the Master keys and Legacy Addresses + + const wallet = { + derivedMasterPrivateKey: this.masterPrivateKey, + derivedMasterPublicKey: this.masterPublicKey, + _tDerivedMasterPrivateKey: this._tMasterPrivateKey, + _tDerivedmasterPublicKey: this._tmasterPublicKey, + seed58: this.seed58, + // derivedPrivateChildKey: this.xPrivateChildKey, + // derivedPublicChildKey: this.xPublicChildKey, + // derivedPrivateGrandChildKey: this.xPrivateGrandChildKey, + // derivedPublicGrandChildKey: this.xPublicGrandChildKey, + address: this.litecoinLegacyAddress, + _taddress: this._tlitecoinLegacyAddress, + }; + + this.wallet = wallet; + return wallet; + } +} diff --git a/src/deps/Base58.ts b/src/encryption/Base58.ts similarity index 100% rename from src/deps/Base58.ts rename to src/encryption/Base58.ts diff --git a/src/deps/bcryptworker.worker.js b/src/encryption/bcryptworker.worker.js similarity index 100% rename from src/deps/bcryptworker.worker.js rename to src/encryption/bcryptworker.worker.js diff --git a/src/deps/bcryptworkerwasm.worker.js b/src/encryption/bcryptworkerwasm.worker.js similarity index 100% rename from src/deps/bcryptworkerwasm.worker.js rename to src/encryption/bcryptworkerwasm.worker.js diff --git a/src/deps/broken-ripemd160.ts b/src/encryption/broken-ripemd160.ts similarity index 100% rename from src/deps/broken-ripemd160.ts rename to src/encryption/broken-ripemd160.ts diff --git a/src/deps/ecbn.ts b/src/encryption/ecbn.ts similarity index 100% rename from src/deps/ecbn.ts rename to src/encryption/ecbn.ts diff --git a/src/deps/ed2curve.ts b/src/encryption/ed2curve.ts similarity index 100% rename from src/deps/ed2curve.ts rename to src/encryption/ed2curve.ts diff --git a/src/backgroundFunctions/encryption.ts b/src/encryption/encryption.ts similarity index 96% rename from src/backgroundFunctions/encryption.ts rename to src/encryption/encryption.ts index def79c0..97f6d75 100644 --- a/src/backgroundFunctions/encryption.ts +++ b/src/encryption/encryption.ts @@ -1,14 +1,14 @@ -import { getBaseApi } from '../background'; -import i18n from '../i18n/i18n'; +import { getBaseApi } from '../background/background.ts'; +import i18n from '../i18n/i18n.ts'; import { createSymmetricKeyAndNonce, decryptGroupData, encryptDataGroup, objectToBase64, -} from '../qdn/encryption/group-encryption'; -import { publishData } from '../qdn/publish/pubish'; -import { getData } from '../utils/chromeStorage'; -import { RequestQueueWithPromise } from '../utils/queue/queue'; +} from '../qdn/encryption/group-encryption.ts'; +import { publishData } from '../qdn/publish/pubish.ts'; +import { getData } from '../utils/chromeStorage.ts'; +import { RequestQueueWithPromise } from '../utils/queue/queue.ts'; export const requestQueueGetPublicKeys = new RequestQueueWithPromise(10); diff --git a/src/deps/kdf.ts b/src/encryption/kdf.ts similarity index 100% rename from src/deps/kdf.ts rename to src/encryption/kdf.ts diff --git a/src/deps/nacl-fast.ts b/src/encryption/nacl-fast.ts similarity index 100% rename from src/deps/nacl-fast.ts rename to src/encryption/nacl-fast.ts diff --git a/src/deps/ripemd160.ts b/src/encryption/ripemd160.ts similarity index 100% rename from src/deps/ripemd160.ts rename to src/encryption/ripemd160.ts diff --git a/src/hooks/useHandlePaymentNotification.tsx b/src/hooks/useHandlePaymentNotification.tsx index 7a13072..e25fae2 100644 --- a/src/hooks/useHandlePaymentNotification.tsx +++ b/src/hooks/useHandlePaymentNotification.tsx @@ -1,7 +1,10 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { getBaseApiReact } from '../App'; import { getData, storeData } from '../utils/chromeStorage'; -import { checkDifference, getNameInfoForOthers } from '../background'; +import { + checkDifference, + getNameInfoForOthers, +} from '../background/background.ts'; import { lastPaymentSeenTimestampAtom } from '../atoms/global'; import { subscribeToEvent, unsubscribeFromEvent } from '../utils/events'; import { useAtom } from 'jotai'; diff --git a/src/hooks/useHandlePrivateApps.tsx b/src/hooks/useHandlePrivateApps.tsx index e1d8288..3876130 100644 --- a/src/hooks/useHandlePrivateApps.tsx +++ b/src/hooks/useHandlePrivateApps.tsx @@ -1,14 +1,14 @@ import { useContext, useState } from 'react'; import { executeEvent } from '../utils/events'; import { getBaseApiReact, QORTAL_APP_CONTEXT } from '../App'; -import { createEndpoint } from '../background'; +import { createEndpoint } from '../background/background.ts'; import { settingsLocalLastUpdatedAtom, sortablePinnedAppsAtom, } from '../atoms/global'; import { saveToLocalStorage } from '../components/Apps/AppsNavBarDesktop'; import { base64ToUint8Array } from '../qdn/encryption/group-encryption'; -import { uint8ArrayToObject } from '../backgroundFunctions/encryption'; +import { uint8ArrayToObject } from '../encryption/encryption.ts'; import { useSetAtom } from 'jotai'; import { useTranslation } from 'react-i18next'; diff --git a/src/hooks/useQortalGetSaveSettings.tsx b/src/hooks/useQortalGetSaveSettings.tsx index 214455b..5fb62fc 100644 --- a/src/hooks/useQortalGetSaveSettings.tsx +++ b/src/hooks/useQortalGetSaveSettings.tsx @@ -12,7 +12,7 @@ import { decryptResource } from '../components/Group/Group'; import { base64ToUint8Array, uint8ArrayToObject, -} from '../backgroundFunctions/encryption'; +} from '../encryption/encryption'; import { useAtom, useSetAtom } from 'jotai'; function fetchFromLocalStorage(key) { diff --git a/src/qdn/encryption/group-encryption.ts b/src/qdn/encryption/group-encryption.ts index 24998e9..6f018ba 100644 --- a/src/qdn/encryption/group-encryption.ts +++ b/src/qdn/encryption/group-encryption.ts @@ -1,8 +1,8 @@ // @ts-nocheck -import Base58 from '../../deps/Base58'; -import ed2curve from '../../deps/ed2curve'; -import nacl from '../../deps/nacl-fast'; +import Base58 from '../../encryption/Base58'; +import ed2curve from '../../encryption/ed2curve'; +import nacl from '../../encryption/nacl-fast'; import i18n from '../../i18n/i18n'; export function base64ToUint8Array(base64: string) { diff --git a/src/qdn/publish/pubish.ts b/src/qdn/publish/pubish.ts index 5f00ffb..d49791b 100644 --- a/src/qdn/publish/pubish.ts +++ b/src/qdn/publish/pubish.ts @@ -1,10 +1,10 @@ // @ts-nocheck import { Buffer } from 'buffer'; -import Base58 from '../../deps/Base58'; -import nacl from '../../deps/nacl-fast'; +import Base58 from '../../encryption/Base58'; +import nacl from '../../encryption/nacl-fast'; import utils from '../../utils/utils'; -import { createEndpoint, getBaseApi } from '../../background'; +import { createEndpoint, getBaseApi } from '../../background/background'; import { getData } from '../../utils/chromeStorage'; export async function reusableGet(endpoint) { @@ -30,6 +30,7 @@ async function reusablePost(endpoint, _body) { data = await response.clone().json(); } catch (e) { data = await response.text(); +<<<<<<< HEAD } return data; } @@ -70,6 +71,7 @@ async function uploadChunkWithRetry(endpoint, formData, index, maxRetries = 3) { await new Promise((res) => setTimeout(res, 10_000)); } } + return data; } async function getKeyPair() { @@ -87,6 +89,11 @@ export const publishData = async ({ service, identifier, uploadType, + file, + service, + identifier, + uploadType, + isBase64, filename, withFee, title, @@ -245,6 +252,7 @@ export const publishData = async ({ return signAndProcessRes; }; +<<<<<<< HEAD const uploadData = async (registeredName: string, data: any, fee: number) => { console.log('data', uploadType, data); let postBody = ''; @@ -359,6 +367,82 @@ export const publishData = async ({ const result = await response.text(); // Base58-encoded unsigned transaction return result; +} + + const uploadData = async (registeredName: string, file: any, fee: number) => { + let postBody = ''; + let urlSuffix = ''; + + if (file != null) { + // If we're sending zipped data, make sure to use the /zip version of the POST /arbitrary/* API + if (uploadType === 'zip') { + urlSuffix = '/zip'; + } + + // If we're sending file data, use the /base64 version of the POST /arbitrary/* API + else if (uploadType === 'file') { + urlSuffix = '/base64'; + } + + // Base64 encode the file to work around compatibility issues between javascript and java byte arrays + if (isBase64) { + postBody = file; + } + + if (!isBase64) { + let fileBuffer = new Uint8Array(await file.arrayBuffer()); + postBody = Buffer.from(fileBuffer).toString('base64'); + } + } + + let uploadDataUrl = `/arbitrary/${service}/${registeredName}${urlSuffix}`; + if (identifier?.trim().length > 0) { + uploadDataUrl = `/arbitrary/${service}/${registeredName}/${identifier}${urlSuffix}`; + } + + uploadDataUrl = uploadDataUrl + `?fee=${fee}`; + + if (filename != null && filename != 'undefined') { + uploadDataUrl = + uploadDataUrl + '&filename=' + encodeURIComponent(filename); + } + + if (title != null && title != 'undefined') { + uploadDataUrl = uploadDataUrl + '&title=' + encodeURIComponent(title); + } + + if (description != null && description != 'undefined') { + uploadDataUrl = + uploadDataUrl + '&description=' + encodeURIComponent(description); + } + + if (category != null && category != 'undefined') { + uploadDataUrl = + uploadDataUrl + '&category=' + encodeURIComponent(category); + } + + if (tag1 != null && tag1 != 'undefined') { + uploadDataUrl = uploadDataUrl + '&tags=' + encodeURIComponent(tag1); + } + + if (tag2 != null && tag2 != 'undefined') { + uploadDataUrl = uploadDataUrl + '&tags=' + encodeURIComponent(tag2); + } + + if (tag3 != null && tag3 != 'undefined') { + uploadDataUrl = uploadDataUrl + '&tags=' + encodeURIComponent(tag3); + } + + if (tag4 != null && tag4 != 'undefined') { + uploadDataUrl = uploadDataUrl + '&tags=' + encodeURIComponent(tag4); + } + + if (tag5 != null && tag5 != 'undefined') { + uploadDataUrl = uploadDataUrl + '&tags=' + encodeURIComponent(tag5); + } + + return await reusablePost(uploadDataUrl, postBody); +>>>>>>> 2d01b3e (Create encryption folder and move files) }; try { diff --git a/src/qortalRequests/get.ts b/src/qortalRequests/get.ts index a698fcc..15576aa 100644 --- a/src/qortalRequests/get.ts +++ b/src/qortalRequests/get.ts @@ -37,12 +37,17 @@ import { getAssetInfo, getPublicKey, transferAsset, +<<<<<<< HEAD } from '../background'; import { getAllUserNames, getNameInfo, uint8ArrayToObject, } from '../backgroundFunctions/encryption'; +======= +} from '../background/background.ts'; +import { getNameInfo, uint8ArrayToObject } from '../encryption/encryption.ts'; +>>>>>>> 2d01b3e (Create encryption folder and move files) import { showSaveFilePicker } from '../hooks/useQortalMessageListener'; import { getPublishesFromAdminsAdminSpace } from '../components/Chat/AdminSpaceInner'; import { extractComponents } from '../components/Chat/MessageDisplay'; @@ -53,9 +58,9 @@ import { validateSecretKey, } from '../components/Group/Group'; import { QORT_DECIMALS } from '../constants/constants'; -import Base58 from '../deps/Base58'; -import ed2curve from '../deps/ed2curve'; -import nacl from '../deps/nacl-fast'; +import Base58 from '../encryption/Base58.ts'; +import ed2curve from '../encryption/ed2curve.ts'; +import nacl from '../encryption/nacl-fast.ts'; import { base64ToUint8Array, createSymmetricKeyAndNonce, @@ -74,7 +79,7 @@ import { getPermission, isRunningGateway, setPermission, -} from '../qortalRequests'; +} from './qortalRequests.ts'; import TradeBotCreateRequest from '../transactions/TradeBotCreateRequest'; import DeleteTradeOffer from '../transactions/TradeBotDeleteRequest'; import signTradeBotTransaction from '../transactions/signTradeBotTransaction'; diff --git a/src/qortalRequests.ts b/src/qortalRequests/qortalRequests.ts similarity index 99% rename from src/qortalRequests.ts rename to src/qortalRequests/qortalRequests.ts index 08a7c4f..9681790 100644 --- a/src/qortalRequests.ts +++ b/src/qortalRequests/qortalRequests.ts @@ -1,5 +1,5 @@ -import { gateways, getApiKeyFromStorage } from './background'; -import { listOfAllQortalRequests } from './hooks/useQortalMessageListener'; +import { gateways, getApiKeyFromStorage } from '../background/background.ts'; +import { listOfAllQortalRequests } from '../hooks/useQortalMessageListener.tsx'; import { addForeignServer, addGroupAdminRequest, @@ -63,9 +63,9 @@ import { signForeignFees, multiPaymentWithPrivateData, transferAssetRequest, -} from './qortalRequests/get'; -import { getData, storeData } from './utils/chromeStorage'; -import { executeEvent } from './utils/events'; +} from './get.ts'; +import { getData, storeData } from '../utils/chromeStorage.ts'; +import { executeEvent } from '../utils/events.ts'; function getLocalStorage(key) { return getData(key).catch((error) => { diff --git a/src/transactions/ChatBase.ts b/src/transactions/ChatBase.ts index c88d634..17cb509 100644 --- a/src/transactions/ChatBase.ts +++ b/src/transactions/ChatBase.ts @@ -1,8 +1,8 @@ // @ts-nocheck import { QORT_DECIMALS, TX_TYPES } from '../constants/constants'; -import nacl from '../deps/nacl-fast'; -import Base58 from '../deps/Base58'; +import nacl from '../encryption/nacl-fast'; +import Base58 from '../encryption/Base58'; import utils from '../utils/utils'; export default class ChatBase { static get utils() { diff --git a/src/transactions/ChatTransaction.ts b/src/transactions/ChatTransaction.ts index fc67531..7abf040 100644 --- a/src/transactions/ChatTransaction.ts +++ b/src/transactions/ChatTransaction.ts @@ -1,8 +1,8 @@ // @ts-nocheck import ChatBase from './ChatBase'; -import nacl from '../deps/nacl-fast'; -import ed2curve from '../deps/ed2curve'; +import nacl from '../encryption/nacl-fast'; +import ed2curve from '../encryption/ed2curve'; import { Sha256 } from 'asmcrypto.js'; import { CHAT_REFERENCE_FEATURE_TRIGGER_TIMESTAMP } from '../constants/constants'; export default class ChatTransaction extends ChatBase { diff --git a/src/transactions/RemoveRewardShareTransaction.ts b/src/transactions/RemoveRewardShareTransaction.ts index c91d389..078c8ed 100644 --- a/src/transactions/RemoveRewardShareTransaction.ts +++ b/src/transactions/RemoveRewardShareTransaction.ts @@ -1,7 +1,7 @@ // @ts-nocheck import { DYNAMIC_FEE_TIMESTAMP } from '../constants/constants'; -import Base58 from '../deps/Base58'; +import Base58 from '../encryption/Base58'; import publicKeyToAddress from '../utils/generateWallet/publicKeyToAddress'; import TransactionBase from './TransactionBase'; export default class RemoveRewardShareTransaction extends TransactionBase { diff --git a/src/transactions/RewardShareTransaction.ts b/src/transactions/RewardShareTransaction.ts index 67131b3..661f7f8 100644 --- a/src/transactions/RewardShareTransaction.ts +++ b/src/transactions/RewardShareTransaction.ts @@ -2,8 +2,8 @@ import TransactionBase from './TransactionBase'; import { Sha256 } from 'asmcrypto.js'; -import nacl from '../deps/nacl-fast'; -import ed2curve from '../deps/ed2curve'; +import nacl from '../encryption/nacl-fast'; +import ed2curve from '../encryption/ed2curve'; import { DYNAMIC_FEE_TIMESTAMP } from '../constants/constants'; import publicKeyToAddress from '../utils/generateWallet/publicKeyToAddress'; export default class RewardShareTransaction extends TransactionBase { diff --git a/src/transactions/TransactionBase.ts b/src/transactions/TransactionBase.ts index 055a08b..f4abf0f 100644 --- a/src/transactions/TransactionBase.ts +++ b/src/transactions/TransactionBase.ts @@ -1,7 +1,7 @@ // @ts-nocheck -import nacl from '../deps/nacl-fast'; -import Base58 from '../deps/Base58'; +import nacl from '../encryption/nacl-fast.js'; +import Base58 from '../encryption/Base58.js'; import utils from '../utils/utils'; import { QORT_DECIMALS, TX_TYPES } from '../constants/constants.js'; export default class TransactionBase { diff --git a/src/transactions/signChat.ts b/src/transactions/signChat.ts index 5995128..bdc3cb9 100644 --- a/src/transactions/signChat.ts +++ b/src/transactions/signChat.ts @@ -1,6 +1,6 @@ // @ts-nocheck -import nacl from '../deps/nacl-fast'; +import nacl from '../encryption/nacl-fast'; import utils from '../utils/utils'; export const signChat = (chatBytes, nonce, keyPair) => { diff --git a/src/transactions/signTradeBotTransaction.ts b/src/transactions/signTradeBotTransaction.ts index 31b7430..fc0e0e5 100644 --- a/src/transactions/signTradeBotTransaction.ts +++ b/src/transactions/signTradeBotTransaction.ts @@ -1,7 +1,7 @@ // @ts-nocheck -import nacl from '../deps/nacl-fast'; -import Base58 from '../deps/Base58'; +import nacl from '../encryption/nacl-fast'; +import Base58 from '../encryption/Base58'; import utils from '../utils/utils'; const signTradeBotTransaction = async (unsignedTxn, keyPair) => { diff --git a/src/utils/decryptChatMessage.ts b/src/utils/decryptChatMessage.ts index 39085e8..d58009f 100644 --- a/src/utils/decryptChatMessage.ts +++ b/src/utils/decryptChatMessage.ts @@ -1,8 +1,8 @@ // @ts-nocheck -import Base58 from '../deps/Base58'; -import ed2curve from '../deps/ed2curve'; -import nacl from '../deps/nacl-fast'; +import Base58 from '../encryption/Base58'; +import ed2curve from '../encryption/ed2curve'; +import nacl from '../encryption/nacl-fast'; import { Sha256 } from 'asmcrypto.js'; export const decryptChatMessage = ( diff --git a/src/utils/decryptWallet.ts b/src/utils/decryptWallet.ts index bf27e8a..3fa002a 100644 --- a/src/utils/decryptWallet.ts +++ b/src/utils/decryptWallet.ts @@ -1,9 +1,9 @@ // @ts-nocheck import { crypto } from '../constants/decryptWallet'; -import Base58 from '../deps/Base58'; +import Base58 from '../encryption/Base58'; import { AES_CBC, HmacSha512 } from 'asmcrypto.js'; -import { doInitWorkers, kdf } from '../deps/kdf'; +import { doInitWorkers, kdf } from '../encryption/kdf'; import i18n from 'i18next'; export const decryptStoredWallet = async (password, wallet) => { diff --git a/src/utils/generateWallet/generateWallet.ts b/src/utils/generateWallet/generateWallet.ts index ee3a683..977f903 100644 --- a/src/utils/generateWallet/generateWallet.ts +++ b/src/utils/generateWallet/generateWallet.ts @@ -1,7 +1,7 @@ // @ts-nocheck import { crypto, walletVersion } from '../../constants/decryptWallet'; -import { doInitWorkers, kdf } from '../../deps/kdf'; +import { doInitWorkers, kdf } from '../../encryption/kdf'; import PhraseWallet from './phrase-wallet'; import * as WORDLISTS from './wordlists'; import FileSaver from 'file-saver'; diff --git a/src/utils/generateWallet/phrase-wallet.ts b/src/utils/generateWallet/phrase-wallet.ts index 0f21cba..3cd9ed1 100644 --- a/src/utils/generateWallet/phrase-wallet.ts +++ b/src/utils/generateWallet/phrase-wallet.ts @@ -3,208 +3,206 @@ Copyright 2017-2018 @ irontiga and vbcs (original developer) */ -import Base58 from '../../deps/Base58' -import {Sha256, Sha512} from 'asmcrypto.js' -import nacl from '../../deps/nacl-fast' -import utils from '../../utils/utils' +import Base58 from '../../encryption/Base58.js'; +import { Sha256, Sha512 } from 'asmcrypto.js'; +import nacl from '../../encryption/nacl-fast.js'; +import utils from '../../utils/utils'; -import {generateSaveWalletData} from './storeWallet.js' +import { generateSaveWalletData } from './storeWallet.js'; -import publicKeyToAddress from './publicKeyToAddress' -import AltcoinHDWallet from "../../deps/AltcoinHDWallet" +import publicKeyToAddress from './publicKeyToAddress'; +import AltcoinHDWallet from '../../encryption/AltcoinHDWallet.js'; export default class PhraseWallet { - constructor(seed, walletVersion) { + constructor(seed, walletVersion) { + this._walletVersion = walletVersion || 2; + this.seed = seed; - this._walletVersion = walletVersion || 2 - this.seed = seed + this.savedSeedData = {}; + this.hasBeenSaved = false; + } - this.savedSeedData = {} - this.hasBeenSaved = false - } + set seed(seed) { + this._byteSeed = seed; + this._base58Seed = Base58.encode(seed); - set seed(seed) { - this._byteSeed = seed - this._base58Seed = Base58.encode(seed) + this._addresses = []; - this._addresses = [] + this.genAddress(0); + } - this.genAddress(0) - } + getAddress(nonce) { + return this._addresses[nonce]; + } - getAddress(nonce) { - return this._addresses[nonce] - } + get addresses() { + return this._addresses; + } - get addresses() { - return this._addresses - } + get addressIDs() { + return this._addresses.map((addr) => { + return addr.address; + }); + } - get addressIDs() { - return this._addresses.map(addr => { - return addr.address - }) - } + get seed() { + return this._byteSeed; + } - get seed() { - return this._byteSeed - } + addressExists(nonce) { + return this._addresses[nonce] != undefined; + } - addressExists(nonce) { - return this._addresses[nonce] != undefined - } + _genAddressSeed(seed) { + let newSeed = new Sha512().process(seed).finish().result; + newSeed = new Sha512() + .process(utils.appendBuffer(newSeed, seed)) + .finish().result; + return newSeed; + } - _genAddressSeed(seed) { - let newSeed = new Sha512().process(seed).finish().result - newSeed = new Sha512().process(utils.appendBuffer(newSeed, seed)).finish().result - return newSeed - } + genAddress(nonce) { + if (nonce >= this._addresses.length) { + this._addresses.length = nonce + 1; + } - genAddress(nonce) { - if (nonce >= this._addresses.length) { - this._addresses.length = nonce + 1 - } + if (this.addressExists(nonce)) { + return this.addresses[nonce]; + } - if (this.addressExists(nonce)) { - return this.addresses[nonce] - } + const nonceBytes = utils.int32ToBytes(nonce); - const nonceBytes = utils.int32ToBytes(nonce) + let addrSeed = new Uint8Array(); + addrSeed = utils.appendBuffer(addrSeed, nonceBytes); + addrSeed = utils.appendBuffer(addrSeed, this._byteSeed); + addrSeed = utils.appendBuffer(addrSeed, nonceBytes); - let addrSeed = new Uint8Array() - addrSeed = utils.appendBuffer(addrSeed, nonceBytes) - addrSeed = utils.appendBuffer(addrSeed, this._byteSeed) - addrSeed = utils.appendBuffer(addrSeed, nonceBytes) + if (this._walletVersion == 1) { + addrSeed = new Sha256() + .process(new Sha256().process(addrSeed).finish().result) + .finish().result; - if (this._walletVersion == 1) { - addrSeed = new Sha256().process( - new Sha256() - .process(addrSeed) - .finish() - .result - ).finish().result + addrSeed = this._byteSeed; + } else { + addrSeed = this._genAddressSeed(addrSeed).slice(0, 32); + } - addrSeed = this._byteSeed - } else { - addrSeed = this._genAddressSeed(addrSeed).slice(0, 32) - } + const addrKeyPair = nacl.sign.keyPair.fromSeed(new Uint8Array(addrSeed)); - const addrKeyPair = nacl.sign.keyPair.fromSeed(new Uint8Array(addrSeed)); + const address = publicKeyToAddress(addrKeyPair.publicKey); + const qoraAddress = publicKeyToAddress(addrKeyPair.publicKey, true); - const address = publicKeyToAddress(addrKeyPair.publicKey); - const qoraAddress = publicKeyToAddress(addrKeyPair.publicKey, true); + // Create Bitcoin HD Wallet + const btcSeed = [...addrSeed]; + const btcWallet = new AltcoinHDWallet({ + mainnet: { + private: 0x0488ade4, + public: 0x0488b21e, + prefix: 0, + }, + testnet: { + private: 0x04358394, + public: 0x043587cf, + prefix: 0x6f, + }, + }).createWallet(new Uint8Array(btcSeed), false); - // Create Bitcoin HD Wallet - const btcSeed = [...addrSeed]; - const btcWallet = new AltcoinHDWallet({ - mainnet: { - private: 0x0488ADE4, - public: 0x0488B21E, - prefix: 0 - }, - testnet: { - private: 0x04358394, - public: 0x043587CF, - prefix: 0x6F - } - }).createWallet(new Uint8Array(btcSeed), false); + // Create Litecoin HD Wallet + const ltcSeed = [...addrSeed]; + const ltcWallet = new AltcoinHDWallet({ + mainnet: { + private: 0x0488ade4, + public: 0x0488b21e, + prefix: 0x30, + }, + testnet: { + private: 0x04358394, + public: 0x043587cf, + prefix: 0x6f, + }, + }).createWallet(new Uint8Array(ltcSeed), false, 'LTC'); - // Create Litecoin HD Wallet - const ltcSeed = [...addrSeed]; - const ltcWallet = new AltcoinHDWallet({ - mainnet: { - private: 0x0488ADE4, - public: 0x0488B21E, - prefix: 0x30 - }, - testnet: { - private: 0x04358394, - public: 0x043587CF, - prefix: 0x6F - } - }).createWallet(new Uint8Array(ltcSeed), false, 'LTC'); + // Create Dogecoin HD Wallet + const dogeSeed = [...addrSeed]; + const dogeWallet = new AltcoinHDWallet({ + mainnet: { + private: 0x02fac398, + public: 0x02facafd, + prefix: 0x1e, + }, + testnet: { + private: 0x04358394, + public: 0x043587cf, + prefix: 0x71, + }, + }).createWallet(new Uint8Array(dogeSeed), false, 'DOGE'); - // Create Dogecoin HD Wallet - const dogeSeed = [...addrSeed]; - const dogeWallet = new AltcoinHDWallet({ - mainnet: { - private: 0x02FAC398, - public: 0x02FACAFD, - prefix: 0x1E - }, - testnet: { - private: 0x04358394, - public: 0x043587CF, - prefix: 0x71 - } - }).createWallet(new Uint8Array(dogeSeed), false, 'DOGE'); + // Create Digibyte HD Wallet + const dgbSeed = [...addrSeed]; + const dgbWallet = new AltcoinHDWallet({ + mainnet: { + private: 0x0488ade4, + public: 0x0488b21e, + prefix: 0x1e, + }, + testnet: { + private: 0x04358394, + public: 0x043587cf, + prefix: 0x7e, + }, + }).createWallet(new Uint8Array(dgbSeed), false, 'DGB'); - // Create Digibyte HD Wallet - const dgbSeed = [...addrSeed]; - const dgbWallet = new AltcoinHDWallet({ - mainnet: { - private: 0x0488ADE4, - public: 0x0488B21E, - prefix: 0x1E - }, - testnet: { - private: 0x04358394, - public: 0x043587CF, - prefix: 0x7E - } - }).createWallet(new Uint8Array(dgbSeed), false, 'DGB'); + // Create Ravencoin HD Wallet + const rvnSeed = [...addrSeed]; + const rvnWallet = new AltcoinHDWallet({ + mainnet: { + private: 0x0488ade4, + public: 0x0488b21e, + prefix: 0x3c, + }, + testnet: { + private: 0x04358394, + public: 0x043587cf, + prefix: 0x6f, + }, + }).createWallet(new Uint8Array(rvnSeed), false, 'RVN'); - // Create Ravencoin HD Wallet - const rvnSeed = [...addrSeed]; - const rvnWallet = new AltcoinHDWallet({ - mainnet: { - private: 0x0488ADE4, - public: 0x0488B21E, - prefix: 0x3C - }, - testnet: { - private: 0x04358394, - public: 0x043587CF, - prefix: 0x6F - } - }).createWallet(new Uint8Array(rvnSeed), false, 'RVN'); + // Create Pirate Chain HD Wallet + const arrrSeed = [...addrSeed]; + const arrrWallet = new AltcoinHDWallet({ + mainnet: { + private: 0x0488ade4, + public: 0x0488b21e, + prefix: [0x16, 0x9a], + }, + testnet: { + private: 0x04358394, + public: 0x043587cf, + prefix: [0x14, 0x51], + }, + }).createWallet(new Uint8Array(arrrSeed), false, 'ARRR'); - // Create Pirate Chain HD Wallet - const arrrSeed = [...addrSeed]; - const arrrWallet = new AltcoinHDWallet({ - mainnet: { - private: 0x0488ADE4, - public: 0x0488B21E, - prefix: [0x16, 0x9A] - }, - testnet: { - private: 0x04358394, - public: 0x043587CF, - prefix: [0x14, 0x51] - } - }).createWallet(new Uint8Array(arrrSeed), false, 'ARRR'); + this._addresses[nonce] = { + address, + btcWallet, + ltcWallet, + dogeWallet, + dgbWallet, + rvnWallet, + arrrWallet, + qoraAddress, + keyPair: { + publicKey: addrKeyPair.publicKey, + privateKey: addrKeyPair.secretKey, + }, + base58PublicKey: Base58.encode(addrKeyPair.publicKey), + seed: addrSeed, + nonce: nonce, + }; + return this._addresses[nonce]; + } - this._addresses[nonce] = { - address, - btcWallet, - ltcWallet, - dogeWallet, - dgbWallet, - rvnWallet, - arrrWallet, - qoraAddress, - keyPair: { - publicKey: addrKeyPair.publicKey, - privateKey: addrKeyPair.secretKey - }, - base58PublicKey: Base58.encode(addrKeyPair.publicKey), - seed: addrSeed, - nonce: nonce - } - return this._addresses[nonce] - } - - generateSaveWalletData(...args) { - return generateSaveWalletData(this, ...args) - } + generateSaveWalletData(...args) { + return generateSaveWalletData(this, ...args); + } } diff --git a/src/utils/generateWallet/publicKeyToAddress.ts b/src/utils/generateWallet/publicKeyToAddress.ts index ef91420..dba25a1 100644 --- a/src/utils/generateWallet/publicKeyToAddress.ts +++ b/src/utils/generateWallet/publicKeyToAddress.ts @@ -1,7 +1,7 @@ // @ts-nocheck -import Base58 from '../../deps/Base58'; -import BROKEN_RIPEMD160 from '../../deps/broken-ripemd160'; -import RIPEMD160 from '../../deps/ripemd160'; +import Base58 from '../../encryption/Base58.js'; +import BROKEN_RIPEMD160 from '../../encryption/broken-ripemd160.js'; +import RIPEMD160 from '../../encryption/ripemd160.js'; import utils from '../../utils/utils'; import { Buffer } from 'buffer'; import { Sha256 } from 'asmcrypto.js'; diff --git a/src/utils/generateWallet/storeWallet.ts b/src/utils/generateWallet/storeWallet.ts index 458543f..c90b549 100644 --- a/src/utils/generateWallet/storeWallet.ts +++ b/src/utils/generateWallet/storeWallet.ts @@ -1,8 +1,8 @@ // @ts-nocheck import { AES_CBC, HmacSha512 } from 'asmcrypto.js'; -import Base58 from '../../deps/Base58'; -import { doInitWorkers, kdf } from '../../deps/kdf.js'; +import Base58 from '../../encryption/Base58.js'; +import { doInitWorkers, kdf } from '../../encryption/kdf.js'; import { crypto as cryptoVals } from '../../constants/decryptWallet.js'; const getRandomValues = crypto diff --git a/src/utils/validateAddress.ts b/src/utils/validateAddress.ts index 4238311..aa01af1 100644 --- a/src/utils/validateAddress.ts +++ b/src/utils/validateAddress.ts @@ -1,6 +1,6 @@ // @ts-nocheck -import Base58 from '../deps/Base58'; +import Base58 from '../encryption/Base58'; export const validateAddress = (address) => { let isAddress = false;