Merge branch '10-wip-utxo-selection-and-storage' into 'main'

Resolve "WIP: UTXO Selection and Storage"

Closes #10

See merge request GeneralProtocols/xo/stack!4
This commit is contained in:
Jim Hamill
2025-01-11 08:39:24 +00:00
156 changed files with 13304 additions and 4595 deletions
-3
View File
@@ -1,3 +0,0 @@
/dist
/node_modules
.eslintrc.js
-13
View File
@@ -1,13 +0,0 @@
{
"extends": [ "@generalprotocols/eslint-config/typescript" ],
"parserOptions":
{
"project": "./tsconfig.json",
"ecmaVersion": "2018",
"sourceType": "module"
},
"env":
{
"jest": true
}
}
-65
View File
@@ -1,65 +0,0 @@
module.exports = {
// https://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy
// This option interrupts the configuration hierarchy at this file
// Remove this if you have an higher level ESLint config file (it usually happens into a monorepos)
root: true,
// https://eslint.vuejs.org/user-guide/#how-to-use-a-custom-parser
// Must use parserOptions instead of "parser" to allow vue-eslint-parser to keep working
// `parser: 'vue-eslint-parser'` is already included with any 'plugin:vue/**' config and should be omitted
parserOptions: {
parser: require.resolve('@typescript-eslint/parser'),
extraFileExtensions: [ '.vue' ]
},
env: {
browser: true,
es2021: true,
node: true,
},
// Rules order is important, please avoid shuffling them
extends: [
// Base ESLint recommended rules
// 'eslint:recommended',
// https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin#usage
// ESLint typescript rules
'plugin:@typescript-eslint/recommended',
// https://github.com/prettier/eslint-config-prettier#installation
// usage with Prettier, provided by 'eslint-config-prettier'.
'prettier'
],
plugins: [
// required to apply rules which need type information
'@typescript-eslint',
// https://github.com/typescript-eslint/typescript-eslint/issues/389#issuecomment-509292674
// Prettier has not been included as plugin to avoid performance impact
// add it as an extension for your IDE
],
// add your custom rules here
rules: {
'prefer-promise-reject-errors': 'off',
quotes: ['warn', 'single', { avoidEscape: true }],
// this rule, if on, would require explicit return type on the `render` function
'@typescript-eslint/explicit-function-return-type': 'off',
// in plain CommonJS modules, you can't use `import foo = require('foo')` to pass this rule, so it has to be disabled
'@typescript-eslint/no-var-requires': 'off',
// The core 'no-unused-vars' rules (in the eslint:recommended ruleset)
// does not work with type definitions
'no-unused-vars': 'off',
// allow debugger during development only
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}
+18 -15
View File
@@ -1,17 +1,20 @@
node_modules/
.nyc_output/
dist/
coverage/
.vscode
yarn.lock
yarn-error.log
unit-tests.xml
e2e-tests.xml
# Dependencies
**/node_modules
# Ignore Vitepress builds/cache/generated-API.
docs/.vitepress/dist
docs/.vitepress/cache
docs/api
# Testing and coverage
**/.nyc_output
**/coverage
**/unit-tests.xml
**/e2e-tests.xml
# Ignore any lerna debug output.
lerna-debug.log
# Build outputs
**/dist
**/tsconfig.tsbuildinfo
# Editor
**/.vscode
# Logs and debug files
**/yarn.lock
**/yarn-error.log
**/lerna-debug.log
+3 -3
View File
@@ -23,9 +23,9 @@ pages:
stage: publish
script:
- npm run docs:build
- mv docs/.vitepress/dist public
- mv packages/docs/dist public
artifacts:
paths:
- public
only:
- main
# only:
# - main
+16
View File
@@ -72,11 +72,13 @@ npm run dev
## Useful NPM Workspace Commands
- List all packages in the workspace:
```bash
npm ls -w
```
- Run a command in a specific package:
```bash
npm run <command> --workspace=@my-monorepo/<package-name>
```
@@ -85,3 +87,17 @@ npm run dev
```bash
npm install <dependency> --workspace=@my-monorepo/<package-name>
```
## Refactor details
We will want to use inheritance in place of IWallet, etc. A neat structure to refactor to is:
- /theThing/
- base-thing.ts
- types.ts
- utils.ts
- ...
- Rename IndexedCollection to ExtMap.
- Rename from method to fromArray.
- Have the from method accept an object.
-92
View File
@@ -1,92 +0,0 @@
import { defineConfig } from 'vitepress';
import typedocSidebar from '../api/typedoc-sidebar.json';
function capitalizeFirstLetter(str: string) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
// NOTE: We can filter the generated sidebar to produce relevant links to documentation.
// See the contents of the typedocSidear import for structure.
function classesOnlySidebar() {
return typedocSidebar.map((rootItem) => {
const srcItem = rootItem.items.find(
(childItem) => childItem.text === 'src'
);
const classes = srcItem?.items.find(
(childItem) => childItem.text === 'Classes'
);
return {
...rootItem,
text: capitalizeFirstLetter(rootItem.text),
items: classes?.items,
};
});
}
// https://vitepress.dev/reference/site-config
export default defineConfig({
title: 'Documentation',
description: 'Documentation and guide for the XO Stack',
themeConfig: {
// Set the logo
logo: {
light: '/logo-light.svg',
dark: '/logo-dark.svg',
},
// Enable search functionality.
search: {
provider: 'local',
},
// https://vitepress.dev/reference/default-theme-config
nav: [
{ text: 'Home', link: '/' },
{ text: 'Tools', link: '/tools' },
],
sidebar: [
{
text: 'Guide',
items: [
{ text: 'Quick Start', link: '/markdown-examples' },
{ text: 'Best Practices', link: '/api-examples' },
],
},
{
text: 'Frameworks',
items: [
{ text: 'Vue', link: '/frameworks/vue' },
{ text: 'React', link: '/frameworks/react' },
{ text: 'Svelte', link: '/frameworks/svelte' },
],
},
{
text: 'API',
// NOTE: In future, we may want to manually specify API items in the sidebar.
// This would allow us to keep some experimental things undocumented.
// But, for now, let's use an autogenerated sidebar so that we don't have to maintain this.
// We can polish it later.
items: classesOnlySidebar(),
},
],
socialLinks: [
{ icon: 'github', link: 'https://gitlab.com/GeneralProtocols/xo/stack' },
],
// This is the outline on the right-hand side of the page.
outline: {
level: [2, 3],
label: 'On this page',
},
},
head: [['link', { rel: 'icon', href: '/favicon.png' }]]
});
-144
View File
@@ -1,144 +0,0 @@
/**
* Customize default theme styling by overriding CSS variables:
* https://github.com/vuejs/vitepress/blob/main/src/client/theme-default/styles/vars.css
*/
/**
* Colors
*
* Each colors have exact same color scale system with 3 levels of solid
* colors with different brightness, and 1 soft color.
*
* - `XXX-1`: The most solid color used mainly for colored text. It must
* satisfy the contrast ratio against when used on top of `XXX-soft`.
*
* - `XXX-2`: The color used mainly for hover state of the button.
*
* - `XXX-3`: The color for solid background, such as bg color of the button.
* It must satisfy the contrast ratio with pure white (#ffffff) text on
* top of it.
*
* - `XXX-soft`: The color used for subtle background such as custom container
* or badges. It must satisfy the contrast ratio when putting `XXX-1` colors
* on top of it.
*
* The soft color must be semi transparent alpha channel. This is crucial
* because it allows adding multiple "soft" colors on top of each other
* to create a accent, such as when having inline code block inside
* custom containers.
*
* - `default`: The color used purely for subtle indication without any
* special meanings attched to it such as bg color for menu hover state.
*
* - `brand`: Used for primary brand colors, such as link text, button with
* brand theme, etc.
*
* - `tip`: Used to indicate useful information. The default theme uses the
* brand color for this by default.
*
* - `warning`: Used to indicate warning to the users. Used in custom
* container, badges, etc.
*
* - `danger`: Used to show error, or dangerous message to the users. Used
* in custom container, badges, etc.
* -------------------------------------------------------------------------- */
:root {
--vp-c-default-1: var(--vp-c-gray-1);
--vp-c-default-2: var(--vp-c-gray-2);
--vp-c-default-3: var(--vp-c-gray-3);
--vp-c-default-soft: var(--vp-c-gray-soft);
--vp-c-brand-1: var(--vp-c-indigo-1);
--vp-c-brand-2: var(--vp-c-indigo-2);
--vp-c-brand-3: var(--vp-c-indigo-3);
--vp-c-brand-soft: var(--vp-c-indigo-soft);
--vp-c-tip-1: var(--vp-c-brand-1);
--vp-c-tip-2: var(--vp-c-brand-2);
--vp-c-tip-3: var(--vp-c-brand-3);
--vp-c-tip-soft: var(--vp-c-brand-soft);
--vp-c-warning-1: var(--vp-c-yellow-1);
--vp-c-warning-2: var(--vp-c-yellow-2);
--vp-c-warning-3: var(--vp-c-yellow-3);
--vp-c-warning-soft: var(--vp-c-yellow-soft);
--vp-c-danger-1: var(--vp-c-red-1);
--vp-c-danger-2: var(--vp-c-red-2);
--vp-c-danger-3: var(--vp-c-red-3);
--vp-c-danger-soft: var(--vp-c-red-soft);
}
/**
* Component: Button
* -------------------------------------------------------------------------- */
:root {
--vp-button-brand-border: transparent;
--vp-button-brand-text: var(--vp-c-white);
--vp-button-brand-bg: var(--vp-c-brand-3);
--vp-button-brand-hover-border: transparent;
--vp-button-brand-hover-text: var(--vp-c-white);
--vp-button-brand-hover-bg: var(--vp-c-brand-2);
--vp-button-brand-active-border: transparent;
--vp-button-brand-active-text: var(--vp-c-white);
--vp-button-brand-active-bg: var(--vp-c-brand-1);
}
/**
* Component: Home
* -------------------------------------------------------------------------- */
:root {
--vp-home-hero-name-color: transparent;
--vp-home-hero-name-background: -webkit-linear-gradient(
120deg,
#38b6ff 30%,
#5271ff
);
/*
--vp-home-hero-image-background-image: linear-gradient(
-45deg,
#5271ff 50%,
#38b6ff 50%
);
--vp-home-hero-image-filter: blur(44px);
*/
}
@media (min-width: 640px) {
:root {
--vp-home-hero-image-filter: blur(56px);
}
}
@media (min-width: 960px) {
:root {
--vp-home-hero-image-filter: blur(68px);
}
}
/**
* Component: Custom Block
* -------------------------------------------------------------------------- */
:root {
--vp-custom-block-tip-border: transparent;
--vp-custom-block-tip-text: var(--vp-c-text-1);
--vp-custom-block-tip-bg: var(--vp-c-brand-soft);
--vp-custom-block-tip-code-bg: var(--vp-c-brand-soft);
}
/**
* Component: Algolia
* -------------------------------------------------------------------------- */
.DocSearch {
--docsearch-primary-color: var(--vp-c-brand-1) !important;
}
-45
View File
@@ -1,45 +0,0 @@
---
# VitePress configuration
layout: home
hero:
name: "XO Stack"
text: "Documentation"
tagline: Building smart applications on the Bitcoin Cash UTXO Network
actions:
- theme: brand
text: Quick Start
link: /markdown-examples.html
- theme: brand
text: GitHub
link: https://gitlab.com/GeneralProtocols/xo/stack
features:
- icon:
light: /icons/api-light.svg
dark: /icons/api-dark.svg
title: API
details: Access powerful APIs to build smart apps on the BCH UTXO Network.
- icon:
light: /icons/framework-light.svg
dark: /icons/framework-dark.svg
title: Framework
details: A solid framework for building scalable applications.
- icon:
light: /icons/tools-light.svg
dark: /icons/tools-dark.svg
title: Tools
details: Essential tools to streamline development and deployment.
---
<!-- Logo section -->
<div class="vp-doc" style="text-align: center; margin: 15px;">
<h4>Developed by:</h4>
</div>
<div style="text-align: center; margin: 10px;">
<a href="https://generalprotocols.com" target="_blank" style="display: inline-block;">
<img class="light-only" src="./gp_logo_light.png" alt="GP Logo" style="width: 100px; height: auto;">
<img class="dark-only" src="./gp_logo_dark.png" alt="GP Logo" style="width: 100px; height: auto;">
</a>
</div>
-85
View File
@@ -1,85 +0,0 @@
# Markdown Extension Examples
This page demonstrates some of the built-in markdown extensions provided by VitePress.
## Syntax Highlighting
VitePress provides Syntax Highlighting powered by [Shiki](https://github.com/shikijs/shiki), with additional features like line-highlighting:
**Input**
````md
```js{4}
export default {
data () {
return {
msg: 'Highlighted!'
}
}
}
```
````
**Output**
```js{4}
export default {
data () {
return {
msg: 'Highlighted!'
}
}
}
```
## Custom Containers
**Input**
```md
::: info
This is an info box.
:::
::: tip
This is a tip.
:::
::: warning
This is a warning.
:::
::: danger
This is a dangerous warning.
:::
::: details
This is a details block.
:::
```
**Output**
::: info
This is an info box.
:::
::: tip
This is a tip.
:::
::: warning
This is a warning.
:::
::: danger
This is a dangerous warning.
:::
::: details
This is a details block.
:::
## More
Check out the documentation for the [full list of markdown extensions](https://vitepress.dev/guide/markdown).
-7
View File
@@ -1,7 +0,0 @@
# Tools
May want to have a Tools/Sandbox section.
I'd leave until later before exploring this more, but it sounds like we can (technically) create custom components.
https://vitepress.dev/guide/using-vue
+34
View File
@@ -0,0 +1,34 @@
// @ts-check
import eslint from '@eslint/js';
import prettierConfig from 'eslint-config-prettier';
import tseslint from 'typescript-eslint';
export default tseslint.config(
eslint.configs.recommended,
...tseslint.configs.recommended,
prettierConfig,
{
// Ignore the following directory patterns.
ignores: [
'**/dist/**',
'**/docs/**',
'**/examples/**',
'**/experiments/**',
'**/node_modules/**',
],
},
{
rules: {
// Allow unused variables if they're prefixed with '_'.
'@typescript-eslint/no-unused-vars': [
'warn',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
},
],
},
},
);
+15
View File
@@ -0,0 +1,15 @@
import { Bytes, Crypto } from '@xo/primitives';
const payload = Bytes.fromHex(
'00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff',
);
console.time('sha256');
for (let i = 0; i < 10_000; i++) {
Crypto.sha256(payload.toBytes());
}
// NOTE: Around 100ms for 10,000 SHA256's on my machine.
// Not too bad, but might still be worth avoiding if trivial.
console.timeEnd('sha256');
+3 -3
View File
@@ -42,18 +42,18 @@ await blockchainLocal.broadcastTransaction(coinbaseTransaction, {
console.log('walletP2PKH unspents', await walletP2PKH.fetchUnspentDirectives());
console.log(
'walletP2PKHReceive unspents',
await walletP2PKHReceive.fetchUnspentDirectives()
await walletP2PKHReceive.fetchUnspentDirectives(),
);
const sweepTx = await walletP2PKH.sweep(
walletP2PKHReceive.getAddress().toLockscriptBytes()
walletP2PKHReceive.getAddress().toLockscriptBytes(),
);
await blockchainLocal.broadcastTransaction(sweepTx);
console.log('walletP2PKH unspents', await walletP2PKH.fetchUnspentDirectives());
console.log(
'walletP2PKHReceive unspents',
await walletP2PKHReceive.fetchUnspentDirectives()
await walletP2PKHReceive.fetchUnspentDirectives(),
);
console.log(blockchainLocal.deriveUtxoSet());
+2 -2
View File
@@ -4,14 +4,14 @@ import { Blockchain, WalletHD } from '@xo/wallet';
const blockchain = new Blockchain(
['bch.imaginary.cash', 'cashnode.bch.ninja', 'electrum.imaginary.cash'],
'Test App',
'1.5'
'1.5',
);
await blockchain.start();
const wallet = WalletHD.fromMnemonic(
'harsh gospel job ordinary garden clay eight cactus replace general prison permit',
blockchain
blockchain,
);
await wallet.scan();
+48
View File
@@ -0,0 +1,48 @@
import { BlockchainElectrum, StorageMemory, WalletHD } from '@xo/wallet';
const ELECTRUM_SERVERS = [
'bch.imaginary.cash',
'cashnode.bch.ninja',
'electrum.imaginary.cash',
];
const blockchainElectrum = new BlockchainElectrum(ELECTRUM_SERVERS);
await blockchainElectrum.start();
const storage = new StorageMemory();
const walletStore = await storage.getChild('wallets');
const walletOneStore = await walletStore.getChild('1');
console.log(walletOneStore);
const cache = new StorageMemory();
const services = {
blockchain: blockchainElectrum,
storage: walletOneStore,
cache: cache,
};
const wallet = await WalletHD.from(
{
mnemonic:
'grape amazing region hand script truck veteran tilt gaze rough despair guard',
},
blockchain,
walletOneStore,
cache,
);
await wallet.start();
console.log(await storage.export());
const txs = await wallet.fetchTransactions();
console.log(txs);
const wallet2 = await WalletHD.fromStorage(services);
await wallet2.start();
console.log(await wallet2.fetchTransactions());
+72
View File
@@ -0,0 +1,72 @@
import { Transaction } from '@xo/primitives';
import { BlockchainLocal, WalletP2PKH } from '@xo/wallet';
const blockchainLocal = new BlockchainLocal();
await blockchainLocal.start();
const services = {
blockchain: blockchainLocal,
};
const walletP2PKH = WalletP2PKH.generateRandom(services);
const walletP2PKHReceive = WalletP2PKH.generateRandom(services);
const coinbaseTransaction = new Transaction({
version: 2,
locktime: 0,
inputs: [
{
outpointIndex: 0,
outpointTransactionHash: new Uint8Array(),
unlockingBytecode: new Uint8Array(),
sequenceNumber: 0,
},
],
outputs: [
{
lockingBytecode: (
await walletP2PKH.getReceivingAddress()
).toLockscriptBytes(),
valueSatoshis: 100_000n,
},
{
lockingBytecode: (
await walletP2PKH.getReceivingAddress()
).toLockscriptBytes(),
valueSatoshis: 150_000n,
},
],
});
await blockchainLocal.broadcastTransaction(coinbaseTransaction, {
skipValidation: true,
});
console.log('walletP2PKH unspents', await walletP2PKH.fetchUnspentDirectives());
console.log(
'walletP2PKHReceive unspents',
await walletP2PKHReceive.fetchUnspentDirectives(),
);
const sendTx = await walletP2PKH.send({
outputs: [
{
lockingBytecode: (
await walletP2PKHReceive.getReceivingAddress()
).toLockscriptBytes(),
valueSatoshis: 150_000n,
},
],
});
console.log(sendTx);
// await blockchainLocal.broadcastTransaction(new Transaction(sendTx));
console.log('walletP2PKH unspents', await walletP2PKH.fetchUnspentDirectives());
console.log(
'walletP2PKHReceive unspents',
await walletP2PKHReceive.fetchUnspentDirectives(),
);
console.log(blockchainLocal.deriveUtxoSet());
+4 -4
View File
@@ -13,7 +13,7 @@ class WalletHDReact extends WalletHD<WalletP2PKHReact> {
node: HdPrivateNodeValid,
electrum: Blockchain,
walletFactory = (privateKeyBytes: Uint8Array, electrum: Blockchain) =>
new WalletP2PKHReact(privateKeyBytes, electrum)
new WalletP2PKHReact(privateKeyBytes, electrum),
) {
super(node, electrum, walletFactory);
@@ -66,17 +66,17 @@ class WalletHDReact extends WalletHD<WalletP2PKHReact> {
export function useWalletHD(node: HdPrivateNodeValid, electrum: Blockchain) {
const walletHD = useMemo(
() => new WalletHDReact(node, electrum),
[node, electrum]
[node, electrum],
);
const wallets = useSyncExternalStore(
walletHD.subscribeToWallets,
walletHD.getWallets
walletHD.getWallets,
);
const shouldMonitor = useSyncExternalStore(
walletHD.subscribeToShouldMonitor,
walletHD.getShouldMonitor
walletHD.getShouldMonitor,
);
const balance = useMemo(() => {
+4 -4
View File
@@ -8,21 +8,21 @@ import {
export function useWalletP2PKH(
privateKeyBytes: Uint8Array,
electrum: Blockchain
electrum: Blockchain,
) {
const wallet = React.useMemo(
() => new WalletP2PKHReact(privateKeyBytes, electrum),
[privateKeyBytes, electrum]
[privateKeyBytes, electrum],
);
const unspents = useSyncExternalStore(
wallet.subscribeToUnspents,
wallet.getUnspents
wallet.getUnspents,
);
const transactions = useSyncExternalStore(
wallet.subscribeToTransactions,
wallet.getTransactions
wallet.getTransactions,
);
const balance = React.useMemo(() => {
+5 -5
View File
@@ -12,7 +12,7 @@ export class WalletP2PKHSvelte extends WalletP2PKH {
// Derived store for balance
public balance: Readable<number> = derived(this.unspents, ($unspents) =>
$unspents.reduce((total, unspent) => total + unspent.value, 0)
$unspents.reduce((total, unspent) => total + unspent.value, 0),
);
constructor(privateKeyBytes: Uint8Array, electrum: Blockchain) {
@@ -28,7 +28,7 @@ export class WalletP2PKHSvelte extends WalletP2PKH {
export function useWalletP2PKHSvelte(
privateKeyBytes: Uint8Array,
electrum: Blockchain
electrum: Blockchain,
): WalletP2PKHSvelte {
return new WalletP2PKHSvelte(privateKeyBytes, electrum);
}
@@ -44,18 +44,18 @@ export class WalletHDSvelte extends WalletHD<WalletP2PKHSvelte> {
let walletBalance = 0;
wallet.balance.subscribe((value) => (walletBalance = value))();
return total + walletBalance;
}, 0)
}, 0),
);
constructor(
node: HdPrivateNodeValid,
electrum: Blockchain,
walletFactory = useWalletP2PKHSvelte
walletFactory = useWalletP2PKHSvelte,
) {
super(node, electrum, walletFactory);
this.events.on('walletsUpdated', (wallets) => this.wallets.set(wallets));
this.events.on('shouldMonitorUpdated', (shouldMonitor) =>
this.shouldMonitor.set(shouldMonitor)
this.shouldMonitor.set(shouldMonitor),
);
}
}
+1 -3
View File
@@ -1,7 +1,5 @@
{
"$schema": "node_modules/lerna/schemas/lerna-schema.json",
"packages": [
"packages/*"
],
"packages": ["packages/*"],
"version": "0.0.0"
}
+3298 -2048
View File
File diff suppressed because it is too large Load Diff
+26 -15
View File
@@ -11,17 +11,25 @@
"packages/*"
],
"scripts": {
"bench": "lerna run bench",
"build": "lerna run build",
"build:primitives": "lerna run build --scope=@xo/primitives --include-dependencies",
"build:wallet": "lerna run build --scope=@xo/wallet --include-dependencies",
"build:vue": "lerna run build --scope=@xo/vue --include-dependencies",
"docs:api": "typedoc --skipErrorChecking",
"docs:dev": "npm run docs:api && vitepress dev docs",
"docs:build": "npm run docs:api && vitepress build docs",
"docs:preview": "npm run docs:api && vitepress preview docs",
"build:primitives": "lerna run build --scope=@xocash/primitives --include-dependencies",
"build:stack": "lerna run build --scope=@xocash/stack --include-dependencies",
"build:vue": "lerna run build --scope=@xocash/vue --include-dependencies",
"build:json-payment-protocol-v2": "lerna run build --scope=@xocash/json-payment-protocol-v2 --include-dependencies",
"docs:api": "lerna run api --scope=@xocash/docs --include-dependencies",
"docs:dev": "lerna run dev --scope=@xocash/docs --include-dependencies",
"docs:build": "lerna run build --scope=@xocash/docs --include-dependencies",
"docs:preview": "lerna run preview --scope=@xocash/docs --include-dependencies",
"format": "prettier --write \"**/*.{js,ts,md,json}\" --ignore-path .gitignore",
"lint": "eslint .",
"test": "ava"
"madge": "npx madge --circular ./packages",
"test": "lerna run test",
"test:coverage": "lerna run test:coverage",
"version:patch": "lerna version patch",
"version:minor": "lerna version minor",
"version:major": "lerna version major",
"watch": "lerna run watch --parallel"
},
"repository": {
"type": "git",
@@ -43,16 +51,19 @@
"@bitauth/libauth": "^3.0.0"
},
"devDependencies": {
"@eslint/js": "^9.10.0",
"@types/eslint__js": "^8.42.3",
"@typescript-eslint/eslint-plugin": "^8.5.0",
"@typescript-eslint/parser": "^8.5.0",
"@vitest/coverage-v8": "^2.1.6",
"eslint": "^9.10.0",
"eslint-config-prettier": "^8.1.0",
"eslint-config-prettier": "^8.10.0",
"eslint-plugin-prettier": "^5.2.1",
"lerna": "^8.1.8",
"prettier": "^2.5.1",
"typedoc": "^0.26.6",
"typedoc-plugin-markdown": "^4.2.6",
"typedoc-vitepress-theme": "^1.0.1",
"typescript": "^5.1.3",
"vitepress": "^1.3.4"
"madge": "^8.0.0",
"prettier": "^3.3.3",
"typescript": "5.7.2",
"typescript-eslint": "^8.6.0",
"vitest": "^2.1.6"
}
}
+8
View File
@@ -0,0 +1,8 @@
# Ignore the generated Vitepress build.
dist/
# Ignore Generated API Markdown Files
src/api
# Ignore Vitepress Cache
src/.vitepress/cache
+25
View File
@@ -0,0 +1,25 @@
{
"name": "@xocash/docs",
"version": "0.0.1",
"description": "XO Cash Stack Documentation",
"private": true,
"type": "module",
"scripts": {
"api": "typedoc --skipErrorChecking",
"build": "npm run api && vitepress build src",
"dev": "npm run api && vitepress dev src",
"preview": "npm run api && vitepress preview src"
},
"author": "",
"license": "ISC",
"dependencies": {
"@xocash/primitives": "*",
"@xocash/stack": "*"
},
"devDependencies": {
"typedoc": "^0.27.5",
"typedoc-plugin-markdown": "^4.3.2",
"typedoc-vitepress-theme": "^1.1.1",
"vitepress": "^1.3.4"
}
}
+215
View File
@@ -0,0 +1,215 @@
import { defineConfig } from 'vitepress';
import typedocSidebar from '../api/typedoc-sidebar.json';
// Special cases map for acronyms and exceptions
const SPECIAL_CASES = {
hd: 'HD',
indexeddb: 'IndexedDB',
inmemory: 'InMemory',
json: 'JSON',
p2p: 'P2P',
p2pkh: 'P2PKH',
p2sh: 'P2SH',
p2sh20: 'P2SH20',
p2sh32: 'P2SH32',
sse: 'SSE',
utxo: 'UTXO',
};
function toPascalCase(str: string) {
// Handle special cases first
const lowerStr = str.toLowerCase();
if (lowerStr.startsWith('@')) {
return str;
}
// Split by common delimiters (hyphen, space, underscore)
return str
.split(/[-\s_]/)
.map((word) => {
if (word.length === 0) return '';
if (SPECIAL_CASES[word]) {
return SPECIAL_CASES[word];
}
// Capitalize first letter, lowercase rest
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
})
.join('');
}
function convertNavToPascalCase(nav: Array<any>) {
return nav.map((item) => {
const result = { ...item };
// Convert the text field
if (result.text) {
// If there was a @ prefix, preserve it
result.text = item.text.startsWith('@')
? result.text
: toPascalCase(result.text);
}
// Recursively process nested items
if (result.items && Array.isArray(result.items)) {
result.items = convertNavToPascalCase(result.items);
}
return result;
});
}
// https://vitepress.dev/reference/site-config
export default defineConfig({
outDir: '../dist',
title: 'Stack',
description:
'XO Stack: Building smart applications on the Bitcoin Cash Network',
themeConfig: {
// Set the logo
logo: {
light: '/logo-light.svg',
dark: '/logo-dark.svg',
},
// Enable search functionality.
// TODO: Re-enable once we release documentation.
/*
search: {
provider: 'local',
},
*/
// https://vitepress.dev/reference/default-theme-config
nav: [
{ text: 'Home', link: '/' },
// TODO: Re-enable once we release documentation
// { text: 'Documentation', link: '/quick-start' },
{ text: 'Tools', link: '/tools/primitives' },
],
sidebar: {
// Default Side Menu.
'/': [
{
text: 'Guide',
items: [
{ text: 'Quick Start', link: '/quick-start' },
{ text: 'Best Practices', link: '/api-examples' },
],
},
{
text: 'Frameworks',
items: [
{ text: 'Vue', link: '/frameworks/vue' },
{ text: 'React', link: '/frameworks/react' },
{ text: 'Svelte', link: '/frameworks/svelte' },
],
},
{
text: 'API',
items: convertNavToPascalCase(typedocSidebar),
},
],
// Side-menu for all routes under /tools/
'/tools/': [
{
text: 'XO Tools',
items: [
{
text: 'Primitives',
link: '/tools/primitives',
collapsed: false,
items: [
{ text: 'Address', link: '/tools/primitives#address' },
{
text: 'Block Header',
link: '/tools/primitives#block-header',
},
{ text: 'Bytes', link: '/tools/primitives#bytes' },
{ text: 'Hasher', link: '/tools/primitives#hasher' },
{
text: 'HD Private Node',
link: '/tools/primitives#hd-private-node',
},
{
text: 'HD Public Node',
link: '/tools/primitives#hd-public-node',
},
{
text: 'Mnemonic',
link: '/tools/primitives#mnemonic',
},
{
text: 'Private Key',
link: '/tools/primitives#private-key',
},
{
text: 'Public Key',
link: '/tools/primitives#public-key',
},
{
text: 'Satoshis',
link: '/tools/primitives#satoshis',
},
{
text: 'Script',
link: '/tools/primitives#script',
},
{
text: 'Transaction',
link: '/tools/primitives#transaction',
},
],
},
/*
{
text: 'Stack',
collapsed: false,
items: [
{
text: 'Blockchain',
items: [{ text: 'Blockchain Electrum' }],
},
],
},
*/
],
},
],
},
/*
*/
socialLinks: [
{ icon: 'github', link: 'https://gitlab.com/GeneralProtocols/xo/stack' },
],
// This is the outline on the right-hand side of the page.
outline: {
level: [2, 4],
label: 'On this page',
},
},
head: [['link', { rel: 'icon', href: '/favicon.png' }]],
// Set the dev and build targets to "esnext"
// NOTE: We do this so that we can support top-level-await.
vite: {
esbuild: {
target: 'esnext',
},
build: {
target: 'esnext',
},
optimizeDeps: {
esbuildOptions: {
target: 'esnext',
},
},
},
});
@@ -0,0 +1,107 @@
<template>
<Tooltip :show="showTooltip && !isCopied">
<button
class="copy-button"
:class="{ 'copied': isCopied }"
@click="handleCopy"
@mouseenter="showTooltip = true"
@mouseleave="showTooltip = false"
>
<Transition mode="out-in">
<img v-if="!isCopied" key="icon" src="../icons/copy.svg" alt="Copy" class="copy-icon" />
<span v-else key="text" class="copied-text">Copied!</span>
</Transition>
</button>
<template #content>Copy</template>
</Tooltip>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import Tooltip from './Tooltip.vue';
type Props = {
content: string;
}
const props = withDefaults(defineProps<Props>(), {
content: ''
});
const isCopied = ref(false);
const showTooltip = ref(false);
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(props.content);
isCopied.value = true;
showTooltip.value = false;
setTimeout(() => {
isCopied.value = false;
}, 2000);
} catch (err) {
console.error('Failed to copy text: ', err);
}
};
</script>
<style scoped>
.tooltip-container {
position: absolute !important;
top: 5px;
right: 5px;
}
.copy-button {
position: relative;
padding: 5px 10px;
font-size: 1rem;
font-weight: bold;
color: white;
background: var(--vp-home-hero-name-background);
border: none;
border-radius: 5px;
cursor: pointer;
text-transform: uppercase;
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
opacity: 0.9;
width: 2.2em;
height: 2.2em;
overflow: hidden;
transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
display: flex;
align-items: center;
justify-content: center;
}
.copy-button:hover {
opacity: 1;
background: var(--primary);
}
.copy-button.copied {
width: 70px;
}
.copy-icon {
width: 28px;
height: 28px;
filter: invert(1);
}
.copied-text {
font-weight: 600;
white-space: nowrap;
font-size: 0.8rem;
}
.v-enter-active,
.v-leave-active {
transition: opacity 0.2s ease;
}
.v-enter-from,
.v-leave-to {
opacity: 0;
}
</style>
@@ -0,0 +1,74 @@
<template>
<div class="labelled-section-container">
<div class="labelled-section">
{{ content || ' ' }}
</div>
<label class="section-label" :class="{ 'is-floating': hasContent }">
{{ label }}
</label>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
export interface Props {
content?: string
label?: string
}
const props = withDefaults(defineProps<Props>(), {
content: '',
label: ''
})
const hasContent = computed(() => props.content.length > 0)
</script>
<style scoped>
.labelled-section-container {
position: relative;
width: 100%;
margin-bottom: 10px;
}
.labelled-section {
box-sizing: content-box;
padding: 10px 8px;
font-size: 1rem;
border: 1px dashed #ccc;
border-radius: 4px;
background: var(--vp-c-bg);
line-height: 1.5;
min-height: calc(1.5em);
font-family: monospace;
max-width: 100%;
text-wrap: wrap;
overflow-wrap: anywhere;
white-space: pre-wrap;
display: flex;
align-items: center;
}
.section-label {
position: absolute;
left: 10px;
top: 50%;
transform: translateY(-50%);
background: var(--vp-c-bg);
padding: 0 4px;
font-size: 1em;
font-family: monospace;
transition: all 0.2s ease;
opacity: 0.5;
}
.section-label.is-floating {
top: 0;
font-size: 0.8em;
transform: translateY(-50%);
font-style: normal;
color: var(--vp-c-text-2);
opacity: 1.0;
}
</style>
@@ -0,0 +1,238 @@
<template>
<div class="input-wrapper">
<h2>Input</h2>
<div class="form-group-row" :class="{ 'extended': state.selectedFromFunction?.extendedInput }">
<div class="form-group select-group">
<label for="functionSelect">Select Function</label>
<select v-model="state.selectedFromFunction">
<option v-for="fromFunction of props.fromFunctions" :key="fromFunction.label" :value="fromFunction">{{ fromFunction.label }}</option>
</select>
</div>
<div class="form-group input-group" :class="{ 'extended': state.selectedFromFunction?.extendedInput }">
<template v-for="(_input, i) of state.selectedFromFunction.inputs" :key="i">
<label for="field">{{ state.selectedFromFunction.inputs[i] }}</label>
<div>
<textarea
v-if="state.selectedFromFunction?.extendedInput"
v-model="state.selectedFromFunction.models[i]"
class="extended-input"
@input="autoGrow($event.target)"
></textarea>
<input
v-else
type="text"
v-model="state.selectedFromFunction.models[i]"
/>
<div v-if="state.error" class="text-error">{{ state.error }}</div>
</div>
</template>
</div>
</div>
<div>
<button type="submit" class="gradient-button" @click="() => setPrimitive(() => state.selectedFromFunction.callback(state.selectedFromFunction.models))">Create Output</button>
</div>
</div>
<div class="section output-section">
<h2>Output</h2>
<template v-for="(toFunction, i) of toFunctions" :key="i">
<div>
<div class="output-box-container">
<LabelledSection :label="toFunction.label" :content="getPrimitive(() => toFunction.callback(state.primitive))" />
<CopyButton :content="getPrimitive(() => toFunction.callback(state.primitive))" />
</div>
</div>
</template>
<template v-if="state.methods.length && state.primitive">
<h2>Methods</h2>
<div class="form-group-row" :class="{ 'extended': state.selectedMethod?.extendedInput }">
<div class="form-group select-group">
<label for="functionSelect">Select Function</label>
<select v-model="state.selectedMethod">
<option v-for="method of props.methods" :key="method.label" :value="method">{{ method.label }}</option>
</select>
</div>
<div class="form-group input-group" :class="{ 'extended': state.selectedMethod?.extendedInput }">
<template v-for="(_input, i) of state.selectedMethod.inputs" :key="i">
<label for="field">{{ state.selectedMethod.inputs[i] }}</label>
<div>
<textarea
v-if="state.selectedMethod?.extendedInput"
v-model="state.selectedMethod.models[i]"
class="extended-input"
@input="autoGrow($event.target)"
></textarea>
<input
v-else
type="text"
v-model="state.selectedMethod.models[i]"
/>
<div v-if="state.error" class="text-error">{{ state.error }}</div>
</div>
</template>
</div>
</div>
<div>
<button type="submit" class="gradient-button" @click="() => executeMethod(state.selectedMethod.callback(state.primitive, state.selectedMethod.models))">Execute Method</button>
</div>
<!-- Result -->
<div>
<div class="output-box-container">
<LabelledSection label="Result" :content="state.selectedMethod.result" />
<CopyButton :content="state.selectedMethod.result" />
</div>
</div>
</template>
</div>
</template>
<script setup generic="Primitive" lang="ts">
import { ref } from 'vue';
import type { Ref } from 'vue';
import LabelledSection from './LabelledSection.vue';
import CopyButton from './CopyButton.vue';
export interface FromFunction<Primitive> {
// The label of the function
label: string,
// Array of inputs that the function takes
inputs: Array<string>,
// Array of models that the input stores its value in
models: Array<any>,
// Function that takes the models and returns the primitive
callback: (value: Array<any>) => Primitive,
// Whether the input is extended onto a new line
extendedInput?: boolean
}
export interface ToFunction<Primitive> {
label: string;
callback: (primitive: Primitive) => string;
result?: string;
}
export interface Method<Primitive> {
// The label of the function
label: string;
// Array of inputs that the function takes
inputs: Array<string>,
// Array of models that the input stores its value in
models: Array<any>,
// Result of method execution,
result?: string;
// Function that takes the models and returns the primitive
callback: (primitive: Primitive, value: Array<any>) => string;
// Whether the input is extended onto a new line
extendedInput?: boolean
}
export interface Props<Primitive> {
fromFunctions: Array<FromFunction<Primitive>>,
toFunctions: Array<ToFunction<Primitive>>,
methods?: Array<Method<Primitive>>,
}
const props = withDefaults(defineProps<Props<Primitive>>(), {
fromFunctions: () => [],
toFunctions: () => [],
methods: () => [],
});
const state: Ref<{
fromFunctions: Array<FromFunction<Primitive>>,
toFunctions: Array<ToFunction<Primitive>>,
methods: Array<Method<Primitive>>,
// Selected In Function
selectedFromFunction: FromFunction<Primitive>,
// Selected Method
selectedMethod?: Method<Primitive>,
// The Primitive.
primitive?: Primitive,
// Error to display if an invalid input was given.
error?: string;
}> = ref({
// From functions, to functions and methods.
fromFunctions: [ ...props.fromFunctions ],
toFunctions: [ ...props.toFunctions ],
methods: [ ...props.methods ],
// The selected function.
selectedFromFunction: props.fromFunctions[0],
// The selected method.
selectedMethod: props.methods[0] || undefined,
// The Primitive.
primitive: undefined,
})
async function setPrimitive(functionToExecute: () => Primitive | Promise<Primitive>): void {
try {
state.value.primitive = await functionToExecute();
state.value.error = undefined;
state.value.toFunctions.forEach((wrappedMethod, i) => {
state.value.toFunctions[i].result = wrappedMethod.callback(state.value.primitive)
});
} catch(error: any) {
state.value.error = `${error}`;
}
}
function getPrimitive(functionToExecute: () => string): string {
try {
if(!state.value.primitive) {
return '';
}
return functionToExecute();
} catch(error: any) {
return error.message;
}
}
async function executeMethod(wrappedMethod: () => string | Promise<string>): string {
try {
if(!state.value.primitive) {
return '';
}
state.value.selectedMethod.result = await wrappedMethod;
} catch(error: any) {
return error.message;
}
};
// Select the first "from" function.
state.value.selectedFromFunction = state.value.fromFunctions[0];
const autoGrow = (element: HTMLTextAreaElement) => {
element.style.height = 'auto'
element.style.height = `${Math.min(element.scrollHeight, 300)}px`
}
</script>
<style>
.text-error {
color: #f46666;
overflow-wrap: break-word;
}
</style>
@@ -0,0 +1,76 @@
<template>
<div class="tooltip-container">
<slot></slot>
<Transition>
<div v-if="show" class="tooltip" :class="position">
<slot name="content"></slot>
</div>
</Transition>
</div>
</template>
<script setup lang="ts">
type Props = {
show: boolean;
position?: 'top' | 'bottom' | 'left' | 'right';
}
withDefaults(defineProps<Props>(), {
position: 'top',
show: false
});
</script>
<style scoped>
.tooltip-container {
position: relative;
display: inline-block;
}
.tooltip {
position: absolute;
background: var(--vp-c-text-1);
color: var(--vp-c-bg);
padding: 4px 8px;
border-radius: 4px;
font-size: 0.8rem;
white-space: nowrap;
pointer-events: none;
z-index: 100;
}
.tooltip.top {
bottom: 100%;
left: 50%;
transform: translateX(-50%) translateY(-6px);
}
.tooltip.bottom {
top: 100%;
left: 50%;
transform: translateX(-50%) translateY(6px);
}
.tooltip.left {
right: 100%;
top: 50%;
transform: translateY(-50%) translateX(-6px);
}
.tooltip.right {
left: 100%;
top: 50%;
transform: translateY(-50%) translateX(6px);
}
.v-enter-active,
.v-leave-active {
transition: opacity 0.2s ease, transform 0.2s ease;
}
.v-enter-from,
.v-leave-to {
opacity: 0;
transform: translateX(-50%) translateY(0);
}
</style>
@@ -36,6 +36,10 @@ body {
font-size: 12px;
}
ul.VPDocOutlineItem.root {
font-weight: bold;
}
.VPSidebarItem.level-2.is-active > .item > .indicator,
.VPSidebarItem.level-3.is-active > .item > .indicator,
.VPSidebarItem.level-4.is-active > .item > .indicator,
@@ -151,3 +155,10 @@ body {
:root:is(.dark) .light-only {
display: none;
}
/* Text colors */
.text-error {
color: #f46666;
overflow-wrap: break-word;
}
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
<svg fill="#000000" height="800px" width="800px" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="0 0 64 64" enable-background="new 0 0 64 64" xml:space="preserve">
<g id="Text-files" stroke="#000000" stroke-width="2" stroke-linejoin="round">
<path fill-rule="evenodd" d="M53.9791489,9.1429005H50.010849c-0.0826988,0-0.1562004,0.0283995-0.2331009,0.0469999V5.0228
C49.7777481,2.253,47.4731483,0,44.6398468,0h-34.422596C7.3839517,0,5.0793519,2.253,5.0793519,5.0228v46.8432999
c0,2.7697983,2.3045998,5.0228004,5.1378999,5.0228004h6.0367002v2.2678986C16.253952,61.8274002,18.4702511,64,21.1954517,64
h32.783699c2.7252007,0,4.9414978-2.1725998,4.9414978-4.8432007V13.9861002
C58.9206467,11.3155003,56.7043495,9.1429005,53.9791489,9.1429005z M7.1110516,51.8661003V5.0228
c0-1.6487999,1.3938999-2.9909999,3.1062002-2.9909999h34.422596c1.7123032,0,3.1062012,1.3422,3.1062012,2.9909999v46.8432999
c0,1.6487999-1.393898,2.9911003-3.1062012,2.9911003h-34.422596C8.5049515,54.8572006,7.1110516,53.5149002,7.1110516,51.8661003z
M56.8888474,59.1567993c0,1.550602-1.3055,2.8115005-2.9096985,2.8115005h-32.783699
c-1.6042004,0-2.9097996-1.2608986-2.9097996-2.8115005v-2.2678986h26.3541946
c2.8333015,0,5.1379013-2.2530022,5.1379013-5.0228004V11.1275997c0.0769005,0.0186005,0.1504021,0.0469999,0.2331009,0.0469999
h3.9682999c1.6041985,0,2.9096985,1.2609005,2.9096985,2.8115005V59.1567993z"/>
<path fill-rule="evenodd" d="M38.6031494,13.2063999H16.253952c-0.5615005,0-1.0159006,0.4542999-1.0159006,1.0158005
c0,0.5615997,0.4544001,1.0158997,1.0159006,1.0158997h22.3491974c0.5615005,0,1.0158997-0.4542999,1.0158997-1.0158997
C39.6190491,13.6606998,39.16465,13.2063999,38.6031494,13.2063999z"/>
<path fill-rule="evenodd" d="M38.6031494,21.3334007H16.253952c-0.5615005,0-1.0159006,0.4542999-1.0159006,1.0157986
c0,0.5615005,0.4544001,1.0159016,1.0159006,1.0159016h22.3491974c0.5615005,0,1.0158997-0.454401,1.0158997-1.0159016
C39.6190491,21.7877007,39.16465,21.3334007,38.6031494,21.3334007z"/>
<path fill-rule="evenodd" d="M38.6031494,29.4603004H16.253952c-0.5615005,0-1.0159006,0.4543991-1.0159006,1.0158997
s0.4544001,1.0158997,1.0159006,1.0158997h22.3491974c0.5615005,0,1.0158997-0.4543991,1.0158997-1.0158997
S39.16465,29.4603004,38.6031494,29.4603004z"/>
<path fill-rule="evenodd" d="M28.4444485,37.5872993H16.253952c-0.5615005,0-1.0159006,0.4543991-1.0159006,1.0158997
s0.4544001,1.0158997,1.0159006,1.0158997h12.1904964c0.5615025,0,1.0158005-0.4543991,1.0158005-1.0158997
S29.0059509,37.5872993,28.4444485,37.5872993z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.7 KiB

@@ -4,6 +4,7 @@ import DefaultTheme from 'vitepress/theme';
import Layout from './Layout.vue';
import './style.css';
import './custom.css';
import './tools.css';
export default {
extends: DefaultTheme,

Before

Width:  |  Height:  |  Size: 80 KiB

After

Width:  |  Height:  |  Size: 80 KiB

Before

Width:  |  Height:  |  Size: 80 KiB

After

Width:  |  Height:  |  Size: 80 KiB

@@ -0,0 +1,560 @@
/**
* Customize default theme styling by overriding CSS variables:
* https://github.com/vuejs/vitepress/blob/main/src/client/theme-default/styles/vars.css
*/
/**
* Colors
*
* Each colors have exact same color scale system with 3 levels of solid
* colors with different brightness, and 1 soft color.
*
* - `XXX-1`: The most solid color used mainly for colored text. It must
* satisfy the contrast ratio against when used on top of `XXX-soft`.
*
* - `XXX-2`: The color used mainly for hover state of the button.
*
* - `XXX-3`: The color for solid background, such as bg color of the button.
* It must satisfy the contrast ratio with pure white (#ffffff) text on
* top of it.
*
* - `XXX-soft`: The color used for subtle background such as custom container
* or badges. It must satisfy the contrast ratio when putting `XXX-1` colors
* on top of it.
*
* The soft color must be semi transparent alpha channel. This is crucial
* because it allows adding multiple "soft" colors on top of each other
* to create a accent, such as when having inline code block inside
* custom containers.
*
* - `default`: The color used purely for subtle indication without any
* special meanings attched to it such as bg color for menu hover state.
*
* - `brand`: Used for primary brand colors, such as link text, button with
* brand theme, etc.
*
* - `tip`: Used to indicate useful information. The default theme uses the
* brand color for this by default.
*
* - `warning`: Used to indicate warning to the users. Used in custom
* container, badges, etc.
*
* - `danger`: Used to show error, or dangerous message to the users. Used
* in custom container, badges, etc.
* -------------------------------------------------------------------------- */
:root {
--vp-c-default-1: var(--vp-c-gray-1);
--vp-c-default-2: var(--vp-c-gray-2);
--vp-c-default-3: var(--vp-c-gray-3);
--vp-c-default-soft: var(--vp-c-gray-soft);
--vp-c-brand-1: var(--vp-c-indigo-1);
--vp-c-brand-2: var(--vp-c-indigo-2);
--vp-c-brand-3: var(--vp-c-indigo-3);
--vp-c-brand-soft: var(--vp-c-indigo-soft);
--vp-c-tip-1: var(--vp-c-brand-1);
--vp-c-tip-2: var(--vp-c-brand-2);
--vp-c-tip-3: var(--vp-c-brand-3);
--vp-c-tip-soft: var(--vp-c-brand-soft);
--vp-c-warning-1: var(--vp-c-yellow-1);
--vp-c-warning-2: var(--vp-c-yellow-2);
--vp-c-warning-3: var(--vp-c-yellow-3);
--vp-c-warning-soft: var(--vp-c-yellow-soft);
--vp-c-danger-1: var(--vp-c-red-1);
--vp-c-danger-2: var(--vp-c-red-2);
--vp-c-danger-3: var(--vp-c-red-3);
--vp-c-danger-soft: var(--vp-c-red-soft);
}
/**
* Component: Button
* -------------------------------------------------------------------------- */
:root {
--vp-button-brand-border: transparent;
--vp-button-brand-text: var(--vp-c-white);
--vp-button-brand-bg: var(--vp-c-brand-3);
--vp-button-brand-hover-border: transparent;
--vp-button-brand-hover-text: var(--vp-c-white);
--vp-button-brand-hover-bg: var(--vp-c-brand-2);
--vp-button-brand-active-border: transparent;
--vp-button-brand-active-text: var(--vp-c-white);
--vp-button-brand-active-bg: var(--vp-c-brand-1);
}
/**
* Component: Home
* -------------------------------------------------------------------------- */
:root {
--vp-home-hero-name-color: transparent;
--vp-home-hero-name-background: -webkit-linear-gradient(
120deg,
#38b6ff 30%,
#5271ff
);
/*
--vp-home-hero-image-background-image: linear-gradient(
-45deg,
#5271ff 50%,
#38b6ff 50%
);
--vp-home-hero-image-filter: blur(44px);
*/
}
@media (min-width: 640px) {
:root {
--vp-home-hero-image-filter: blur(56px);
}
}
@media (min-width: 960px) {
:root {
--vp-home-hero-image-filter: blur(68px);
}
}
/**
* Component: Custom Block
* -------------------------------------------------------------------------- */
:root {
--vp-custom-block-tip-border: transparent;
--vp-custom-block-tip-text: var(--vp-c-text-1);
--vp-custom-block-tip-bg: var(--vp-c-brand-soft);
--vp-custom-block-tip-code-bg: var(--vp-c-brand-soft);
}
/**
* Component: Algolia
* -------------------------------------------------------------------------- */
.DocSearch {
--docsearch-primary-color: var(--vp-c-brand-1) !important;
}
/**
* Overrides
*/
:root {
--primary: #5271ff;
--vp-nav-logo-height: 48px;
}
html.dark {
--primary: #38b6ff;
}
body {
font-size: 14px;
}
.vp-nav .title {
font-size: 24px !important;
}
.vp-doc h1 {
font-size: 24px;
}
.vp-doc h2 {
font-size: 22px;
color: var(--primary);
font-weight: bold;
margin-top: 15px;
margin-bottom: 5px;
border: none !important;
line-height: 1.2;
}
.vp-doc h3 {
font-size: 16px;
}
.vp-doc h4 {
font-size: 14px;
opacity: 0.75;
}
.VPSidebarItem .text {
font-size: 12px;
}
.VPSidebarItem.level-2.is-active > .item > .indicator,
.VPSidebarItem.level-3.is-active > .item > .indicator,
.VPSidebarItem.level-4.is-active > .item > .indicator,
.VPSidebarItem.level-5.is-active > .item > .indicator {
background-color: var(--primary) !important;
}
.VPSidebarItem.level-0.is-active > .item .link > .text,
.VPSidebarItem.level-1.is-active > .item .link > .text,
.VPSidebarItem.level-2.is-active > .item .link > .text,
.VPSidebarItem.level-3.is-active > .item .link > .text,
.VPSidebarItem.level-4.is-active > .item .link > .text,
.VPSidebarItem.level-5.is-active > .item .link > .text {
color: var(--primary) !important;
}
.VPSidebarItem.level-0.is-link > .item > .link:hover .text,
.VPSidebarItem.level-1.is-link > .item > .link:hover .text,
.VPSidebarItem.level-2.is-link > .item > .link:hover .text,
.VPSidebarItem.level-3.is-link > .item > .link:hover .text,
.VPSidebarItem.level-4.is-link > .item > .link:hover .text,
.VPSidebarItem.level-5.is-link > .item > .link:hover .text {
color: var(--primary) !important;
}
.outline-title {
font-size: 12px !important;
}
.outline-link {
font-size: 12px !important;
}
/* Customization of VitePress CSS */
:root {
--vp-home-hero-name-color: transparent;
--vp-home-hero-name-background: -webkit-linear-gradient(
120deg,
#5271ff,
#38b6ff
);
}
.VPButton.brand {
background: linear-gradient(-45deg, #5271ff, #38b6ff) !important;
}
.VPButton.brand:hover {
background: linear-gradient(45deg, #5271ff, #5271ff) !important;
}
/* .vitepress/theme/custom.css */
.image-container {
display: flex;
justify-content: center;
align-items: center;
height: 100%; /* Ensure it takes up the full height of the parent */
width: 100%; /* Ensure it takes up the full width of the parent */
}
/* .vitepress/theme/custom.css */
/* Container for all icons and arrows */
.icon-container {
display: flex;
align-items: center; /* Align the icons and arrows vertically */
justify-content: center; /* Center the icons and arrows horizontally */
gap: 20px; /* Space between the icons and arrows */
}
/* BCH icon styling */
.bch-icon {
width: 64px;
height: 64px;
transform: rotate(-15deg); /* Rotate the BCH icon by 15 degrees to the left */
fill: currentColor;
}
/* Stack icon styling */
.stack-icon {
width: 64px;
height: 64px;
fill: currentColor;
}
/* Apps icon styling */
.apps-icon {
width: 64px;
height: 64px;
fill: currentColor;
}
/* Arrow between Stack and BCH */
.right-arrow {
width: 24px;
height: 24px;
}
/* Arrow between BCH and Apps */
.left-arrow {
width: 24px;
height: 24px;
}
/* Light / dark mode logos */
:root:not(.dark) .dark-only {
display: none;
}
:root:is(.dark) .light-only {
display: none;
}
/* Feature box override */
.feature-box-or {
flex-direction: row !important;
text-align: center !important;
}
.feature-box-or h2 {
border: none !important;
padding-top: 10px !important;
margin: 0 !important;
}
.feature-box-or img {
margin: auto !important;
}
/* Promo on front page */
.promo {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
padding: 20px;
}
.promo-text {
flex: 2; /* Adjusted flex value for more text space */
min-width: 250px; /* Ensures text is responsive */
}
.promo-text h1 {
font-size: 2rem; /* Adjust font size as needed */
margin: 0;
}
.promo-text p {
font-size: 1.1rem; /* Slightly larger text for better readability */
margin-top: 10px;
}
.promo-text .clip {
background: var(--vp-home-hero-name-background);
-webkit-background-clip: text;
background-clip: text;
color: var(
--vp-home-hero-name-color
); /* Make the text color transparent to reveal background */
font-weight: bold;
padding: 0 5px;
}
.promo-image {
position: relative; /* To position the animated elements inside */
flex: 1; /* Reduce the image's width */
min-width: 150px; /* Ensures the image is smaller */
max-width: 250px; /* Set a max width for the image */
text-align: right;
}
.promo-image img {
max-width: 100%;
height: auto;
position: relative; /* Image is above the animated icons */
z-index: 1; /* Ensure image is in front of the icons */
}
/* X and O animation styles behind promo-image */
.animated-bg {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none; /* Ignore background interactions */
z-index: 0; /* Ensure the animated elements are behind the image */
}
.xo {
position: absolute;
font-size: 1.5rem;
}
.xo-1,
.xo-3 {
color: var(--primary); /* X elements using --primary color */
}
.xo-2,
.xo-4 {
color: var(--vp-c-text-1); /* O elements using --vp-c-text-1 color */
}
/* Unique positions and animations for each XO element */
.xo-1 {
top: 10%;
left: 15%;
animation:
rotate-small 6s infinite linear,
move-elliptical 10s infinite ease-in-out;
}
.xo-2 {
top: 40%;
left: 60%;
animation:
rotate-large 8s infinite linear,
move-circular 12s infinite ease-in-out;
}
.xo-3 {
top: 70%;
left: 30%;
animation:
rotate-reverse 5s infinite linear,
move-diagonal 14s infinite ease-in-out;
}
.xo-4 {
top: 20%;
left: 80%;
animation:
rotate-small-reverse 7s infinite linear,
move-random 16s infinite ease-in-out;
}
/* Keyframe for self-rotation: Small */
@keyframes rotate-small {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
/* Keyframe for self-rotation: Large */
@keyframes rotate-large {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(720deg);
}
}
/* Keyframe for reverse self-rotation */
@keyframes rotate-reverse {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(-360deg);
}
}
@keyframes rotate-small-reverse {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(-720deg);
}
}
/* Keyframe for elliptical movement */
@keyframes move-elliptical {
0% {
transform: translate(0, 0);
}
25% {
transform: translate(60px, 40px);
}
50% {
transform: translate(120px, 0);
}
75% {
transform: translate(60px, -40px);
}
100% {
transform: translate(0, 0);
}
}
/* Keyframe for circular movement */
@keyframes move-circular {
0% {
transform: translate(0, 0);
}
25% {
transform: translate(50px, 50px);
}
50% {
transform: translate(100px, 0);
}
75% {
transform: translate(50px, -50px);
}
100% {
transform: translate(0, 0);
}
}
/* Keyframe for diagonal movement */
@keyframes move-diagonal {
0% {
transform: translate(0, 0);
}
50% {
transform: translate(100px, 100px);
}
100% {
transform: translate(0, 0);
}
}
/* Keyframe for random, unpredictable movement */
@keyframes move-random {
0% {
transform: translate(0, 0);
}
20% {
transform: translate(40px, -30px);
}
40% {
transform: translate(80px, 50px);
}
60% {
transform: translate(-50px, -40px);
}
80% {
transform: translate(30px, 70px);
}
100% {
transform: translate(0, 0);
}
}
@media (max-width: 768px) {
.promo {
flex-direction: column;
text-align: center;
}
.promo-image {
margin-top: 20px;
}
}
@@ -0,0 +1,145 @@
.tool h2 {
font-size: 16px;
}
/* Wrapper for input section */
.input-wrapper {
margin-bottom: 20px;
}
/* Flex container for dropdown and input */
.form-group-row {
display: flex;
flex-wrap: wrap; /* Ensure responsiveness */
gap: 15px; /* Space between dropdown and input */
margin-bottom: 15px;
}
.form-group-row.extended {
flex-direction: column;
}
/* Form group styling */
.form-group {
flex: 1;
min-width: 200px;
}
.select-group {
flex: 1;
min-width: 200px;
max-width: 50%;
}
.input-group {
flex: 1;
min-width: 200px;
}
.input-group.extended {
max-width: 100%;
width: 100%;
}
.form-group label {
display: block;
font-weight: bold;
margin-bottom: 5px;
}
.form-group select,
.form-group input,
.form-group button {
width: 100%; /* Makes fields responsive */
padding: 10px;
font-size: 1rem;
border: 1px solid #ccc;
border-radius: 4px;
}
/* Extended input styling */
.extended-input {
width: 100%;
min-height: 2.5rem;
max-height: 300px;
resize: none;
padding: 0.5rem;
line-height: 1.5;
font-family: inherit;
font-size: inherit;
border: 1px solid var(--vp-c-divider);
border-radius: 4px;
background: var(--vp-c-bg-alt);
}
.form-group button {
background-color: #333;
cursor: pointer;
}
.form-group button:hover {
background-color: #555;
}
/* Output section */
.output-section {
margin-top: 20px;
margin-bottom: 50px;
}
.output-box-container {
position: relative;
margin-top: 15px;
}
.output-box-label {
font-size: 0.8em;
}
.output-box {
box-sizing: content-box;
border: 1px dashed #ccc;
padding: 10px;
min-height: 24px;
overflow-wrap: break-word;
white-space: pre-wrap;
font-family: monospace;
}
.placeholder {
text-align: center;
color: #888;
font-style: italic;
margin-top: 20px;
}
/* Gradient Button Styling */
.gradient-button {
padding: 10px 20px;
font-size: 1rem;
font-weight: bold;
color: white;
background: var(--vp-home-hero-name-background);
border: none;
width: 100%;
margin: auto;
border-radius: 10px; /* Full-rounded button */
cursor: pointer;
text-transform: uppercase;
box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1); /* Soft shadow */
}
.gradient-button:hover {
background: var(--primary);
}
/* Mobile responsiveness */
@media (max-width: 768px) {
.select-group {
max-width: 100%;
}
.input-group {
width: 100%;
}
}
@@ -18,12 +18,15 @@ const { theme, page, frontmatter } = useData()
## Results
### Theme Data
<pre>{{ theme }}</pre>
### Page Data
<pre>{{ page }}</pre>
### Page Frontmatter
<pre>{{ frontmatter }}</pre>
```
@@ -36,12 +39,15 @@ const { site, theme, page, frontmatter } = useData()
## Results
### Theme Data
<pre>{{ theme }}</pre>
### Page Data
<pre>{{ page }}</pre>
### Page Frontmatter
<pre>{{ frontmatter }}</pre>
## More
@@ -7,4 +7,3 @@ npm install @xo/react
```
## Usage
@@ -7,4 +7,3 @@ npm install @xo/svelte
```
## Usage

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 29 KiB

+169
View File
@@ -0,0 +1,169 @@
---
# VitePress configuration
layout: home
hero:
name: 'XO Stack'
text: 'On Bitcoin Cash'
tagline: Building smart applications on the BCH UTXO Network
actions:
- theme: brand
text: Tools
link: /tools/primitives
- theme: brand
text: GitLab
link: https://gitlab.com/GeneralProtocols/xo/stack
---
<!--
TODO: When we have docs public, move this back into the top config section above.
- theme: brand
text: Quick Start
link: /quick-start
-->
<!-- Promo section on front page with animated X and O behind the image -->
<div class="promo">
<div class="promo-text">
<h1>Create robust scalable <span class="clip">Bitcoin Cash</span> apps, faster than ever before.</h1>
<p>XO provides cutting-edge tools to help developers create Bitcoin Cash apps with ease and efficiency. With a focus on scalability, security, and speed, you can bring your app to life in no time.</p>
<p>Start building now and unlock the full potential of Bitcoin Cash in the digital economy!</p>
</div>
<div class="promo-image">
<!-- Animated X and O elements behind the image section -->
<div class="animated-bg">
<span class="xo xo-1">x</span>
<span class="xo xo-2">o</span>
<span class="xo xo-3">o</span>
<span class="xo xo-4">x</span>
</div>
<img src="/icons/stack_light.png" alt="Stack Light Image" />
</div>
</div>
<!-- Feature section -->
<div class="VPFeatures VPHomeFeatures">
<div class="container">
<h1 style="text-align:center;margin:20px">Stack Features</h1>
<div class="items" style="">
<div class="item grid-3">
<div class="VPLink no-icon VPFeature feature-box-or">
<article class="box">
<img class="VPImage dark-only" height="48" width="48" src="/icons/api-dark.svg" alt="">
<img class="VPImage light-only" height="48" width="48" src="/icons/api-light.svg" alt="">
<h2 class="title">API</h2>
<p class="details">Access powerful APIs to build smart apps on the BCH UTXO Network.</p>
<!--v-if-->
</article>
</div>
</div>
<div class="item grid-3">
<div class="VPLink no-icon VPFeature feature-box-or">
<article class="box">
<img class="VPImage dark-only" height="48" width="48" src="/icons/framework-dark.svg" alt="">
<img class="VPImage light-only" height="48" width="48" src="/icons/framework-light.svg" alt="">
<h2 class="title">Framework</h2>
<p class="details">A solid framework for building scalable applications.</p>
<!--v-if-->
</article>
</div>
</div>
<div class="item grid-3">
<div class="VPLink no-icon VPFeature feature-box-or">
<article class="box">
<img class="VPImage dark-only" height="48" width="48" src="/icons/tools-dark.svg" alt="">
<img class="VPImage light-only" height="48" width="48" src="/icons/tools-light.svg" alt="">
<h2 class="title">Tools</h2>
<p class="details">Essential tools to streamline development and deployment.</p>
<!--v-if-->
</article>
</div>
</div>
</div>
</div>
</div>
<!-- Footer Logo section -->
<div class="vp-doc" style="text-align: center; margin: 15px;">
<h4>Developed by:</h4>
</div>
<div style="text-align: center; margin: 10px;">
<a href="https://generalprotocols.com" target="_blank" style="display: inline-block;">
<img class="light-only" src="./gp_logo_light.png" alt="GP Logo" style="width: 100px; height: auto;">
<img class="dark-only" src="./gp_logo_dark.png" alt="GP Logo" style="width: 100px; height: auto;">
</a>
</div>
<style scoped>
.items {
display: grid; grid-template-columns: repeat(3, 1fr); gap: 40px;
}
.VPFeature {
display: block;
border: 1px solid var(--vp-c-bg-soft);
border-radius: 12px;
height: 100%;
background-color: var(--vp-c-bg-soft);
transition: border-color 0.25s, background-color 0.25s;
}
.VPFeature.link:hover {
border-color: var(--vp-c-brand-1);
}
.box {
display: flex;
flex-direction: column;
padding: 24px;
height: 100%;
}
.box > :deep(.VPImage) {
margin-bottom: 20px;
}
.icon {
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 20px;
border-radius: 6px;
background-color: var(--vp-c-default-soft);
width: 48px;
height: 48px;
font-size: 24px;
transition: background-color 0.25s;
}
.title {
line-height: 24px;
font-size: 16px;
font-weight: 600;
}
.details {
flex-grow: 1;
padding-top: 8px;
line-height: 24px;
font-size: 14px;
font-weight: 500;
color: var(--vp-c-text-2);
}
.link-text {
padding-top: 8px;
}
.link-text-value {
display: flex;
align-items: center;
font-size: 14px;
font-weight: 500;
color: var(--vp-c-brand-1);
}
.link-text-icon {
margin-left: 6px;
}
</style>
@@ -0,0 +1,75 @@
### Double-Spends and Detecting Conflicting State
1. Currently DSP's are constrained to P2PKH.
2. We may be able to extend these to **some** P2SH - but the requirement is that the P2SH must have an `OP_CHECKSIG`.
3. There will be at least some (potentially many) kinds of P2SH that lack an `OP_CHECKSIG`.
4. One problem that we have is that we cannot reliably determine (with Electrum) whether a P2SH may have been double-spent.
5. ???
6. Lack of profit
The point you're trying to get at is that Nodes on the network can have a differing mempool state.
How do we detect that? Fulcrum can't really provide us with that information.
How do we handle it if we can detect it? E.g. avoiding any "contentious" dependencies.
Do we have to store a whole graph?
For now, do owe just broadcast to one of our nodes and then broadcast to ALL of our nodes 5s later to see if there's contention?
### Electrum 4.0.1 Notes
1. Maybe default constructor generic to `ElectrumClientEvents`:
```ts
class ElectrumClient<ElectrumEvents extends ElectrumClientEvents = ElectrumClientEvents>
```
2. `RequestResponse` might be typed incorrectly: It now takes `RPCParameter | RPCParameter[]` which are defined as follows: `string | number | boolean | null;` (note that it only accept parameters, not responses which are often/maybe-always JSON).
Previously, it would accept:
```
export type RequestResponse =
| object
| string
| number
| boolean
| null
| RequestResponse[];
```
Perhaps we could type it: `export type RequestResponse = RPCParameter & object | Array<RPCParameter & object>;` (replace `object` with something like `RPCResponse`, but I think that might be taken already?)
3. `RPCNotification` might be typed incorrectly (or maybe this is for future proofing?). The `params` property is marked as optional (but I think all notifications will have at least one). Might be more elegant to have it required and just return an empty array.
4. The current approach still requires polyfills because `@electrum/sockets` itself is imported by `@electrum/network` and `@electrum/sockets` exports `ElectrumTcpSocket`.
A workable approach might be:
1. Move socket interface back to `@electum/network`.
2. Move the `ElectrumWebSocket` back to `@electrum/network`.
3. Rename `@electrum/sockets` to `@electrum/tcp-socket` and only include the TCP Socket in there.
4. This will still allow third-parties to define their own sockets (e.g. `@custom/electrum-libp2p-socket`).
5. This is what's required for polyfilling in Vite currently:
```sh
npm install events
npm install vite-plugin-node-polyfills
```
```js
[
nodePolyfills,
{
include: ['events', 'net', 'tls'],
// NOTE: Not disabling these causes an error on Vite Polyfills V0.22.
globals: {
Buffer: false,
global: false,
process: false,
},
},
],
```

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 29 KiB

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 29 KiB

Before

Width:  |  Height:  |  Size: 80 KiB

After

Width:  |  Height:  |  Size: 80 KiB

Before

Width:  |  Height:  |  Size: 140 KiB

After

Width:  |  Height:  |  Size: 140 KiB

Before

Width:  |  Height:  |  Size: 77 KiB

After

Width:  |  Height:  |  Size: 77 KiB

Before

Width:  |  Height:  |  Size: 77 KiB

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

+218
View File
@@ -0,0 +1,218 @@
# Quickstart
Install the XO Stack
```sh
npm install @xo/stack
```
Example Usage:
```ts
// Import XO Modules.
import { Address, BlockchainElectrum, StorageMemory } from '@xo/stack';
// The Electrum Servers we will be using.
const ELECTRUM_SERVERS = [
'bch.imaginary.cash',
'cashnode.bch.ninja',
'electrum.imaginary.cash',
];
// Create an instance of the services that WalletHD will require.
// NOTE: Other storage adapters currently broken, in the midst of refactor.
const blockchainElectrum = new BlockchainElectrum(ELECTRUM_SERVERS);
const cachesStore = new StorageMemory();
const walletsStore = new StorageMemory();
// Start each of our services.
await Promise.all([
blockchainElectrum.start(),
cachesStore.start(),
walletsStore.start(),
]);
// Create an instance of a HDWallet.
const walletHD = await Wallet.from(
{
derivationPath: "m/44'/145'/0'",
mnemonic:
'page pencil stock planet limb cluster assault speak off joke private pioneer',
},
{
blockchain: blockchainElectrum,
cache: cachesStore,
storage: walletsStore,
},
);
// Scan the wallet and start monitoring addresess for transactions.
await walletHD.start();
// Send a transaction to the network, automatically populating UTXOs to match the output amount.
// NOTE: Pre-signed inputs can be provided and change outputs will be automatically appended.
const txResult = await walletHD.send({
outputs: [
{
lockingBytecode: Address.fromCashAddr(
'bitcoincash:qpc7mdjncqzf96vfzfaaqfrmru4rpg5qeq4m237t78',
).toLockscriptBytes(),
valueSatoshis: 10_000,
},
],
});
```
## Structure/Patterns
General structure:
- All blockchain adapters will implement `IBlockhain`
- All storage adapters will implement `IStorage`
- All wallets will implement `IWallet`
- Likewise for any other "service" we need in XO Stack (e.g. BCMR?, Prices?).
Most (almost all?) service methods in our interfaces will be `async`. This is so that we can handle situations where things might be remote (or require OS approval of some sort). For example:
1. Storage Adapters will need to allow backup to third-party services (so the methods must be `async`).
2. Some Wallets **may** have remote dependencies (e.g. imagine a Multisig, Co-pay-like service).
3. Wallets on IOS may have to tie in, in some way, with the host OS (to get approvals).
4. There is also the `ServiceWorker` ideal where we would like to be able to run everything in a `ServiceWorker` and communicate to/from it from frontend. I'm not sure whether this will be realizable in practice yet.
The approach here aims to be extendable: If there is something that the XO Stack does not support, someone can:
1. Extend existing XO classes to customize it to their own needs
2. BYO their own adapter
3. Create their own wallet type that can still leverage other parts of XO stack
### Wallets
Wallets can be **composed** of other Wallets. For example:
- WalletP2PKH is standalone
- WalletHD **has many** WalletP2PKH
- SomeCustomWallet **may have many** WalletHD (or other kinds of wallet).
The only requirement is that a Wallet **MUST** implement the IWallet interface.
### Blockchain
Blockchains represent a connection to the BCH Network ("Blockchain" might not be the best term, but let's bikeshed over that later). This blockchain might be:
- Via Electrum-Cash (current implementation)
- Via Chaingraph (not sure if we'll implement this, but it probably wouldn't be too difficult)
- Local (as in, something like an in-memory "regtest")
We will likely want redundancies or possibly a fallback to a "local" blockchain in some cases where a device is disconnected from the internet (e.g. online merchant, offline customer).
The current plan (not implemented yet) is to create a main `Blockchain` class that can be instantiated something like follows:
```ts
const blockchain = new Blockchain([
new BlockchainElectrum(...),
new BlockchainLocal(...),
]);
```
This `Blockchain` class will still implement the `IBlockchain` interface, but will try to direct requests to the correct Blockchain instance. This still needs more fleshing out.
### Stores
A **store** is just a means of storing data. It can be in-memory, to a file (e.g. SQLite), to somewhere remote (Firebase, MySQL, MongoDB, etc).
It is hierachical, meaning it can be structured like a tree (not just a simple KV table). This is in anticipation of WalletSets which likely going to have complex data structures. Ideally, where possible, we'll want our adapters to only mutate the relevant portion of an entry as opposed to the ENTIRE entry for a wallet (which would increase I/O and the risk of corruption).
As with `Blockchain`, we'll want support for redundancies (e.g. Local and Remote Backups).
The current plan (not implemented yet) is to create a `Storage` class that can be instantiated something like follows:
```ts
const storage = new Storage([
// Local store on Mobile Devices.
new StorageSQLite(...),
// GP's storage service.
new StorageGPStore(...),
]);
```
This still needs a bit more fleshing out but, to allow syncing, UIDs (or WalletSet Activity IDs) will probably be used where possible (as opposed to autoincrement-like indexes).
### Double-Spends and Detecting Conflicting State
1. Currently DSP's are constrained to P2PKH.
2. We may be able to extend these to **some** P2SH - but the requirement is that the P2SH must have an `OP_CHECKSIG`.
3. There will be at least some (potentially many) kinds of P2SH that lack an `OP_CHECKSIG`.
4. One problem that we have is that we cannot reliably determine (with Electrum) whether a P2SH may have been double-spent.
5. ???
6. Lack of profit
The point you're trying to get at is that Nodes on the network can have a differing mempool state.
How do we detect that? Fulcrum can't really provide us with that information.
How do we handle it if we can detect it? E.g. avoiding any "contentious" dependencies.
Do we have to store a whole graph?
Do we just broadcast to one of our nodes and then broadcast to ALL of our nodes ~5s later to see if there's contention?
### Electrum 4.0.1 Notes
1. Maybe default constructor generic to `ElectrumClientEvents`:
```ts
class ElectrumClient<ElectrumEvents extends ElectrumClientEvents = ElectrumClientEvents>
```
2. `RequestResponse` might be typed incorrectly: It now takes `RPCParameter | RPCParameter[]` which are defined as follows: `string | number | boolean | null;` (note that it only accept parameters, not responses which are often/maybe-always JSON).
Previously, it would accept:
```
export type RequestResponse =
| object
| string
| number
| boolean
| null
| RequestResponse[];
```
Perhaps we could type it: `export type RequestResponse = RPCParameter & object | Array<RPCParameter & object>;` (replace `object` with something like `RPCResponse`, but I think that might be taken already?)
3. `RPCNotification` might be typed incorrectly (or maybe this is for future proofing?). The `params` property is marked as optional (but I think all notifications will have at least one). Might be more elegant to have it required and just return an empty array.
4. The current approach still requires polyfills because `@electrum/sockets` itself is imported by `@electrum/network` and `@electrum/sockets` exports `ElectrumTcpSocket`.
A workable approach might be:
1. Move socket interface back to `@electum/network`.
2. Move the `ElectrumWebSocket` back to `@electrum/network`.
3. Rename `@electrum/sockets` to `@electrum/tcp-socket` and only include the TCP Socket in there.
4. This will still allow third-parties to define their own sockets (e.g. `@custom/electrum-libp2p-socket`).
5. This is what's required for polyfilling in Vite currently:
```sh
npm install events
npm install vite-plugin-node-polyfills
```
```js
[
nodePolyfills,
{
include: ['events', 'net', 'tls'],
// NOTE: Not disabling these causes an error on Vite Polyfills V0.22.
globals: {
Buffer: false,
global: false,
process: false,
},
},
],
```
## Markdown Extensions (TODO: Remove me later)
Check out the documentation for the [full list of markdown extensions](https://vitepress.dev/guide/markdown).
+6
View File
@@ -0,0 +1,6 @@
<script lang="ts" setup>
</script>
<!-- Resume Markdown parsing -->
TODO: Once we have other tools, we might want to turn this into a page like that on Quick Start that presents a "box" of each Tool Group.
@@ -0,0 +1,605 @@
import {
Address,
BlockHeader,
Bytes,
encodeExtendedJson,
decodeExtendedJson,
Hasher,
HDPrivateNode,
HDPublicNode,
Mnemonic,
PrivateKey,
PublicKey,
Satoshis,
Script,
Transaction,
} from '@xocash/primitives';
export const address = {
from: [
{
label: 'From',
inputs: ['CashAddr or Legacy Address'],
models: [''],
callback: (args: [string]) => Address.from(...args),
extendedInput: true,
},
{
label: 'From CashAddr',
inputs: ['CashAddr'],
models: [''],
callback: (args: [string]) => Address.fromCashAddr(...args),
extendedInput: true,
},
{
label: 'From Legacy',
inputs: ['Legacy Address'],
models: [''],
callback: (args: [string]) => Address.fromLegacy(...args),
extendedInput: true,
},
{
label: 'From Redeem Script Hex (P2SH20)',
inputs: ['RedeemScript Hex'],
models: [''],
callback: (args: [string]) =>
Address.fromRedeemScriptHex(...args, 'P2SH20'),
extendedInput: true,
},
{
label: 'From Redeem Script Hex (P2SH32)',
inputs: ['RedeemScript Hex'],
models: [''],
callback: (args: [string]) =>
Address.fromRedeemScriptHex(...args, 'P2SH32'),
extendedInput: true,
},
{
label: 'From Lockscript Hex',
inputs: ['Lockscript Hex'],
models: [''],
callback: (args: [string]) => Address.fromLockscriptHex(...args),
extendedInput: true,
},
{
label: 'From Hash160 Hex',
inputs: ['Hash160 Hex'],
models: [''],
callback: (args: [string]) => Address.fromHash160Hex(...args),
extendedInput: true,
},
],
to: [
{
label: 'To CashAddr (mainnet)',
callback: (address: Address) => address.toCashAddr('bitcoincash'),
},
{
label: 'To CashAddr (testnet)',
callback: (address: Address) => address.toCashAddr('bchtest'),
},
{
label: 'To CashAddr (regtest)',
callback: (address: Address) => address.toCashAddr('bchreg'),
},
{
label: 'To TokenAware CashAddr (mainnet)',
callback: (address: Address) => address.toTokenAddress('bitcoincash'),
},
{
label: 'To TokenAware CashAddr (testnet)',
callback: (address: Address) => address.toTokenAddress('bchtest'),
},
{
label: 'To TokenAware CashAddr (regtest)',
callback: (address: Address) => address.toTokenAddress('bchreg'),
},
{
label: 'To Legacy',
callback: (address: Address) => address.toLegacy(),
},
{
label: 'To Hash160/RIPEMD Hex',
callback: (address: Address) => address.toHash160Hex(),
},
{
label: 'To Lockscript Hex',
callback: (address: Address) => address.toLockscriptHex(),
},
{
label: 'To Lockscript ASM',
callback: (address: Address) => address.toLockscriptAsm(),
},
],
};
export const blockHeader = {
from: [
{
label: 'From Hex',
inputs: ['UTF-8'],
models: [''],
callback: (args: [string]) => BlockHeader.fromHex(...args),
},
],
to: [
{
label: 'To Raw',
callback: (blockHeader: BlockHeader) => blockHeader.toRaw(),
},
{
label: 'Version',
callback: (blockHeader: BlockHeader) => blockHeader.getVersion(),
},
{
label: 'Previous Block Hash',
callback: (blockHeader: BlockHeader) =>
blockHeader.getPreviousBlockHashHex(),
},
{
label: 'Merkle Root',
callback: (blockHeader: BlockHeader) => blockHeader.getMerkleRootHex(),
},
{
label: 'Timestamp',
callback: (blockHeader: BlockHeader) =>
blockHeader.getTimestamp().toString(),
},
{
label: 'Bits',
callback: (blockHeader: BlockHeader) => blockHeader.getBits().toString(),
},
{
label: 'Nonce',
callback: (blockHeader: BlockHeader) => blockHeader.getNonce().toString(),
},
],
};
export const bytes = {
from: [
{
label: 'From Base64',
inputs: ['Base64'],
models: [''],
callback: (args: [string]) => Bytes.fromBase64(...args),
},
{
label: 'From Hex',
inputs: ['Hex'],
models: [''],
callback: (args: [string]) => Bytes.fromHex(...args),
},
{
label: 'From UTF-8',
inputs: ['UTF-8'],
models: [''],
callback: (args: [string]) => Bytes.fromUtf8(...args),
},
],
to: [
{
label: 'To Base64',
callback: (bytes: Bytes) => bytes.toBase64(),
},
{
label: 'To Hex',
callback: (bytes: Bytes) => bytes.toHex(),
},
{
label: 'To UTF-8',
callback: (bytes: Bytes) => bytes.toUtf8(),
},
],
};
export const hasher = {
from: [
{
label: 'From Hex',
inputs: ['Hex'],
models: [''],
callback: (args: [string]) => Hasher.fromHex(...args),
},
{
label: 'From Base64',
inputs: ['Base64'],
models: [''],
callback: (args: [string]) => Hasher.fromBase64(...args),
},
{
label: 'From UTF-8',
inputs: ['UTF-8'],
models: [''],
callback: (args: [string]) => Hasher.fromUTF8(...args),
},
],
to: [
{
label: 'To Sha256 Hex',
callback: (hasher: Hasher) => hasher.toSHA256Hex(),
},
{
label: 'To RipeMD160 Hex',
callback: (hasher: Hasher) => hasher.toRIPEMD160Hex(),
},
{
label: 'To Hash160 Hex',
callback: (hasher: Hasher) => hasher.toHash160Hex(),
},
{
label: 'To Hash256 Hex',
callback: (hasher: Hasher) => hasher.toHash256Hex(),
},
],
};
export const hdPrivateNode = {
from: [
{
label: 'Generate Random',
inputs: ['Derivation Path'],
models: ["m/44'/145'/0'/0/1"],
callback: () => HDPrivateNode.generateRandom(),
},
{
label: 'From Mnemonic',
inputs: ['Mnemonic', 'Derivation Path'],
models: ['', "m/44'/145'/0'/0/1"],
callback: (args: [string]) => HDPrivateNode.fromMnemonic(...args),
},
{
label: 'From XPriv Key',
inputs: ['XPriv Key', 'Derivation Path'],
models: ['', "m/44'/145'/0'/0/1"],
callback: (args: [string]) => HDPrivateNode.fromXPriv(...args),
},
{
label: 'From Raw',
inputs: ['Raw (LibAuth Format/ExtJSON Encoded)'],
models: [''],
callback: (args: [string]) =>
HDPrivateNode.fromRaw(decodeExtendedJson(args.join(''))),
extendedInput: true,
},
],
to: [
{
label: 'To XPriv Key',
callback: (hdPrivateNode: HDPrivateNode) => hdPrivateNode.toXPriv(),
},
{
label: 'To String',
callback: (hdPrivateNode: HDPrivateNode) => hdPrivateNode.toString(),
},
{
label: 'To Raw (LibAuth Format/ExtJSON Encoded)',
callback: (hdPrivateNode: HDPrivateNode) =>
encodeExtendedJson(hdPrivateNode.toRaw(), 2),
},
{
label: 'To XPub Key',
callback: (hdPrivateNode: HDPrivateNode) =>
hdPrivateNode.deriveHDPublicNode().toXPub(),
},
],
};
export const hdPublicNode = {
from: [
{
label: 'From XPub Key',
inputs: ['XPub Key'],
models: [''],
callback: (args: [string]) => HDPublicNode.fromXPub(...args),
},
{
label: 'From Raw',
inputs: ['Raw (LibAuth Format/ExtJSON Encoded)'],
models: [''],
callback: (args: [string]) =>
HDPublicNode.fromRaw(decodeExtendedJson(args.join(''))),
extendedInput: true,
},
],
to: [
{
label: 'To XPub Key',
callback: (hdPublicNode: HDPublicNode) => hdPublicNode.toXPub(),
},
{
label: 'To String',
callback: (hdPublicNode: HDPublicNode) => hdPublicNode.toString(),
},
{
label: 'To Raw (LibAuth Format/ExtJSON Encoded)',
callback: (hdPublicNode: HDPublicNode) =>
encodeExtendedJson(hdPublicNode.toRaw(), 2),
},
],
};
export const mnemonic = {
from: [
{
label: 'Generate Random',
callback: () => Mnemonic.generateRandom(),
},
{
label: 'From String',
inputs: ['String'],
models: [''],
callback: (args: [string]) => Mnemonic.fromString(...args),
extendedInput: true,
},
],
to: [
{
label: 'To String (without passphrase)',
callback: (mnemonic: Mnemonic) => mnemonic.toString(false),
},
{
label: 'To String (with passphrase)',
callback: (mnemonic: Mnemonic) => mnemonic.toString(true),
},
{
label: 'Words',
callback: (mnemonic: Mnemonic) => mnemonic.toWords(),
},
{
label: 'Passphrase',
callback: (mnemonic: Mnemonic) => mnemonic.getPassphrase(),
},
],
};
// TODO: Message Signing outputs. Maybe add an `extension` flag to the `to` that allows another input field and uses that to generate the outputs
export const privateKey = {
from: [
{
label: 'Generate Random',
callback: () => PrivateKey.generateRandom(),
},
{
label: 'From Hex',
inputs: ['Hex'],
models: [''],
callback: (args: [string]) => PrivateKey.fromHex(...args),
},
{
label: 'From WIF',
inputs: ['WIF'],
models: [''],
callback: (args: [string]) => PrivateKey.fromWIF(...args),
},
],
to: [
{
label: 'To Hex',
callback: (privateKey: PrivateKey) => privateKey.toHex(),
},
{
label: 'To WIF',
callback: (privateKey: PrivateKey) => privateKey.toWif(),
},
{
label: 'To String',
callback: (privateKey: PrivateKey) => privateKey.toString(),
},
{
label: 'Derived Public Key (Hex)',
callback: (privateKey: PrivateKey) =>
privateKey.derivePublicKey().toString(),
},
{
label: 'Derived BCH Address (CashAddr)',
callback: (privateKey: PrivateKey) =>
privateKey.derivePublicKey().deriveAddress().toCashAddr('bitcoincash'),
},
],
methods: [
{
label: 'Sign Message (Schnorr)',
inputs: ['UTF8'],
models: ['Your text here'],
callback: (privateKey: PrivateKey, args: [string]) =>
Bytes.fromBytes(privateKey.signMessageSchnorr(...args)).toHex(),
},
{
label: 'Sign Message (DER)',
inputs: ['UTF8'],
models: ['Your text here'],
callback: (privateKey: PrivateKey, args: [string]) =>
Bytes.fromBytes(privateKey.signMessageDER(...args)).toHex(),
},
],
};
export const publicKey = {
from: [
{
label: 'From Hex',
inputs: ['Hex'],
models: [''],
callback: (args: [string]) => PublicKey.fromHex(...args),
},
{
label: 'From WIF',
inputs: ['WIF'],
models: [''],
callback: (args: [string]) =>
PrivateKey.fromWIF(...args).derivePublicKey(),
},
],
to: [
{
label: 'Derived Hash160 Hex',
callback: (publicKey: PublicKey) => publicKey.deriveHash160Hex(),
},
{
label: 'Derived Address',
callback: (publicKey: PublicKey) =>
publicKey.deriveAddress().toCashAddr(),
},
{
label: 'To Hex',
callback: (publicKey: PublicKey) => publicKey.toHex(),
},
{
label: 'To String',
callback: (publicKey: PublicKey) => publicKey.toString(),
},
],
methods: [
{
label: 'Verify Message (Schnorr)',
inputs: ['Message (UTF8)', 'Signature (Hex)'],
models: ['Your text here'],
callback: (publicKey: PublicKey, args: [string, string]) =>
publicKey.verifyMessageSchnorr(...args).toString(),
},
{
label: 'Verify Message (DER)',
inputs: ['Message (UTF8)', 'Signature (Hex)'],
models: ['Your text here'],
callback: (publicKey: PublicKey, args: [string, string]) =>
publicKey.verifyMessageDER(...args).toString(),
},
],
};
export const satoshis = {
from: [
{
label: 'From Sats',
inputs: ['Sats'],
models: [''],
callback: (args: [number]) => Satoshis.fromSats(...args),
},
{
label: 'From Bits',
inputs: ['Bits'],
models: [''],
callback: (args: [number]) => Satoshis.fromBits(...args),
},
{
label: 'From MBCH',
inputs: ['MBCH'],
models: [''],
callback: (args: [number]) => Satoshis.fromMBCH(...args),
},
{
label: 'From BCH',
inputs: ['BCH'],
models: [''],
callback: (args: [number]) => Satoshis.fromBCH(...args),
},
],
to: [
{
label: 'To Sats',
callback: (satoshis: Satoshis) => satoshis.toSats().toString(),
},
{
label: 'To Bits',
callback: (satoshis: Satoshis) => satoshis.toBits().toString(),
},
{
label: 'To MBCH',
callback: (satoshis: Satoshis) => satoshis.toMBCH().toString(),
},
{
label: 'To BCH',
callback: (satoshis: Satoshis) => satoshis.toBCH().toString(),
},
],
};
export const script = {
from: [
{
label: 'From ASM',
inputs: ['ASM'],
models: [''],
callback: (args: [string]) => Script.fromASM(...args),
},
{
label: 'From Hex',
inputs: ['Hex'],
models: [''],
callback: (args: [string]) => Script.fromHex(...args),
},
],
to: [
{
label: 'To ASM',
callback: (script: Script) => script.toASM(),
},
{
label: 'To Hex',
callback: (script: Script) => script.toHex(),
},
],
};
export const transaction = {
from: [
{
label: 'From Hex',
inputs: ['Hex'],
models: [''],
callback: (args: [string]) => Transaction.fromHex(...args),
extendedInput: true,
},
{
label: 'From Raw',
inputs: ['Raw (LibAuth Format/ExtJSON Encoded)'],
models: [''],
callback: (args: [...string[]]) =>
Transaction.fromRaw(decodeExtendedJson(args.join(''))),
extendedInput: true,
},
],
to: [
{
label: 'To Transaction Hash Hex',
callback: (transaction: Transaction) => transaction.toHashHex(),
},
{
label: 'To Raw (LibAuth Format/ExtJSON Encoded)',
callback: (transaction: Transaction) =>
encodeExtendedJson(transaction.toRaw(), 2),
},
{
label: 'To Hex',
callback: (transaction: Transaction) => transaction.toHex(),
},
{
label: 'Version',
callback: (transaction: Transaction) =>
transaction.getVersion().toString(),
},
{
label: 'Inputs',
callback: (transaction: Transaction) => {
return encodeExtendedJson(transaction.getInputs(), 2);
},
},
{
label: 'Outputs',
callback: (transaction: Transaction) => {
return encodeExtendedJson(transaction.getOutputs(), 2);
},
},
{
label: 'Locktime',
callback: (transaction: Transaction) =>
transaction.getLocktime().toString(),
},
{
label: 'Is Coinbase',
callback: (transaction: Transaction) =>
transaction.isCoinbase().toString(),
},
],
};
+146
View File
@@ -0,0 +1,146 @@
<script lang="ts" setup>
import PrimitiveToolVue, { type FromFunction, type ToFunction } from '@theme/components/PrimitiveTool.vue'
// Import our tool functions
import {
address,
blockHeader,
bytes,
hasher,
hdPrivateNode,
hdPublicNode,
mnemonic,
privateKey,
publicKey,
satoshis,
script,
transactionHash,
transaction,
} from './primitive-functions.ts'
</script>
<!-- Resume Markdown parsing -->
# Primitive Tools
## Address
<div class="tool">
<p>A Utility tool for converting between different address formats.</p>
<PrimitiveToolVue
:fromFunctions="address.from"
:toFunctions="address.to"
/>
</div>
## Block Header
<div class="tool">
<p>A utility tool for converting between different byte representations.</p>
<PrimitiveToolVue
:fromFunctions="blockHeader.from"
:toFunctions="blockHeader.to"
/>
</div>
## Bytes
<div class="tool">
<p>A utility tool for converting between different byte representations.</p>
<PrimitiveToolVue
:fromFunctions="bytes.from"
:toFunctions="bytes.to"
/>
</div>
## Hasher
<div class="tool">
<p>A utility tool for computing various cryptographic hashes commonly used in Bitcoin Cash.</p>
<PrimitiveToolVue
:fromFunctions="hasher.from"
:toFunctions="hasher.to"
/>
</div>
## HD Private Node
<div class="tool">
<p>A utility tool for generating and manipulating HD Private Nodes.</p>
<PrimitiveToolVue
:fromFunctions="hdPrivateNode.from"
:toFunctions="hdPrivateNode.to"
/>
</div>
## HD Public Node
<div class="tool">
<p>A utility tool for generating and manipulating HD Public Nodes.</p>
<PrimitiveToolVue
:fromFunctions="hdPublicNode.from"
:toFunctions="hdPublicNode.to"
/>
</div>
## Mnemonic
<div class="tool">
<p>A utility tool for generating and validating BIP39 Mnemonics. Note that mnemonics will be normalized by removing redundant whitespace and will also be validated against the BIP39 English Word List (other word-lists can be specified via the API)</p>
<PrimitiveToolVue
:fromFunctions="mnemonic.from"
:toFunctions="mnemonic.to"
/>
</div>
## Private Key
<div class="tool">
<p>A utility tool for generating and manipulating Private Keys.</p>
<PrimitiveToolVue
:fromFunctions="privateKey.from"
:toFunctions="privateKey.to"
:methods="privateKey.methods"
/>
</div>
## Public Key
<div class="tool">
<p>A utility tool for generating and manipulating Public Keys.</p>
<PrimitiveToolVue
:fromFunctions="publicKey.from"
:toFunctions="publicKey.to"
:methods="publicKey.methods"
/>
</div>
## Satoshis
<div class="tool">
<p>A utility tool for converting between Bitcoin Cash value units.</p>
<PrimitiveToolVue
:fromFunctions="satoshis.from"
:toFunctions="satoshis.to"
/>
</div>
## Script
<div class="tool">
<p>A utility tool for generating and manipulating Script objects.</p>
<PrimitiveToolVue
:fromFunctions="script.from"
:toFunctions="script.to"
/>
</div>
## Transaction
<div class="tool">
<p>A utility tool for generating and manipulating Transaction objects.</p>
<PrimitiveToolVue
:fromFunctions="transaction.from"
:toFunctions="transaction.to"
/>
</div>
@@ -0,0 +1,34 @@
import { Bytes } from '@xocash/primitives';
import { Encryption } from '@xocash/stack';
export const encryption = {
from: [
{
label: 'From Passphrase',
inputs: ['Passphrase'],
models: [''],
callback: (args: [string]) => Encryption.fromPassphrase(...args),
extendedInput: true,
},
],
to: [],
methods: [
{
label: 'Encrypt',
inputs: ['UTF8'],
models: ['Your text here'],
callback: async (encryption: Encryption, args: [string]) =>
Bytes.fromBytes(await encryption.encrypt(...args)).toHex(),
},
{
label: 'Decrypt',
inputs: ['Hex'],
models: ['Encrypted Data (hex)'],
callback: async (encryption: Encryption, args: [string]) =>
Bytes.fromBytes(
await encryption.decrypt(Bytes.fromHex(...args).toBytes()),
).toUtf8(),
},
],
};
+23
View File
@@ -0,0 +1,23 @@
<script lang="ts" setup>
import PrimitiveToolVue, { type FromFunction, type ToFunction } from '@theme/components/PrimitiveTool.vue'
// Import our tool functions
import {
encryption
} from './utils-functions.ts'
</script>
<!-- Resume Markdown parsing -->
# Utils
## Encryption
<div class="tool">
<p>A Utility tool for converting between different address formats.</p>
<PrimitiveToolVue
:fromFunctions="encryption.from"
:toFunctions="encryption.to"
:methods="encryption.methods"
/>
</div>
+37
View File
@@ -0,0 +1,37 @@
{
"entryPointStrategy": "packages",
"entryPoints": ["../primitives/", "../stack/"],
"plugin": ["typedoc-plugin-markdown", "typedoc-vitepress-theme"],
"docsRoot": "./src",
"out": "./src/api",
"sidebar": {
"autoConfiguration": true,
"format": "vitepress",
"pretty": true,
"collapsed": true
},
"indexFormat": "table",
"parametersFormat": "table",
"interfacePropertiesFormat": "table",
"classPropertiesFormat": "table",
"propertyMembersFormat": "table",
"typeDeclarationFormat": "table",
"enumMembersFormat": "table",
"useCodeBlocks": true,
"sort": ["static-first"],
"exclude": "**/*+(index|.spec|.e2e|.browser|.node|.types).ts",
"excludeInternal": true,
"excludeProtected": true,
"excludePrivate": true,
"excludeReferences": true,
"outputFileStrategy": "modules",
"hideGroupHeadings": true
/*
"categorizeByGroup": false,
"navigation": {
"includeCategories": false,
"includeGroups": true
}
*/
}
@@ -0,0 +1,3 @@
# XO Primitives
TODO
@@ -1,7 +1,7 @@
{
"name": "@xo/vue",
"name": "@xocash/json-payment-protocol-v2",
"version": "0.0.1",
"description": "XO Stack Wallet - Vue",
"description": "JSON Payment Protocol V2",
"type": "module",
"main": "dist/index.js",
"module": "dist/index.js",
@@ -14,10 +14,5 @@
"prepublishOnly": "npm run build"
},
"author": "",
"license": "ISC",
"dependencies": {
"@xo/primitives": "^0.0.1",
"@xo/wallet": "^0.0.1",
"vue": "^3.4.38"
}
"license": "ISC"
}
@@ -0,0 +1,338 @@
import {
binsAreEqual,
hexToBin,
secp256k1,
sha256,
utf8ToBin,
} from '@bitauth/libauth';
export type TrustedKeys = {
[identity: string]: {
owner: string;
expirationDate: string;
domains: Array<string>;
publicKeys: Array<string>;
};
};
export interface PaymentOptionsResponse {
time: string; // ISO date string
expires: string; // ISO date string
memo: string;
paymentUrl: string;
paymentId: string;
paymentOptions: Array<{
chain: string;
currency: string;
network: string;
estimatedAmount: number;
requiredFeeRate: number;
minerFee: number;
decimals: number;
selected: boolean;
}>;
}
export interface PaymentRequestBody {
chain: string;
currency?: string;
}
export interface PaymentRequestResponse {
time: string; // ISO date string
expires: string; // ISO date string
memo: string;
paymentUrl: string;
paymentId: string;
chain: string;
network: string;
instructions: Array<{
type: string;
requiredFeeRate?: number;
outputs: Array<{
amount: number;
address: string;
}>;
}>;
}
export interface PaymentVerificationBody {
chain: string;
transactions: Array<{
tx: string;
}>;
currency: string;
}
export interface PaymentBody {
chain: string;
transactions: Array<{
tx: string;
}>;
}
export interface PaymentResponse {
memo: string;
transactions: Array<{
tx: string;
}>;
}
// These are fetched from https://bitpay.com/signingKeys/paymentProtocol.json
// Note that the expiration date is 2018, so I'm not sure wallets would even be using these anymore.
export const DEFAULT_TRUSTED_KEYS: TrustedKeys = {
mh65MN7drqmwpCRZcEeBEE9ceQCQ95HtZc: {
owner: 'BitPay, Inc.',
expirationDate: '2018-12-04T00:00:00.000Z',
domains: ['test.bitpay.com'],
publicKeys: [
'03159069584176096f1c89763488b94dbc8d5e1fa7bf91f50b42f4befe4e45295a',
'03de8bc75ff1fd82133dd1777fa08449032d4a7ac58c234545ffb7da38bc94aea1',
],
},
'1DbY94wCcLRM1Y6RGFg457JyqBbsYxzfiN': {
owner: 'BitPay, Inc.',
expirationDate: '2018-12-03T00:00:00.000Z',
domains: ['bitpay.com'],
publicKeys: [
'03218884b9a42334195ec32344d487ef291fda4b6e712a7858e9836c2d326e0c08',
'027ffb2cc626a97bc3b449ae3b28b0acf07bc900bba8912d60ca12ad2b616cbe72',
'03a29de86e138106a329bc6db085f02d8e19f59249204dfd5cc797fcb36b8ed93c',
'022ba5469ec10a1d12911a5ca39c45bd0de24db83145507ffaf1fb6a3ca047f717',
'03065b167ac14111efdbf7708708ecf44d22ed0e97af3c656a183162dabf5a59bf',
'03dc0f18eadf553705ab87421d264204a9fcb8a7984997e07a867cbf55972908eb',
'02cab72d4d5d0c9ede7617562e42c485dcfb34db52fd0e6a3de62462040ac1ce90',
'02e184ad56dee82bbaf290144f24b7ab8e508f6c26e9181c8501c8219a7e1999b1',
'027b7d555a3444936ddb200ca640f41aa8c89851fbbb13521b5aaa32d75df57cc8',
'03c3872f9c42c1c2fca77a77727f3b180cdc811754f6b560d298f1ce63c78df484',
'02527a9029fbb09ec9a02471e03296932d20544d3935fa492e2f74a1f79a0c48f6',
'03adbd79e63b046cc25c70b2c1f428a410e1ca46f88fb6c387f2883090b9fa0367',
'02c9f1fbf8afa5a9b6a22a6c442b184e7e72a8b173c4a06beb11a5b700f024b06e',
'0386126eaa4f7bc816ea0c5841cdd1086704167c126e03c17dbd5fc899469091bb',
'03271e4ea488ed0d1294dce6f3554c5d6f9cb068a847f500f2ea392148402499f1',
],
},
};
export class JSONPaymentProtocolV2 {
constructor(
public opts: {
verifySignatures: boolean;
allowUnknownIdentities: boolean;
} = {
verifySignatures: false,
allowUnknownIdentities: true,
},
public trustedKeys: TrustedKeys = DEFAULT_TRUSTED_KEYS,
) {}
async paymentOptions(url: string): Promise<PaymentOptionsResponse> {
const response = await fetch(url, {
method: 'GET',
headers: {
accept: 'application/payment-options',
'x-paypro-version': '2',
},
});
if (!response.ok) {
throw new Error(`${(await response.text()) || response.status}`);
}
const responseRaw = await response.text();
if (this.opts.verifySignatures) {
this.verifyResponseSignature(url, responseRaw, response.headers);
}
return JSON.parse(responseRaw);
}
async paymentRequest(
url: string,
body: PaymentRequestBody = {
chain: 'BCH',
currency: 'BCH',
},
): Promise<PaymentRequestResponse> {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/payment-request',
'x-paypro-version': '2',
},
body: JSON.stringify(body),
});
if (!response.ok) {
throw new Error(`${(await response.text()) || response.status}`);
}
const responseRaw = await response.text();
if (this.opts.verifySignatures) {
this.verifyResponseSignature(url, responseRaw, response.headers);
}
return JSON.parse(responseRaw);
}
async paymentVerifcation(
url: string,
body: PaymentVerificationBody,
): Promise<void> {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/payment',
'x-paypro-version': '2',
},
body: JSON.stringify(body),
});
if (!response.ok) {
throw new Error(`${(await response.text()) || response.status}`);
}
const responseRaw = await response.text();
if (this.opts.verifySignatures) {
this.verifyResponseSignature(url, responseRaw, response.headers);
}
return JSON.parse(responseRaw);
}
async payment(url: string, body: PaymentBody): Promise<PaymentResponse> {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/payment',
'x-paypro-version': '2',
},
body: JSON.stringify(body),
});
if (!response.ok) {
throw new Error(`${(await response.text()) || response.status}`);
}
const responseRaw = await response.text();
if (this.opts.verifySignatures) {
this.verifyResponseSignature(url, responseRaw, response.headers);
}
return JSON.parse(responseRaw);
}
protected verifyResponseSignature(
url: string,
rawBody: string,
headers: Headers,
): void {
// Parse the URL so we can extract the hostname.
const parsedUrl = new URL(url);
const { hostname } = parsedUrl;
// Extract necessary headers.
const digest = headers.get('digest');
const signature = headers.get('signature');
const signatureType = headers.get('x-signature-type');
const identity = headers.get('x-identity');
// Ensure that expected hash was provided.
if (typeof digest !== 'string' || !digest) {
throw new Error('Invalid digest header provided');
}
// Ensure that an identity was provided.
if (typeof identity !== 'string' || !identity) {
throw new Error('Invalid identity header provided.');
}
// Ensure that a signature was provided.
if (typeof signature !== 'string' || !signature) {
throw new Error('Invalid signature header provided.');
}
// Ensure that signature type is "ecc".
if (typeof signatureType !== 'string' || signatureType !== 'ecc') {
throw new Error(
`Unsupported signature type "${signatureType}" (must be "ecc")`,
);
}
// Split the digest into type and content.
const [digestType, digestHash] = digest.split('=');
// Ensure that digest type is SHA-256.
if (digestType !== 'SHA-256') {
throw new Error(
`Unsupported Digest Type (${digestType}). Must be "SHA-256"`,
);
}
// Ensure that digest is present.
if (!digestHash) {
throw new Error('Invalid digest header. Must be of form SHA-256=hash');
}
// Try to find a key for this identity in our trusted keys.
const keyData = this.trustedKeys[identity];
// If we could not find a key...
if (!keyData) {
// And we do not allow unknown entities, throw an error.
if (!this.opts.allowUnknownIdentities) {
throw new Error(`No keys available for identity "${identity}"`);
}
// Compile all our known domains into a single array.
const domains = Object.values(this.trustedKeys).flatMap(
(entry) => entry.domains,
);
// If this hostname is contained in our known domains, throw an error.
if (domains.includes(hostname)) {
throw new Error(
`"${hostname}" has a trusted key, but it belongs to another identity`,
);
}
// Otherwise, just return.
return;
}
// Ensure that the domain is whitelisted for this identity.
if (!keyData.domains.includes(hostname)) {
throw new Error(
`${hostname} is not included in this identity's trusted domains`,
);
}
// Calculate the hash of the body.
const actualHash = sha256.hash(utf8ToBin(rawBody));
// Ensure the actual hash matches the expected hash.
if (!binsAreEqual(actualHash, hexToBin(digestHash))) {
throw new Error('Provided digest does not match actual digest');
}
// Iterate through each of the whitelisted public keys and see if any of them can match the expected signature.
const didVerifySuccessfully = keyData.publicKeys.some((publicKey) => {
return secp256k1.verifySignatureCompact(
hexToBin(signature),
hexToBin(publicKey),
actualHash,
);
});
// If none of the public keys can verify the signature, throw an error.
if (!didVerifySuccessfully) {
throw new Error(
`Failed to verify the signature against any of the identity's (${identity}) listed public keys`,
);
}
}
}
@@ -4,11 +4,6 @@
"outDir": "./dist",
"rootDir": "./src"
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist"
]
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
+5 -2
View File
@@ -1,5 +1,5 @@
{
"name": "@xo/primitives",
"name": "@xocash/primitives",
"version": "0.0.1",
"description": "XO Stack Primitives",
"type": "module",
@@ -11,7 +11,10 @@
],
"scripts": {
"build": "tsc --build --clean && tsc --build",
"prepublishOnly": "npm run build"
"prepublishOnly": "npm run build",
"test": "vitest",
"test:coverage": "vitest run --coverage",
"watch": "tsc --watch"
},
"author": "",
"license": "ISC"
+93 -42
View File
@@ -28,6 +28,25 @@ export class Address {
this.addressContents = addressContents;
}
/**
* Decode a Cash Address or Legacy Address.
*
* @param address {string} The address to attempt to decode.
*
* @throws {Error} If address cannot be decoded.
*
* @returns {Address} Instance of Address.
*/
public static from(address: string): Address {
// Attempt to decode as a Cash Address.
try {
return Address.fromCashAddr(address);
} catch (_error) {
// And if that fails, attempt to decode as a Base58 Address.
return Address.fromLegacy(address);
}
}
/**
* Decode a CashAddr into an Address Entity.
*
@@ -40,13 +59,19 @@ export class Address {
* @example
* const address = Address.fromCashAddr('bitcoincash:qpeqv9k9j3l7fepp9du24f9pr5jdu7c2mvn4wwldav')
*/
public static fromCashAddr(cashAddr: string): Address {
// CashAddr
const decodeResult = decodeCashAddress(cashAddr);
public static fromCashAddr(
cashAddr: string,
tryPrefixes: Array<string> = ['', 'bitcoincash', 'bchtest', 'bchreg'],
): Address {
// Try all prefixes (including empty string) until we find a valid decode
const decodeResult = tryPrefixes
.map((prefix) =>
decodeCashAddress(prefix ? `${prefix}:${cashAddr}` : cashAddr),
)
.find((result) => typeof result !== 'string');
// If a string is returned, this indicates an error...
if (typeof decodeResult === 'string') {
throw new Error(decodeResult);
if (!decodeResult) {
throw new Error('Invalid address format');
}
// Define the encode type in advance.
@@ -55,9 +80,11 @@ export class Address {
// Determine the encoding to use based on the Decoding Result's Type.
switch (decodeResult.type) {
case 'p2pkh':
case 'p2pkhWithTokens':
encodeType = 'P2PKH';
break;
case 'p2sh':
case 'p2shWithTokens':
encodeType = decodeResult.payload.length === 32 ? 'P2SH32' : 'P2SH20';
break;
default:
@@ -106,25 +133,6 @@ export class Address {
return new Address({ payload: decodeResult.payload, type: encodeType });
}
/**
* Decode a Cash Address or Legacy Address.
*
* @param address {string} The address to attempt to decode.
*
* @throws {Error} If address cannot be decoded.
*
* @returns {Address} Instance of Address.
*/
public static fromCashAddrOrLegacy(address: string): Address {
// Attempt to decode as a Cash Address.
try {
return Address.fromCashAddr(address);
} catch (error) {
// And if that fails, attempt to decode as a Base58 Address.
return Address.fromLegacy(address);
}
}
/**
* Instantiate an address from Contract Bytecode.
*
@@ -136,7 +144,7 @@ export class Address {
*/
public static fromRedeemScript(
contractBytes: Uint8Array,
type: 'P2SH20' | 'P2SH32' = 'P2SH32'
type: 'P2SH20' | 'P2SH32' = 'P2SH32',
): Address {
// Do an initial SHA256 on the Contract Bytes.
let payload = sha256.hash(contractBytes);
@@ -164,7 +172,7 @@ export class Address {
*/
public static fromRedeemScriptHex(
hex: string,
type: 'P2SH20' | 'P2SH32' = 'P2SH32'
type: 'P2SH20' | 'P2SH32' = 'P2SH32',
): Address {
if (!isHex(hex)) {
throw new Error('Invalid hex');
@@ -227,12 +235,12 @@ export class Address {
*/
public static fromHash160(
hash160: Uint8Array,
type: AddressType = 'P2PKH'
type: AddressType = 'P2PKH',
): Address {
// If the Hash160 bytes is not 20 in length, it is invalid...
if (hash160.length !== 20) {
throw new Error(
`Invalid hash160 length: Expected 20 (Received ${hash160.length})`
`Invalid hash160 length: Expected 20 (Received ${hash160.length})`,
);
}
@@ -251,7 +259,7 @@ export class Address {
*/
public static fromHash160Hex(
hash160Hex: string,
type: AddressType = 'P2PKH'
type: AddressType = 'P2PKH',
): Address {
if (!isHex(hash160Hex)) {
throw new Error('Invalid hex');
@@ -262,10 +270,14 @@ export class Address {
return Address.fromHash160(hash160Bytes, type);
}
public static fromRaw(addressContents: KnownAddressTypeContents) {
return new this(addressContents);
}
public static isValid(address: string): boolean {
try {
Address.fromCashAddrOrLegacy(address);
} catch (error) {
Address.from(address);
} catch (_error) {
return false;
}
@@ -275,7 +287,7 @@ export class Address {
public static isValidLegacy(address: string): boolean {
try {
Address.fromLegacy(address);
} catch (error) {
} catch (_error) {
return false;
}
@@ -285,7 +297,7 @@ export class Address {
public static isValidCashAddr(address: string): boolean {
try {
Address.fromCashAddr(address);
} catch (error) {
} catch (_error) {
return false;
}
@@ -330,25 +342,60 @@ export class Address {
*/
public toCashAddr(
networkPrefix: 'bitcoincash' | 'bchtest' | 'bchreg' = 'bitcoincash',
supportTokens = false
): string {
// Define the encode type in advance.
let encodeType: 'p2pkh' | 'p2sh' | 'p2pkhWithTokens' | 'p2shWithTokens';
let encodeType: 'p2pkh' | 'p2sh';
// Determine the encoding to use based on the Address Content's Type.
switch (this.addressContents.type) {
case 'P2PKH':
encodeType = supportTokens ? 'p2pkhWithTokens' : 'p2pkh';
encodeType = 'p2pkh';
break;
case 'P2SH20':
encodeType = supportTokens ? 'p2shWithTokens' : 'p2sh';
break;
case 'P2SH32':
encodeType = supportTokens ? 'p2shWithTokens' : 'p2sh';
encodeType = 'p2sh';
break;
default:
throw new Error(
`Unsupported address type: ${this.addressContents.type}`
`Unsupported address type: ${this.addressContents.type}`,
);
}
// NOTE: This function will throw if the payload is invalid.
return encodeCashAddress({
prefix: networkPrefix,
type: encodeType,
payload: this.addressContents.payload,
}).address;
}
/**
* Converts this address to a Tokens Address format.
*
* @param networkPrefix {'bitcoincash' | 'bchtest' | 'bchreg'} The Cash Address Network prefix.
*
* @throws {Error} If address cannot be encoded as a CashAddr.
*
* @returns {string} The address in Token Address format.
*/
public toTokenAddress(
networkPrefix: 'bitcoincash' | 'bchtest' | 'bchreg' = 'bitcoincash',
): string {
// Define the encode type in advance.
let encodeType: 'p2pkhWithTokens' | 'p2shWithTokens';
// Determine the encoding to use based on the Address Content's Type.
switch (this.addressContents.type) {
case 'P2PKH':
encodeType = 'p2pkhWithTokens';
break;
case 'P2SH20':
case 'P2SH32':
encodeType = 'p2shWithTokens';
break;
default:
throw new Error(
`Unsupported address type: ${this.addressContents.type}`,
);
}
@@ -381,7 +428,7 @@ export class Address {
break;
default:
throw new Error(
`Unsupported address type: ${this.addressContents.type}`
`Unsupported address type: ${this.addressContents.type}`,
);
}
@@ -419,4 +466,8 @@ export class Address {
return lockscriptAsm;
}
public toRaw() {
return { ...this.addressContents };
}
}
+182
View File
@@ -0,0 +1,182 @@
import { binToHex, hexToBin, isHex, hash256 } from '@bitauth/libauth';
export interface BlockHeaderRaw {
version: number;
previousBlockHash: Uint8Array;
merkleRoot: Uint8Array;
timestamp: number;
bits: number;
nonce: number;
}
/**
* Represents a Bitcoin Cash block header.
* This class handles parsing and serialization of BCH block headers between different formats
* (raw object, bytes, hex) and provides access to individual header fields.
*/
export class BlockHeader {
/**
* Creates a new BlockHeader instance.
* @param version - The block version
* @param previousBlockHash - Hash of the previous block (32 bytes)
* @param merkleRoot - Merkle root of the block's transactions (32 bytes)
* @param timestamp - Block timestamp in seconds since Unix epoch
* @param bits - Compact representation of the target threshold
* @param nonce - Value modified during mining to make the block hash valid
*/
constructor(
private readonly version: number,
private readonly previousBlockHash: Uint8Array,
private readonly merkleRoot: Uint8Array,
private readonly timestamp: number,
private readonly bits: number,
private readonly nonce: number,
) {}
/**
* Creates a BlockHeader instance from a byte array.
* @param bytes - 80-byte array containing the serialized block header
* @returns A new BlockHeader instance
* @throws Error if the byte array length is not 80
*/
static fromBytes(bytes: Uint8Array): BlockHeader {
if (bytes.length !== 80) {
throw new Error('Invalid block header length');
}
const view = new DataView(bytes.buffer);
return new BlockHeader(
view.getInt32(0, true),
bytes.slice(4, 36),
bytes.slice(36, 68),
view.getUint32(68, true),
view.getUint32(72, true),
view.getUint32(76, true),
);
}
/**
* Creates a BlockHeader instance from a hex string.
* @param hex - 160-character hex string representing the block header
* @returns A new BlockHeader instance
* @throws Error if the hex string length is not 160
*/
static fromHex(hex: string): BlockHeader {
// Ensure that the given string is hex.
if (!isHex(hex)) {
throw new Error('The given string is not valid hexadecimal.');
}
return BlockHeader.fromBytes(hexToBin(hex));
}
/**
* Creates a BlockHeader instance from a raw object representation.
* @param obj - Object containing the block header fields
* @returns A new BlockHeader instance
*/
static fromRaw(obj: BlockHeaderRaw): BlockHeader {
return new BlockHeader(
obj.version,
obj.previousBlockHash,
obj.merkleRoot,
obj.timestamp,
obj.bits,
obj.nonce,
);
}
/**
* Serializes the block header to a byte array.
* @returns 80-byte array containing the serialized block header
*/
toBytes(): Uint8Array {
const buffer = new ArrayBuffer(80);
const view = new DataView(buffer);
const bytes = new Uint8Array(buffer);
view.setInt32(0, this.version, true);
bytes.set(this.previousBlockHash, 4);
bytes.set(this.merkleRoot, 36);
view.setUint32(68, this.timestamp, true);
view.setUint32(72, this.bits, true);
view.setUint32(76, this.nonce, true);
return bytes;
}
/**
* Converts the block header to a raw object representation.
* @returns Object containing the block header fields
*/
toRaw(): BlockHeaderRaw {
return {
version: this.version,
previousBlockHash: this.previousBlockHash,
merkleRoot: this.merkleRoot,
timestamp: this.timestamp,
bits: this.bits,
nonce: this.nonce,
};
}
/**
* Converts the block header to a hex string.
* @returns 160-character hex string representing the block header
*/
toHex(): string {
return binToHex(this.toBytes());
}
// Getters
getVersion(): number {
return this.version;
}
getPreviousBlockHash(): Uint8Array {
return this.previousBlockHash;
}
getMerkleRoot(): Uint8Array {
return this.merkleRoot;
}
getTimestamp(): number {
return this.timestamp;
}
getBits(): number {
return this.bits;
}
getNonce(): number {
return this.nonce;
}
/**
* Gets the previous block hash as a hex string.
* @returns 64-character hex string
*/
getPreviousBlockHashHex(): string {
return binToHex(this.previousBlockHash);
}
/**
* Gets the merkle root as a hex string.
* @returns 64-character hex string
*/
getMerkleRootHex(): string {
return binToHex(this.merkleRoot);
}
/**
* Calculates the hash of this block header.
* @returns 32-byte array containing the block hash
*/
getHash(): Uint8Array {
return hash256(this.toBytes());
}
/**
* Gets the block hash as a hex string.
* @returns 64-character hex string
*/
getHashHex(): string {
return binToHex(this.getHash());
}
}
+31 -18
View File
@@ -27,6 +27,19 @@ export class Bytes {
this.bytes = bytes;
}
/**
* Instantiates bytes from an Uint8Array.
*
* @param bytes The bytes as a Uint8Array.
*
* @throws {Error} If Base64 is invalid.
*
* @returns Instance of Bytes.
*/
public static fromBytes(bytes: Uint8Array): Bytes {
return new this(bytes);
}
/**
* Instantiates bytes from a Base64 string.
*
@@ -34,7 +47,7 @@ export class Bytes {
*
* @throws {Error} If Base64 is invalid.
*
* @returns {Bytes} Instance of Bytes.
* @returns Instance of Bytes.
*/
public static fromBase64(base64: string): Bytes {
// If the Base64 is invalid, throw an error.
@@ -42,43 +55,43 @@ export class Bytes {
throw new Error('Invalid base64 string');
}
return new Bytes(base64ToBin(base64));
return new this(base64ToBin(base64));
}
/**
* Instantiates bytes from a BigInt (LE encoded).
*
* @param number {number} The bigint number.
* @param number The bigint number.
*
* @throws {Error} If number is invalid.
*
* @returns {Bytes} Instance of Bytes.
* @returns Instance of Bytes.
*/
public static fromBigInt(number: bigint): Bytes {
return new Bytes(bigIntToBinUintLE(number));
return new this(bigIntToBinUintLE(number));
}
/**
* Instantiates bytes from a BigInt (64 Bit LE encoded).
*
* @param number {number} The bigint number.
* @param number The bigint number.
*
* @throws {Error} If number is invalid.
*
* @returns {Bytes} Instance of Bytes.
* @returns Instance of Bytes.
*/
public static fromBigInt64(number: bigint): Bytes {
return new Bytes(bigIntToBinUint64LE(number));
return new this(bigIntToBinUint64LE(number));
}
/**
* Instantiates bytes from a hex string.
*
* @param hex {string} The hex string.
* @param hex The hex string.
*
* @throws {Error} If hex is invalid.
*
* @returns {Bytes} Instance of Bytes.
* @returns Instance of Bytes.
*/
public static fromHex(hex: string): Bytes {
// If the hex is invalid, throw an error.
@@ -86,24 +99,24 @@ export class Bytes {
throw new Error('Invalid hexidecimal string');
}
return new Bytes(hexToBin(hex));
return new this(hexToBin(hex));
}
/**
* Instantiates bytes from a UTF8 string.
*
* @param utf8 {string} The UTF8 string.
* @param utf8 The UTF8 string.
*
* @returns {Bytes} Instance of Bytes.
* @returns Instance of Bytes.
*/
public static fromUtf8(utf8: string): Bytes {
return new Bytes(utf8ToBin(utf8));
return new this(utf8ToBin(utf8));
}
/**
* Return bytes as a Base64 string.
*
* @returns {string} Bytes as a Base64 string.
* @returns Bytes as a Base64 string.
*/
public toBase64(): string {
return binToBase64(this.bytes);
@@ -116,7 +129,7 @@ export class Bytes {
/**
* Return bytes as a hex string.
*
* @returns {string} Bytes as a hex string.
* @returns Bytes as a hex string.
*/
public toHex(): string {
return binToHex(this.bytes);
@@ -125,7 +138,7 @@ export class Bytes {
/**
* Return bytes as a UTF8 string
*
* @returns {string} Bytes as a UTF8 string.
* @returns Bytes as a UTF8 string.
*/
public toUtf8(): string {
return binToUtf8(this.bytes);
@@ -134,7 +147,7 @@ export class Bytes {
/**
* Return bytes as a Uint8Array
*
* @returns {Uint8Array} Bytes as a Uint8Array.
* @returns Bytes as a Uint8Array.
*/
public toBytes(): Uint8Array {
return this.bytes;
-58
View File
@@ -1,58 +0,0 @@
import {
ripemd160,
sha256,
} from '@bitauth/libauth';
/**
* Crypto Module.
*/
export class Crypto
{
/**
* SHA256 hash the given input
*
* @param input {Uint8Array} The input to hash.
*
* @returns {Uint8Array} The SHA256 Hash of the given input.
*/
public static sha256(input: Uint8Array): Uint8Array
{
return sha256.hash(input);
}
/**
* RIPEMD160 hash the given input
*
* @param input {Uint8Array} The input to hash.
*
* @returns {Uint8Array} The RIPEMD160 Hash of the given input.
*/
public static ripemd160(input: Uint8Array): Uint8Array
{
return ripemd160.hash(input);
}
/**
* Double SHA256 hash the given input
*
* @param input {Uint8Array} The input to hash.
*
* @returns {Uint8Array} The Double SHA256 Hash of the given input.
*/
public static hash256(input: Uint8Array): Uint8Array
{
return sha256.hash(sha256.hash(input));
}
/**
* RIPEMD160 and then SHA256 hash the given input
*
* @param input {Uint16Array} The input to hash.
*
* @returns {Uint8Array} The RIPEMD160+SHA256 Hash of the given input.
*/
public static hash160(input: Uint8Array): Uint8Array
{
return ripemd160.hash(sha256.hash(input));
}
}
+122
View File
@@ -0,0 +1,122 @@
// TODO: These are intended as temporary stand-ins until this functionality has been implemented directly in LibAuth.
// We are doing this so that we may better standardize with the rest of the BCH eco-system in future.
// See: https://github.com/bitauth/libauth/pull/108
import { binToHex, hexToBin } from '@bitauth/libauth';
export const extendedJsonReplacer = function (value: any): any {
if (typeof value === 'bigint') {
return `<bigint: ${value.toString()}n>`;
} else if (value instanceof Uint8Array) {
return `<Uint8Array: ${binToHex(value)}>`;
}
return value;
};
export const extendedJsonReviver = function (value: any): any {
// Define RegEx that matches our Extended JSON fields.
const bigIntRegex = /^<bigint: (?<bigint>[+-]?[0-9]*)n>$/;
const uint8ArrayRegex = /^<Uint8Array: (?<hex>[a-f0-9]*)>$/;
// Only perform a check if the value is a string.
// NOTE: We can skip all other values as all Extended JSON encoded fields WILL be a string.
if (typeof value === 'string') {
// Check if this value matches an Extended JSON encoded bigint.
const bigintMatch = value.match(bigIntRegex);
if (bigintMatch) {
// Access the named group directly instead of using array indices
const { bigint } = bigintMatch.groups!;
// Return the value casted to bigint.
return BigInt(bigint);
}
const uint8ArrayMatch = value.match(uint8ArrayRegex);
if (uint8ArrayMatch) {
// Access the named group directly instead of using array indices
const { hex } = uint8ArrayMatch.groups!;
// Return the value casted to bigint.
return hexToBin(hex);
}
}
// Return the original value.
return value;
};
export const encodeExtendedJsonObject = function (value: any): any {
// If this is an object type (and it is not null - which is technically an "object")...
// ... and it is not an ArrayBuffer (e.g. Uint8Array) which is also technically an "object...
if (
typeof value === 'object' &&
value !== null &&
!ArrayBuffer.isView(value)
) {
// If this is an array, recursively call this function on each value.
if (Array.isArray(value)) {
return value.map(encodeExtendedJsonObject);
}
// Declare object to store extended JSON entries.
const encodedObject: any = {};
// Iterate through each entry and encode it to extended JSON.
for (const [key, valueToEncode] of Object.entries(value)) {
encodedObject[key] = encodeExtendedJsonObject(valueToEncode);
}
// Return the extended JSON encoded object.
return encodedObject;
}
// Return the replaced value.
return extendedJsonReplacer(value);
};
export const decodeExtendedJsonObject = function (value: any): any {
// If this is an object type (and it is not null - which is technically an "object")...
// ... and it is not an ArrayBuffer (e.g. Uint8Array) which is also technically an "object...
if (
typeof value === 'object' &&
value !== null &&
!ArrayBuffer.isView(value)
) {
// If this is an array, recursively call this function on each value.
if (Array.isArray(value)) {
return value.map(decodeExtendedJsonObject);
}
// Declare object to store decoded JSON entries.
const decodedObject: any = {};
// Iterate through each entry and decode it from extended JSON.
for (const [key, valueToEncode] of Object.entries(value)) {
decodedObject[key] = decodeExtendedJsonObject(valueToEncode);
}
// Return the extended JSON encoded object.
return decodedObject;
}
// Return the revived value.
return extendedJsonReviver(value);
};
export const encodeExtendedJson = function (
value: any,
space: number | undefined = undefined,
): string {
const replacedObject = encodeExtendedJsonObject(value);
const stringifiedObject = JSON.stringify(replacedObject, null, space);
return stringifiedObject;
};
export const decodeExtendedJson = function (json: string): any {
const parsedObject = JSON.parse(json);
const revivedObject = decodeExtendedJsonObject(parsedObject);
return revivedObject;
};
+137
View File
@@ -0,0 +1,137 @@
import {
isHex,
isBase64,
binToHex,
base64ToBin,
hexToBin,
utf8ToBin,
ripemd160,
sha256,
} from '@bitauth/libauth';
/**
* Represents a hash primitive that provides various cryptographic hashing capabilities.
* This class handles conversions between different formats (bytes, hex, UTF-8) and
* supports multiple hashing algorithms (SHA256, RIPEMD160, Hash160, Hash256).
*/
export class Hasher {
/**
* Creates a new Hash instance.
* @param bytes - The byte array representation of the data to be hashed
*/
constructor(public bytes: Uint8Array) {}
/**
* Creates a Hash instance from a byte array.
* @param bytes - The byte array to create the hash from
* @returns A new Hash instance containing the provided bytes
*/
public static fromBytes(bytes: Uint8Array) {
return new this(bytes);
}
/**
* Creates a Hash instance from a Base64 string.
* @param base64 - The Base64 string to create the hash from
* @returns A new Hash instance containing the bytes converted from the Base64 string
* @throws {Error} If the provided string is not valid Base64
*/
public static fromBase64(base64: string) {
// Ensure that the given string is base64.
if (!isBase64(base64)) {
throw new Error('The given string is not valid Base64.');
}
return new this(base64ToBin(base64));
}
/**
* Creates a Hash instance from a hexadecimal string.
* @param hex - The hexadecimal string to create the hash from
* @returns A new Hash instance containing the bytes converted from the hex string
* @throws {Error} If the provided string is not valid hexadecimal
*/
public static fromHex(hex: string) {
// Ensure that the given string is hex.
if (!isHex(hex)) {
throw new Error('The given string is not valid hexadecimal.');
}
return new this(hexToBin(hex));
}
/**
* Creates a Hash instance from a UTF-8 string.
* @param utf8 - The UTF-8 string to create the hash from
* @returns A new Hash instance containing the bytes converted from the UTF-8 string
*/
public static fromUTF8(utf8: string) {
return new this(utf8ToBin(utf8));
}
/**
* Computes the SHA256 hash of the stored bytes.
* @returns A Uint8Array containing the SHA256 hash
*/
public toSHA256Bytes(): Uint8Array {
return sha256.hash(this.bytes);
}
/**
* Computes the SHA256 hash of the stored bytes and returns it as a hexadecimal string.
* @returns The SHA256 hash as a hexadecimal string
*/
public toSHA256Hex(): string {
return binToHex(this.toSHA256Bytes());
}
/**
* Computes the RIPEMD160 hash of the stored bytes.
* @returns A Uint8Array containing the RIPEMD160 hash
*/
public toRIPEMD160Bytes(): Uint8Array {
return ripemd160.hash(this.bytes);
}
/**
* Computes the RIPEMD160 hash of the stored bytes and returns it as a hexadecimal string.
* @returns The RIPEMD160 hash as a hexadecimal string
*/
public toRIPEMD160Hex(): string {
return binToHex(this.toRIPEMD160Bytes());
}
/**
* Computes the Hash160 (RIPEMD160(SHA256(x))) of the stored bytes.
* This is commonly used in cryptocurrency addresses.
* @returns A Uint8Array containing the Hash160 value
*/
public toHash160Bytes(): Uint8Array {
return ripemd160.hash(this.toSHA256Bytes());
}
/**
* Computes the Hash160 (RIPEMD160(SHA256(x))) of the stored bytes and returns it as a hexadecimal string.
* @returns The Hash160 value as a hexadecimal string
*/
public toHash160Hex(): string {
return binToHex(this.toHash160Bytes());
}
/**
* Computes the Hash256 (SHA256(SHA256(x))) of the stored bytes.
* This is commonly used for computing block hashes in Bitcoin.
* @returns A Uint8Array containing the Hash256 value
*/
public toHash256Bytes(): Uint8Array {
return sha256.hash(this.toSHA256Bytes());
}
/**
* Computes the Hash256 (SHA256(SHA256(x))) of the stored bytes and returns it as a hexadecimal string.
* @returns The Hash256 value as a hexadecimal string
*/
public toHash256Hex(): string {
return binToHex(sha256.hash(this.toSHA256Bytes()));
}
}
+100 -17
View File
@@ -5,6 +5,7 @@ import {
encodeHdPrivateKey,
decodeHdPrivateKey,
deriveHdPath,
deriveHdPathRelative,
deriveHdPublicNode,
deriveHdPrivateNodeFromSeed,
deriveSeedFromBip39Mnemonic,
@@ -40,7 +41,21 @@ export class HDPrivateNode {
*
* @throws {Error} If HD Private Node cannot be created.
*
* @returns {HDPrivateNode} The created HD Private Node.
* @returns The created HD Private Node.
*/
public static fromBytes(seed: Uint8Array): HDPrivateNode {
// Return a new HD Private Node from the given seed.
return this.fromSeed(seed);
}
/**
* Creates a HD Private Node from a raw seed.
*
* @param seed The raw seed bytes.
*
* @throws {Error} If HD Private Node cannot be created.
*
* @returns The created HD Private Node.
*/
public static fromSeed(seed: Uint8Array): HDPrivateNode {
// If the seed is not 32 bytes, throw an error.
@@ -59,7 +74,7 @@ export class HDPrivateNode {
}
// Return a new HD Private Node from the given seed.
return new HDPrivateNode(deriveResult);
return new this(deriveResult);
}
/**
@@ -69,14 +84,14 @@ export class HDPrivateNode {
*
* @throws {Error} If HD Private Node cannot be created.
*
* @returns {HDPrivateNode} The created HD Private Node.
* @returns The created HD Private Node.
*/
public static fromMnemonic(mnemonic: string): HDPrivateNode {
// Derive the seed from the mnemonic.
const seed = deriveSeedFromBip39Mnemonic(mnemonic);
// Return a new HDPrivateNode from the given seed.
return HDPrivateNode.fromSeed(seed);
return this.fromSeed(seed);
}
/**
@@ -86,7 +101,7 @@ export class HDPrivateNode {
*
* @throws {Error} If HD Private Node cannot be created.
*
* @returns {HDPrivateNode} The created HD Private Node.
* @returns The created HD Private Node.
*/
public static fromXPriv(xpriv: string): HDPrivateNode {
// Attempt to decode the XPriv Key.
@@ -98,7 +113,18 @@ export class HDPrivateNode {
}
// Return a new HD Private Node from the given XPriv.
return new HDPrivateNode(decodeResult.node);
return new this(decodeResult.node);
}
/**
* Creates a HD Private Node from raw node data.
*
* @param node The raw node data.
*
* @returns The created HD Private Node.
*/
public static fromRaw(node: HdPrivateNodeValid) {
return new this(node);
}
/**
@@ -106,7 +132,7 @@ export class HDPrivateNode {
*
* @throws {Error} If HD Private Node cannot be created.
*
* @returns {HDPrivateNode} The created HD Private Node.
* @returns The created HD Private Node.
*/
public static generateRandom(): HDPrivateNode {
// Attempt to derive HD Private Node from randomly generated bytes.
@@ -118,23 +144,29 @@ export class HDPrivateNode {
}
// Return the new HD Private Node from the random bytes.
return new HDPrivateNode(deriveResult);
return new this(deriveResult);
}
/**
* Returns the XPriv string for this node.
* Checks if the given XPriv string is a valid HD Private Key.
*
* @returns {string} The XPriv string for this node.
* @param xpriv The XPriv string to check.
*
* @returns True if the XPriv string is valid, false otherwise.
*/
public toString(): string {
// Return the Mainnet XPriv.
return this.toXPriv();
public static isXPriv(xpriv: string): boolean {
try {
this.fromXPriv(xpriv);
return true;
} catch (_error) {
return false;
}
}
/**
* Gets the Private Key entity for this node.
*
* @returns {PrivateKey} The Private Key Entity for this node.
* @returns The Private Key Entity for this node.
*/
public privateKey(): PrivateKey {
// Return a Private Key Entity from the private key of our node.
@@ -148,7 +180,7 @@ export class HDPrivateNode {
*
* @throws {Error} If HD Private Node cannot be derived.
*
* @returns {HDPrivateNode} The derived HD Private Node
* @returns The derived HD Private Node
*/
public derivePath(path: string): HDPrivateNode {
// Attempt to derive the given path.
@@ -163,10 +195,32 @@ export class HDPrivateNode {
return new HDPrivateNode(derivePathResult);
}
/**
* Derives a HD Private Node from the given relative BIP32 path.
*
* @param path {string} The BIP32 Path (e.g. 0/0).
*
* @throws {Error} If HD Private Node cannot be derived.
*
* @returns The derived HD Private Node
*/
public deriveRelativePath(path: string): HDPrivateNode {
// Attempt to derive the given path.
const derivePathResult = deriveHdPathRelative(this.node, path);
// If a string is returned, this indicates an error...
if (typeof derivePathResult === 'string') {
throw new Error(derivePathResult);
}
// Return a new HD Private Node Entity derived from the given path.
return new HDPrivateNode(derivePathResult);
}
/**
* Derives a HD Public Node from this Private Node.
*
* @returns {HDPublicNode} The derived HD Public Node
* @returns The derived HD Public Node
*/
public deriveHDPublicNode(): HDPublicNode {
// Derive a HD Public Node from this HD Private Node.
@@ -176,12 +230,22 @@ export class HDPrivateNode {
return new HDPublicNode(publicNode);
}
/**
* Returns the Private Key of this node (as a Uint8Array).
*
* @returns The Node's Private Key (as a Uint8Array).
*/
public toBytes(): Uint8Array {
// Encode the XPriv from our node info.
return this.node.privateKey;
}
/**
* Converts this node to an XPriv Key for export.
*
* @param network {HdKeyNetwork} The network to encode for.
*
* @returns {string} The XPriv Key.
* @returns The XPriv Key.
*/
public toXPriv(network: HdKeyNetwork = 'mainnet'): string {
// Create our node info structure.
@@ -193,4 +257,23 @@ export class HDPrivateNode {
// Encode the XPriv from our node info.
return encodeHdPrivateKey(nodeInfo).hdPrivateKey;
}
/**
* Returns the XPriv string for this node.
*
* @returns The XPriv string for this node.
*/
public toString(): string {
// Return the Mainnet XPriv.
return this.toXPriv();
}
/**
* Returns the raw node data.
*
* @returns The raw node data.
*/
public toRaw(): HdPrivateNodeValid {
return this.node;
}
}
+30 -13
View File
@@ -50,20 +50,23 @@ export class HDPublicNode {
return new HDPublicNode(decodeResult.node);
}
/**
* Returns the XPub string for this node.
*
* @returns {string} The XPub string for this node.
*/
public toString(): string {
// Return the Mainnet XPub.
return this.toXPub();
public static fromRaw(node: HdPublicNodeValid) {
return new this(node);
}
public static isXPub(xpub: string): boolean {
try {
this.fromXPub(xpub);
return true;
} catch (_error) {
return false;
}
}
/**
* Gets the Public Key Entity for this node.
*
* @returns {PublicKey} The Public Key Entity for this node.
* @returns The Public Key Entity for this node.
*/
public publicKey(): PublicKey {
// Return a Public Key Entity from the public key of our node.
@@ -73,11 +76,11 @@ export class HDPublicNode {
/**
* Derives a HD Public Node from the given BIP32 path.
*
* @param path {string} The BIP32 Path (e.g. m/44'/145'/0'/0/1).
* @param path The BIP32 Path (e.g. m/44'/145'/0'/0/1).
*
* @throws {Error} If HD Public Node cannot be derived.
*
* @returns {HDPrivateNode} The derived HD Public Node
* @returns The derived HD Public Node
*/
public derivePath(path: string): HDPublicNode {
// Attempt to derive the given path.
@@ -95,9 +98,9 @@ export class HDPublicNode {
/**
* Converts this node to an XPub Key for export.
*
* @param network {HdKeyNetwork} The network to encode for.
* @param network The network to encode for.
*
* @returns {string} The XPub Key.
* @returns The XPub Key.
*/
public toXPub(network: HdKeyNetwork = 'mainnet'): string {
// Create our node info structure.
@@ -109,4 +112,18 @@ export class HDPublicNode {
// Encode the XPub from our node info.
return encodeHdPublicKey(nodeInfo).hdPublicKey;
}
public toRaw(): HdPublicNodeValid {
return this.node;
}
/**
* Returns the XPub string for this node.
*
* @returns {string} The XPub string for this node.
*/
public toString(): string {
// Return the Mainnet XPub.
return this.toXPub();
}
}
+6 -1
View File
@@ -1,11 +1,16 @@
export * from './address.js';
export * from './block-header.js';
export * from './bytes.js';
export * from './crypto.js';
export * from './ext-json.js';
export * from './hasher.js';
export * from './hd-private-node.js';
export * from './hd-public-node.js';
export * from './mnemonic.js';
export * from './private-key.js';
export * from './public-key.js';
export * from './satoshis.js';
export * from './script.js';
export * from './transaction.js';
export * from './transaction-hash.js';
export * from './utils.js';
export * from './utxo.js';
+246
View File
@@ -0,0 +1,246 @@
import {
generateBip39MnemonicNonStandard,
bip39WordListEnglish,
} from '@bitauth/libauth';
export type MnemonicRaw = {
words: string[];
passphrase?: string;
}
/**
* Class representing a BIP39 Mnemonic phrase.
* Supports 12, 15, 18, 21, and 24 word phrases with optional passphrase.
*/
export class Mnemonic {
public static VALID_WORD_COUNTS = new Set([12, 15, 18, 21, 24]);
/**
* Instantiate Mnemonic from a phrase string.
*
* @param phrase The complete phrase (mnemonic words + optional passphrase).
* @param wordList Optional wordlist (defaults to English BIP-39 wordlist).
* @throws {Error} If the mnemonic is invalid.
*/
constructor(private mnemonic: MnemonicRaw) {}
/**
* Instantiates a mnemonic from a string or array of words
*
* @param phraseOrWords The mnemonic phrase as a string or array of words
* @param dictionary Optional wordlist (defaults to English BIP-39 wordlist).
* @throws {Error} If mnemonic could not be generated.
* @returns Instance of Mnemonic.
*/
public static from(phraseOrWords: string | Array<string>, wordList: Array<string> = bip39WordListEnglish) {
// If this is a list of words...
if (Array.isArray(phraseOrWords)) {
return this.fromWords(phraseOrWords, wordList);
}
return this.fromString(phraseOrWords, wordList);
}
/**
* Instantiates a mnemonic from a string
*
* @param phrase The mnemonic phrase as a string
* @param dictionary Optional wordlist (defaults to English BIP-39 wordlist).
* @throws {Error} If mnemonic could not be generated.
* @returns Instance of Mnemonic.
*/
public static fromString(phrase: string, wordList: Array<string> = bip39WordListEnglish) {
// Split into words and remove any whitespace.
const allWords = phrase
.trim()
.split(/\s+/)
.map((word) => word.trim());
return this.fromWords(allWords, wordList);
}
/**
* Instantiates a mnemonic from an array of words.
*
* @param words Array of words (strings) that represent the mnemonic
* @param dictionary Optional wordlist (defaults to English BIP-39 wordlist).
* @throws {Error} If mnemonic could not be generated.
* @returns Instance of Mnemonic.
*/
public static fromWords(words: Array<string>, wordList: Array<string> = bip39WordListEnglish) {
// Check if last word is a passphrase by looking at total count
const hasPassphrase =
words.length === 13 ||
words.length === 16 ||
words.length === 19 ||
words.length === 22 ||
words.length === 25;
// Parse words and optional passphrase
const mnemonicRaw: MnemonicRaw = {
words: hasPassphrase ? words.slice(0, -1) : words,
}
if(hasPassphrase) {
mnemonicRaw.passphrase = words[words.length - 1]
}
// Validate word count
if (!Mnemonic.VALID_WORD_COUNTS.has(mnemonicRaw.words.length)) {
throw new Error(
`Invalid word count ${mnemonicRaw.words.length}. BIP-39 requires 12, 15, 18, 21, or 24 words` +
`${hasPassphrase ? ' (excluding passphrase)' : ''}`,
);
}
// Normalize and validate words against dictionary
const wordSet = new Set(wordList);
// Convert all words to lower-case.
mnemonicRaw.words = mnemonicRaw.words.map((word) => word.toLowerCase());
// Find any words that are not present in our dictionary (i.e. invalid words).
const invalidWords = mnemonicRaw.words.reduce((invalidWords, word) => {
if (!wordSet.has(word)) {
invalidWords.push(word);
}
return invalidWords;
}, [] as Array<string>);
// If there are invalid words that are not present in the provided dictionary, throw an error.
if (invalidWords.length) {
throw new Error(
`The following words are not valid with the provided dictionary: ${invalidWords.join(' ')}`,
);
}
return new this(mnemonicRaw);
}
/**
* Instantiates a mnemonic from its raw (serialized) mnemonic representation.
*
* @remarks this method is unsafe and should only use trusted data.
*
* @param mnemonicRaw The raw menmonic data.
* @throws {Error} If mnemonic could not be generated.
* @returns Instance of Mnemonic.
*/
public static fromRaw(mnemonicRaw: MnemonicRaw) {
return new this(mnemonicRaw);
}
/**
* Generates a random mnemonic phrase.
*
* @param dictionary Optional wordlist (defaults to English BIP-39 wordlist).
* @throws {Error} If mnemonic could not be generated.
* @returns Instance of Mnemonic.
*/
public static generateRandom(
passphrase?: string,
dictionary: string[] = bip39WordListEnglish,
): Mnemonic {
// Attempt to generate mnemonic.
const mnemonicResult = generateBip39MnemonicNonStandard(dictionary);
if (typeof mnemonicResult === 'string') {
throw new Error(mnemonicResult);
}
// Turn phrase parts (phrase) into an array so that we can append the passphrase later (if present).
const words = mnemonicResult.phrase.split(/\s+/);
// If there is a passphrase, append it.
if (passphrase) {
words.push(passphrase);
}
// Return the generated phrase (with passphrase appended - if present).
return this.fromWords(words, dictionary);
}
/**
* Validates a mnemonic phrase.
*
* @param phraseOrWords The mnemonic phrase or words to validate.
* @param wordList Optional wordlist (defaults to English BIP-39 wordlist).
* @returns boolean indicating if the phrase is valid.
*/
public static isValid(
phraseOrWords: string | Array<string>,
wordList: string[] = bip39WordListEnglish,
): boolean {
try {
this.from(phraseOrWords, wordList);
return true;
} catch {
return false;
}
}
/**
* Checks if a word exists in the provided dictionary.
*
* @param word Word to check.
* @param dictionary Optional wordlist (defaults to English BIP-39 wordlist).
* @returns boolean indicating if the word is valid.
*/
public static isValidWord(
word: string,
dictionary: string[] = bip39WordListEnglish,
): boolean {
return dictionary.includes(word.toLowerCase());
}
/**
* Gets the passphrase if one exists.
*
* @returns The passphrase or undefined if none exists.
*/
public getPassphrase(): string | undefined {
return this.mnemonic.passphrase;
}
/**
* Returns the complete phrase as a string.
*
* @param includePassphrase Whether to include the passphrase in the output.
* @returns Complete phrase as a string.
*/
public toString(includePassphrase: boolean = true): string {
// Join the menmonic words, separating them using a space character.
const mnemonicWords = this.mnemonic.words.join(' ');
// If we should include the passphrase - and a passphrase is present...
if (includePassphrase && this.mnemonic.passphrase) {
return `${mnemonicWords} ${this.mnemonic.passphrase}`;
}
// Return the words.
return mnemonicWords;
}
/**
* Gets the number of words in the mnemonic (excluding passphrase).
*
* @returns Number of words.
*/
public toWords(includePassphrase: boolean = true): Array<string> {
const words = [ ...this.mnemonic.words ];
if(this.mnemonic.passphrase && includePassphrase) {
words.push(this.mnemonic.passphrase);
}
return words;
}
/**
* Returns a serializable represntation of the class
*
* @returns A serializable reprentation of the class.
*/
public toRaw(): MnemonicRaw {
return { ...this.mnemonic };
}
}
+194 -66
View File
@@ -7,7 +7,6 @@ import {
generatePrivateKey,
hexToBin,
isHex,
binToUtf8,
utf8ToBin,
bigIntToCompactUint,
secp256k1,
@@ -37,7 +36,7 @@ export class PrivateKey {
// Ensure that the Private Key is valid.
if (!secp256k1.validatePrivateKey(bytes)) {
throw new Error(
`Private Key is invalid: Must be >= 0x01 and <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140.`
`Private Key is invalid: Must be >= 0x01 and <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140.`,
);
}
@@ -70,7 +69,7 @@ export class PrivateKey {
// Ensure that the given string is hex.
if (!isHex(privateKeyHex)) {
throw new Error(
`The given string (${privateKeyHex}) is not valid hexadecimal.`
`The given string (${privateKeyHex}) is not valid hexadecimal.`,
);
}
@@ -90,7 +89,7 @@ export class PrivateKey {
*/
public static fromWIF(
wif: string,
removePrefixes = ['bitcoincash:', 'wif:']
removePrefixes = ['bitcoincash:', 'wif:'],
): PrivateKey {
// Remove the prefixes from the WIF (if they exist).
const wifWithoutPrefixes = removePrefixes.reduce((result, prefix) => {
@@ -105,6 +104,22 @@ export class PrivateKey {
throw new Error(decodeResult);
}
// Ensure the Private Key is valid by checking the length (32 bytes = uncompressed private key, 33 bytes = compressed private key).
// NOTE: This is to work around a LibAuth bug where decodePrivateKeyWif does not verify the version of the Base58 string.
// This means that we will get a false positive on Base58/Legacy addresses as being valid WIFs.
// Once the below PR is merged into LibAuth (and we've updated to the new version), we can remove the following code.
// https://github.com/bitauth/libauth/pull/147
const isValidPrivateKey =
decodeResult.privateKey.length === 32 ||
decodeResult.privateKey.length === 33;
// If it is not a valid private key, then it is not a WIF,
if (!isValidPrivateKey) {
throw new Error(
`Expected 32 or 33 bytes WIF, received ${decodeResult.privateKey.length}`,
);
}
// Return a new Private Key entity.
return new PrivateKey(decodeResult.privateKey);
}
@@ -120,6 +135,15 @@ export class PrivateKey {
return new PrivateKey(bytes);
}
public static isWIF(wif: string, removePrefixes = ['bitcoincash:', 'wif:']) {
try {
this.fromWIF(wif, removePrefixes);
return true;
} catch (_error) {
return false;
}
}
/**
* Derive the public key from this private key.
*
@@ -141,101 +165,83 @@ export class PrivateKey {
}
/**
* Sign a message hash with this Private Key using a Recoverable Compact Signature.
* Sign a message using a recoverable compact signature format.
*
* @param messageHash {Uint8Array} The hash of the message.
* @param message The message to sign, either as a Uint8Array or string.
* If a string is provided, it will be converted to UTF-8 bytes.
*
* @throws {Error} If message hash cannot be signed.
* @throws {Error} If message cannot be signed.
*
* @returns {Uint8Array} The generated signature.
* @returns The generated recoverable compact signature.
*/
public signMessageHashRecoverableCompact(
messageHash: Uint8Array
): RecoverableSignature {
// Attempt to sign the message.
const signResult = secp256k1.signMessageHashRecoverableCompact(
this.bytes,
messageHash
);
// If a string is returned, this indicates an error...
if (typeof signResult === 'string') {
throw new Error(signResult);
public signMessageRecoverableCompact(message: Uint8Array | string) {
if (typeof message === 'string') {
message = utf8ToBin(message);
}
// Return the signature.
return signResult;
const messageHash = sha256.hash(message);
return this.signMessageHashRecoverableCompact(messageHash);
}
/**
* Sign a message hash with this Private Key using a Compact Signature.
* Sign a message using a compact signature format.
*
* @param messageHash {Uint8Array} The hash of the message.
* @param message The message to sign, either as a Uint8Array or string.
* If a string is provided, it will be converted to UTF-8 bytes.
*
* @throws {Error} If message hash cannot be signed.
* @throws {Error} If message cannot be signed.
*
* @returns {Uint8Array} The generated signature.
* @returns The generated compact signature.
*/
public signMessageHashCompact(messageHash: Uint8Array): Uint8Array {
// Attempt to sign the message.
const signResult = secp256k1.signMessageHashCompact(
this.bytes,
messageHash
);
// If a string is returned, this indicates an error...
if (typeof signResult === 'string') {
throw new Error(signResult);
public signMessageCompact(message: Uint8Array | string) {
if (typeof message === 'string') {
message = utf8ToBin(message);
}
// Return the signature.
return signResult;
const messageHash = sha256.hash(message);
return this.signMessageHashCompact(messageHash);
}
/**
* Sign a message hash with this Private Key using a Schnorr Signature.
* Sign a message using the Schnorr signature scheme.
*
* @param messageHash {Uint8Array} The hash of the message.
* @param message The message to sign, either as a Uint8Array or string.
* If a string is provided, it will be converted to UTF-8 bytes.
*
* @throws {Error} If message hash cannot be signed.
* @throws {Error} If message cannot be signed.
*
* @returns {Uint8Array} The generated signature.
* @returns The generated Schnorr signature.
*/
public signMessageHashSchnorr(messageHash: Uint8Array): Uint8Array {
// Attempt to sign the message.
const signResult = secp256k1.signMessageHashSchnorr(
this.bytes,
messageHash
);
// If a string is returned, this indicates an error...
if (typeof signResult === 'string') {
throw new Error(signResult);
public signMessageSchnorr(message: Uint8Array | string) {
if (typeof message === 'string') {
message = utf8ToBin(message);
}
// Return the signature.
return signResult;
const messageHash = sha256.hash(message);
return this.signMessageHashSchnorr(messageHash);
}
/**
* Sign a message hash with this Private Key using a DER Signature.
* Sign a message using DER (Distinguished Encoding Rules) format.
*
* @param messageHash {Uint8Array} The hash of the message.
* @param message The message to sign, either as a Uint8Array or string.
* If a string is provided, it will be converted to UTF-8 bytes.
*
* @throws {Error} If message hash cannot be signed.
* @throws {Error} If message cannot be signed.
*
* @returns {Uint8Array} The generated signature.
* @returns The generated DER signature.
*/
public signMessageHashDER(messageHash: Uint8Array): Uint8Array {
const signResult = secp256k1.signMessageHashDER(this.bytes, messageHash);
// If a string is returned, this indicates an error...
if (typeof signResult === 'string') {
throw new Error(signResult);
public signMessageDER(message: Uint8Array | string) {
if (typeof message === 'string') {
message = utf8ToBin(message);
}
// Return the signature.
return signResult;
const messageHash = sha256.hash(message);
return this.signMessageHashDER(messageHash);
}
/**
@@ -279,6 +285,128 @@ export class PrivateKey {
return electronEncoding;
}
/**
* Sign a message hash with this Private Key using a Recoverable Compact Signature.
*
* @param messageHash {Uint8Array} The hash of the message.
*
* @throws {Error} If message hash cannot be signed.
*
* @returns {Uint8Array} The generated signature.
*/
public signMessageHashRecoverableCompact(
messageHash: Uint8Array | string,
): RecoverableSignature {
// If a string was given, convert it from hex to bytes.
// TODO: Consider using Bytes class - it ensures valid hex.
if (typeof messageHash === 'string') {
messageHash = hexToBin(messageHash);
}
// Attempt to sign the message.
const signResult = secp256k1.signMessageHashRecoverableCompact(
this.bytes,
messageHash,
);
// If a string is returned, this indicates an error...
if (typeof signResult === 'string') {
throw new Error(signResult);
}
// Return the signature.
return signResult;
}
/**
* Sign a message hash with this Private Key using a Compact Signature.
*
* @param messageHash {Uint8Array} The hash of the message.
*
* @throws {Error} If message hash cannot be signed.
*
* @returns {Uint8Array} The generated signature.
*/
public signMessageHashCompact(messageHash: Uint8Array | string): Uint8Array {
// If a string was given, convert it from hex to bytes.
// TODO: Consider using Bytes class - it ensures valid hex.
if (typeof messageHash === 'string') {
messageHash = hexToBin(messageHash);
}
// Attempt to sign the message.
const signResult = secp256k1.signMessageHashCompact(
this.bytes,
messageHash,
);
// If a string is returned, this indicates an error...
if (typeof signResult === 'string') {
throw new Error(signResult);
}
// Return the signature.
return signResult;
}
/**
* Sign a message hash with this Private Key using a Schnorr Signature.
*
* @param messageHash {Uint8Array} The hash of the message.
*
* @throws {Error} If message hash cannot be signed.
*
* @returns {Uint8Array} The generated signature.
*/
public signMessageHashSchnorr(messageHash: Uint8Array | string): Uint8Array {
// If a string was given, convert it from hex to bytes.
// TODO: Consider using Bytes class - it ensures valid hex.
if (typeof messageHash === 'string') {
messageHash = hexToBin(messageHash);
}
// Attempt to sign the message.
const signResult = secp256k1.signMessageHashSchnorr(
this.bytes,
messageHash,
);
// If a string is returned, this indicates an error...
if (typeof signResult === 'string') {
throw new Error(signResult);
}
// Return the signature.
return signResult;
}
/**
* Sign a message hash with this Private Key using a DER Signature.
*
* @param messageHash {Uint8Array} The hash of the message.
*
* @throws {Error} If message hash cannot be signed.
*
* @returns {Uint8Array} The generated signature.
*/
public signMessageHashDER(messageHash: Uint8Array | string): Uint8Array {
// If a string was given, convert it from hex to bytes.
// TODO: Consider using Bytes class - it ensures valid hex.
if (typeof messageHash === 'string') {
messageHash = hexToBin(messageHash);
}
const signResult = secp256k1.signMessageHashDER(this.bytes, messageHash);
// If a string is returned, this indicates an error...
if (typeof signResult === 'string') {
throw new Error(signResult);
}
// Return the signature.
return signResult;
}
/**
* Convert the raw bytes of this Private Key to hexadecimal encoding.
*
+83 -27
View File
@@ -7,6 +7,7 @@ import {
secp256k1,
sha256,
ripemd160,
utf8ToBin,
} from '@bitauth/libauth';
/**
@@ -19,7 +20,7 @@ export class PublicKey {
/**
* Construct a new Public Key.
*
* @param bytes {Uint8Array} The raw bytes (33) for the Public Key.
* @param bytes The raw bytes (33) for the Public Key.
*/
constructor(bytes: Uint8Array) {
// Ensure that exactly 33 Bytes are given.
@@ -33,17 +34,30 @@ export class PublicKey {
/**
* Create a Public Key entity from the given hexadecimal string.
*
* @param publicKeyHex {string} Hexadecimal encoding of the Public Key bytes.
* @param publicKeyBytes Uint8Array containing the Public Key bytes.
*
* @throws {Error} If Public Key cannot be created.
*
* @returns {PublicKey} The created Public Key entity.
* @returns The created Public Key entity.
*/
public static fromBytes(publicKeyBytes: Uint8Array): PublicKey {
return new PublicKey(publicKeyBytes);
}
/**
* Create a Public Key entity from the given hexadecimal string.
*
* @param publicKeyHex Hexadecimal encoding of the Public Key bytes.
*
* @throws {Error} If Public Key cannot be created.
*
* @returns The created Public Key entity.
*/
public static fromHex(publicKeyHex: string): PublicKey {
// Ensure that the given string is hex.
if (!isHex(publicKeyHex)) {
throw new Error(
`The given string (${publicKeyHex}) is not valid hexadecimal.`
`The given string (${publicKeyHex}) is not valid hexadecimal.`,
);
}
@@ -57,7 +71,7 @@ export class PublicKey {
/**
* Derive the Hash160 for this Public Key.
*
* @returns {Uint8Array} The Hash160 of the Public Key.
* @returns The Hash160 of the Public Key.
*/
public deriveHash160(): Uint8Array {
// SHA256 Hash the public key.
@@ -73,7 +87,7 @@ export class PublicKey {
/**
* Derive the Hash160 as Hex for this Public Key.
*
* @returns {string} The Hash160 of the Public Key as hex.
* @returns The Hash160 of the Public Key as hex.
*/
public deriveHash160Hex(): string {
const hash160Bytes = this.deriveHash160();
@@ -84,7 +98,7 @@ export class PublicKey {
/**
* Derive the Address for this Public Key.
*
* @returns {Address} The Address for this Public Key.
* @returns The Address for this Public Key.
*/
public deriveAddress(): Address {
// Get the RIPEMD160 Hash of the Public Key.
@@ -94,22 +108,48 @@ export class PublicKey {
return Address.fromHash160(ripemd160Hash, 'P2PKH');
}
public verifyMessageSchnorr(
message: Uint8Array | string,
signature: Uint8Array | string,
) {
if (typeof message === 'string') {
message = utf8ToBin(message);
}
const messageHash = sha256.hash(message);
return this.verifyMessageHashSchnorr(messageHash, signature);
}
public verifyMessageDER(
message: Uint8Array | string,
signature: Uint8Array | string,
) {
if (typeof message === 'string') {
message = utf8ToBin(message);
}
const messageHash = sha256.hash(message);
return this.verifyMessageHashDER(messageHash, signature);
}
/**
* Verify that a compact message hash was signed with the corresponding Private Key.
*
* @param messageHash {Uint8Array} The hash of the message.
* @param signature {Uint8Array) The signature of the message.
* @param messageHash The hash of the message.
* @param signature The signature of the message.
*
* @returns {boolean} True if signature and message hash verifies, false otherwise..
* @returns True if signature and message hash verifies, false otherwise..
*/
public verifyMessageHashCompact(
messageHash: Uint8Array,
signature: Uint8Array
signature: Uint8Array,
): boolean {
const validity = secp256k1.verifySignatureCompact(
signature,
this.bytes,
messageHash
messageHash,
);
return validity;
@@ -118,19 +158,27 @@ export class PublicKey {
/**
* Verify that a DER message hash was signed with the corresponding Private Key.
*
* @param messageHash {Uint8Array} The hash of the message.
* @param signature {Uint8Array) The signature of the message.
* @param messageHash The hash of the message.
* @param signature The signature of the message.
*
* @returns {boolean} True if signature and message hash verifies, false otherwise..
* @returns True if signature and message hash verifies, false otherwise..
*/
public verifyMessageHashDER(
messageHash: Uint8Array,
signature: Uint8Array
messageHash: Uint8Array | string,
signature: Uint8Array | string,
): boolean {
if (typeof messageHash === 'string') {
messageHash = hexToBin(messageHash);
}
if (typeof signature === 'string') {
signature = hexToBin(signature);
}
const validity = secp256k1.verifySignatureDER(
signature,
this.bytes,
messageHash
messageHash,
);
return validity;
@@ -139,19 +187,27 @@ export class PublicKey {
/**
* Verify that a Schnorr message hash was signed with the corresponding Private Key.
*
* @param messageHash {Uint8Array} The hash of the message.
* @param signature {Uint8Array) The signature of the message.
* @param messageHash The hash of the message.
* @param signature The signature of the message.
*
* @returns {boolean} True if signature and message hash verifies, false otherwise..
* @returns True if signature and message hash verifies, false otherwise..
*/
public verifyMessageHashSchnorr(
messageHash: Uint8Array,
signature: Uint8Array
messageHash: Uint8Array | string,
signature: Uint8Array | string,
): boolean {
if (typeof messageHash === 'string') {
messageHash = hexToBin(messageHash);
}
if (typeof signature === 'string') {
signature = hexToBin(signature);
}
const validity = secp256k1.verifySignatureSchnorr(
signature,
this.bytes,
messageHash
messageHash,
);
return validity;
@@ -160,7 +216,7 @@ export class PublicKey {
/**
* Encode the raw bytes of this Public Key to a hexadecimal representation.
*
* @returns {string} The raw bytes Public Key encoded as Hexadecimal.
* @returns The raw bytes Public Key encoded as Hexadecimal.
*/
public toHex(): string {
return binToHex(this.bytes);
@@ -169,7 +225,7 @@ export class PublicKey {
/**
* Get the raw bytes of this Public Key.
*
* @returns {Uint8Array} The raw bytes of the Public Key.
* @returns The raw bytes of the Public Key.
*/
public toBytes(): Uint8Array {
// Return the raw bytes for this Public Key.
@@ -179,7 +235,7 @@ export class PublicKey {
/**
* Return the hexadecimal representation of the raw bytes of the Public Key.
*
* @returns {string} The raw bytes of the Public Key as hexadecimal.
* @returns The raw bytes of the Public Key as hexadecimal.
*/
public toString(): string {
// Return the raw Public Key byes encoded as a hexadecimal string.
+14
View File
@@ -6,6 +6,7 @@ import {
binToHex,
hexToBin,
isHex,
parseScript,
} from '@bitauth/libauth';
/**
@@ -23,6 +24,19 @@ export class Script {
this.bytes = bytes;
}
/**
* Create a Script Entity from the given Assembly String.
*
* @param asm {string} String of assembly code.
*
* @throws {Error} If script cannot be decoded.
*
* @returns {Script} The created Script Entity.
*/
public static fromBytes(bytes: Uint8Array): Script {
return new Script(bytes);
}
/**
* Create a Script Entity from the given Assembly String.
*
+78 -89
View File
@@ -1,106 +1,95 @@
import {
binToHex,
hexToBin,
hashTransaction,
isHex,
} from '@bitauth/libauth';
import { binToHex, hexToBin, hashTransaction, isHex } from '@bitauth/libauth';
/**
* Transaction Hash Primitive.
*/
export class TransactionHash
{
public readonly bytes: Uint8Array;
export class TransactionHash {
public readonly bytes: Uint8Array;
/**
* Instantiates TransactionHash from a Transaction Hash's bytes.
*
* @param bytes {Uint8Array} The Transaction Hash's bytes.
*/
constructor(bytes: Uint8Array)
{
// If bytes is not exactly 32, then this is an invalid transaction hash...
if(bytes.length !== 32)
{
throw(new Error(`Invalid Transaction Hash: Expected 32 bytes but received ${bytes.length}`));
}
/**
* Instantiates TransactionHash from a Transaction Hash's bytes.
*
* @param bytes {Uint8Array} The Transaction Hash's bytes.
*/
constructor(bytes: Uint8Array) {
// If bytes is not exactly 32, then this is an invalid transaction hash...
if (bytes.length !== 32) {
throw new Error(
`Invalid Transaction Hash: Expected 32 bytes but received ${bytes.length}`,
);
}
this.bytes = bytes;
}
this.bytes = bytes;
}
/**
* Instantiates TransactionHash from a hex string.
*
* @param hex {string} The hex string.
*
* @throws {Error} If hex is invalid.
*
* @returns {TransactionHash} Instance of TransactionHash.
*/
public static fromHex(hex: string): TransactionHash
{
if(!isHex(hex))
{
throw(new Error('Invalid hex provided'));
}
/**
* Instantiates TransactionHash from a hex string.
*
* @param hex {string} The hex string.
*
* @throws {Error} If hex is invalid.
*
* @returns {TransactionHash} Instance of TransactionHash.
*/
public static fromHex(hex: string): TransactionHash {
if (!isHex(hex)) {
throw new Error('Invalid hex provided');
}
const bytes = hexToBin(hex);
const bytes = hexToBin(hex);
return new TransactionHash(bytes);
}
return new TransactionHash(bytes);
}
/**
* Instantiates TransactionHash from a Transaction's bytes.
*
* @param transactionBytes {Uint8Array} The Transaction's bytes.
*
* @returns {TransactionHash} Instance of TransactionHash.
*/
public static fromTransactionBytes(transactionBytes: Uint8Array): TransactionHash
{
const transactionHash = hashTransaction(transactionBytes);
/**
* Instantiates TransactionHash from a Transaction's bytes.
*
* @param transactionBytes {Uint8Array} The Transaction's bytes.
*
* @returns {TransactionHash} Instance of TransactionHash.
*/
public static fromTransactionBytes(
transactionBytes: Uint8Array,
): TransactionHash {
const transactionHash = hashTransaction(transactionBytes);
return new TransactionHash(hexToBin(transactionHash));
}
return new TransactionHash(hexToBin(transactionHash));
}
/**
* Instantiates TransactionHash from a Transaction's bytes in hex.
*
* @param transactionHex {Uint8Array} The Transaction's bytes in hex.
*
* @throws {Error} If hex is invalid.
*
* @returns {TransactionHash} Instance of TransactionHash.
*/
public static fromTransactionHex(transactionHex: string): TransactionHash
{
if(!isHex(transactionHex))
{
throw(new Error('Invalid hex provided'));
}
/**
* Instantiates TransactionHash from a Transaction's bytes in hex.
*
* @param transactionHex {Uint8Array} The Transaction's bytes in hex.
*
* @throws {Error} If hex is invalid.
*
* @returns {TransactionHash} Instance of TransactionHash.
*/
public static fromTransactionHex(transactionHex: string): TransactionHash {
if (!isHex(transactionHex)) {
throw new Error('Invalid hex provided');
}
const bytes = hexToBin(transactionHex);
const bytes = hexToBin(transactionHex);
return TransactionHash.fromTransactionBytes(bytes);
}
return TransactionHash.fromTransactionBytes(bytes);
}
/**
* Returns transaction hash as a hex string.
*
* @returns {string} Hex string of the Transaction Hash.
*/
public toHex(): string
{
return binToHex(this.bytes);
}
/**
* Returns transaction hash as a hex string.
*
* @returns {string} Hex string of the Transaction Hash.
*/
public toHex(): string {
return binToHex(this.bytes);
}
/**
* Returns transaction hash as a Uint8Array.
*
* @returns {Uint8Array} Uint8Array of the Transaction Hash.
*/
public toBytes(): Uint8Array
{
return this.bytes;
}
/**
* Returns transaction hash as a Uint8Array.
*
* @returns {Uint8Array} Uint8Array of the Transaction Hash.
*/
public toBytes(): Uint8Array {
return this.bytes;
}
}
+71 -34
View File
@@ -10,19 +10,47 @@ import {
import type { TransactionBCH } from '@bitauth/libauth';
/**
* Transaction Entity.
* Transaction Primitive.
*/
export class Transaction {
constructor(public transaction: TransactionBCH) {}
/**
* Create a Transaction Entity from the given byte data.
* Instantiates a transaction from either:
*
* @param bytes {Uint8Array} The raw byte data of the transaction.
* 1. Transaction bytecode
* 2. Transaction bytecode (in hexadecimal format)
*
* @param transaction The transaction in one of the above formats.
*
* @throws {Error} If transaction data cannot be decoded.
*
* @returns {Transaction} The created Transaction Entity.
* @returns The created Transaction Primitive.
*/
public static from(transaction: Uint8Array | string) {
// Handle string (hex) case
if (typeof transaction === 'string') {
return Transaction.fromHex(transaction);
}
// Handle Uint8Array case
if (transaction instanceof Uint8Array) {
return Transaction.fromBytes(transaction);
}
throw new TypeError(
'Invalid transaction input type. Expected Uint8Array, or hex string',
);
}
/**
* Create a Transaction Primitive from the given byte data.
*
* @param bytes The raw byte data of the transaction.
*
* @throws {Error} If transaction data cannot be decoded.
*
* @returns {Transaction} The created Transaction Primitive.
*/
public static fromBytes(bytes: Uint8Array): Transaction {
// Attempt to decode the raw transaction bytes.
@@ -33,18 +61,18 @@ export class Transaction {
throw new Error(decodeResult);
}
// Return a new instance of the Transaction Entity created from the decode result.
// Return a new instance of the Transaction Primitive created from the decode result.
return new Transaction(decodeResult);
}
/**
* Create a Transaction Entity from the given byte data encoded as hexadecimal string.
* Create a Transaction Primitive from the given byte data encoded as hexadecimal string.
*
* @param hex {string} The raw byte data (encoded as hexadecimal string) of the transaction.
* @param hex The raw byte data (encoded as hexadecimal string) of the transaction.
*
* @throws {Error} If transaction cannot be decoded.
*
* @returns {Transaction} The created Transaction Entity.
* @returns {Transaction} The created Transaction Primitive.
*/
public static fromHex(hex: string): Transaction {
// Ensure that the given string is hex.
@@ -59,12 +87,17 @@ export class Transaction {
return Transaction.fromBytes(bytes);
}
public static fromAny(bytesOrHex: Uint8Array | string) {
if (typeof bytesOrHex === 'string') {
return Transaction.fromHex(bytesOrHex);
}
return Transaction.fromBytes(bytesOrHex);
/**
* Create a Transaction Primitive from LibAuth's TransactionBCH type.
*
* @remarks This method is UNSAFE and should only be used where input is trusted.
*
* @param transaction The transaction object (as per LibAuth).
*
* @returns The created Transaction Primitive.
*/
public static fromRaw(transaction: TransactionBCH) {
return new this(transaction);
}
public toBytes(): Uint8Array {
@@ -91,6 +124,30 @@ export class Transaction {
return this.toHash().toBytes();
}
public toRaw(): TransactionBCH {
return this.transaction;
}
public isCoinbase(): boolean {
// A coinbase transaction MUST only have one input
if (this.getInputs().length !== 1) {
return false;
}
const input = this.getInputs()[0];
// Check if the outpoint transaction hash is all zeros (32 bytes of 0x00)
const isOutpointZero = input.outpointTransactionHash.every(
(byte) => byte === 0x00,
);
// Check if the outpoint index is 0xFFFFFFFF (or -1 in signed 32-bit integer representation)
const isOutpointIndexMax = input.outpointIndex === 0xffffffff;
// Both conditions must be true for a coinbase transaction
return isOutpointZero && isOutpointIndexMax;
}
public getVersion() {
return this.transaction.version;
}
@@ -106,24 +163,4 @@ export class Transaction {
public getLocktime() {
return this.transaction.locktime;
}
public isCoinbase(): boolean {
// A coinbase transaction MUST only have one input
if (this.getInputs().length !== 1) {
return false;
}
const input = this.getInputs()[0];
// Check if the outpoint transaction hash is all zeros (32 bytes of 0x00)
const isOutpointZero = input.outpointTransactionHash.every(
(byte) => byte === 0x00
);
// Check if the outpoint index is 0xFFFFFFFF (or -1 in signed 32-bit integer representation)
const isOutpointIndexMax = input.outpointIndex === 0xffffffff;
// Both conditions must be true for a coinbase transaction
return isOutpointZero && isOutpointIndexMax;
}
}
+168
View File
@@ -0,0 +1,168 @@
import { Transaction } from './transaction.js';
import { binToHex } from '@bitauth/libauth';
/**
* Sort transactions by the order in which they should be broadcast.
*/
export function sortTransactions(
transactions: Array<Transaction>,
): Array<Transaction> {
const transactionMap = transactions.reduce(
(map, transaction) => {
const txHash = transaction.toHash().toHex();
map[txHash] = transaction;
return map;
},
{} as Record<string, Transaction>,
);
const visited = new Set<string>();
const order: Transaction[] = [];
const visit = (txid: string) => {
if (visited.has(txid)) return;
const tx = transactionMap[txid];
if (!tx) return;
visited.add(txid);
// First, visit all transactions that this transaction depends on
for (const input of tx.getInputs()) {
const outpointTransactionHashHex = binToHex(
input.outpointTransactionHash,
);
visit(outpointTransactionHashHex);
}
order.push(tx);
};
// Start the topological sort from each transaction
for (const tx of Object.values(transactionMap)) {
visit(tx.toHash().toHex());
}
return order;
}
export class ExtMap<T> extends Map<PropertyKey, T> {
/**
* Creates a new ExtMap from an array using a key selector
*/
static fromArray<T, K extends PropertyKey>(
array: readonly T[],
keySelector: (item: T) => K,
): ExtMap<T> {
const collection = new ExtMap<T>();
array.forEach((item) => {
const key = keySelector(item);
collection.set(key, item);
});
return collection;
}
static fromObject<T>(object: { [key: PropertyKey]: T }): ExtMap<T> {
const collection = new ExtMap<T>();
for (let [key, value] of Object.entries(object)) {
collection.set(key, value);
}
return collection;
}
/**
* Flattens an array of ExtMaps into a single ExtMap
* Last collection's values take precedence for duplicate keys
*/
static flatten<T>(collections: ExtMap<T>[]): ExtMap<T> {
const flattened = new ExtMap<T>();
collections.forEach((collection) => {
for (const [key, value] of collection.entries()) {
flattened.set(key, value);
}
});
return flattened;
}
getOrFail(key: string): T {
const value = this.get(key);
if (!value) {
throw new Error(`Failed to find key "${key}"`);
}
return value;
}
/**
* Returns a new ExtMap with filtered entries
*/
filter(predicate: (value: T, key: PropertyKey) => boolean): ExtMap<T> {
const filtered = new ExtMap<T>();
for (const [key, value] of this.entries()) {
if (predicate(value, key)) {
filtered.set(key, value);
}
}
return filtered;
}
/**
* Returns a new ExtMap with mapped values
*/
map<U>(mapper: (value: T, key: PropertyKey) => U): ExtMap<U> {
const mapped = new ExtMap<U>();
for (const [key, value] of this.entries()) {
mapped.set(key, mapper(value, key));
}
return mapped;
}
/**
* Returns a new ExtMap with entries sorted by the given comparator
* @param comparator - Function to determine the sort order
* @returns A new ExtMap with sorted entries
*/
sort(comparator: (a: T, b: T) => number): ExtMap<T> {
const entries = Array.from(this.entries());
const sorted = new ExtMap<T>();
entries
.sort(([, valueA], [, valueB]) => comparator(valueA, valueB))
.forEach(([key, value]) => {
sorted.set(key, value);
});
return sorted;
}
/**
* Converts the collection to a plain object
*/
toObject(): Record<PropertyKey, T> {
return Object.fromEntries(this.entries());
}
/**
* Converts the collection to an array of values
*/
toArray(): T[] {
return Array.from(this.values());
}
/**
* Converts the collection to a Set
* @param callback - Optional function to transform keys before adding to Set
* @returns A Set containing either the keys or transformed values
*/
toSet<U = PropertyKey>(callback?: (key: PropertyKey, value: T) => U): Set<U> {
const set = new Set<U>();
for (const [key, value] of this.entries()) {
set.add(callback ? callback(key, value) : (key as U));
}
return set;
}
}
+78
View File
@@ -0,0 +1,78 @@
import { type Input, type Output, binToHex } from '@bitauth/libauth';
import { ExtMap } from './utils.js';
// TODO: I want to make these a class.
// But it's really painful to do in TS.
// TS cannot extend an interface, it can only implement them.
// This means that we would have to redefine each property explicitly.
// But a getId function on UTXOs would be ergonomic.
// TODO: Maybe just compose it and have an "output" object, ya' dingus.
export class Outpoint {
constructor(
public outpointTransactionHash: Uint8Array,
public outpointIndex: number,
) {}
static fromInput(
input: Pick<Input, 'outpointTransactionHash' | 'outpointIndex'>,
) {
return new this(input.outpointTransactionHash, input.outpointIndex);
}
toString() {
const outpointHashHex = binToHex(this.outpointTransactionHash);
return `${outpointHashHex}:${this.outpointIndex}`;
}
}
export class UTXO {
constructor(
public outpoint: Outpoint,
public output: Output,
) {}
static from(outpoint: Outpoint, output: Output) {
return new this(outpoint, output);
}
flatten() {
return {
...this.outpoint,
...this.output,
};
}
}
export type UTXOSet = ExtMap<UTXO>;
// TODO: Sort me better. If you work out a better name for your UTXO Set above, you might be able to put me in that class.
// Or maybe I do just work best as a stand-alone function?
// “Sometimes, the elegant implementation is just a function. Not a method. Not a class. Not a framework. Just a function.” — John Carmack
export function calculateBalanceSats(unspents: Array<UTXO>) {
// Iterate over each unspent and return the total satoshi balance.
return unspents.reduce((totalSats, unspent) => {
return (totalSats = totalSats + unspent.output.valueSatoshis);
}, 0n);
}
export type TokenBalances = { [categoryId: string]: bigint };
export function calculateBalanceTokens(unspents: Array<UTXO>) {
// Declare an object to store token category IDs to their balances.
const tokenBalances: TokenBalances = {};
// Iterate through each unspent and, if it has a token, add it to our balances.
unspents.forEach((unspent) => {
if (unspent.output.token) {
const tokenCategoryHex = binToHex(unspent.output.token.category);
const currentTokenTotal = tokenBalances[tokenCategoryHex] || 0n;
const newTotal = currentTokenTotal + unspent.output.token.amount;
tokenBalances[tokenCategoryHex] = newTotal;
}
});
// Return the token balances map.
return tokenBalances;
}
+320
View File
@@ -0,0 +1,320 @@
import { describe, it, expect } from 'vitest';
import { Mnemonic, MnemonicRaw } from '~/src/mnemonic';
describe('Success cases', () => {
// Simple array of cases
const testCases: Array<{
fromString: string;
fromWords: Array<string>;
passphrase?: string;
raw: MnemonicRaw;
toString: string;
toStringWithoutPassphrase: string;
toWords: Array<string>;
toWordsWithoutPassphrase: Array<string>;
}> = [
// No pass-phrase
{
fromString:
'goose just fan kidney barrel album wave crowd movie flame cousin exhaust',
fromWords: [
'goose',
'just',
'fan',
'kidney',
'barrel',
'album',
'wave',
'crowd',
'movie',
'flame',
'cousin',
'exhaust',
],
raw: {
words: [
'goose',
'just',
'fan',
'kidney',
'barrel',
'album',
'wave',
'crowd',
'movie',
'flame',
'cousin',
'exhaust',
],
},
toString:
'goose just fan kidney barrel album wave crowd movie flame cousin exhaust',
toStringWithoutPassphrase:
'goose just fan kidney barrel album wave crowd movie flame cousin exhaust',
toWords: [
'goose',
'just',
'fan',
'kidney',
'barrel',
'album',
'wave',
'crowd',
'movie',
'flame',
'cousin',
'exhaust',
],
toWordsWithoutPassphrase: [
'goose',
'just',
'fan',
'kidney',
'barrel',
'album',
'wave',
'crowd',
'movie',
'flame',
'cousin',
'exhaust',
],
},
// Passphrase
{
fromString:
'goose just fan kidney barrel album wave crowd movie flame cousin exhaust GeneralProtocols!',
fromWords: [
'goose',
'just',
'fan',
'kidney',
'barrel',
'album',
'wave',
'crowd',
'movie',
'flame',
'cousin',
'exhaust',
'GeneralProtocols!',
],
passphrase: 'GeneralProtocols!',
raw: {
words: [
'goose',
'just',
'fan',
'kidney',
'barrel',
'album',
'wave',
'crowd',
'movie',
'flame',
'cousin',
'exhaust',
],
passphrase: 'GeneralProtocols!',
},
toString:
'goose just fan kidney barrel album wave crowd movie flame cousin exhaust GeneralProtocols!',
toStringWithoutPassphrase:
'goose just fan kidney barrel album wave crowd movie flame cousin exhaust',
toWords: [
'goose',
'just',
'fan',
'kidney',
'barrel',
'album',
'wave',
'crowd',
'movie',
'flame',
'cousin',
'exhaust',
'GeneralProtocols!',
],
toWordsWithoutPassphrase: [
'goose',
'just',
'fan',
'kidney',
'barrel',
'album',
'wave',
'crowd',
'movie',
'flame',
'cousin',
'exhaust',
],
},
];
it.each(testCases)(
'from(string)',
({ fromString: phrase, raw: expected }) => {
const mnemonic = Mnemonic.from(phrase);
expect(mnemonic.toRaw()).toStrictEqual(expected);
},
);
it.each(testCases)('from(words)', ({ fromWords, raw: expected }) => {
const mnemonic = Mnemonic.from(fromWords);
expect(mnemonic.toRaw()).toStrictEqual(expected);
});
it.each(testCases)('fromString', ({ fromString, raw: expected }) => {
const mnemonic = Mnemonic.fromString(fromString);
expect(mnemonic.toRaw()).toStrictEqual(expected);
});
it.each(testCases)('fromWords', ({ fromWords, raw: expected }) => {
const mnemonic = Mnemonic.fromWords(fromWords);
expect(mnemonic.toRaw()).toStrictEqual(expected);
});
it.each(testCases)('fromWords', ({ fromWords, raw: expected }) => {
const mnemonic = Mnemonic.fromWords(fromWords);
expect(mnemonic.toRaw()).toStrictEqual(expected);
});
it.each(testCases)('toString', ({ toString, raw }) => {
const mnemonic = Mnemonic.fromRaw(raw);
expect(mnemonic.toString()).toStrictEqual(toString);
});
it.each(testCases)(
'toString(withoutPassphrase)',
({ toStringWithoutPassphrase, raw }) => {
const mnemonic = Mnemonic.fromRaw(raw);
expect(mnemonic.toString(false)).toStrictEqual(toStringWithoutPassphrase);
},
);
it.each(testCases)('toWords', ({ toWords, raw }) => {
const mnemonic = Mnemonic.fromRaw(raw);
expect(mnemonic.toWords()).toStrictEqual(toWords);
});
it.each(testCases)(
'toWords(withoutPassphrase)',
({ toWordsWithoutPassphrase, passphrase, raw }) => {
const mnemonic = Mnemonic.fromRaw(raw);
expect(mnemonic.toWords(false)).toStrictEqual(toWordsWithoutPassphrase);
},
);
it.each(testCases)('getPassphrase', ({ passphrase, raw }) => {
const mnemonic = Mnemonic.fromRaw(raw);
expect(mnemonic.getPassphrase()).toStrictEqual(passphrase);
});
});
describe('Generate Cases', () => {
it('generateRandom should return instance of Mnemonic', () => {
const mnemonic = Mnemonic.generateRandom();
expect(mnemonic).toBeInstanceOf(Mnemonic);
});
it('generateRandom should return instance of Mnemonic with passphrase', () => {
const mnemonic = Mnemonic.generateRandom('GeneralProtocols!');
expect(mnemonic).toBeInstanceOf(Mnemonic);
expect(mnemonic.getPassphrase()).toBe('GeneralProtocols!');
});
});
describe('Validations', () => {
it('isValid should succeed if valid mnemonic', () => {
const isValid = Mnemonic.isValid(
'goose just fan kidney barrel album wave crowd movie flame cousin exhaust',
);
expect(isValid).toBe(true);
});
it('isValid should fail if invalid mnemonic', () => {
// 11 words.
const isValid = Mnemonic.isValid(
'goose just fan kidney barrel album wave crowd movie flame cousin',
);
expect(isValid).toBe(false);
});
it('isValidWord should succeed if word is in word list', () => {
const isValid = Mnemonic.isValidWord('goose');
expect(isValid).toBe(true);
});
it('isValidWord should fail if word is not in word list', () => {
const isValid = Mnemonic.isValidWord('fnord');
expect(isValid).toBe(false);
});
});
describe('Fail cases', () => {
it('fromString should fail if invalid number of words', () => {
expect(() => {
// 11 words.
Mnemonic.fromString(
'goose just fan kidney barrel album wave crowd movie flame cousin',
);
}).toThrow();
});
it('generateRandom should fail if invalid wordList contains invalid number of words', () => {
expect(() => {
// 11 words.
Mnemonic.generateRandom('GeneralProtocols!', ['one', 'two', 'three']);
}).toThrow();
});
it('fromWords should fail if invalid number of words', () => {
expect(() => {
// 11 words.
Mnemonic.fromWords([
'goose',
'just',
'fan',
'kidney',
'barrel',
'album',
'wave',
'crowd',
'movie',
'flame',
'cousin',
]);
}).toThrow();
});
it('fromString should fail if word not in dictionary', () => {
expect(() => {
// Invalid word "fnord".
Mnemonic.fromString(
'fnord just fan kidney barrel album wave crowd movie flame cousin exhaust',
);
}).toThrow();
});
it('fromWord should fail if word not in dictionary', () => {
expect(() => {
// Invalid word "fnord".
Mnemonic.fromWords([
'fnord',
'just',
'fan',
'kidney',
'barrel',
'album',
'wave',
'crowd',
'movie',
'flame',
'cousin',
'exhaust',
]);
}).toThrow();
});
});
+6 -1
View File
@@ -2,7 +2,12 @@
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src"
"rootDir": "./src",
"paths": {
"~/*": [
"./*"
]
}
},
"include": [
"src/**/*"
+18
View File
@@ -0,0 +1,18 @@
{
"entryPointStrategy": "expand",
"entryPoints": ["src"],
"exclude": "**/index*.ts",
"excludeInternal": true,
"excludeProtected": true,
"excludePrivate": true,
"categorizeByGroup": false,
"indexFormat": "table",
"parametersFormat": "table",
"interfacePropertiesFormat": "table",
"classPropertiesFormat": "table",
"propertyMembersFormat": "table",
"typeDeclarationFormat": "table",
"enumMembersFormat": "table",
"useCodeBlocks": true,
"sort": ["static-first"]
}
+13
View File
@@ -0,0 +1,13 @@
import { defineConfig } from 'vitest/config';
import path from 'path';
export default defineConfig({
test: {
// vitest config
},
resolve: {
alias: {
'~': path.resolve(__dirname, './'),
},
},
});
@@ -1,11 +1,9 @@
{
"name": "@xo/wallet",
"name": "@xocash/stack",
"version": "0.0.1",
"description": "XO Stack Wallet",
"description": "XO Cash Stack",
"type": "module",
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"types": "dist/index.types.d.ts",
"exports": {
".": {
"browser": {
@@ -22,16 +20,19 @@
"dist"
],
"scripts": {
"bench": "vitest bench",
"build": "tsc --build --clean && tsc --build",
"prepublishOnly": "npm run build"
"prepublishOnly": "npm run build",
"test": "vitest",
"test:coverage": "vitest run --coverage",
"watch": "tsc --watch"
},
"author": "",
"license": "ISC",
"dependencies": {
"@electrum-cash/network": "^3.3.0",
"@xo/primitives": "^0.0.1",
"idb-keyval": "^6.2.1",
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7"
"@electrum-cash/network": "^4.1.1",
"@electrum-cash/protocol": "2.1.0-development.8075178089",
"@xocash/primitives": "*",
"idb": "^8.0.0"
}
}
@@ -0,0 +1,155 @@
import { EventEmitter } from '../utils';
import {
type AddressCallback,
type BlockchainUTXOs,
type BlockchainTransactions,
type TransactionCallback,
} from './types.js';
import { type Transaction } from '@xocash/primitives';
export type BlockchainEvents = {
isConnectedUpdated: boolean;
blockHeightUpdated: number | undefined;
};
/**
* Abstract base class representing a blockchain interface implementation.
* Extends EventEmitter to provide blockchain-specific event handling capabilities.
*
* This class serves as a template for concrete blockchain implementations,
* providing a standardized interface for common blockchain operations such as
* fetching transactions, managing UTXOs, and handling blockchain subscriptions.
*
* @abstract
* @extends {EventEmitter<BlockchainEvents>}
*/
export abstract class BaseBlockchain extends EventEmitter<BlockchainEvents> {
// TODO: Lockscript might be better as the Subscribe Handler.
// From this, we can convert it to address.
// Fulcrum has Scripthash too - but I'm hesitant about this.
// Scripthash means SHA256'ing the Lockscript.
// This is fine - but, at scale, will become expensive.
// For example, imagine a HDWallet with 2000+ addresses.
// And we want to subscribe to all of them.
// Alternatively, we could just pass in an Address Primitive?
// And then have the Adapter decide what it wants to use?
/**
* Initializes the blockchain connection and required resources.
* Should be called before performing any blockchain operations.
*
* @abstract
* @returns {Promise<void>} A promise that resolves when the blockchain connection is established
* @throws {Error} If the connection cannot be established
*/
abstract start(): Promise<void>;
/**
* Gracefully terminates the blockchain connection and cleans up resources.
* Should be called when blockchain operations are no longer needed.
*
* @abstract
* @returns {Promise<void>} A promise that resolves when the shutdown is complete
*/
abstract stop(): Promise<void>;
/**
* Retrieves all unspent transaction outputs (UTXOs) for a given address.
*
* @abstract
* @param {string} address - The blockchain address to query
* @returns {Promise<BlockchainUTXOs>} A promise that resolves with the unspent outputs
* @throws {Error} If the address is invalid or the query fails
*/
abstract fetchUnspents(address: string): Promise<BlockchainUTXOs>;
/**
* Retrieves detailed information about a specific transaction.
*
* @abstract
* @param {string} txHash - The transaction hash/ID to look up
* @returns {Promise<Transaction>} A promise that resolves with the transaction details
* @throws {Error} If the transaction cannot be found or the query fails
*/
abstract fetchTransaction(txHash: string): Promise<Transaction>;
/**
* Retrieves all transactions associated with a specific address.
*
* @abstract
* @param {string} address - The blockchain address to query
* @returns {Promise<BlockchainTransactions>} A promise that resolves with the list of transactions
* @throws {Error} If the address is invalid or the query fails
*/
abstract fetchTransactions(address: string): Promise<BlockchainTransactions>;
/**
* Broadcasts a raw transaction to the blockchain network.
*
* @abstract
* @param {Uint8Array} transaction - The serialized transaction data to broadcast
* @returns {Promise<void>} A promise that resolves when the transaction is successfully broadcast
* @throws {Error} If the transaction is invalid or broadcasting fails
*/
abstract broadcastTransaction(transaction: Uint8Array): Promise<void>;
/**
* Subscribes to updates for a specific blockchain address.
* The provided callback will be invoked when relevant events occur for the address.
*
* @abstract
* @param {string} address - The blockchain address to monitor
* @param {AddressCallback} callback - The callback function to handle address-related events
* @returns {Promise<void>} A promise that resolves when the subscription is established
* @throws {Error} If the subscription cannot be created
*/
abstract subscribeAddress(
address: string,
callback: AddressCallback,
): Promise<void>;
/**
* Removes a subscription for a specific blockchain address.
*
* @abstract
* @param {string} address - The blockchain address to unsubscribe from
* @param {AddressCallback} callback - The callback function to remove
* @returns {Promise<void>} A promise that resolves when the subscription is removed
* @throws {Error} If the subscription cannot be removed
*/
abstract unsubscribeAddress(
address: string,
callback: AddressCallback,
): Promise<void>;
/**
* Subscribes to updates for a specific transaction.
* The provided callback will be invoked when relevant events occur for the transaction.
*
* @abstract
* @param {string} transactionHash - The transaction hash to monitor
* @param {TransactionCallback} callback - The callback function to handle transaction-related events
* @returns {Promise<void>} A promise that resolves when the subscription is established
* @throws {Error} If the subscription cannot be created
*/
abstract subscribeTransaction(
transactionHash: string,
callback: TransactionCallback,
): Promise<void>;
/**
* Removes a subscription for a specific transaction.
*
* @abstract
* @param {string} transactionHash - The transaction hash to unsubscribe from
* @param {TransactionCallback} callback - The callback function to remove
* @returns {Promise<void>} A promise that resolves when the subscription is removed
* @throws {Error} If the subscription cannot be removed
*/
abstract unsubscribeTransaction(
transactionHash: string,
callback: TransactionCallback,
): Promise<void>;
}
@@ -0,0 +1,544 @@
import { BaseBlockchain } from './base-blockchain.js';
import {
type AddressCallback,
type TransactionCallback,
type BlockchainTransaction,
type BlockchainUTXO,
} from './types.js';
import { type BaseStore, StoreInMemory } from '../storage';
import {
Address,
ExtMap,
Outpoint,
Transaction,
TransactionHash,
UTXO,
} from '@xocash/primitives';
import { ElectrumClient, RPCParameter } from '@electrum-cash/network';
import {
type ElectrumProtocolEvents,
type AddressSubscribeNotification,
type HeadersSubscribeNotification,
type TransactionSubscribeNotification,
initializeElectrumClient,
broadcastTransaction,
fetchUnspentTransactionOutputs,
fetchHistory,
fetchTransaction,
subscribeToBlockheaderUpdates,
} from '@electrum-cash/protocol';
import { hexToBin } from '@bitauth/libauth';
export interface BroadcastOpts {
timeoutMs: number;
waitUntilSeen: boolean;
}
export type BlockchainElectrumEvents = {
isConnectedUpdated: boolean;
blockHeightUpdated: number | undefined;
};
export type BlockchainElectrumOpts = {
servers: Array<string>;
application: string;
};
export class BlockchainElectrum extends BaseBlockchain {
// Composables.
electrumClient!: ElectrumClient<ElectrumProtocolEvents>;
// State.
isConnected = false;
blockHeight: number | undefined = undefined;
// Subscriptions State.
addressSubscriptions: Map<string, Set<AddressCallback>> = new Map();
transactionSubscriptions: Map<string, Set<TransactionCallback>> = new Map();
constructor(
public readonly store: BaseStore = new StoreInMemory(),
public readonly opts: BlockchainElectrumOpts = {
servers: [
'bch.imaginary.cash',
'cashnode.bch.ninja',
'electrum.imaginary.cash',
],
application: 'XOApp',
},
) {
super();
}
async start() {
// TODO: We want to use a Cluster instead of a Client, but as of 2022-07-07 there are issues with Subscriptions on Cluster.
// See: https://gitlab.com/GeneralProtocols/anyhedge/whitelabel/frontend/-/issues/76
// Iterate over each server in our list of servers.
// NOTE: We are still using an Electrum Client due to the above bug.
// But, if we cannot connect to the first server, we will try the second (and third if given, etc) as a fallback.
for (const electrumServer of this.opts.servers) {
// Initialize an Electrum client using the given server.
const electrum = await initializeElectrumClient(
this.opts.application,
electrumServer,
);
// Attempt to connect to this Electrum Server.
try {
await electrum.connect();
this.isConnected = true;
this.emit('isConnectedUpdated', this.isConnected);
} catch (error) {
console.warn(error);
// If it fails to connect, try the next server in our list.
continue;
}
// Save the client.
this.electrumClient = electrum;
// Setup notification handler for connected event.
this.electrumClient.on('connected', () => {
// Set the isConnected property to true.
this.isConnected = true;
// Emit an event.
this.emit('isConnectedUpdated', this.isConnected);
});
// Setup notification handler for disconnected event.
this.electrumClient.on('disconnected', () => {
// Set the isConnected property to false.
this.isConnected = false;
// Emit an event.
this.emit('isConnectedUpdated', this.isConnected);
});
// TODO: Implement me and work out interface.
this.electrumClient.on(
'blockchain.headers.subscribe',
this.handleNewBlockchainHeaders.bind(this),
);
this.electrumClient.on(
'blockchain.address.subscribe',
this.handleAddressStatusUpdates.bind(this),
);
this.electrumClient.on(
'blockchain.transaction.subscribe',
this.handleTransactionStatusUpdates.bind(this),
);
// Subscribe to block header notifications.
await subscribeToBlockheaderUpdates(this.electrumClient);
// Return to prevent further execution.
return;
}
// Throw an error if we failed to connect to any of our Electrum Servers.
throw new Error(
'Failed to connect to Electrum. Please try restarting your browser and ensure you are currently connected to the internet.',
);
}
async stop() {
// Disconnect from Electrum.
this.electrumClient.disconnect();
}
async fetchUnspents(address: string) {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
// Define the cache key.
const cacheKey = `addressUnspents.${address}`;
// Attempt to get the address unspents from the cache or fetch them if not available.
const addressUnspents = await this.store.getOrSet(cacheKey, async () => {
return await fetchUnspentTransactionOutputs(
this.electrumClient,
address,
true,
true,
);
});
// Work out the locking byecode from the address.
const lockingBytecode = Address.from(address).toLockscriptBytes();
// Transform the unspents into our UTXO format.
const utxos: Array<BlockchainUTXO> = addressUnspents.map((unspent) => {
const outpoint = new Outpoint(hexToBin(unspent.tx_hash), unspent.tx_pos);
return {
height: unspent.height,
utxo: UTXO.from(outpoint, {
valueSatoshis: BigInt(unspent.value),
token: unspent.token_data
? {
amount: BigInt(unspent.token_data.amount),
category: hexToBin(unspent.token_data.category),
nft: unspent.token_data.nft
? {
capability: unspent.token_data.nft.capability,
commitment: hexToBin(unspent.token_data.nft.commitment),
}
: undefined,
}
: undefined,
lockingBytecode,
}),
};
});
// Index the UTXOs by hashInHex:index.
const utxosIndexed = ExtMap.fromArray(utxos, (blockchainUTXO) => {
return blockchainUTXO.utxo.outpoint.toString();
});
// Return the unspents.
return utxosIndexed;
}
async fetchTransaction(txHash: string) {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
// Define the cache key.
const cacheKey = `transactions.${txHash}`;
// Attempt to get the transaction hex from the cache or fetch it if not available.
const transactionHex = await this.store.getOrSet(cacheKey, async () => {
return await fetchTransaction(this.electrumClient, txHash);
});
// Decode the hex into our transaction primitive.
const transaction = Transaction.fromHex(transactionHex);
// Attempt to get the transaction hex from the cache or fetch it if not available.
// NOTE: We store JSON as opposed to hex because it is MUCH faster to decode.
/*
const transaction = new Transaction(
await this.store.getOrSet(cacheKey, async () => {
const tx = await fetchTransaction(this.electrumClient, txHash);
return Transaction.fromHex(tx).transaction;
}),
);
*/
// Return the transaction hex.
return transaction;
}
async fetchTransactions(address: string) {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
// Define the cache key.
const cacheKey = `addressHistory.${address}`;
// Attempt to get the transaction history from the cache or fetch them if not available.
const addressHistory = await this.store.getOrSet(cacheKey, async () => {
return await fetchHistory(this.electrumClient, address);
});
// Get the transactions for each history item.
const transactions: Array<BlockchainTransaction> = await Promise.all(
addressHistory.map(async (item) => ({
hash: TransactionHash.fromHex(item.tx_hash),
height: item.height,
transaction: await this.fetchTransaction(item.tx_hash),
})),
);
// Index the transactions by their hash (in hex).
const transactionsIndexed = ExtMap.fromArray(transactions, (tx) =>
tx.hash.toHex(),
);
// Return the transactions.
return transactionsIndexed;
}
async waitForTransaction(
tx: Uint8Array | Transaction | string,
timeoutMs = 10_000,
) {
// Cast the transaction.
if (!(tx instanceof Transaction)) {
tx = Transaction.from(tx);
}
// Attempt to broadcast the transaction.
const waitForTxPromise = new Promise<void>(async (resolve, reject) => {
// Set a timeout.
const timeout = setTimeout(() => {
reject(new Error(`Failed to broadcast ${tx.toHashHex()}`));
}, timeoutMs);
// Create a subscribe function so that we get notified when transaction is seen by network
const subscribeCallback = (_height: number | null) => {
clearTimeout(timeout);
this.unsubscribeTransaction(tx.toHashHex(), subscribeCallback);
resolve();
};
// Subscribe to the transaction.
await this.subscribeTransaction(tx.toHashHex(), subscribeCallback);
});
return waitForTxPromise;
}
// TODO: Split out the "waitUntilSeen" into own function.
// This'll be useful for protocols like BIP70/JPP/CashConnect, etc.
// Also consider a fail callback:
// If a "waitFor" fails, we probably want to invalidate the tx by sending those inputs elsewhere.
async broadcastTransaction(
tx: Transaction | Uint8Array | string,
opts: BroadcastOpts = { timeoutMs: 10_000, waitUntilSeen: true },
) {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
// Cast the transaction.
if (!(tx instanceof Transaction)) {
tx = Transaction.from(tx);
}
// Create a promise that will resolve when transaction is seen.
const waitForTxPromise = this.waitForTransaction(tx, opts.timeoutMs);
// Broadcast the transaction to our Electrum node.
await broadcastTransaction(this.electrumClient, tx.toHex());
// Wait for the transaction to be seen.
await waitForTxPromise;
}
async subscribeAddress(address: string, callback: AddressCallback) {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
// Get or create the set of callbacks for this transaction
let callbacks = this.addressSubscriptions.get(address);
if (!callbacks) {
callbacks = new Set();
this.addressSubscriptions.set(address, callbacks);
await this.electrumClient.subscribe(
'blockchain.address.subscribe',
address,
);
}
// Add the callback to the set
callbacks.add(callback);
}
async unsubscribeAddress(address: string, callback: AddressCallback) {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
// Get the callbacks set for this address
const callbacks = this.addressSubscriptions.get(address);
if (!callbacks) {
return;
}
// Remove the specific callback
callbacks.delete(callback);
// If there are no more callbacks, remove the address entry
// and potentially unsubscribe from blockchain updates
if (callbacks.size === 0) {
this.transactionSubscriptions.delete(address);
await this.electrumClient.unsubscribe(
'blockchain.address.unsubscribe',
address,
);
}
}
async subscribeTransaction(
transactionHash: string,
callback: TransactionCallback,
) {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
// Get or create the set of callbacks for this transaction
let callbacks = this.transactionSubscriptions.get(transactionHash);
if (!callbacks) {
callbacks = new Set();
this.transactionSubscriptions.set(transactionHash, callbacks);
await this.electrumClient.subscribe(
'blockchain.transaction.subscribe',
transactionHash,
);
}
// Add the callback to the set
callbacks.add(callback);
}
async unsubscribeTransaction(
transactionHash: string,
callback: TransactionCallback,
) {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
// Get the callbacks set for this transaction
const callbacks = this.transactionSubscriptions.get(transactionHash);
if (!callbacks) {
return;
}
// Remove the specific callback
callbacks.delete(callback);
// If there are no more callbacks, remove the transaction entry
// and potentially unsubscribe from blockchain updates
if (callbacks.size === 0) {
this.transactionSubscriptions.delete(transactionHash);
await this.electrumClient.subscribe(
'blockchain.transaction.subscribe',
transactionHash,
);
}
}
async request(method: string, ...parameters: Array<RPCParameter>) {
// Wait for connection to be established before attempting to subscribe.
// TODO: Consider doing this at a higher level.
if (!this.isConnected) {
await this.waitFor('isConnectedUpdated', (isConnected) => isConnected);
}
const response = await this.electrumClient.request(method, ...parameters);
if (response instanceof Error) {
throw response;
}
return response;
}
protected handleNewBlockchainHeaders(
notification: HeadersSubscribeNotification,
) {
// Extract height from the first param.
// NOTE: This is an object.
// https://electrum-cash-protocol.readthedocs.io/en/latest/protocol-methods.html#blockchain-headers-subscribe
const { height } = notification.params[0];
// Assign the block height.
this.blockHeight = height;
// Emit an event to update the blockheight.
this.emit('blockHeightUpdated', this.blockHeight);
}
protected async handleAddressStatusUpdates(
notification: AddressSubscribeNotification,
) {
// Extract parameters.
const address = notification.params[0];
const status = notification.params[1];
// Get the cached status hash for this address.
const cachedStatus = await this.store.get(`addressStatus.${address}`);
// If our cache is outdated, clear the caches for this address.
if (cachedStatus !== status) {
await this.store.delete(`addressUnspents.${address}`);
await this.store.delete(`addressHistory.${address}`);
}
// Cache the new status.
await this.store.set(`addressStatus.${address}`, status);
// Get the callbacks for this transaction
const callbacks = this.addressSubscriptions.get(address);
if (!callbacks) {
return;
}
// Execute all callbacks for this transaction.
for (const callback of callbacks) {
try {
callback(status);
} catch (error) {
// Handle or log any callback execution errors
console.error(
`Error executing callback for address ${address}:`,
error,
);
}
}
}
protected handleTransactionStatusUpdates(
notification: TransactionSubscribeNotification,
) {
const txHash = notification.params[0];
const height = notification.params[1];
// Get the callbacks for this transaction
const callbacks = this.transactionSubscriptions.get(txHash);
if (!callbacks) {
return;
}
// Execute all callbacks for this transaction.
for (const callback of callbacks) {
try {
callback(height);
} catch (error) {
// Handle or log any callback execution errors
console.error(
`Error executing callback for transaction ${txHash}:`,
error,
);
}
}
}
}
@@ -1,11 +1,20 @@
import type {
AddressCallback,
IBlockchain,
TransactionCallback,
UTXO,
} from './interface.js';
import { BaseBlockchain } from './base-blockchain.js';
import {
type AddressCallback,
type TransactionCallback,
type BlockchainTransaction,
type BlockchainTransactions,
type BlockchainUTXO,
type BlockchainUTXOs,
} from './types.js';
import { Address, Transaction } from '@xo/primitives';
import {
Address,
ExtMap,
Outpoint,
Transaction,
UTXO,
} from '@xocash/primitives';
import {
type Output,
@@ -13,17 +22,17 @@ import {
createVirtualMachineBCH,
} from '@bitauth/libauth';
export type UTXOSet = { [outpointHashAndIndex: string]: UTXO };
// Local Blockchain Adapter.
// This simulates the BCH Blockchain.
export class BlockchainLocal implements IBlockchain {
private transactions: Map<string, Transaction>;
export class BlockchainLocal extends BaseBlockchain {
private transactions: BlockchainTransactions;
private addressSubscriptions: Map<string, Set<AddressCallback>>;
private transactionSubscriptions: Map<string, Set<TransactionCallback>>;
constructor() {
this.transactions = new Map();
super();
this.transactions = new ExtMap<BlockchainTransaction>();
this.addressSubscriptions = new Map();
this.transactionSubscriptions = new Map();
}
@@ -36,32 +45,43 @@ export class BlockchainLocal implements IBlockchain {
console.log('BlockchainLocal: Stopped');
}
async fetchUnspents(address: string): Promise<UTXO[]> {
async fetchUnspents(address: string) {
// Derive the current UTXO set.
const utxoSet = this.deriveUtxoSet();
// Filter for only UTXOs matching the given address.
return Object.values(utxoSet).filter((utxo) => {
const utxoSet = this.deriveUtxoSet().filter((blockchainUTXO) => {
// Decode the address and locking bytecode.
const utxoAddress = Address.fromLockscriptBytes(utxo.lockingBytecode);
const needleAddress = Address.fromCashAddrOrLegacy(address);
const utxoAddress = Address.fromLockscriptBytes(
blockchainUTXO.utxo.output.lockingBytecode,
);
const needleAddress = Address.from(address);
// Compare the lockscript hex.
return utxoAddress.toLockscriptHex() === needleAddress.toLockscriptHex();
});
return utxoSet;
}
async fetchTransactions(address: string): Promise<Transaction[]> {
return this.getAllTransactions().filter((tx) => {
async fetchTransaction(txHash: string) {
const tx = this.transactions.get(txHash);
if (!tx) {
throw new Error(`Transaction "${txHash}" does not exist`);
}
return tx.transaction;
}
async fetchTransactions(address: string) {
return this.transactions.filter((tx) => {
// Check if any input or output involves the address
// This is a simplified check and might need to be more sophisticated in a real implementation
return (
tx
tx.transaction
.getInputs()
.some((input) =>
binToHex(input.unlockingBytecode).includes(address)
binToHex(input.unlockingBytecode).includes(address),
) ||
tx
tx.transaction
.getOutputs()
.some((output) => binToHex(output.lockingBytecode).includes(address))
);
@@ -70,11 +90,11 @@ export class BlockchainLocal implements IBlockchain {
async broadcastTransaction(
tx: Transaction | Uint8Array | string,
opts: { skipValidation: boolean } = { skipValidation: false }
opts: { skipValidation: boolean } = { skipValidation: false },
) {
// Cast to transaction object.
if (!(tx instanceof Transaction)) {
tx = Transaction.fromAny(tx);
tx = Transaction.from(tx);
}
// Derive the UTXO set so that we can find source outputs.
@@ -87,15 +107,28 @@ export class BlockchainLocal implements IBlockchain {
input.outpointIndex
}`;
return utxoSet[utxoId];
const blockchainUTXO = utxoSet.get(utxoId);
if (!blockchainUTXO) {
throw new Error(`BlockchainUTXO "${utxoId}" does not exist`);
}
return blockchainUTXO.utxo;
});
// Validate the transaction.
BlockchainLocal.validateTransaction(tx, sourceOutputs);
BlockchainLocal.validateTransaction(
tx,
sourceOutputs.map((utxo) => utxo.output),
);
}
// Add the transaction.
this.addTransaction(tx);
this.addTransaction({
hash: tx.toHash(),
transaction: tx,
height: 0,
});
// Notify our address and transaction subscribers.
this.notifyAddressSubscribers(tx);
@@ -104,8 +137,7 @@ export class BlockchainLocal implements IBlockchain {
async subscribeAddress(address: string, callback: AddressCallback) {
// Convert the address to it's lockscript hex so that it's consistently represented.
const lockscriptHex =
Address.fromCashAddrOrLegacy(address).toLockscriptHex();
const lockscriptHex = Address.from(address).toLockscriptHex();
// If no subscriptions exist yet on this lockscript, create a new Set.
if (!this.addressSubscriptions.has(lockscriptHex)) {
@@ -118,8 +150,7 @@ export class BlockchainLocal implements IBlockchain {
async unsubscribeAddress(address: string, callback: AddressCallback) {
// Convert the address to it's lockscript hex so that it's consistently represented.
const lockscriptHex =
Address.fromCashAddrOrLegacy(address).toLockscriptHex();
const lockscriptHex = Address.from(address).toLockscriptHex();
// Find all callbacks this lockscript is subscribed to.
const callbacks = this.addressSubscriptions.get(lockscriptHex);
@@ -133,7 +164,7 @@ export class BlockchainLocal implements IBlockchain {
async subscribeTransaction(
transactionHash: string,
callback: TransactionCallback
callback: TransactionCallback,
) {
if (!this.transactionSubscriptions.has(transactionHash)) {
this.transactionSubscriptions.set(transactionHash, new Set());
@@ -143,7 +174,7 @@ export class BlockchainLocal implements IBlockchain {
async unsubscribeTransaction(
transactionHash: string,
callback: TransactionCallback
callback: TransactionCallback,
) {
const callbacks = this.transactionSubscriptions.get(transactionHash);
if (callbacks) {
@@ -160,8 +191,9 @@ export class BlockchainLocal implements IBlockchain {
// First, notify all source output listeners.
tx.getInputs().forEach((input) => {
const sourceOutput =
utxoState[`${input.outpointTransactionHash};${input.outpointIndex}`];
const sourceOutput = utxoState.get(
`${input.outpointTransactionHash};${input.outpointIndex}`,
);
// If there is no corresponding source output, skip this notification.
// NOTE: This can occur if skipValidation is set to true in broadcast (which would be used for "coinbase" transactions).
@@ -170,7 +202,7 @@ export class BlockchainLocal implements IBlockchain {
}
const address = Address.fromLockscriptBytes(
sourceOutput.lockingBytecode
sourceOutput.utxo.output.lockingBytecode,
).toLockscriptHex();
const callbacks = this.addressSubscriptions.get(address);
@@ -183,7 +215,7 @@ export class BlockchainLocal implements IBlockchain {
// Then notify all output listeners.
tx.getOutputs().forEach((output) => {
const address = Address.fromLockscriptBytes(
output.lockingBytecode
output.lockingBytecode,
).toLockscriptHex();
const callbacks = this.addressSubscriptions.get(address);
@@ -203,127 +235,47 @@ export class BlockchainLocal implements IBlockchain {
}
}
addTransaction(tx: Transaction) {
this.transactions.set(tx.toHashHex(), tx);
addTransaction(tx: BlockchainTransaction) {
this.transactions.set(tx.hash.toHex(), tx);
}
removeTransaction(txHash: string) {
this.transactions.delete(txHash);
}
removeDependentTransactions(txHash: string): string[] {
const removedTxids: string[] = [];
const toRemove: Set<string> = new Set([txHash]);
const findDependents = (id: string) => {
for (const [otherTxid, tx] of this.transactions) {
if (
tx
.getInputs()
.some((input) => binToHex(input.outpointTransactionHash) === id)
) {
toRemove.add(otherTxid);
findDependents(otherTxid);
}
}
};
findDependents(txHash);
for (const id of toRemove) {
if (this.transactions.has(id)) {
this.transactions.delete(id);
removedTxids.push(id);
}
}
return removedTxids;
}
getTransaction(txHash: string): Transaction | undefined {
return this.transactions.get(txHash);
}
getAllTransactions(): Transaction[] {
return Array.from(this.transactions.values());
}
deriveUtxoSet(): UTXOSet {
const utxoMap: UTXOSet = {};
deriveUtxoSet(): BlockchainUTXOs {
const utxoMap: BlockchainUTXOs = new ExtMap();
// First, add all outputs as potential UTXOs
for (const tx of this.transactions.values()) {
const txHash = tx.toHash();
tx.getOutputs().forEach((output, outpointIndex) => {
const utxo: UTXO = {
outpointTransactionHash: txHash.toBytes(),
outpointIndex,
valueSatoshis: output.valueSatoshis,
lockingBytecode: output.lockingBytecode,
tx.transaction.getOutputs().forEach((output, outpointIndex) => {
const utxo: BlockchainUTXO = {
height: 0,
utxo: UTXO.from(new Outpoint(tx.hash.toBytes(), outpointIndex), {
valueSatoshis: output.valueSatoshis,
lockingBytecode: output.lockingBytecode,
}),
};
utxoMap[`${txHash.toHex()}:${outpointIndex}`] = utxo;
utxoMap.set(`${tx.hash.toHex()}:${outpointIndex}`, utxo);
});
}
// Then, remove all spent outputs
for (const tx of this.transactions.values()) {
tx.getInputs().forEach((input) => {
tx.transaction.getInputs().forEach((input) => {
const outpointTransactionHashHex = binToHex(
input.outpointTransactionHash
input.outpointTransactionHash,
);
delete utxoMap[`${outpointTransactionHashHex}:${input.outpointIndex}`];
utxoMap.delete(`${outpointTransactionHashHex}:${input.outpointIndex}`);
});
}
return utxoMap;
}
getDependentTransactions(txHash: string): Transaction[] {
return this.getAllTransactions().filter((tx) => {
tx.getInputs().some((input) => {
const outpointTransactionHashHex = binToHex(
input.outpointTransactionHash
);
return outpointTransactionHashHex === txHash;
});
});
}
getBroadcastOrder(): Transaction[] {
const visited = new Set<string>();
const order: Transaction[] = [];
const visit = (txid: string) => {
if (visited.has(txid)) return;
const tx = this.transactions.get(txid);
if (!tx) return;
visited.add(txid);
// First, visit all transactions that this transaction depends on
for (const input of tx.getInputs()) {
const outpointTransactionHashHex = binToHex(
input.outpointTransactionHash
);
visit(outpointTransactionHashHex);
}
order.push(tx);
};
// Start the topological sort from each transaction
for (const tx of this.transactions.values()) {
visit(tx.toHashHex());
}
return order;
}
/**
* @todo Consider moving this to Transaction Primitive. Trade-off is that it's probably big. Maybe standalone util?
* @remarks Consider moving this to Transaction Primitive. Trade-off is that it's probably big. Maybe standalone util?
*/
static validateTransaction(tx: Transaction, sourceOutputs: Array<Output>) {
const virtualMachine = createVirtualMachineBCH();
@@ -1,8 +1,9 @@
import { IBlockchain, AddressCallback, TransactionCallback } from './interface';
import { BaseBlockchain } from './base-blockchain.js';
import { type AddressCallback, type TransactionCallback } from './types.js';
import { BlockchainElectrum } from './blockchain-electrum.js';
import { BlockchainLocal } from './blockchain-local.js';
import { Transaction } from '@xo/primitives';
import { Transaction } from '@xocash/primitives';
/**
* The idea here is that this will implement the IBlockchain interface.
@@ -18,17 +19,15 @@ import { Transaction } from '@xo/primitives';
* ])
* ```
*/
export class Blockchain implements IBlockchain {
export class Blockchain extends BaseBlockchain {
blockchainLocal: BlockchainLocal;
blockchainElectrum: BlockchainElectrum;
constructor() {
super();
this.blockchainLocal = new BlockchainLocal();
this.blockchainElectrum = new BlockchainElectrum(
['bch.imaginary.cash', 'cashnode.bch.ninja', 'electrum.imaginary.cash'],
'BCHApp',
'1.5'
);
this.blockchainElectrum = new BlockchainElectrum();
}
async start() {
@@ -53,6 +52,14 @@ export class Blockchain implements IBlockchain {
}
}
async fetchTransaction(txHash: string) {
if (this.blockchainElectrum.isConnected) {
return await this.blockchainElectrum.fetchTransaction(txHash);
} else {
return await this.blockchainLocal.fetchTransaction(txHash);
}
}
async fetchTransactions(address: string) {
if (this.blockchainElectrum.isConnected) {
return await this.blockchainElectrum.fetchTransactions(address);
@@ -69,24 +76,24 @@ export class Blockchain implements IBlockchain {
}
}
async subscribeAddress(address: string, callback: AddressCallback) {
async subscribeAddress(_address: string, _callback: AddressCallback) {
throw new Error('Not yet implemented');
}
async unsubscribeAddress(address: string, callback: AddressCallback) {
async unsubscribeAddress(_address: string, _callback: AddressCallback) {
throw new Error('Not yet implemented');
}
async subscribeTransaction(
transactionHash: string,
callback: TransactionCallback
_transactionHash: string,
_callback: TransactionCallback,
) {
throw new Error('Not yet implemented');
}
async unsubscribeTransaction(
transactionHash: string,
callback: TransactionCallback
_transactionHash: string,
_callback: TransactionCallback,
) {
throw new Error('Not yet implemented');
}
@@ -1,5 +1,5 @@
export * from './base-blockchain.js';
export * from './blockchain.js';
export * from './blockchain-electrum.js';
export * from './blockchain-electrum-types.js';
export * from './blockchain-local.js';
export * from './interface.js';
export * from './types.js';
+28
View File
@@ -0,0 +1,28 @@
import { Transaction, TransactionHash, UTXO, ExtMap } from '@xocash/primitives';
export type AddressCallback = (status: string | null) => void;
export type TransactionCallback = (height: number | null) => void;
export type BlockchainTransaction = {
hash: TransactionHash;
height: number;
transaction: Transaction;
// TODO: DSP
// Wait, why the fuck would I need a DSP for Transaction? Did I mean to do this on UTXO?
};
export type BlockchainTransactions = ExtMap<BlockchainTransaction>;
// TODO: You were considering using classes that extend INdexedCollection. E.g.
// class BlockchainUTXOs extends ExtMap<BlockchainUTXO>
// This probably isn't a bad idea:
// 1. You nest calculateBalanceSats and calculateBalanceTokens under it
// 2. You could also do sorting methods (more pertinent for BLockchainTransactions above)
export type BlockchainUTXO = {
height: number;
utxo: UTXO;
// TODO: DSP
};
// NOTE: To minimize refactors later, use this name elsewhere; not the `ExtMap<Type>` form.
export type BlockchainUTXOs = ExtMap<BlockchainUTXO>;
+5
View File
@@ -0,0 +1,5 @@
// Export modules that work across all platforms.
export * from './index.js';
// These exports will only work in a browser environment.
export * from './storage/store-indexeddb.js';

Some files were not shown because too many files have changed in this diff Show More