initial commit

This commit is contained in:
Joshua Seigler 2022-11-16 14:26:08 -05:00
commit 9a0b1c1254
No known key found for this signature in database
28 changed files with 42055 additions and 0 deletions

4
.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
node_modules
/build
/*.log
/local-certs

22
README.md Normal file
View file

@ -0,0 +1,22 @@
# js-wallet
## CLI Commands
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# test the production build locally
npm run serve
# run tests with jest and enzyme
npm run test
```
For detailed explanation on how things work, checkout the [CLI Readme](https://github.com/developit/preact-cli/blob/master/README.md).

41614
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

44
package.json Normal file
View file

@ -0,0 +1,44 @@
{
"private": true,
"name": "js-wallet",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"build": "preact build",
"serve": "sirv build --port 8443 --cors --single --http3 --key ./local-certs/localhost-key.pem --cert ./local-certs/localhost.pem",
"dev": "preact watch",
"lint": "eslint src",
"test": "jest"
},
"eslintConfig": {
"extends": "preact",
"ignorePatterns": [
"build/"
]
},
"devDependencies": {
"enzyme": "^3.10.0",
"enzyme-adapter-preact-pure": "^2.0.0",
"eslint": "^6.0.1",
"eslint-config-preact": "^1.1.0",
"jest": "^24.9.0",
"jest-preset-preact": "^1.0.0",
"preact-cli": "^3.0.0",
"sirv-cli": "1.0.3"
},
"dependencies": {
"@noble/hashes": "^1.1.3",
"@preact/signals": "^1.1.2",
"localforage": "^1.10.0",
"preact": "^10.3.2",
"preact-render-to-string": "^5.1.4",
"preact-router": "^3.2.1"
},
"jest": {
"preset": "jest-preset-preact",
"setupFiles": [
"<rootDir>/tests/__mocks__/browserMocks.js",
"<rootDir>/tests/__mocks__/setupTests.js"
]
}
}

BIN
src/assets/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 626 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

21
src/components/app.js Normal file
View file

@ -0,0 +1,21 @@
import { h } from "preact";
import { Router } from "preact-router";
import Header from "./header";
// Code-splitting is automated for `routes` directory
import Home from "../routes/home";
// import Profile from '../routes/profile';
const App = () => (
<div id="app">
<Header />
<Router>
<Home path="/" />
{/* <Profile path="/profile/" user="me" />
<Profile path="/profile/:user" /> */}
</Router>
</div>
);
export default App;

View file

@ -0,0 +1,16 @@
import { h } from 'preact';
import { Link } from 'preact-router/match';
import style from './style.css';
const Header = () => (
<header class={style.header}>
<h1>Preact App</h1>
<nav>
<Link activeClassName={style.active} href="/">Home</Link>
<Link activeClassName={style.active} href="/profile">Me</Link>
<Link activeClassName={style.active} href="/profile/john">John</Link>
</nav>
</header>
);
export default Header;

View file

@ -0,0 +1,48 @@
.header {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 56px;
padding: 0;
background: #673AB7;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
z-index: 50;
}
.header h1 {
float: left;
margin: 0;
padding: 0 15px;
font-size: 24px;
line-height: 56px;
font-weight: 400;
color: #FFF;
}
.header nav {
float: right;
font-size: 100%;
}
.header nav a {
display: inline-block;
height: 56px;
line-height: 56px;
padding: 0 15px;
min-width: 50px;
text-align: center;
background: rgba(255,255,255,0);
text-decoration: none;
color: #FFF;
will-change: background-color;
}
.header nav a:hover,
.header nav a:active {
background: rgba(0,0,0,0.2);
}
.header nav a.active {
background: rgba(0,0,0,0.4);
}

4
src/index.js Normal file
View file

@ -0,0 +1,4 @@
import './style';
import App from './components/app';
export default App;

21
src/manifest.json Normal file
View file

@ -0,0 +1,21 @@
{
"name": "js-wallet",
"short_name": "js-wallet",
"start_url": "/",
"display": "standalone",
"orientation": "portrait",
"background_color": "#fff",
"theme_color": "#673ab8",
"icons": [
{
"src": "/assets/icons/android-chrome-192x192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "/assets/icons/android-chrome-512x512.png",
"type": "image/png",
"sizes": "512x512"
}
]
}

58
src/routes/home/index.js Normal file
View file

@ -0,0 +1,58 @@
import { h } from "preact";
import style from "./style.css";
import localforage from "localforage";
import { signal, effect } from "@preact/signals";
import { pubkeyHash } from "../../utils/base58check";
const keyPair = signal(null);
const bytesFetched = signal(false);
const publicKeyString = signal(null);
effect(() => {
if (keyPair.value && keyPair.value.publicKey) {
window.crypto.subtle
.exportKey("spki", keyPair.value.publicKey)
.then(
(value) => (publicKeyString.value = pubkeyHash(new Uint8Array(value)))
);
}
});
localforage
.getItem("firstKey")
.then((value) => {
if (value !== null) {
keyPair.value = value;
console.info("Fetched an existing key");
} else {
console.info("No existing key found");
window.crypto.subtle
.generateKey(
{
name: "ECDSA",
namedCurve: "P-256",
},
true,
["sign", "verify"]
)
.then((value) => {
keyPair.value = value;
localforage.setItem("firstKey", value).then(() => {
console.info("Saved a new key");
});
});
}
bytesFetched.value = true;
})
.catch((err) => console.error(err));
const Home = () => {
return (
<div class={style.home}>
<h1>Home</h1>
<p>This is the Home component.</p>
<p>Public key: {publicKeyString}</p>
</div>
);
};
export default Home;

View file

@ -0,0 +1,5 @@
.home {
padding: 56px 20px;
min-height: 100%;
width: 100%;
}

View file

@ -0,0 +1,31 @@
import { h } from 'preact';
import {useEffect, useState} from "preact/hooks";
import style from './style.css';
// Note: `user` comes from the URL, courtesy of our router
const Profile = ({ user }) => {
const [time, setTime] = useState(Date.now());
const [count, setCount] = useState(10);
useEffect(() => {
let timer = setInterval(() => setTime(Date.now()), 1000);
return () => clearInterval(timer);
}, []);
return (
<div class={style.profile}>
<h1>Profile: {user}</h1>
<p>This is the user profile for a user named { user }.</p>
<div>Current time: {new Date(time).toLocaleString()}</div>
<p>
<button onClick={() => setCount((count) => count + 1)}>Click Me</button>
{' '}
Clicked {count} times.
</p>
</div>
);
}
export default Profile;

View file

@ -0,0 +1,5 @@
.profile {
padding: 56px 20px;
min-height: 100%;
width: 100%;
}

20
src/style/index.css Normal file
View file

@ -0,0 +1,20 @@
html, body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
background: #FAFAFA;
font-family: 'Helvetica Neue', arial, sans-serif;
font-weight: 400;
color: #444;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
* {
box-sizing: border-box;
}
#app {
height: 100%;
}

4
src/sw.js Normal file
View file

@ -0,0 +1,4 @@
import { getFiles, setupPrecaching, setupRouting } from 'preact-cli/sw/';
setupRouting();
setupPrecaching(getFiles());

15
src/template.html Normal file
View file

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><% preact.title %></title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="apple-touch-icon" href="<%= htmlWebpackPlugin.files.publicPath %>assets/icons/apple-touch-icon.png">
<% preact.headEnd %>
</head>
<body>
<% preact.bodyEnd %>
</body>
</html>

81
src/utils/base58check.js Normal file
View file

@ -0,0 +1,81 @@
import { sha256 } from "@noble/hashes/sha256";
import { ripemd160 } from "@noble/hashes/ripemd160";
function base58encode(
B, //Uint8Array raw byte input
A = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" //Base58 characters (i.e. "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
) {
let d = [], //the array for storing the stream of base58 digits
s = "", //the result string variable that will be returned
i, //the iterator variable for the byte input
j, //the iterator variable for the base58 digit array (d)
c, //the carry amount variable that is used to overflow from the current base58 digit to the next base58 digit
n; //a temporary placeholder variable for the current base58 digit
for (i in B) {
//loop through each byte in the input stream
(j = 0), //reset the base58 digit iterator
(c = B[i]); //set the initial carry amount equal to the current byte amount
s += c || s.length ^ i ? "" : 1; //prepend the result string with a "1" (0 in base58) if the byte stream is zero and non-zero bytes haven't been seen yet (to ensure correct decode length)
while (j in d || c) {
//start looping through the digits until there are no more digits and no carry amount
n = d[j]; //set the placeholder for the current base58 digit
n = n ? n * 256 + c : c; //shift the current base58 one byte and add the carry amount (or just add the carry amount if this is a new digit)
c = (n / 58) | 0; //find the new carry amount (floored integer of current digit divided by 58)
d[j] = n % 58; //reset the current base58 digit to the remainder (the carry amount will pass on the overflow)
j++; //iterate to the next base58 digit
}
}
while (j--)
//since the base58 digits are backwards, loop through them in reverse order
s += A[d[j]]; //lookup the character associated with each base58 digit
return s; //return the final base58 string
}
function base58decode(
S, //Base58 encoded string input
A = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" //Base58 characters (i.e. "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
) {
let d = [], //the array for storing the stream of decoded bytes
b = [], //the result byte array that will be returned
i, //the iterator variable for the base58 string
j, //the iterator variable for the byte array (d)
c, //the carry amount variable that is used to overflow from the current byte to the next byte
n; //a temporary placeholder variable for the current byte
for (i in S) {
//loop through each base58 character in the input string
(j = 0), //reset the byte iterator
(c = A.indexOf(S[i])); //set the initial carry amount equal to the current base58 digit
if (c < 0)
//see if the base58 digit lookup is invalid (-1)
return undefined; //if invalid base58 digit, bail out and return undefined
c || b.length ^ i ? i : b.push(0); //prepend the result array with a zero if the base58 digit is zero and non-zero characters haven't been seen yet (to ensure correct decode length)
while (j in d || c) {
//start looping through the bytes until there are no more bytes and no carry amount
n = d[j]; //set the placeholder for the current byte
n = n ? n * 58 + c : c; //shift the current byte 58 units and add the carry amount (or just add the carry amount if this is a new byte)
c = n >> 8; //find the new carry amount (1-byte shift of current byte value)
d[j] = n % 256; //reset the current byte to the remainder (the carry amount will pass on the overflow)
j++; //iterate to the next byte
}
}
while (j--)
//since the byte array is backwards, loop through it in reverse order
b.push(d[j]); //append each byte to the result
return new Uint8Array(b); //return the final byte array in Uint8Array format
}
const VERSION_MAINNET_PUBKEY = 0;
const VERSION_TESTNET_PUBKEY = 111;
export function pubkeyHash(bytes, isTestnet = false) {
const version = isTestnet ? VERSION_TESTNET_PUBKEY : VERSION_MAINNET_PUBKEY;
const hash160 = ripemd160(sha256(bytes));
const withVersion = [version, ...hash160.values()];
const doubleSHA = sha256(sha256(new Uint8Array(withVersion)));
const checksum = [...doubleSHA.values()].slice(0, 3);
const unencodedAddress = new Uint8Array([
...withVersion,
...checksum.values(),
]);
return base58encode(unencodedAddress);
}

View file

@ -0,0 +1,21 @@
// Mock Browser API's which are not supported by JSDOM, e.g. ServiceWorker, LocalStorage
/**
* An example how to mock localStorage is given below 👇
*/
/*
// Mocks localStorage
const localStorageMock = (function() {
let store = {};
return {
getItem: (key) => store[key] || null,
setItem: (key, value) => store[key] = value.toString(),
clear: () => store = {}
};
})();
Object.defineProperty(window, 'localStorage', {
value: localStorageMock
}); */

View file

@ -0,0 +1,3 @@
// This fixed an error related to the CSS and loading gif breaking my Jest test
// See https://facebook.github.io/jest/docs/en/webpack.html#handling-static-assets
module.exports = 'test-file-stub';

View file

@ -0,0 +1,6 @@
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-preact-pure';
configure({
adapter: new Adapter()
});

12
tests/header.test.js Normal file
View file

@ -0,0 +1,12 @@
import { h } from 'preact';
import Header from '../src/components/header';
// See: https://github.com/preactjs/enzyme-adapter-preact-pure
import { shallow } from 'enzyme';
describe('Initial Test of the Header', () => {
test('Header renders 3 nav items', () => {
const context = shallow(<Header />);
expect(context.find('h1').text()).toBe('Preact App');
expect(context.find('Link').length).toBe(3);
});
});