JSFiddle - React, Tailwind, and code Playground
by Josh Pullen
JavaScript
import { html, render, useState, useEffect } from "https://unpkg.com/htm/preact/standalone.module.js";
function App() {
const [nonce, setNonce] = useState("0")
const messagePrefix = "Alice pays Bob 100 LD\nBob pays Charlie 20 LD\nCharlie pays You 50 LD\n";
const message = messagePrefix + nonce;
const [hash, setHash] = useState(null);
useEffect(() => {
let cancelled = false;
(async () => {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
const hashArray = Array.from(new Uint8Array(hashBuffer));;
const hashString = hashArray
.map(byte => byte.toString(2).padStart(8, "0"))
.join("");
if (!cancelled) {
setHash(hashString);
}
})();
return () => {
cancelled = true;
}
}, [message]);
const zeroCount = (hash || "").split("1")[0].length;
return html`
<div
style=${{
display: "flex",
flexDirection: "column",
alignItems: "center"
}}
>
<pre
style=${{
alignSelf: "stretch",
border: "1px solid #ccc",
boxShadow: "inset 0 1px 3px rgba(0, 0, 0, 0.2)",
borderRadius: 4,
resize: "none",
padding: "8px 12px",
fontFamily: "sans-serif",
fontSize: 18,
margin: 0
}}
>
${messagePrefix}
<input
type="number"
step="1"
min="0"
value=${nonce}
onInput=${(event) => {
setNonce(event.target.value);
}}
style=${{
font: "inherit",
border: "1px solid #ccc",
borderRadius: 3,
padding: "2px 4px"
}}
/>
</pre>
<${SHAArrow} />
<div
style=${{
fontFamily: "monospace",
fontSize: 18,
maxWidth: "32ch",
wordBreak: "break-word",
margin:...