Resolve "WIP: UTXO Selection and Storage"

This commit is contained in:
Jim Hamill
2025-01-11 08:39:24 +00:00
parent f934216d68
commit 33fd9bac4d
156 changed files with 13304 additions and 4595 deletions
+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,54 @@
<!-- .vitepress/theme/MyLayout.vue -->
<script setup>
import DefaultTheme from 'vitepress/theme'
const { Layout } = DefaultTheme
</script>
<template>
<Layout>
<!-- Override the home-hero-image slot with the Stack, BCH, and Apps icons along with gradient arrows -->
<template #home-hero-image>
<div class="icon-container">
<!-- Stack Icon -->
<svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="stack-icon">
<path d="m2.394 15.759s7.554 4.246 9.09 5.109c.165.093.333.132.492.132.178 0 .344-.049.484-.127 1.546-.863 9.155-5.113 9.155-5.113.246-.138.385-.393.385-.656 0-.566-.614-.934-1.116-.654 0 0-7.052 3.958-8.539 4.77-.211.115-.444.161-.722.006-1.649-.928-8.494-4.775-8.494-4.775-.502-.282-1.117.085-1.117.653 0 .262.137.517.382.655zm0-3.113s7.554 4.246 9.09 5.109c.165.093.333.132.492.132.178 0 .344-.049.484-.127 1.546-.863 9.155-5.113 9.155-5.113.246-.138.385-.393.385-.656 0-.566-.614-.934-1.116-.654 0 0-7.052 3.958-8.539 4.77-.211.115-.444.161-.722.006-1.649-.928-8.494-4.775-8.494-4.775-.502-.282-1.117.085-1.117.653 0 .262.137.517.382.655zm10.271-9.455c-.246-.128-.471-.191-.692-.191-.223 0-.443.065-.675.191l-8.884 5.005c-.276.183-.414.444-.414.698 0 .256.139.505.414.664l8.884 5.006c.221.133.447.203.678.203.223 0 .452-.065.689-.203l8.884-5.006c.295-.166.451-.421.451-.68 0-.25-.145-.503-.451-.682z" fill-rule="nonzero"/>
</svg>
<!-- Right Arrow with gradient -->
<svg width="24" height="24" xmlns="http://www.w3.org/2000/svg" fill="url(#gradient)" fill-rule="evenodd" clip-rule="evenodd" class="right-arrow" stroke="url(#gradient)" stroke-width="2">
<defs>
<linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#5271ff;stop-opacity:1" />
<stop offset="100%" style="stop-color:#38b6ff;stop-opacity:1" />
</linearGradient>
</defs>
<path d="M4 .755l14.374 11.245-14.374 11.219.619.781 15.381-12-15.391-12-.609.755z"/>
</svg>
<!-- BCH Icon -->
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="currentColor" class="bch-icon">
<path d="M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm-.5 12.497v2.503c1.984 0 3.344-.188 3.344-1.258 0-1.148-1.469-1.245-3.344-1.245zm2.789-2.247c0-1-1.039-1.25-2.789-1.25v2.5c1.105 0 2.789-.078 2.789-1.25zm-2.289-7.25c-4.971 0-9 4.029-9 9s4.029 9 9 9 9-4.029 9-9-4.029-9-9-9zm1 13.5v1.5h-1v-1.511h-.5v1.511h-1v-1.511h-2.484l.25-1.489h.539c.442 0 .695-.425.695-.854v-4.444c0-.416-.242-.702-.683-.702h-.817v-1.5h2.5v-1.5h1v1.5h.5v-1.5h1v1.526c2.158.073 3.012.891 3.257 1.812.29 1.09-.429 2.005-1.046 2.228.75.192 1.789.746 1.789 2.026 0 1.741-1.344 2.908-4 2.908z"/>
</svg>
<!-- Left Arrow with gradient -->
<svg width="24" height="24" xmlns="http://www.w3.org/2000/svg" fill="url(#gradient)" fill-rule="evenodd" clip-rule="evenodd" class="left-arrow" stroke="url(#gradient)" stroke-width="2">
<defs>
<linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#5271ff;stop-opacity:1" />
<stop offset="100%" style="stop-color:#38b6ff;stop-opacity:1" />
</linearGradient>
</defs>
<path d="M20 .755l-14.374 11.245 14.374 11.219-.619.781-15.381-12 15.391-12 .609.755z"/>
</svg>
<!-- Apps Icon -->
<svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="apps-icon">
<path d="m21 4c0-.478-.379-1-1-1h-16c-.62 0-1 .519-1 1v16c0 .621.52 1 1 1h16c.478 0 1-.379 1-1zm-16.5.5h15v15h-15zm6.75 9.25v3.25c0 .53-.47 1-1 1h-3.25c-.53 0-1-.47-1-1v-3.25c0-.53.47-1 1-1h3.25c.53 0 1 .47 1 1zm0-6.75v3.25c0 .53-.47 1-1 1h-3.25c-.53 0-1-.47-1-1v-3.25c0-.53.47-1 1-1h3.25c.53 0 1 .47 1 1zm6.75 0v3.25c0 .53-.47 1-1 1h-3.25c-.53 0-1-.47-1-1v-3.25c0-.53.47-1 1-1h3.25c.53 0 1 .47 1 1z" fill-rule="nonzero"/>
</svg>
</div>
</template>
</Layout>
</template>
@@ -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>
@@ -0,0 +1,164 @@
: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: 20px;
}
.vp-doc h3 {
font-size: 16px;
}
.vp-doc h4 {
font-size: 14px;
opacity: 0.75;
}
.VPSidebarItem .text {
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,
.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;
}
/* 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

@@ -0,0 +1,15 @@
// https://vitepress.dev/guide/custom-theme
import type { Theme } from 'vitepress';
import DefaultTheme from 'vitepress/theme';
import Layout from './Layout.vue';
import './style.css';
import './custom.css';
import './tools.css';
export default {
extends: DefaultTheme,
Layout,
enhanceApp({ app, router, siteData }) {
// ...
},
} satisfies Theme;
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 80 KiB

File diff suppressed because one or more lines are too long

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%;
}
}
+55
View File
@@ -0,0 +1,55 @@
---
outline: deep
---
# Runtime API Examples
This page demonstrates usage of some of the runtime APIs provided by VitePress.
The main `useData()` API can be used to access site, theme, and page data for the current page. It works in both `.md` and `.vue` files:
```md
<script setup>
import { useData } from 'vitepress'
const { theme, page, frontmatter } = useData()
</script>
## Results
### Theme Data
<pre>{{ theme }}</pre>
### Page Data
<pre>{{ page }}</pre>
### Page Frontmatter
<pre>{{ frontmatter }}</pre>
```
<script setup>
import { useData } from 'vitepress'
const { site, theme, page, frontmatter } = useData()
</script>
## Results
### Theme Data
<pre>{{ theme }}</pre>
### Page Data
<pre>{{ page }}</pre>
### Page Frontmatter
<pre>{{ frontmatter }}</pre>
## More
Check out the documentation for the [full list of runtime APIs](https://vitepress.dev/reference/runtime-api#usedata).
+9
View File
@@ -0,0 +1,9 @@
# React
## Install
```sh
npm install @xo/react
```
## Usage
+9
View File
@@ -0,0 +1,9 @@
# Svelte
## Install
```sh
npm install @xo/svelte
```
## Usage
+9
View File
@@ -0,0 +1,9 @@
# Vue
## Install
```sh
npm install @xo/vue
```
## Usage
Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

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,
},
},
],
```
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 80 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 140 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 77 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 13 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 13 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 15 KiB

File diff suppressed because one or more lines are too long

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';
@@ -3,6 +3,4 @@ export * from './index.js';
// These exports will only work in a NodeJS (backend) environment.
// NOTE: We import and export each module with a common alias so that any leveraging libraries can use the common name and maintain cross-platform compatibility.
import { StorageSQLite } from './storage/storage-sqlite.js';
export { StorageSQLite };
export { StorageSQLite as StorageLocal };
// export * from './storage/storage-local.node.js';
@@ -1,3 +1,7 @@
// Export all our primitives as a convenience.
export * from '@xocash/primitives';
// Export all of our stack-specific modules.
export * from './blockchain/index.js';
export * from './storage/index.js';
export * from './utils/index.js';
+3
View File
@@ -0,0 +1,3 @@
// Export all of our stack-specific modules.
export * from './index.browser.js';
export * from './index.node.js';
+1
View File
@@ -0,0 +1 @@
Will be nice if we can make this adapter based as with other services.
+271
View File
@@ -0,0 +1,271 @@
import { Encryption, EventEmitter } from '../utils';
export type StorageOpts = {
syncInMemory?: boolean;
encryption?: Encryption;
};
export type StoreEvents = {
set: { key: string; value: any };
delete: { key: string };
clear: undefined;
};
export abstract class BaseStorage {
abstract listStores(): Promise<Array<string>>;
abstract createStore(
storeName: string,
opts: StorageOpts,
): Promise<BaseStore>;
abstract getStore(
storeName: string,
opts: StorageOpts,
): Promise<BaseStore | null>;
abstract createOrGetStore(
storeName: string,
opts: StorageOpts,
): Promise<BaseStore>;
abstract deleteStore(storeName: string): Promise<void>;
abstract deleteDatabase(): Promise<void>;
}
/**
* Represents a wrapper object for accessing and manipulating a stored value.
*/
export type StoreValueProxy<T> = {
/**
* Gets the current value from the store
*/
get(): Promise<T | undefined>;
/**
* Gets the current value from the store or fails if undefined.
*/
getOrFail(): Promise<T>;
/**
* Sets a new value in the store
* @param newValue The value to store
*/
set(newValue: T): Promise<void>;
};
/**
* Abstract base class for implementing key-value storage with event emission capabilities.
* Extends EventEmitter to provide event handling for store operations.
*
* @example
* ```typescript
* class MyStore extends BaseStore {
* async keys(): Promise<Array<string>> {
* // Implementation
* }
*
* async get<T>(key: string): Promise<T | undefined> {
* // Implementation
* }
*
* async set<T>(key: string, value: T): Promise<void> {
* // Implementation
* }
*
* async delete(key: string): Promise<void> {
* // Implementation
* }
* }
* ```
*/
export abstract class BaseStore extends EventEmitter<StoreEvents> {
/**
* Returns an array of all keys in the store.
*/
abstract keys(): Promise<Array<string>>;
/**
* Retrieves a value from the store by its key.
*
* @template T The type of the value to retrieve
* @param key The key to lookup
*/
abstract get<T>(key: string): Promise<T | undefined>;
/**
* Stores a value in the store with the specified key.
*
* @template T The type of the value to store
* @param key The key under which to store the value
* @param value The value to store
*/
abstract set<T>(key: string, value: T): Promise<void>;
/**
* Removes a value from the store by its key.
*
* @param key The key to remove
*/
abstract delete(key: string): Promise<void>;
/**
* Retrieves all key-value pairs from the store.
*
* @template T The type of the values in the store
*/
async all<T>(): Promise<{ [key: string]: T }> {
const keys = await this.keys();
const values = await Promise.all(keys.map((key) => this.get<T>(key)));
return keys.reduce(
(acc, key, index) => {
const value = values[index];
if (value !== undefined) {
acc[key] = value;
}
return acc;
},
{} as { [key: string]: T },
);
}
/**
* Removes all key-value pairs from the store.
*/
async clear(): Promise<void> {
const keys = await this.keys();
await Promise.all(keys.map((key) => this.delete(key)));
}
/**
* Checks if a key exists in the store.
*
* @param key The key to check
*/
async has(key: string): Promise<boolean> {
return (await this.get(key)) ? true : false;
}
/**
* Retrieves multiple values from the store by their keys.
* Filters out undefined values from the results.
*
* @template T The type of the values to retrieve
* @param keys Array of keys to retrieve
*/
async batchGet<T>(keys: Array<string>): Promise<Map<string, T>> {
const results = await Promise.all(
keys.map(async (key) => {
const value = await this.get(key);
return [key, value] as const;
}),
);
return new Map(
results.filter(([_, value]) => value !== undefined) as [string, T][],
);
}
/**
* Stores multiple key-value pairs in the store.
* Emits 'set' events for each key-value pair.
*
* @template T The type of the values to store
* @param items Map of key-value pairs to store
*/
async batchSet<T>(items: Map<string, T>): Promise<void> {
await Promise.all(
Array.from(items).map(([key, value]) => {
return this.set(key, value);
}),
);
items.forEach((value, key) => {
this.emit('set', { key, value });
});
}
/**
* Closes the store connection. Override this method in implementing classes if needed.
*/
async close(): Promise<void> {}
/**
* Retrieves a value from the store by its key, throwing an error if the value doesn't exist.
*
* @template T The type of the value to retrieve
* @param key The key to lookup
*/
async getOrFail<T>(key: string): Promise<T> {
// Attempt to get the value from the store.
const value = await this.get<T>(key);
// If the value does not exist, throw an error.
if (typeof value === 'undefined') {
throw new Error(`Failed to get key "${key}"`);
}
// Return the value.
return value;
}
/**
* Retrieves a value from the store by its key, or sets it using the provided setter function if it doesn't exist.
*
* @template T The type of the value to retrieve or set
* @param key The key to lookup
* @param setter Function to generate the value if it doesn't exist
*/
async getOrSet<T>(key: string, setter: () => T | Promise<T>): Promise<T> {
// Attempt to get the value from the store.
let value = await this.get<T>(key);
// If it is undefined, use the setter to set it.
if (typeof value === 'undefined') {
value = await setter();
await this.set(key, value);
}
// Return the value.
return value;
}
/**
* Creates a wrapper object that provides convenient access to a stored value.
* The wrapper allows getting and setting the value using async property access.
*
* @template T The type of the value to wrap
* @param key The key under which the value is stored
* @returns An object with a getter and setter for the stored value
*
* @example
* ```typescript
* const numValue = store.proxy<number>('myNumber');
* const value = await numValue.get(); // gets the stored value
* await numValue.set(42); // sets the stored value
* ```
*/
proxy<T>(key: string): StoreValueProxy<T> {
const self = this;
return {
/**
* Gets the current value from the store
*/
get(): Promise<T | undefined> {
return self.get<T>(key);
},
/**
* Gets the current value from the store or fails if undefined
*/
getOrFail(): Promise<T> {
return self.getOrFail<T>(key);
},
/**
* Sets a new value in the store
*/
async set(newValue: T): Promise<void> {
await self.set(key, newValue);
},
};
}
}
+3
View File
@@ -0,0 +1,3 @@
export * from './base-store.js';
export * from './store-inmemory.js';
export * from './store-inmemory-synced.js';
@@ -0,0 +1,255 @@
import { BaseStorage, BaseStore, StorageOpts } from './base-store.js';
import { StoreInMemorySynced } from './store-inmemory-synced.js';
import {
Encryption,
} from '../utils';
import {
encodeExtendedJsonObject,
decodeExtendedJsonObject,
} from '@xocash/primitives';
import { openDB, deleteDB, IDBPDatabase } from 'idb';
export class StorageIndexedDB extends BaseStorage {
private constructor(
private db: IDBPDatabase,
private dbName: string,
) {
super();
}
public static async createOrOpen(dbName: string) {
try {
// Check if database exists by attempting to open it at current version
const existingDb = await openDB(dbName, undefined);
return new StorageIndexedDB(existingDb, dbName);
} catch (error) {
// If database doesn't exist, create it at version 1
const newDb = await openDB(dbName, 1, {
upgrade(_db) {
// Initial database creation - no stores needed by default
},
});
return new StorageIndexedDB(newDb, dbName);
}
}
async listStores() {
return Array.from(this.db.objectStoreNames);
}
async createStore(storeName: string, opts: StorageOpts = {}) {
if (!this.db.objectStoreNames.contains(storeName)) {
const currentVersion = this.db.version;
this.db.close();
const db = await openDB(this.dbName, currentVersion + 1, {
upgrade(db) {
db.createObjectStore(storeName);
},
});
this.db = db;
}
const store = await StoreIndexedDB.create(
this.db,
storeName,
opts.encryption,
);
return opts.syncInMemory ? await StoreInMemorySynced.create(store) : store;
}
async getStore(storeName: string, opts: StorageOpts = {}) {
try {
if (!this.db.objectStoreNames.contains(storeName)) {
return null;
}
const store = await StoreIndexedDB.create(
this.db,
storeName,
opts.encryption,
);
return opts.syncInMemory ? StoreInMemorySynced.create(store) : store;
} catch (error) {
return null;
}
}
async createOrGetStore(storeName: string, opts: StorageOpts = {}) {
const existing = await this.getStore(storeName, opts);
if (existing) {
return existing;
}
return this.createStore(storeName, opts);
}
async deleteStore(storeName: string) {
if (this.db.objectStoreNames.contains(storeName)) {
const currentVersion = this.db.version;
this.db.close();
const db = await openDB(this.dbName, currentVersion + 1, {
upgrade(db) {
db.deleteObjectStore(storeName);
},
});
this.db = db;
}
}
async deleteDatabase() {
this.db.close();
await deleteDB(this.dbName);
}
}
/**
* Implementation of BaseStore using IndexedDB as the storage backend.
*/
export class StoreIndexedDB extends BaseStore {
constructor(
public db: IDBPDatabase,
public storeName: string,
public encryption?: Encryption,
) {
super();
/*
this.broadcastChannel = new BroadcastChannel(
`StoreIndexedDB:${db.name}.${this.storeName}`,
);
this.broadcastChannel.onmessage = (message) => {
this.emit('set', message);
};
*/
}
/**
* Factory method to create a new instance of StoreIndexedDB.
* Provides a more convenient way to instantiate the store when working with promises.
*
* @param db - An instance of an upgraded and opened IndexedDB database
* @param storeName - The name of the object store within the database to use
*
* @example
* ```typescript
* const store = await StoreIndexedDB.create(db, 'myStore');
* ```
*/
static async create(
db: IDBPDatabase,
storeName: string,
encryption?: Encryption,
) {
return new this(db, storeName, encryption);
}
async all<T>() {
const tx = this.db.transaction(this.storeName, 'readonly');
const store = tx.objectStore(this.storeName);
const keys = await store.getAllKeys();
const values = await store.getAll();
return keys.reduce(
(acc, key, index) => {
acc[key.toString()] = decodeExtendedJsonObject(values[index]);
return acc;
},
{} as { [key: string]: T },
);
}
async keys() {
const tx = this.db.transaction(this.storeName, 'readonly');
const store = tx.objectStore(this.storeName);
const keys = await store.getAllKeys();
return keys.map((key) => key.toString());
}
async get<T>(key: string) {
const encodedValue = await this.db.get(this.storeName, key);
const decryptedValue = this.encryption
? this.encryption.decrypt(encodedValue)
: encodedValue;
return decodeExtendedJsonObject(decryptedValue) as T;
}
async set<T>(key: string, value: T) {
const encodedValue = encodeExtendedJsonObject(value);
const encryptedValue = this.encryption
? this.encryption.encrypt(encodedValue)
: encodedValue;
await this.db.put(this.storeName, encryptedValue, key);
this.emit('set', { key, value });
}
async delete(key: string) {
await this.db.delete(this.storeName, key);
this.emit('delete', { key });
}
async batchGet<T>(keys: string[]): Promise<Map<string, T>> {
const tx = this.db.transaction(this.storeName, 'readonly');
const store = tx.objectStore(this.storeName);
const results = await Promise.all(
keys.map(async (key) => {
const value = await store.get(key);
return [
key,
value ? decodeExtendedJsonObject(value) : undefined,
] as const;
}),
);
await tx.done;
return new Map(
results.filter(([_, value]) => value !== undefined) as [string, T][],
);
}
async batchSet<T>(items: Map<string, T>) {
const tx = this.db.transaction(this.storeName, 'readwrite');
const store = tx.objectStore(this.storeName);
await Promise.all(
Array.from(items).map(([key, value]) => {
const encodedValue = encodeExtendedJsonObject(value);
return store.put(encodedValue, key);
}),
);
await tx.done;
items.forEach((value, key) => {
this.emit('set', { key, value });
});
}
async clear() {
await this.db.clear(this.storeName);
this.emit('clear', undefined);
}
async has(key: string) {
const tx = this.db.transaction(this.storeName, 'readonly');
const store = tx.objectStore(this.storeName);
const result = await store.getKey(key);
return result !== undefined;
}
async close() {
this.db.close();
}
}
@@ -0,0 +1,82 @@
import { BaseStore } from './base-store.js';
import { StoreInMemory } from './store-inmemory.js';
/**
* Storage Adapter that takes another Storage Adapter (e.g. IndexedDB) and "syncs" its contents to system memory for faster read access.
*
* All read operations will use system memory - all write operations will use the provided adapter.
*/
export class StoreInMemorySynced extends BaseStore {
constructor(
private inMemoryCache: StoreInMemory,
private store: BaseStore,
) {
super();
// Hook into all write operations so that we can sync the In-Memory cache.
this.store.on('set', async (payload) => {
await this.inMemoryCache.set(payload.key, payload.value);
this.emit('set', { key: payload.key, value: payload.value });
});
this.store.on('delete', async (payload) => {
await this.inMemoryCache.delete(payload.key);
this.emit('delete', { key: payload.key });
});
this.store.on('clear', async () => {
await this.inMemoryCache.clear();
this.emit('clear', undefined);
});
}
static async create(store: BaseStore) {
// Instantiate in-memory cache and IndexedDB.
const inMemoryCache = new StoreInMemory();
// Create instance of this store.
const memorySyncedStore = new this(inMemoryCache, store);
// Sync the data from IndexedDB into the In-Memory cache.
const indexedDBEntries = await store.all();
for (let [key, value] of Object.entries(indexedDBEntries)) {
inMemoryCache.set(key, value);
}
// Return our instance of this store.
return memorySyncedStore;
}
async all<T>() {
return await this.inMemoryCache.all<T>();
}
async keys() {
return await this.inMemoryCache.keys();
}
async get<T>(key: string) {
// TODO: Consider whether you want to structuredClone this to prevent mutation.
return await this.inMemoryCache.get<T>(key);
}
async set<T>(key: string, value: T) {
await this.store.set(key, value);
}
async delete(key: string) {
await this.store.delete(key);
}
async clear() {
await this.store.clear();
}
async has(key: string) {
return await this.inMemoryCache.has(key);
}
async close() {
await this.store.close();
}
}
@@ -0,0 +1,52 @@
import { BaseStore } from './base-store.js';
/**
* Implementation of BaseStore using Memory as the storage backend.
*
* @remarks
* This implementation can be used testing and caching of expensive operations.
*/
export class StoreInMemory extends BaseStore {
private store: Map<string, any>;
constructor() {
super();
this.store = new Map();
}
async all<T>() {
const result: { [key: string]: T } = {};
for (const [key, value] of this.store.entries()) {
result[key] = value as T;
}
return result;
}
async keys() {
return Array.from(this.store.keys());
}
async get<T>(key: string) {
return this.store.get(key) as T;
}
async set<T>(key: string, value: T) {
this.store.set(key, value);
this.emit('set', { key, value });
}
async delete(key: string) {
this.store.delete(key);
this.emit('delete', { key });
}
async clear() {
this.store.clear();
this.emit('clear', undefined);
}
async has(key: string) {
return this.store.has(key);
}
}
+122
View File
@@ -0,0 +1,122 @@
// TODO: Consider whether we should shuffle this to Stack Util (as opposed to Primitive).
// It is async which breaks from our Primitive patterns.
import { utf8ToBin } from '@bitauth/libauth';
// NOTE: We need to provide a default salt otherwise we would be deriving a key per each operation.
// This would be far too computationally expensive.
// TODO: Allow the salt to be customized in an options argument to the constructor.
export const DEFAULT_XO_SALT =
'cash.xo.default_salt_for_encryption_aabbccddeeff00112233445566778899';
export type EncryptionOpts = {
algorithm: string;
keyLength: number;
salt: Uint8Array;
ivLength: number;
iterations: number;
};
export class Encryption {
constructor(
private key: CryptoKey,
public opts: EncryptionOpts,
) {}
static async fromBytes(key: Uint8Array, opts: Partial<EncryptionOpts> = {}) {
// Merge the provided options into our default options.
const encryptionOpts = {
algorithm: 'AES-GCM',
keyLength: 256,
salt: utf8ToBin(DEFAULT_XO_SALT),
ivLength: 16,
iterations: 100_000,
...opts,
};
// Create a key derivation key
const keyMaterialBase = await crypto.subtle.importKey(
'raw',
key,
'PBKDF2',
false,
['deriveBits', 'deriveKey'],
);
// Derive the actual encryption key
const derivedKey = await crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: encryptionOpts.salt,
iterations: encryptionOpts.iterations,
hash: 'SHA-256',
},
keyMaterialBase,
{
name: encryptionOpts.algorithm,
length: encryptionOpts.keyLength,
},
false,
['encrypt', 'decrypt'],
);
return new Encryption(derivedKey, encryptionOpts);
}
static async fromPassphrase(
passphrase: string,
opts: Partial<EncryptionOpts> = {},
) {
const key = utf8ToBin(passphrase);
return this.fromBytes(key, opts);
}
async encrypt(payload: Uint8Array | string): Promise<Uint8Array> {
// Convert string payload to Uint8Array if needed
const data = typeof payload === 'string' ? utf8ToBin(payload) : payload;
// Generate random IV
const iv = crypto.getRandomValues(new Uint8Array(this.opts.ivLength));
// Encrypt the data
const encryptedData = await crypto.subtle.encrypt(
{
name: this.opts.algorithm,
iv,
},
this.key,
data,
);
// Combine IV and encrypted data
const result = new Uint8Array(iv.length + encryptedData.byteLength);
result.set(iv);
result.set(new Uint8Array(encryptedData), iv.length);
return result;
}
async decrypt(payload: Uint8Array | string): Promise<Uint8Array> {
// Ensure payload is Uint8Array
if (typeof payload === 'string') {
throw new Error('Encrypted payload must be Uint8Array');
}
// Extract IV and encrypted data
const iv = payload.slice(0, this.opts.ivLength);
const encryptedData = payload.slice(this.opts.ivLength);
// Decrypt the data
const decryptedData = await crypto.subtle.decrypt(
{
name: this.opts.algorithm,
iv,
},
this.key,
encryptedData,
);
return new Uint8Array(decryptedData);
}
}
+146
View File
@@ -0,0 +1,146 @@
// TODO: You'll probably want to use WeakRef's here.
export type EventMap = Record<string, unknown>;
type Listener<T> = (detail: T) => void;
interface ListenerEntry<T> {
listener: Listener<T>;
wrappedListener: Listener<T>;
debounceTime?: number;
once?: boolean;
}
export class EventEmitter<T extends EventMap> {
private listeners: Map<keyof T, Set<ListenerEntry<T[keyof T]>>> = new Map();
on<K extends keyof T>(
type: K,
listener: Listener<T[K]>,
debounceMilliseconds?: number,
): Listener<T[K]> {
const wrappedListener =
debounceMilliseconds && debounceMilliseconds > 0
? this.debounce(listener, debounceMilliseconds)
: listener;
if (!this.listeners.has(type)) {
this.listeners.set(type, new Set());
}
const listenerEntry: ListenerEntry<T[K]> = {
listener,
wrappedListener,
debounceTime: debounceMilliseconds,
};
this.listeners.get(type)?.add(listenerEntry as ListenerEntry<T[keyof T]>);
return listener;
}
once<K extends keyof T>(
type: K,
listener: Listener<T[K]>,
debounceMilliseconds?: number,
): Listener<T[K]> {
const wrappedListener: Listener<T[K]> = (detail: T[K]) => {
this.off(type, listener);
listener(detail);
};
const debouncedListener =
debounceMilliseconds && debounceMilliseconds > 0
? this.debounce(wrappedListener, debounceMilliseconds)
: wrappedListener;
if (!this.listeners.has(type)) {
this.listeners.set(type, new Set());
}
const listenerEntry: ListenerEntry<T[K]> = {
listener,
wrappedListener: debouncedListener,
debounceTime: debounceMilliseconds,
once: true,
};
this.listeners.get(type)?.add(listenerEntry as ListenerEntry<T[keyof T]>);
return listener;
}
off<K extends keyof T>(type: K, listener: Listener<T[K]>): void {
const listeners = this.listeners.get(type);
if (!listeners) return;
const listenerEntry = Array.from(listeners).find(
(entry) =>
entry.listener === listener || entry.wrappedListener === listener,
);
if (listenerEntry) {
listeners.delete(listenerEntry);
}
}
emit<K extends keyof T>(type: K, payload: T[K]): boolean {
const listeners = this.listeners.get(type);
if (!listeners) return false;
listeners.forEach((entry) => {
entry.wrappedListener(payload);
});
return listeners.size > 0;
}
removeAllListeners(): void {
this.listeners.clear();
}
async waitFor<K extends keyof T>(
type: K,
predicate: (payload: T[K]) => boolean,
timeoutMs?: number,
): Promise<T[K]> {
return new Promise((resolve, reject) => {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const listener = (payload: T[K]) => {
if (predicate(payload)) {
// Clean up
this.off(type, listener);
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
resolve(payload);
}
};
// Set up timeout if specified
if (timeoutMs !== undefined) {
timeoutId = setTimeout(() => {
this.off(type, listener);
reject(new Error(`Timeout waiting for event "${String(type)}"`));
}, timeoutMs);
}
this.on(type, listener);
});
}
private debounce<K extends keyof T>(
func: Listener<T[K]>,
wait: number,
): Listener<T[K]> {
let timeout: ReturnType<typeof setTimeout>;
return (detail: T[K]) => {
if (timeout !== null) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
func(detail);
}, wait);
};
}
}
@@ -1,17 +1,20 @@
export class CashRPCError extends Error {
constructor(message: string, public readonly details?: string) {
export class ExtError extends Error {
constructor(
message: string,
public readonly details?: string,
) {
super(message);
// Capture the stack trace (V8 engines only)
// This step ensures the stack trace is captured correctly
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CashRPCError);
Error.captureStackTrace(this, ExtError);
} else {
this.stack = new Error().stack;
console.error(this.stack);
}
// 👇️ because we are extending a built-in class
Object.setPrototypeOf(this, CashRPCError.prototype);
Object.setPrototypeOf(this, ExtError.prototype);
}
}
}
+6
View File
@@ -0,0 +1,6 @@
export * from './encryption.js';
export * from './event-emitter.js';
export * from './ext-error.js';
export * from './memoizer.js';
export * from './misc.js';
export * from './uuid.js';
+55
View File
@@ -0,0 +1,55 @@
// TODO: We may want to move this to @xocash/primitives.
export class Memoizer {
private cache = new Map<string, any>();
/**
* Gets a cached value for the given key, computing it if it doesn't exist.
*
* @param key - The key to look up or store the value under
* @param compute - Function to compute the value if it's not cached
* @returns The cached or computed value
*/
get<K extends string, V>(key: K, compute: () => V): V {
if (!this.cache.has(key)) {
this.cache.set(key, compute());
}
return this.cache.get(key) as V;
}
/**
* Checks if a value exists for the given key.
*
* @param key - The key to check
* @returns Whether the key exists in the cache
*/
has(key: string): boolean {
return this.cache.has(key);
}
/**
* Deletes a cached value.
*
* @param key - The key to delete
* @returns Whether a value was deleted
*/
delete(key: string): boolean {
return this.cache.delete(key);
}
/**
* Clears all cached values.
*/
clear(): void {
this.cache.clear();
}
/**
* Gets all cached keys.
*
* @returns Array of cached keys
*/
keys(): string[] {
return Array.from(this.cache.keys());
}
}
+17
View File
@@ -0,0 +1,17 @@
import { binToHex } from '@bitauth/libauth';
// TODO: Put unsorted stuff in here and then try to sort them somewhere more sensible later.
export function getOutpointId(outpoint: {
outpointTransactionHash: Uint8Array;
outpointIndex: number;
}): string {
const outpointHashHex = binToHex(outpoint.outpointTransactionHash);
return `${outpointHashHex}:${outpoint.outpointIndex}`;
}
// TODO: Jason uses form timestampMs_entityId
export function generateActivityId() {
return Date.now().toString();
}
+205
View File
@@ -0,0 +1,205 @@
// TODO: This probably needs some work.
// The reason this exists is that Browser's native EventSource is rubbish:
// 1. It does not allow passing of headers.
// 2. It is browser-only (this implementation aims to work for Node also)
// 3. It does not handle disconnects/reconnects gracefully
// 4. It does not handle last-event-id (important for history).
// 5. It does not allow a custom fetch function (probably not necessary, but there's a reason I'd rather support this which I'll explain some other time).
// This might eventually be shifted out of XO/stack package and into its own.
// Q: "Why not just leverage an existing package?"
// A: They're all bad - the "go to" is a Microsoft (@azure/fetch-event-soruce) that is no longer maintained.
// It does not support NodeJS (or Workers) and we cannot depend upon forks of it.
export interface SSEOptions {
fetch?: typeof fetch;
headers?: Record<string, string>;
onMessage?: (event: SSEMessageEvent) => void;
onError?: (error: Error) => void;
onOpen?: () => void;
onClose?: () => void;
maxRetries?: number;
retryDelay?: number;
}
export interface SSEMessageEvent {
data: string;
type: string;
id: string | null;
lastEventId: string;
origin: string;
}
export interface SSEEvent {
data: string;
event: string;
id: string | null;
}
export class SSEClient {
private url: string;
private options: Required<Omit<SSEOptions, 'headers'>> & {
headers: Record<string, string>;
};
private abortController: AbortController | null;
private retryCount: number;
private lastEventId: string;
private connected: boolean;
constructor(url: string, options: SSEOptions = {}) {
this.url = url;
this.options = {
fetch: globalThis.fetch,
headers: {},
onMessage: () => {},
onError: () => {},
onOpen: () => {},
onClose: () => {},
maxRetries: 5,
retryDelay: 3000,
...options,
};
this.abortController = null;
this.retryCount = 0;
this.lastEventId = '';
this.connected = false;
}
public async connect(): Promise<void> {
if (this.connected) {
return;
}
this.abortController = new AbortController();
try {
const response = await this.options.fetch(this.url, {
headers: {
Accept: 'text/event-stream',
'Cache-Control': 'no-cache',
'Last-Event-ID': this.lastEventId,
...this.options.headers,
},
signal: this.abortController.signal,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
if (!response.body) {
throw new Error('ReadableStream not supported');
}
this.connected = true;
this.options.onOpen();
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) {
this.handleDisconnect();
break;
}
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split(/\r\n|\r|\n/);
buffer = this.processEventStream(lines);
}
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
return;
}
this.options.onError(
error instanceof Error ? error : new Error(String(error)),
);
this.handleDisconnect();
if (this.retryCount < this.options.maxRetries) {
this.retryCount++;
setTimeout(() => this.connect(), this.options.retryDelay);
}
}
}
private processEventStream(lines: string[]): string {
let event: SSEEvent = {
data: '',
event: 'message',
id: null,
};
for (let i = 0; i < lines.length - 1; i++) {
const line = lines[i];
if (line.length === 0) {
// Empty line means dispatch the event
if (event.data.length > 0) {
this.dispatchEvent(event);
event = {
data: '',
event: 'message',
id: null,
};
}
continue;
}
const [fieldName, ...fieldValue] = line.split(':');
const value = fieldValue.join(':').trim();
switch (fieldName) {
case 'event':
event.event = value;
break;
case 'data':
event.data += value + '\n';
break;
case 'id':
event.id = value;
this.lastEventId = value;
break;
case 'retry': {
const retryInt = parseInt(value, 10);
if (!isNaN(retryInt)) {
this.options.retryDelay = retryInt;
}
break;
}
}
}
// Return the last incomplete line as the new buffer
return lines[lines.length - 1];
}
private dispatchEvent(event: SSEEvent): void {
const messageEvent: SSEMessageEvent = {
data: event.data.slice(0, -1), // Remove trailing newline
type: event.event,
id: event.id,
lastEventId: this.lastEventId,
origin: this.url,
};
this.options.onMessage(messageEvent);
}
private handleDisconnect(): void {
this.connected = false;
this.options.onClose();
}
public close(): void {
if (this.abortController) {
this.abortController.abort();
this.handleDisconnect();
}
}
}
+31
View File
@@ -0,0 +1,31 @@
export function generateUUIDV7(customTimestamp?: bigint) {
// Step 1: Get the current timestamp in milliseconds
const timestamp = customTimestamp ?? BigInt(Date.now()); // Use BigInt to handle 48-bit values
// Step 2: Convert the timestamp to a 48-bit hexadecimal string
const timestampHex = timestamp.toString(16).padStart(12, '0'); // Ensure 12 hex characters
// Step 3: Generate 74 bits (19 hex characters) of random data
const randomHex = crypto
.getRandomValues(new Uint8Array(10))
.map((b) => Number(b.toString(16).padStart(2, '0')))
.join(''); // 10 bytes = 20 hex characters
// Step 4: Combine fields to form the UUID
const version = '7'; // Version 7 (0111)
const variant = '8'; // Variant 1 (10xx) is "8", "9", "a", or "b"
return (
`${timestampHex.substring(0, 8)}-${timestampHex.substring(8, 12)}` + // Timestamp (48 bits)
`-${version}${randomHex.substring(0, 3)}` + // Version (4 bits) + 12 random bits
`-${variant}${randomHex.substring(3, 6)}` + // Variant (2 bits) + 14 random bits
`-${randomHex.substring(6)}` // Remaining 48 random bits
);
}
/**
* Extract the timestamp from a UUID v7
*/
export function getTimestampFromUUID(uuid: string): bigint {
return BigInt(parseInt(uuid.slice(0, 8), 16));
}
+240
View File
@@ -0,0 +1,240 @@
// An activity represents an event that should be saved to persistent storage(s).
// TODO: Read more into LibAuth's concept of these.
// Jason mentions pruning, but I don't quite understand how that will be done yet.
// He also has the concept of "extensions" - but I'm not sure this has been fleshed out yet.
import { generateUUIDV7, getTimestampFromUUID } from '../utils';
import { BaseStore } from '../storage';
// TODO: Think about different activities
// TemplateActivity
// CashConnectActivity
// CoinLockActivity
// TODO: StorageMany adapter should be configurable to make it so set() cannot fail.
// However, for optimization, get() should probably only retrieve from a primary (usually local) adapter.
// Otherwise, shit will be too slow if we're doing a get() or all() from a remote source.
// This may also solve the AES256 problem: Local does not need to be encrypted per se.
// Sync from Remote (encrypted) to Local (non-encrypted) can happen in the background.
// TODO: I still haven't quite wrapped my head around LibAuth approach.
// But I imagine there'll be some kind of "Mutable" vs "Immutable" concept for Activities.
// Because we need to compile a "snapshot" based on Activities, if we add a Mutable Activity, we can prune previous Mutable Activities of the same identifier.
// This will help massively with optimization:
// 1. Our set of Activities becomes smaller (computation/storage = faster/better)
// 2. Syncing will take less time
// For the above, this probably means that we want to keep our Activities limited to one mutation.
// For example, we ideally wouldn't want an Activity that modifies/refers to multiple values.
// { type: 'freezeCoins', coins: [...] }
// ... because we cannot sync them efficiently (we need the entire history).
// Whereas, if we do:
// { type: 'freezeCoin' }
// ... and have an identifer, we can ensure that each wallet only syncs the latest frozen coin.
// Amendment 2024-11-20:
// For mutable, we could use property "unique: boolean".
// For priority (e.g. txTime activity), we could use property "policy: "earlist" | latest"
// Type definitions
export type Activity<Type extends string, ValueType> = {
timestamp?: bigint;
type: Type;
id: string;
value: ValueType;
};
// Standardized Activities.
export type WalletName = Activity<'WalletName', string>;
export type WalletDescription = Activity<'WalletDescription', string>;
export type TransactionFirstSeen = Activity<'TransactionFirstSeen', string>;
export type TransactionMemo = Activity<'TransactionMemo', string>;
// XO-specific Activities.
// TODO: These probably don't belong here and should be moved to the Wallet Codebase.
export type XOWalletColor = Activity<'XOWalletColor', string>;
export type XOTransactionCategory = Activity<'XOTransactionCategory', string>;
export type XOFrozenCoin = Activity<'XOFrozenCoin', boolean>;
export type SnapshotByType = {
[type: string]: {
[id: string]: Activity<string, any>;
};
};
// Policy type definitions
export type PolicyFunction<T = any> = (
existingActivity: Activity<string, T> | undefined,
newActivity: Activity<string, T>,
) => Activity<string, T>;
export class Activities {
// TODO: Consider splitting into its own mutable class: ActivitySnapshot.
// This might be cleaner as we'll likely want to be able to view a raw timeline of activities.
// So we can make Activities have its own methods for that without cluttering the class.
public snapshot: SnapshotByType = {};
private policies = new Map<string, PolicyFunction>();
// Add a map to track store keys for each snapshot key
private storeKeyMap = new Map<string, string>();
constructor(public store: BaseStore) {
this.store.on(
'set',
async (payload: { key: string; value: Activity<string, any> }) => {
// When a new activity is added, process it individually
await this.processActivity(payload.key, payload.value);
},
);
}
/**
* Get all activities of a specific type
*/
public getActivitiesByType<T>(type: string): Activity<string, T>[] {
return Object.values(this.snapshot[type] || {});
}
/**
* Get a specific activity by type and id
*/
public getActivity<T>(
type: string,
id: string,
): Activity<string, T> | undefined {
return this.snapshot[type]?.[id];
}
/**
* Process a single activity and update the snapshot
*/
private async processActivity(
storeKey: string,
activity: Activity<string, any>,
) {
if (!activity.timestamp) {
console.warn('Activity without timestamp encountered:', storeKey);
return;
}
const snapshotKey = this.getSnapshotKey(activity);
const existingActivity = this.getActivityFromSnapshot(
activity.type,
activity.id,
);
// Apply policy to determine which activity to keep
const keptActivity = this.applyPolicy(existingActivity, activity);
// Update snapshot with the kept activity
this.setActivityInSnapshot(keptActivity);
if (keptActivity === activity) {
// If we kept the new activity, update the store key mapping
const oldStoreKey = this.storeKeyMap.get(snapshotKey);
if (oldStoreKey) {
// Delete the old activity from the store
await this.store.delete(oldStoreKey);
}
this.storeKeyMap.set(snapshotKey, storeKey);
} else {
// If we kept the existing activity, delete the new activity from the store
await this.store.delete(storeKey);
}
}
/**
* Add a new activity to the store
*/
public async addActivity(activity: Activity<string, any>) {
const timestamp = activity.timestamp ?? BigInt(Date.now());
const activityWithTimestamp = {
...activity,
timestamp,
};
const key = generateUUIDV7(timestamp);
await this.store.set(key, activityWithTimestamp);
// Note: We don't need to call processActivity here as the 'set' event will trigger it
}
/**
* Compile a full snapshot from scratch (only needed for initialization or recovery)
*/
public async compileSnapshot() {
// Clear existing snapshot
this.snapshot = {};
// Get all activity data from our store
const activities = await this.store.all<Activity<string, any>>();
const entries = Object.entries(activities);
// Sort activities by timestamp using UUID v7's embedded timestamp
const activitiesSorted = entries.sort(([keyA], [keyB]) => {
const timestampA = getTimestampFromUUID(keyA);
const timestampB = getTimestampFromUUID(keyB);
return Number(timestampA - timestampB);
});
// Process each activity in order
for (const [storeKey, activity] of activitiesSorted) {
await this.processActivity(storeKey, activity);
}
return this.snapshot;
}
/**
* Register a policy for handling conflicts between activities of the same type
* @param type Activity type to register policy for
* @param policyFn Function that decides which activity to keep
*/
public registerPolicy(type: string, policyFn: PolicyFunction) {
this.policies.set(type, policyFn);
}
/**
* Get an activity from the snapshot by type and id
*/
private getActivityFromSnapshot(
type: string,
id: string,
): Activity<string, any> | undefined {
return this.snapshot[type]?.[id];
}
/**
* Set an activity in the snapshot, creating necessary object structure
*/
private setActivityInSnapshot(activity: Activity<string, any>) {
if (!this.snapshot[activity.type]) {
this.snapshot[activity.type] = {};
}
this.snapshot[activity.type][activity.id] = activity;
}
/**
* Get the snapshot key for an activity
*/
private getSnapshotKey(activity: Activity<string, any>): string {
return `${activity.type}:${activity.id}`;
}
/**
* Apply policy to determine which activity should be kept
*/
private applyPolicy(
existingActivity: Activity<string, any> | undefined,
newActivity: Activity<string, any>,
): Activity<string, any> {
const policy = this.policies.get(newActivity.type);
if (!policy) {
// Default policy: compare timestamps
if (!existingActivity) return newActivity;
return existingActivity.timestamp! >= newActivity.timestamp!
? existingActivity
: newActivity;
}
return policy(existingActivity, newActivity);
}
}
+154
View File
@@ -0,0 +1,154 @@
import {
type InputTemplateBCH,
type TransactionTemplate,
type WalletAddresses,
type WalletTransactions,
} from './types.js';
import { type BlockchainUTXOs } from '../blockchain';
import { type EventMap, EventEmitter } from '../utils';
import { type TokenBalances, type Address } from '@xocash/primitives';
/**
* Common interface for all wallet types.
*
* @remarks
*
* All function signatures are deliberately asynchronous to accommodate for cases where wallets might be remote.
* For example, we might eventually want to support a multisig service.
* Or we might have to support some other custodial "Apple Pay"-like OS-interface to get accepted onto their app store.
*/
export abstract class BaseWallet<
WalletEvents extends EventMap,
> extends EventEmitter<WalletEvents> {
/**
* Start monitoring this wallet for any transaction activity.
*/
abstract start(): Promise<void>;
/**
* Stop monitoring this wallet for any transaction activity.
*/
abstract stop(): Promise<void>;
/**
* Remove any event listeners from this wallet.
*/
abstract destroy(): Promise<void>;
/**
* Fetch all transactions from the blockchain involving this wallet.
*
* @remarks
*
* We will want to add a query argument so that workers can use this efficiently:
*
* ```ts
* {
* limit?: number;
* offset?: number;
* sort?: () => number;
* filter?: () => boolean;
* }
* ```
*
* This "query" argument should be turned into a generic type as we will want to re-use it for Activities.
*/
abstract getTransactions(): Promise<WalletTransactions>;
/**
* Fetch all unspents from the blockchain belonging to this wallet.
*/
abstract getUnspents(): Promise<BlockchainUTXOs>;
/**
* Fetch all unspents from the blockchain belonging to this wallet.
*
* @remarks
*
* I was considering removing this and just storing unspents as "UTXOSignable"s.
* But that might not be ideal if we want to have Watch-only wallets.
* A better approach might be to have Fetch Unspents return `Array<UTXO | UTXOSignable>`
* Still need to flesh that out.
*
* EDIT: We're going to want to store state for caching anyway...
* May as well just getUnspentDirectives() from the local state instead of fetch.
* Likewise for balances.
*/
abstract getUnspentDirectives(): Promise<Array<InputTemplateBCH>>;
/**
* Get the satoshi balance of this wallet.
*
* @remarks
*
* Consider confirmed/unconfirmed balances (or some other representation).
*
* This becomes important in some instances because services like BitPay require one confirmation.
* This'll also have bearing on how we define our UTXO Selection strategies.
*/
abstract getBalanceSats(): Promise<bigint>;
/**
* Get the token balance of this wallet.
*
* @remarks
*
* Consider confirmed/unconfirmed balances (or some other representation).
*
* This becomes important in some instances because services like BitPay require one confirmation.
* This'll also have bearing on how we define our UTXO Selection strategies.
*/
abstract getBalanceTokens(): Promise<TokenBalances>;
/**
* Get all addresses belonging to this wallet.
*/
abstract getAddresses(): Promise<WalletAddresses>;
/**
* Get the address that this wallet should receive to.
*
* @remarks
*
* Not all wallets will have an address (e.g. a HD Wallet), but should still be able to return an address that:
* a) Change will be sent to.
* b) Funds should be received to.
*/
abstract getReceivingAddress(): Promise<Address>;
/**
* Select UTXOs from this wallet to meet the amounts required.
*
* @remarks
*
* TODO: We are going to want to return the Transaction that was compiled.
*
* TODO: This should accept a second argument (probably function) that can filter/sory UTXOs.
* The intent here is to provide a "spending policy". E.g. Only use (or prioritise) UTXOs with 1-conf.
*/
abstract signTransaction(
template: Partial<TransactionTemplate>,
): Promise<Uint8Array>;
/**
* Select UTXOs from this wallet to meet the amounts required and broadcast it to the Blockchain.
*
* @remarks
*
* TODO: We are going to want to return the Transaction that was compiled.
*/
abstract sendTransaction(
template: Partial<TransactionTemplate>,
): Promise<void>;
// TODO: This should be a push-only list.
// Need to understand how Jason's pruning approach works.
// It might make more sense to "key" activities by type:
// This would allow us to filter more effectively each time a new activity is added.
// As it stands, we would have to collate the entire list if it's done by timestamp.
abstract addActivity<T>(activity: T): Promise<void>;
abstract export(): Promise<string>;
}
@@ -1,3 +1,7 @@
export * from './activities.js';
export * from './base-wallet.js';
export * from './transaction-builder.js';
export * from './types.js';
export * from './wallet-hd.js';
export * from './wallet-p2pkh.js';
export * from './wallet-p2sh20.js';
@@ -0,0 +1,289 @@
import { type WalletUTXO } from './types.js';
import { type UTXOSet, ExtMap, Outpoint } from '@xocash/primitives';
import {
type TransactionTemplateFixed,
type CompilerBCH,
type TransactionBCH,
binsAreEqual,
binToHex,
hexToBin,
encodeTransactionBCH,
encodeTransactionOutput,
generateTransaction,
getDustThreshold,
} from '@bitauth/libauth';
// TODO: This could probably still use a refactor, but isn't terrible anymore.
/**
* Transaction Builder that takes a template and can populate appropriate UTXOs.
*
* @remarks
*
* Note that this will only populate required Satoshis and Mutable Tokens.
*
* @experimental
*/
export class TransactionBuilder {
public unspents: Array<WalletUTXO>;
constructor(
public readonly transaction: TransactionTemplateFixed<CompilerBCH>,
unspents: Array<WalletUTXO> = [],
public sourceOutputs: UTXOSet = new ExtMap(),
) {
// This class will "shift" (remove) unspents from the array so to ensure we don't mutate the source array, we clone it.
// NOTE: We cannot do a structuredClone here. It will not work in all cases.
this.unspents = [...unspents];
}
public calculateInputSats(): bigint {
return this.transaction.inputs.reduce((inputSats, input) => {
// Get the satoshi amount for this input.
// NOTE: If this is not a signable UTXO, we attempt to find the satoshi amount in the provided source outputs.
const valueSatoshis =
input.unlockingBytecode instanceof Uint8Array
? this.sourceOutputs.getOrFail(Outpoint.fromInput(input).toString())
.output.valueSatoshis
: input.unlockingBytecode.valueSatoshis;
// Return the accumulated satoshi amount.
return (inputSats += valueSatoshis);
}, 0n);
}
public calculateInputTokens(): Map<string, bigint> {
// NOTE: We cannot index by Uint8Array, so we convert the category to hexadecimal form.
const tokensRequired: Map<string, bigint> = new Map();
// Iterate over each input so that we can calculate the total required for each token category.
this.transaction.inputs.forEach((input) => {
// Get the source output for this input.
// NOTE: If this is not a signable UTXO, we attempt to find the source output in the provided source outputs.
const sourceOutput =
input.unlockingBytecode instanceof Uint8Array
? this.sourceOutputs.getOrFail(Outpoint.fromInput(input).toString())
.output
: input.unlockingBytecode;
// If the source output contains fungible tokens...
if (sourceOutput.token && !sourceOutput.token.nft) {
// Convert the token category to hex so we can index it in a map.
const categoryHex = binToHex(sourceOutput.token.category);
// Get the current total for the given category.
const currentTokenTotal = tokensRequired.get(categoryHex) || 0n;
// Calculate the new total for the given category.
const newTotal = currentTokenTotal + sourceOutput.token.amount;
// Set the new total for the given category.
tokensRequired.set(categoryHex, newTotal);
}
});
return tokensRequired;
}
public calculateOutputSats(): bigint {
return this.transaction.outputs.reduce(
(outputTotal, output) => (outputTotal += output.valueSatoshis),
0n,
);
}
public calculateOutputTokens(): Map<string, bigint> {
// NOTE: We must use a Map (as opposed to object) if we're indexing by Uint8Array.
const tokensRequired: Map<string, bigint> = new Map();
this.transaction.outputs.forEach((output) => {
// If this output has a token and it is not an NFT...
if (output.token && !output.token.nft) {
const currentTokenTotal =
tokensRequired.get(binToHex(output.token.category)) || 0n;
const newTotal = currentTokenTotal + output.token.amount;
tokensRequired.set(binToHex(output.token.category), newTotal);
}
});
return tokensRequired;
}
public calculateFeeSats(): bigint {
return BigInt(this.toBytes().length);
}
public calculateRequiredSats(): bigint {
const outputSats = this.calculateOutputSats();
const feeSats = this.calculateFeeSats();
const requiredSats = feeSats + outputSats;
return requiredSats;
}
public addTokensFromUnspents(): TransactionBuilder {
// Calculate the tokens required for this transaction.
const tokensRequired = this.calculateOutputTokens();
// Interate through each token and add inputs to meet the required amount.
tokensRequired.forEach((requiredAmountForToken, categoryId) => {
// Find unspents containing this category ID.
const unspentsContainingToken = this.unspents.filter((unspent) =>
binsAreEqual(
unspent.unlockingBytecode.token?.category || new Uint8Array(),
hexToBin(categoryId),
),
);
// Sort them so that we prioritize the largest amounts first.
const unspentsContainingTokenSorted = unspentsContainingToken.sort(
(a, b) =>
Number(b.unlockingBytecode.token?.amount || 0) -
Number(a.unlockingBytecode.token?.amount || 0),
);
// Loop until we have enough input tokens to match the required amount of output tokens.
while (
(this.calculateInputTokens().get(categoryId) || 0n) <
requiredAmountForToken
) {
// Get the unspent to add from the top of our list and remove it.
const unspent = unspentsContainingTokenSorted.shift();
// If there are no more unspents, it means we have insufficient funds, so throw an error.
if (!unspent) {
throw new Error(
`Failed to select UTXOs: ${
this.calculateInputTokens().get(categoryId) || 0n
} of token (${categoryId}) available, ${requiredAmountForToken} required`,
);
}
// Append this Input.
this.transaction.inputs.push(unspent);
}
});
return this;
}
public addSatoshisFromUnspents(): TransactionBuilder {
// Find unspents without tokens.
const unspentsWithoutTokens = this.unspents.filter(
(unspent) => typeof unspent.unlockingBytecode.token === 'undefined',
);
// Sort them so that we prioritize the largest amounts first.
const unspentsWithoutTokensSorted = unspentsWithoutTokens.sort((a, b) =>
Number(
b.unlockingBytecode.valueSatoshis - a.unlockingBytecode.valueSatoshis,
),
);
// Iterate over each unspent until we get the amount desired.
while (
this.calculateInputSats() <
this.calculateOutputSats() + this.calculateFeeSats()
) {
// Get the unspent to add from the top of our list and remove it.
const unspent = unspentsWithoutTokensSorted.shift();
// If there are no more unspents, it means we have insufficient funds, so throw an error.
if (!unspent) {
throw new Error(
`Failed to select UTXOs: ${this.calculateInputSats()} of sats available, ${this.calculateRequiredSats()} required`,
);
}
// Append this unspent.
this.transaction.inputs.push(unspent);
}
return this;
}
public addTokenChangeOutputs(
changeLockingBytecode: Uint8Array,
): TransactionBuilder {
// Calculate input and output token totals.
const inputTokens = this.calculateInputTokens();
const outputTokens = this.calculateOutputTokens();
// Iterate over each input and add a token change output (if there is change).
inputTokens.forEach((amount, categoryId) => {
const inputAmount = amount;
const outputAmount = outputTokens.get(categoryId) || 0n;
const changeAmount = inputAmount - outputAmount;
// Add the change output.
this.transaction.outputs.push({
lockingBytecode: changeLockingBytecode,
valueSatoshis: 1000n,
token: {
category: hexToBin(categoryId),
amount: changeAmount,
},
});
});
return this;
}
public addSatoshiChangeOutput(
changeLockingBytecode: Uint8Array,
): TransactionBuilder {
// NOTE: This might lead to over-paying the tx fee slightly.
const changeOutputTemplate = {
lockingBytecode: changeLockingBytecode,
valueSatoshis: 0n,
};
const changeOutputFee =
BigInt(encodeTransactionOutput(changeOutputTemplate).length) + 4n;
// Calculate the input satoshis and the current transaction fee.
const inputSats = this.calculateInputSats();
const outputSats = this.calculateOutputSats();
const transactionFee = this.calculateFeeSats() + changeOutputFee;
// Calculate the change satoshis.
const changeSats = inputSats - (outputSats + transactionFee);
// If the Change Output would be less than the dust threshold, do nothing.
if (changeSats < getDustThreshold(changeOutputTemplate)) {
return this;
}
// Add the change output.
this.transaction.outputs.push({
lockingBytecode: changeLockingBytecode,
valueSatoshis: changeSats,
});
// Return transaction with Satoshi Change Output.
return this;
}
public generate(): TransactionBCH {
// Generate the transaction
const generatedTransaction = generateTransaction(this.transaction);
// Ensure the transaction generated successfully.
if (!generatedTransaction.success) {
// lmao but better to show it to help devs.
const errors = generatedTransaction.errors
.map((error) => error.errors.map((error) => error.error).join(','))
.join(',');
throw new Error(`Failed to generate transaction: ${errors}`);
}
return generatedTransaction.transaction;
}
public toBytes(): Uint8Array {
const generatedTransaction = this.generate();
return encodeTransactionBCH(generatedTransaction);
}
}
+51
View File
@@ -0,0 +1,51 @@
import { type BaseBlockchain, type BlockchainTransaction } from '../blockchain';
import { type BaseStore } from '../storage';
import { Address, ExtMap } from '@xocash/primitives';
import {
type InputTemplate,
type CompilerBCH,
type CompilationData,
type CompilationDirectiveUnlocking,
type TransactionTemplateFixed,
type Output,
} from '@bitauth/libauth';
export type WalletServices = {
blockchain: BaseBlockchain;
store?: BaseStore;
cache?: BaseStore;
};
export type InputTemplateBCH = InputTemplate<
CompilerBCH,
false,
CompilationData
>;
// TODO: Rename me to WalletUTXO
export type WalletUTXO = {
outpointIndex: number;
outpointTransactionHash: Uint8Array;
sequenceNumber: number;
unlockingBytecode: CompilationDirectiveUnlocking<
CompilerBCH,
CompilationData<never>
>;
};
export type TransactionTemplate = TransactionTemplateFixed<CompilerBCH>;
export type FilterAndSortCallback = () => Promise<Array<InputTemplateBCH>>;
export type IWalletActivities<T> = { [id: string]: T };
// NOTE: We index this by Lockscript Hex so that we can find CashAddr, Legacy or other.
export type WalletAddresses = ExtMap<Address>;
export type WalletTransaction = BlockchainTransaction & {
sourceOutputs: Array<Output>;
};
export type WalletTransactions = ExtMap<WalletTransaction>;
+523
View File
@@ -0,0 +1,523 @@
// Import the Stamp class to derive the private keys
import { BaseWallet } from './base-wallet.js';
import { type TransactionTemplate } from './types.js';
import { TransactionBuilder } from './transaction-builder.js';
import { type WalletServices } from './types.js';
import {
WalletP2PKH,
WalletP2PKHFactory,
useWalletP2PKH,
} from './wallet-p2pkh.js';
import {
type BaseBlockchain,
type BlockchainTransactions,
type BlockchainUTXOs,
} from '../blockchain';
import {
type BaseStore,
type StoreValueProxy,
StoreInMemory,
} from '../storage';
import {
type TokenBalances,
HDPrivateNode,
ExtMap,
calculateBalanceSats,
calculateBalanceTokens,
encodeExtendedJson,
} from '@xocash/primitives';
import { hexToBin } from '@bitauth/libauth';
export const DERIVATION_PATH = "m/44'/145'/0'";
export const ADDRESS_GAP = 20;
// These constants correspond to the "change" path in BIP44.
// See: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
export const CHAIN_EXTERNAL = 0;
export const CHAIN_INTERNAL = 1;
export type WalletHDGenesisData = {
type: 'WalletHD';
derivationPath: string;
addressGap?: number;
} & ({ seed: string } | { mnemonic: string } | { xpriv: string });
export type WalletHDEvents<WalletType> = {
walletDataUpdated: WalletHDGenesisData;
shouldMonitorUpdated: boolean;
walletsUpdated: Array<WalletType>;
transactionsUpdated: BlockchainTransactions;
unspentsUpdated: BlockchainUTXOs;
stateUpdated: string | null;
};
/**
* A Hierarhical Determinstic (BIP44) Wallet.
*
* @example
*
* ```ts
* // Define services to use.
* const services = {
* blockchain,
* cache,
* storage,
* }
*
* // Instantiate an instance of WalletHD.
* const walletHD = await WalletHD.from({
* derivationPath: "m/44'/145'/0'",
* mnemonic: 'page pencil stock planet limb cluster assault speak off joke private pioneer'
* // or "seed" or "xpub"
* }, services);
*
* // Scan for transactions and start monitoring.
* await wallet = await walletHD.start();
* ```
*/
export class WalletHD<
WalletType extends WalletP2PKH = WalletP2PKH,
> extends BaseWallet<WalletHDEvents<WalletType>> {
// Mutable State.
public shouldMonitor = false;
// Store values that are proxied for convenience/clarity.
// NOTE: We define these for clarity so that we can see the state stored with this wallet.
public genesisData: StoreValueProxy<WalletHDGenesisData>;
// Store child wallets, grouped by chain ("change") path in BIP44 spec.
public wallets: { [chainPath: number]: Array<WalletType> } = {};
constructor(
public blockchain: BaseBlockchain,
public store: BaseStore,
public cache: BaseStore,
public hdPrivateNode: HDPrivateNode,
private walletFactory: WalletP2PKHFactory<WalletType> = useWalletP2PKH,
) {
super();
// Initialize empty arrays for our wallets.
this.wallets[CHAIN_EXTERNAL] = [];
this.wallets[CHAIN_INTERNAL] = [];
// Initialize proxies to our stored data.
this.genesisData = this.store.proxy('genesisData');
}
static async from<T extends typeof WalletHD>(
this: T,
services: WalletServices,
genesisData?: WalletHDGenesisData,
walletFactory?: WalletP2PKHFactory<any>,
) {
// Assign in memory stores as defaults in case otherwise not provided.
const servicesFinal = {
...{
store: new StoreInMemory(),
cache: new StoreInMemory(),
},
...services,
};
// If we are attempting to create a new wallet...
if (genesisData) {
// Ensure that the provided store does not already contain data.
if (Object.keys(await servicesFinal.store.all()).length) {
throw new Error(`Provided store already contains data`);
}
// Store the wallet genesis data.
await servicesFinal.store.set<WalletHDGenesisData>(
'genesis',
genesisData,
);
}
// Retrieve our genesis data and extract the private key.
const retrievedGenesisData =
await servicesFinal.store.getOrFail<WalletHDGenesisData>('genesis');
let hdPrivateNode: HDPrivateNode;
// Instantiate the HDPrivateNode from the type specified in metadata.
if ('seed' in retrievedGenesisData) {
hdPrivateNode = HDPrivateNode.fromSeed(
hexToBin(retrievedGenesisData.seed),
);
} else if ('mnemonic' in retrievedGenesisData) {
hdPrivateNode = HDPrivateNode.fromMnemonic(retrievedGenesisData.mnemonic);
} else {
hdPrivateNode = HDPrivateNode.fromXPriv(retrievedGenesisData.xpriv);
}
// Return a new instance of WalletHD.
return new this(
servicesFinal.blockchain,
servicesFinal.store,
servicesFinal.cache,
hdPrivateNode,
walletFactory,
) as InstanceType<T>;
}
async start() {
// Get the genesis data.
const genesisData = await this.genesisData.getOrFail();
// Get the address gap.
const addressGap = genesisData.addressGap || ADDRESS_GAP;
// Scan the HDWallet for child wallets.
await this.scan(0, addressGap);
// Declare storage for our start promises.
const startPromises: Promise<void>[] = [];
// Iterate over each chain path and start each wallet.
for (const chainWallets of Object.values(this.wallets)) {
for (const wallet of chainWallets) {
startPromises.push(wallet.start());
}
}
// Wait for all of our start promises to complete.
await Promise.all(startPromises);
}
async stop() {
// Declare storage for our stop promises.
const stopPromises: Promise<void>[] = [];
// Iterate over each chain path and stop each wallet.
for (const chainWallets of Object.values(this.wallets)) {
for (const wallet of chainWallets) {
stopPromises.push(wallet.stop());
}
}
// Wait for all of our stop promises to complete.
await Promise.all(stopPromises);
}
async destroy() {
this.removeAllListeners();
}
async getTransactions() {
// Declare storage for our fetch promises.
const fetchPromises = [];
// Iterate over each chain path and fetch transactions for each wallet.
for (const chainWallets of Object.values(this.wallets)) {
for (const wallet of chainWallets) {
fetchPromises.push(wallet.getTransactions());
}
}
// Wait for all of our fetch promises to complete.
const txs = await Promise.all(fetchPromises);
// Flatten (and deduplicate) the transactions.
const txsFlattened = ExtMap.flatten(txs);
// Emit an event to notify that transactions have been updated.
this.emit('transactionsUpdated', txsFlattened);
// Return the deduplicated transactions.
return txsFlattened;
}
async getUnspents() {
// Declare storage for our fetch promises.
const fetchPromises = [];
// Iterate over each chain path and fetch unspents for each wallet.
for (const chainWallets of Object.values(this.wallets)) {
for (const wallet of chainWallets) {
fetchPromises.push(wallet.getUnspents());
}
}
// Wait for all of our fetch promises to complete.
const unspents = await Promise.all(fetchPromises);
// Flatten them.
const unspentsFlattened = ExtMap.flatten(unspents);
// Return the unspents.
return unspentsFlattened;
}
async getUnspentDirectives() {
// Declare storage for our fetch promises.
const fetchPromises = [];
// Iterate over each chain path and fetch unspent directives for each wallet.
for (const chainWallets of Object.values(this.wallets)) {
for (const wallet of chainWallets) {
fetchPromises.push(wallet.getUnspentDirectives());
}
}
// Wait for all of our fetch promises to complete.
const unspentDirectives = await Promise.all(fetchPromises);
// Flatten them.
const unspentsFlattened = unspentDirectives.flat();
// Return the unspents.
return unspentsFlattened;
}
async getBalanceSats() {
// Fetch our unspents.
const unspents = await this.getUnspents();
// Get the individual UTXOs.
const utxos = unspents
.map((blockchainUTXO) => blockchainUTXO.utxo)
.toArray();
// Calculate the balance.
return calculateBalanceSats(utxos);
}
async getBalanceTokens(): Promise<TokenBalances> {
// Fetch our unspents.
const unspents = await this.getUnspents();
// Get the individual UTXOs.
const utxos = unspents
.map((blockchainUTXO) => blockchainUTXO.utxo)
.toArray();
// Calculate the token balances.
return calculateBalanceTokens(utxos);
}
async getAddresses() {
const chainPaths = [CHAIN_EXTERNAL, CHAIN_INTERNAL];
let addressPromises = [];
for (const chainPath of chainPaths) {
addressPromises.push(
...this.wallets[chainPath].map((wallet) =>
wallet.getReceivingAddress(),
),
);
}
const addresses = await Promise.all(addressPromises);
return ExtMap.fromArray(addresses, (address) => address.toLockscriptHex());
}
async getReceivingAddress(chainPath = CHAIN_EXTERNAL) {
// TODO: Derive a new wallet, not the first one you lazy fuckhead.
// You'll probably need to refactor your scan() approach.
let receivingWallet = this.wallets[chainPath][0];
// If there is no receiving wallet, create one.
// TODO: This is fucked. You need to rethink deriveWallets.
if (!receivingWallet) {
this.deriveWallets(1, chainPath);
receivingWallet = this.wallets[chainPath][0];
}
// Return the receiving address of the derived wallet.
return receivingWallet.privateKey.derivePublicKey().deriveAddress();
}
async signTransaction(
txTemplate: Partial<TransactionTemplate>,
): Promise<Uint8Array> {
// Populate the final transaction template by merging with defaults.
// NOTE: This is just a convenience to make "send" easier to use.
const txTemplateFinal: TransactionTemplate = {
...{
version: 2,
locktime: 0,
inputs: [],
outputs: [],
},
...txTemplate,
};
// Get the receiving address of this wallet.
// NOTE: As per BIP44 spec, we set the change address to use the internal chain.
const changeAddress = await this.getReceivingAddress(CHAIN_EXTERNAL);
// Get the change locking bytecode (change address) for this wallet.
const changeLockingBytecode = changeAddress.toLockscriptBytes();
// Fetch unspents that are usable by this wallet.
const unspents = await this.getUnspentDirectives();
// Create an instance of our transaction builder and populate with our Wallet's UTXOs.
// NOTE: We must deal with tokens first and satoshis last.
// The reason is that the change output will be determined based on transaction fee.
const txBuilder = new TransactionBuilder(txTemplateFinal, unspents)
.addTokensFromUnspents()
.addTokenChangeOutputs(changeLockingBytecode)
.addSatoshisFromUnspents()
.addSatoshiChangeOutput(changeLockingBytecode);
// Generate the transaction.
const generatedTxBytes = txBuilder.toBytes();
return generatedTxBytes;
}
async sendTransaction(txTemplate: Partial<TransactionTemplate>) {
// Sign the transaction template.
const generatedTxBytes = await this.signTransaction(txTemplate);
// Broadcast the transaction to the blockchain.
await this.blockchain.broadcastTransaction(generatedTxBytes);
}
async addActivity<T>(activity: T) {
// Generate an Activity ID.
// TODO: Look more into how LibAuth intends to do this.
const activityId = Date.now().toString();
// Store the data.
await this.store.set<T>(activityId, activity);
}
async export() {
const allData = await this.store.all();
const asJson = encodeExtendedJson(allData);
return asJson;
}
async deriveWallets(
count: number,
chainPath = CHAIN_EXTERNAL,
startIndex = 0,
) {
// Get the derivation path from the genesis data.
const genesisData = await this.genesisData.getOrFail();
// Create an array to store our wallets.
const newWallets: Array<WalletType> = [];
// Create the given count of wallets.
for (let i = 0; i < count; i++) {
// Define the derivation path.
const derivationPath = `${genesisData.derivationPath}/${chainPath}/${startIndex + i}`;
// Derive the private key at the given path.
const privateKeyHex = await this.cache.getOrSet(derivationPath, () => {
const childNode = this.hdPrivateNode.derivePath(derivationPath);
return childNode.privateKey().toHex();
});
// Create a child P2PKH wallet for this Private Key.
const wallet = await this.walletFactory(
{
blockchain: this.blockchain,
cache: this.cache,
},
{
type: 'WalletP2PKH',
privateKey: privateKeyHex,
},
);
// Subscribe to wallet-state updates.
wallet.on('stateUpdated', async () => {
this.emit('stateUpdated', null);
});
// Start monitoring the wallet.
wallet.start();
// Add the wallet to our list of wallets.
newWallets.push(wallet);
}
// Set our wallets.
this.wallets[chainPath] = [...this.wallets[chainPath], ...newWallets];
// Return the wallets.
return newWallets;
}
async scan(
startIndex = 0,
addressGap = 20,
chainPaths: Array<number> = [CHAIN_EXTERNAL, CHAIN_INTERNAL],
) {
// Iterate over each of the provided chain (change) paths.
for (const chainPath of chainPaths) {
// Array to store active wallet nodes
const wallets: Array<WalletType> = [];
let currentIndex = startIndex;
let emptyAddressCount = 0;
// Continue scanning until we find 'addressGap' consecutive empty addresses
while (emptyAddressCount < addressGap) {
// Derive a number of wallets equivalent to our addressGap.
const batch: Array<WalletType> = await this.deriveWallets(
addressGap,
chainPath,
currentIndex,
);
// Get the transaction history of each wallet in the batch
const results = await Promise.all(
batch.map((wallet) => wallet.getTransactions()),
);
// Process the results
for (let i = 0; i < results.length; i++) {
if (results[i].size > 0) {
// This address has transactions, add it to nodes and reset empty address count
wallets.push(batch[i]);
emptyAddressCount = 0;
} else {
// This address is empty, increment the empty address count
emptyAddressCount++;
}
currentIndex++;
// If we've found 'addressGap' consecutive empty addresses, stop scanning
if (emptyAddressCount >= addressGap) {
break;
}
}
}
}
this.emit('stateUpdated', null);
}
}
//-----------------------------------------------------------------------------
// Factories Types/Functions
//-----------------------------------------------------------------------------
export type WalletHDFactory<T extends WalletHD = WalletHD> = (
services: WalletServices,
genesisData?: WalletHDGenesisData,
walletFactory?: WalletP2PKHFactory<any>,
) => Promise<T>;
export async function useWalletHD<T extends WalletHD = WalletHD>(
services: WalletServices,
genesisData?: WalletHDGenesisData,
walletFactory?: WalletP2PKHFactory<any>,
): Promise<T> {
return (await WalletHD.from(services, genesisData, walletFactory)) as T;
}

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