@bsv/create-dpp-app 0.0.0-stage → 0.1.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +203 -0
- package/NOTICE +2 -0
- package/PATENTS +12 -0
- package/README.md +93 -2
- package/dist/index.js +125 -0
- package/package.json +57 -4
- package/template/Dockerfile +37 -0
- package/template/README.md +389 -0
- package/template/_dockerignore +6 -0
- package/template/_env.example +122 -0
- package/template/_github/workflows/ci.yml +23 -0
- package/template/_gitignore +8 -0
- package/template/_prettierrc +6 -0
- package/template/apps/api/API.md +119 -0
- package/template/apps/api/package.json +39 -0
- package/template/apps/api/src/auth.ts +55 -0
- package/template/apps/api/src/bound-profiles.ts +590 -0
- package/template/apps/api/src/claims.ts +204 -0
- package/template/apps/api/src/cli.ts +99 -0
- package/template/apps/api/src/config.ts +180 -0
- package/template/apps/api/src/custody.ts +358 -0
- package/template/apps/api/src/dev-index.ts +120 -0
- package/template/apps/api/src/env-file.ts +55 -0
- package/template/apps/api/src/env.ts +14 -0
- package/template/apps/api/src/epcis/exchange.ts +434 -0
- package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
- package/template/apps/api/src/epcis/routes.ts +364 -0
- package/template/apps/api/src/epcis/sources.ts +142 -0
- package/template/apps/api/src/go-live.ts +226 -0
- package/template/apps/api/src/http-error.ts +15 -0
- package/template/apps/api/src/identifiers.ts +57 -0
- package/template/apps/api/src/index-client.ts +261 -0
- package/template/apps/api/src/index-projects.ts +53 -0
- package/template/apps/api/src/lifecycle-authority.ts +49 -0
- package/template/apps/api/src/lifecycle.ts +485 -0
- package/template/apps/api/src/main.ts +58 -0
- package/template/apps/api/src/parties.ts +68 -0
- package/template/apps/api/src/platform.ts +176 -0
- package/template/apps/api/src/portability/commands.ts +224 -0
- package/template/apps/api/src/portability/export.ts +708 -0
- package/template/apps/api/src/portability/package.ts +270 -0
- package/template/apps/api/src/portability/restore.ts +863 -0
- package/template/apps/api/src/profiles.ts +125 -0
- package/template/apps/api/src/reader.ts +265 -0
- package/template/apps/api/src/resolver.ts +159 -0
- package/template/apps/api/src/sector-examples.ts +390 -0
- package/template/apps/api/src/server.ts +613 -0
- package/template/apps/api/src/store.ts +426 -0
- package/template/apps/api/src/validation-engine.ts +172 -0
- package/template/apps/api/src/wallet.ts +359 -0
- package/template/apps/api/src/worker.ts +113 -0
- package/template/apps/api/src/writer.ts +603 -0
- package/template/apps/api/test/bound-http.test.ts +496 -0
- package/template/apps/api/test/bound-profiles.test.ts +547 -0
- package/template/apps/api/test/config.test.ts +160 -0
- package/template/apps/api/test/custody-journal.test.ts +415 -0
- package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
- package/template/apps/api/test/custom-profile.test.ts +167 -0
- package/template/apps/api/test/env-file.test.ts +53 -0
- package/template/apps/api/test/epcis-fixtures.ts +270 -0
- package/template/apps/api/test/epcis-http.test.ts +1179 -0
- package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
- package/template/apps/api/test/epcis-separation.test.ts +253 -0
- package/template/apps/api/test/epcis-web.test.ts +230 -0
- package/template/apps/api/test/exit-exercise.test.ts +1038 -0
- package/template/apps/api/test/external-index.test.ts +32 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
- package/template/apps/api/test/go-live.test.ts +179 -0
- package/template/apps/api/test/gs1-global-setup.ts +33 -0
- package/template/apps/api/test/gs1-test-env.ts +5 -0
- package/template/apps/api/test/identifier-host.test.ts +256 -0
- package/template/apps/api/test/index-projects.test.ts +81 -0
- package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
- package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
- package/template/apps/api/test/lifecycle.test.ts +147 -0
- package/template/apps/api/test/manifest-notice.test.ts +36 -0
- package/template/apps/api/test/network-guard.ts +113 -0
- package/template/apps/api/test/portability.test.ts +655 -0
- package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
- package/template/apps/api/test/retired-profiles.test.ts +216 -0
- package/template/apps/api/test/sector-cutover.test.ts +95 -0
- package/template/apps/api/test/sector-forms.test.ts +420 -0
- package/template/apps/api/test/unjoined-index.test.ts +62 -0
- package/template/apps/api/test/validation-engine.test.ts +328 -0
- package/template/apps/api/test/wallet-monitor.test.ts +38 -0
- package/template/apps/api/test/writer-journal.test.ts +327 -0
- package/template/apps/api/tsconfig.json +9 -0
- package/template/apps/api/vitest.config.ts +12 -0
- package/template/apps/web/components.json +21 -0
- package/template/apps/web/index.html +12 -0
- package/template/apps/web/package.json +33 -0
- package/template/apps/web/src/app.tsx +55 -0
- package/template/apps/web/src/components/bits.tsx +188 -0
- package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
- package/template/apps/web/src/components/bound/field-view.tsx +237 -0
- package/template/apps/web/src/components/bound/pieces.tsx +169 -0
- package/template/apps/web/src/components/bound/readings.tsx +152 -0
- package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
- package/template/apps/web/src/components/claim-dialog.tsx +344 -0
- package/template/apps/web/src/components/epcis-events.tsx +119 -0
- package/template/apps/web/src/components/layout.tsx +135 -0
- package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
- package/template/apps/web/src/components/passport-form.tsx +244 -0
- package/template/apps/web/src/components/read-passport.tsx +49 -0
- package/template/apps/web/src/components/reading.tsx +150 -0
- package/template/apps/web/src/components/ui/alert.tsx +65 -0
- package/template/apps/web/src/components/ui/badge.tsx +47 -0
- package/template/apps/web/src/components/ui/button.tsx +63 -0
- package/template/apps/web/src/components/ui/card.tsx +91 -0
- package/template/apps/web/src/components/ui/dialog.tsx +156 -0
- package/template/apps/web/src/components/ui/input.tsx +20 -0
- package/template/apps/web/src/components/ui/label.tsx +21 -0
- package/template/apps/web/src/components/ui/select.tsx +189 -0
- package/template/apps/web/src/components/ui/separator.tsx +25 -0
- package/template/apps/web/src/components/ui/table.tsx +115 -0
- package/template/apps/web/src/components/ui/tabs.tsx +90 -0
- package/template/apps/web/src/components/ui/textarea.tsx +17 -0
- package/template/apps/web/src/index.css +81 -0
- package/template/apps/web/src/lib/api.ts +396 -0
- package/template/apps/web/src/lib/auth.ts +10 -0
- package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
- package/template/apps/web/src/lib/bound/display.ts +122 -0
- package/template/apps/web/src/lib/bound/fields.ts +128 -0
- package/template/apps/web/src/lib/bound/form-model.ts +521 -0
- package/template/apps/web/src/lib/bound/forms.ts +15 -0
- package/template/apps/web/src/lib/bound/identity.ts +48 -0
- package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
- package/template/apps/web/src/lib/bound/units.ts +37 -0
- package/template/apps/web/src/lib/epcis.ts +345 -0
- package/template/apps/web/src/lib/format.ts +87 -0
- package/template/apps/web/src/lib/lifecycle.ts +350 -0
- package/template/apps/web/src/lib/session.tsx +92 -0
- package/template/apps/web/src/lib/use-load.ts +46 -0
- package/template/apps/web/src/main.tsx +18 -0
- package/template/apps/web/src/pages/accept.tsx +113 -0
- package/template/apps/web/src/pages/brand.tsx +94 -0
- package/template/apps/web/src/pages/brands.tsx +104 -0
- package/template/apps/web/src/pages/events.tsx +388 -0
- package/template/apps/web/src/pages/home.tsx +51 -0
- package/template/apps/web/src/pages/new-passport.tsx +137 -0
- package/template/apps/web/src/pages/operations.tsx +169 -0
- package/template/apps/web/src/pages/passport.tsx +632 -0
- package/template/apps/web/src/pages/public-passport.tsx +64 -0
- package/template/apps/web/src/pages/sign-in.tsx +93 -0
- package/template/apps/web/src/pages/verify.tsx +30 -0
- package/template/apps/web/src/pages/wallet.tsx +141 -0
- package/template/apps/web/tsconfig.json +29 -0
- package/template/apps/web/vite.config.ts +23 -0
- package/template/deploy/compose.yml +38 -0
- package/template/package.json +48 -0
- package/template/tsconfig.base.json +13 -0
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
// The platform wallet: a BRC-100 wallet the API owns, which countersigns
|
|
2
|
+
// every state as publisher, funds and submits the transactions, and
|
|
3
|
+
// obtains their merkle proofs. Live it is
|
|
4
|
+
// @bsv/wallet-toolbox on a SQLite file with a root key from the environment;
|
|
5
|
+
// in tests it is a ProtoWallet with a fixed key and made-up funding, which
|
|
6
|
+
// is what makes the first run need no money.
|
|
7
|
+
//
|
|
8
|
+
// Funding needs nothing from the person paying: the wallet derives a BRC-29
|
|
9
|
+
// receive key for a random prefix and suffix with the "anyone" sender, hands
|
|
10
|
+
// out its address, and takes the payment in with internalizeAction.
|
|
11
|
+
import { mkdirSync } from 'node:fs'
|
|
12
|
+
import { createRequire } from 'node:module'
|
|
13
|
+
import { dirname } from 'node:path'
|
|
14
|
+
import {
|
|
15
|
+
Beef,
|
|
16
|
+
LockingScript,
|
|
17
|
+
MerklePath,
|
|
18
|
+
P2PKH,
|
|
19
|
+
PrivateKey,
|
|
20
|
+
ProtoWallet,
|
|
21
|
+
PublicKey,
|
|
22
|
+
PushDrop,
|
|
23
|
+
Random,
|
|
24
|
+
Transaction,
|
|
25
|
+
UnlockingScript,
|
|
26
|
+
Utils,
|
|
27
|
+
type WalletInterface,
|
|
28
|
+
type WalletProtocol,
|
|
29
|
+
} from '@bsv/sdk'
|
|
30
|
+
import { OWNER_PROTOCOL_ID, type DataSigner } from '@bsv/dpp-protocol'
|
|
31
|
+
import type { Network } from './config.js'
|
|
32
|
+
|
|
33
|
+
export interface Tip {
|
|
34
|
+
tx: Transaction
|
|
35
|
+
txid: string
|
|
36
|
+
outputIndex: number
|
|
37
|
+
beef: number[]
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface Built {
|
|
41
|
+
tx: Transaction
|
|
42
|
+
txid: string
|
|
43
|
+
beef: number[]
|
|
44
|
+
/** The wallet's reference for an unsent action, needed to abort it; an issue that needed no signature has none. */
|
|
45
|
+
reference?: string
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The wallet side of a write: build a state's transaction unsent, send it
|
|
50
|
+
* and report only the network's answer, abort an unsent one, and read a
|
|
51
|
+
* mined transaction's merkle path. Its shape is the same live and in tests,
|
|
52
|
+
* so everything after the build is one code path.
|
|
53
|
+
*/
|
|
54
|
+
export class ActionAlreadySeen extends Error {}
|
|
55
|
+
|
|
56
|
+
export interface WriterAdapter {
|
|
57
|
+
build(args: { lockingScript: LockingScript; tip?: Tip & { signer: PublisherWallet }; passportId: string }): Promise<Built>
|
|
58
|
+
send(built: Built): Promise<'accepted' | 'refused' | 'unanswered'>
|
|
59
|
+
discard(built: Built): Promise<void>
|
|
60
|
+
merklePathFor(txid: string): Promise<MerklePath | undefined>
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The slice of the platform wallet the packages call: publisher signature and public key derivation. */
|
|
64
|
+
export type PublisherWallet = DataSigner & {
|
|
65
|
+
getPublicKey: ProtoWallet['getPublicKey']
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface FundingAddress {
|
|
69
|
+
address: string
|
|
70
|
+
derivationPrefix: string
|
|
71
|
+
derivationSuffix: string
|
|
72
|
+
senderIdentityKey: string
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface PlatformWallet {
|
|
76
|
+
kind: 'toolbox' | 'test'
|
|
77
|
+
network: Network
|
|
78
|
+
identityKey: string
|
|
79
|
+
publisher: PublisherWallet
|
|
80
|
+
/** Signs acceptance records with createSignature under the managed record protocol: the same wallet that publishes, one derivation from its root. */
|
|
81
|
+
custodian: DataSigner
|
|
82
|
+
adapter: WriterAdapter
|
|
83
|
+
fundingAddress(): Promise<FundingAddress>
|
|
84
|
+
/** Take in a payment made to a funding address, by its transaction id, once it is on the network. */
|
|
85
|
+
internalize(funding: FundingAddress, txid: string): Promise<{ satoshis: number }>
|
|
86
|
+
balance(): Promise<number>
|
|
87
|
+
close(): Promise<void>
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const BRC29_PROTOCOL: WalletProtocol = [2, '3241645161d8']
|
|
91
|
+
/** The "anyone" key: the sender of a payment that needs no key from the payer. */
|
|
92
|
+
export const ANYONE_IDENTITY_KEY = new PrivateKey(1).toPublicKey().toString()
|
|
93
|
+
|
|
94
|
+
function pathContains(path: MerklePath, txid: string): boolean {
|
|
95
|
+
try {
|
|
96
|
+
path.computeRoot(txid)
|
|
97
|
+
return true
|
|
98
|
+
} catch {
|
|
99
|
+
return false
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ------------------------------------------------------------- the toolbox wallet
|
|
104
|
+
|
|
105
|
+
export interface ToolboxWalletOptions {
|
|
106
|
+
network: Network
|
|
107
|
+
rootKeyHex: string
|
|
108
|
+
filePath: string
|
|
109
|
+
wocApiKey?: string
|
|
110
|
+
arcUrl?: string
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function openToolboxWallet(options: ToolboxWalletOptions): Promise<PlatformWallet> {
|
|
114
|
+
// CommonJS, loaded once here: the toolbox carries its own copy of the SDK,
|
|
115
|
+
// so its objects cross into this module as bytes and hex, never as instances.
|
|
116
|
+
const toolbox = await import('@bsv/wallet-toolbox')
|
|
117
|
+
const { Monitor, Services, Setup, StorageKnex, Task, Wallet, WalletStorageManager } = toolbox
|
|
118
|
+
// The toolbox loads the SDK's CommonJS build; its key deriver must come from that same copy.
|
|
119
|
+
const sdkCjs = createRequire(import.meta.url)('@bsv/sdk') as typeof import('@bsv/sdk')
|
|
120
|
+
const chain = options.network
|
|
121
|
+
const rootKey = PrivateKey.fromHex(options.rootKeyHex)
|
|
122
|
+
const identityKey = rootKey.toPublicKey().toString()
|
|
123
|
+
|
|
124
|
+
mkdirSync(dirname(options.filePath), { recursive: true })
|
|
125
|
+
const knex = Setup.createSQLiteKnex(options.filePath)
|
|
126
|
+
const storage = new StorageKnex({
|
|
127
|
+
chain,
|
|
128
|
+
knex,
|
|
129
|
+
commissionSatoshis: 0,
|
|
130
|
+
commissionPubKeyHex: undefined,
|
|
131
|
+
feeModel: { model: 'sat/kb', value: 100 },
|
|
132
|
+
})
|
|
133
|
+
await storage.migrate('platform_wallet', Utils.toHex(Random(33)))
|
|
134
|
+
await storage.makeAvailable()
|
|
135
|
+
const manager = new WalletStorageManager(identityKey, storage)
|
|
136
|
+
await manager.makeAvailable()
|
|
137
|
+
|
|
138
|
+
const serviceOptions = Services.createDefaultOptions(chain)
|
|
139
|
+
if (options.wocApiKey != null) serviceOptions.whatsOnChainApiKey = options.wocApiKey
|
|
140
|
+
if (options.arcUrl != null) serviceOptions.arcUrl = options.arcUrl
|
|
141
|
+
const services = new Services(serviceOptions)
|
|
142
|
+
const monitor = new Monitor(Monitor.createDefaultWalletMonitorOptions(chain, manager, services))
|
|
143
|
+
// Wallet sends stay under the writer's publishing gate. The monitor only follows headers and proofs.
|
|
144
|
+
monitor.addTask(new Task.TaskNewHeader(monitor))
|
|
145
|
+
monitor.addTask(new Task.TaskCheckForProofs(monitor))
|
|
146
|
+
const keyDeriver = new sdkCjs.CachedKeyDeriver(sdkCjs.PrivateKey.fromHex(options.rootKeyHex))
|
|
147
|
+
const wallet = new Wallet({ chain, keyDeriver: keyDeriver as unknown as ConstructorParameters<typeof Wallet>[0]['keyDeriver'], storage: manager, services, monitor })
|
|
148
|
+
const { user } = await storage.findOrInsertUser(identityKey)
|
|
149
|
+
// The monitor asks a header source for proofs once a block is a minute old and attaches them to the wallet's transactions.
|
|
150
|
+
const monitoring = monitor.startTasks()
|
|
151
|
+
|
|
152
|
+
const brc100 = wallet as unknown as WalletInterface
|
|
153
|
+
|
|
154
|
+
const adapter: WriterAdapter = {
|
|
155
|
+
async build({ lockingScript, tip, passportId }) {
|
|
156
|
+
const output = {
|
|
157
|
+
lockingScript: lockingScript.toHex(),
|
|
158
|
+
satoshis: 1,
|
|
159
|
+
outputDescription: 'dpp passport state',
|
|
160
|
+
basket: 'dpp',
|
|
161
|
+
customInstructions: JSON.stringify({ passportId }),
|
|
162
|
+
}
|
|
163
|
+
const actionOptions = { noSend: true, randomizeOutputs: false, acceptDelayedBroadcast: false }
|
|
164
|
+
if (tip == null) {
|
|
165
|
+
// The genesis needs no signature from this application: the wallet returns it signed, with no reference.
|
|
166
|
+
const created = await brc100.createAction({ description: 'dpp issue', outputs: [output], options: actionOptions })
|
|
167
|
+
if (created.tx == null || created.txid == null) {
|
|
168
|
+
if (created.signableTransaction?.reference != null) await brc100.abortAction({ reference: created.signableTransaction.reference }).catch(() => undefined)
|
|
169
|
+
throw new Error('the wallet did not return a signed transaction')
|
|
170
|
+
}
|
|
171
|
+
return { tx: Transaction.fromAtomicBEEF(created.tx), txid: created.txid, beef: Array.from(created.tx) }
|
|
172
|
+
}
|
|
173
|
+
// The funding wallet builds the action and adds the controller's signature to the passport input.
|
|
174
|
+
const created = await brc100.createAction({
|
|
175
|
+
description: 'dpp state',
|
|
176
|
+
inputBEEF: tip.beef,
|
|
177
|
+
inputs: [{ outpoint: `${tip.txid}.${tip.outputIndex}`, unlockingScriptLength: 73, inputDescription: 'dpp passport tip' }],
|
|
178
|
+
outputs: [output],
|
|
179
|
+
options: actionOptions,
|
|
180
|
+
})
|
|
181
|
+
const signable = created.signableTransaction
|
|
182
|
+
if (signable == null) throw new Error('the wallet did not return a transaction to sign')
|
|
183
|
+
try {
|
|
184
|
+
const unsigned = Transaction.fromAtomicBEEF(signable.tx)
|
|
185
|
+
const at = unsigned.inputs.findIndex((input) => (input.sourceTXID ?? input.sourceTransaction?.id('hex')) === tip.txid && input.sourceOutputIndex === tip.outputIndex)
|
|
186
|
+
if (at === -1) throw new Error('the wallet built a transaction that does not spend the tip')
|
|
187
|
+
const unlockingScript = await new PushDrop(tip.signer as WalletInterface).unlock(OWNER_PROTOCOL_ID, passportId, 'self').sign(unsigned, at)
|
|
188
|
+
const signed = await brc100.signAction({ reference: signable.reference, spends: { [at]: { unlockingScript: unlockingScript.toHex() } }, options: { noSend: true } })
|
|
189
|
+
if (signed.tx == null || signed.txid == null) throw new Error('the wallet did not return a signed transaction')
|
|
190
|
+
return { tx: Transaction.fromAtomicBEEF(signed.tx), txid: signed.txid, beef: Array.from(signed.tx), reference: signable.reference }
|
|
191
|
+
} catch (cause) {
|
|
192
|
+
// The action already holds the wallet's inputs: give them back before stopping.
|
|
193
|
+
await brc100.abortAction({ reference: signable.reference }).catch(() => undefined)
|
|
194
|
+
throw cause
|
|
195
|
+
}
|
|
196
|
+
},
|
|
197
|
+
async send(built) {
|
|
198
|
+
// Sections 4 and 5: a send-only action, reporting nothing but the network's answer.
|
|
199
|
+
let result
|
|
200
|
+
try {
|
|
201
|
+
result = await brc100.createAction({ description: 'dpp send', options: { sendWith: [built.txid], acceptDelayedBroadcast: false } })
|
|
202
|
+
} catch (cause) {
|
|
203
|
+
const reviews = ((cause as { reviewActionResults?: Array<{ txid: string; status: string }> })?.reviewActionResults ?? [])
|
|
204
|
+
return reviews.some((r) => r.txid === built.txid && r.status === 'invalidTx') ? 'refused' : 'unanswered'
|
|
205
|
+
}
|
|
206
|
+
const status = result.sendWithResults?.find((r) => r.txid === built.txid)?.status
|
|
207
|
+
if (status === 'unproven') return 'accepted'
|
|
208
|
+
if (status === 'failed') return 'refused'
|
|
209
|
+
return 'unanswered'
|
|
210
|
+
},
|
|
211
|
+
async discard(built) {
|
|
212
|
+
// An unsent action holds the wallet's inputs until it is sent or aborted; an issue without a reference is found by its txid.
|
|
213
|
+
// A retry after a local abort or network rejection finds a terminal wallet row.
|
|
214
|
+
const [held] = await storage.findTransactions({ partial: { userId: user.userId, txid: built.txid }, noRawTx: true })
|
|
215
|
+
if (held?.status === 'failed' || held?.noSendExpiryState === 'cancelled') return
|
|
216
|
+
const result = await brc100.abortAction({ reference: built.reference ?? built.txid })
|
|
217
|
+
if (!result.aborted) throw new ActionAlreadySeen(`the wallet already sees ${built.txid} on the network`)
|
|
218
|
+
},
|
|
219
|
+
async merklePathFor(txid) {
|
|
220
|
+
// The wallet attaches the proof as part of being a wallet, but can list a transaction only while its output is unspent.
|
|
221
|
+
const outputs = await brc100.listOutputs({ basket: 'dpp', include: 'entire transactions', limit: 10000 })
|
|
222
|
+
if (outputs.BEEF != null) {
|
|
223
|
+
const beef = Beef.fromBinary(outputs.BEEF)
|
|
224
|
+
const held = beef.findTxid(txid)
|
|
225
|
+
const path = held?.bumpIndex == null ? held?.tx?.merklePath : beef.bumps[held.bumpIndex]
|
|
226
|
+
if (path != null && pathContains(path, txid)) return path
|
|
227
|
+
}
|
|
228
|
+
// Once spent, ask the services directly.
|
|
229
|
+
try {
|
|
230
|
+
const found = await services.getMerklePath(txid)
|
|
231
|
+
if (found.merklePath != null) {
|
|
232
|
+
const path = MerklePath.fromHex(found.merklePath.toHex())
|
|
233
|
+
if (pathContains(path, txid)) return path
|
|
234
|
+
}
|
|
235
|
+
} catch {
|
|
236
|
+
// No proof yet, or no header source: the worker asks again later.
|
|
237
|
+
}
|
|
238
|
+
return undefined
|
|
239
|
+
},
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
return {
|
|
243
|
+
kind: 'toolbox',
|
|
244
|
+
network: chain,
|
|
245
|
+
identityKey,
|
|
246
|
+
publisher: brc100 as unknown as PublisherWallet,
|
|
247
|
+
custodian: brc100 as unknown as DataSigner,
|
|
248
|
+
adapter,
|
|
249
|
+
async fundingAddress() {
|
|
250
|
+
const derivationPrefix = Utils.toBase64(Random(8))
|
|
251
|
+
const derivationSuffix = Utils.toBase64(Random(8))
|
|
252
|
+
const { publicKey } = await brc100.getPublicKey({ protocolID: BRC29_PROTOCOL, keyID: `${derivationPrefix} ${derivationSuffix}`, counterparty: ANYONE_IDENTITY_KEY, forSelf: true })
|
|
253
|
+
return { address: PublicKey.fromString(publicKey).toAddress(chain === 'test' ? 'testnet' : 'mainnet'), derivationPrefix, derivationSuffix, senderIdentityKey: ANYONE_IDENTITY_KEY }
|
|
254
|
+
},
|
|
255
|
+
async internalize(funding, txid) {
|
|
256
|
+
const beef = await services.getBeefForTxid(txid)
|
|
257
|
+
const tx = Transaction.fromHex(Utils.toHex(beef.findTxid(txid)?.tx?.toBinary() ?? []))
|
|
258
|
+
const wanted = new P2PKH().lock(funding.address).toHex()
|
|
259
|
+
const outputs = tx.outputs.map((o, outputIndex) => ({ o, outputIndex })).filter(({ o }) => o.lockingScript.toHex() === wanted)
|
|
260
|
+
if (outputs.length === 0) throw new Error(`${txid} pays nothing to ${funding.address}`)
|
|
261
|
+
await brc100.internalizeAction({
|
|
262
|
+
tx: beef.toBinaryAtomic(txid),
|
|
263
|
+
outputs: outputs.map(({ outputIndex }) => ({
|
|
264
|
+
outputIndex,
|
|
265
|
+
protocol: 'wallet payment',
|
|
266
|
+
paymentRemittance: { derivationPrefix: funding.derivationPrefix, derivationSuffix: funding.derivationSuffix, senderIdentityKey: funding.senderIdentityKey },
|
|
267
|
+
})),
|
|
268
|
+
description: 'Funding the platform wallet',
|
|
269
|
+
})
|
|
270
|
+
return { satoshis: outputs.reduce((sum, { o }) => sum + (o.satoshis ?? 0), 0) }
|
|
271
|
+
},
|
|
272
|
+
async balance() {
|
|
273
|
+
const { outputs } = await brc100.listOutputs({ basket: 'default', limit: 10000 })
|
|
274
|
+
return outputs.filter((o) => o.spendable).reduce((sum, o) => sum + o.satoshis, 0)
|
|
275
|
+
},
|
|
276
|
+
async close() {
|
|
277
|
+
monitor.stopTasks()
|
|
278
|
+
try {
|
|
279
|
+
await monitoring
|
|
280
|
+
} finally {
|
|
281
|
+
await wallet.destroy()
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// ---------------------------------------------------------------- the test wallet
|
|
288
|
+
|
|
289
|
+
const ANYONE_CAN_SPEND = new LockingScript([{ op: 0x51 }])
|
|
290
|
+
|
|
291
|
+
/** A funding output with a made-up proof, standing in for coins a wallet would hold. Anyone can spend it, which is why it is never used live. */
|
|
292
|
+
function syntheticFunding(): Transaction {
|
|
293
|
+
const tx = new Transaction()
|
|
294
|
+
tx.addOutput({ satoshis: 10_000, lockingScript: ANYONE_CAN_SPEND })
|
|
295
|
+
tx.merklePath = MerklePath.fromCoinbaseTxidAndHeight(tx.id('hex'), 800_000)
|
|
296
|
+
return tx
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* A wallet for tests and dry runs: fixed keys, synthetic funding, transactions
|
|
301
|
+
* built here the way a wallet would fund them, and made-up proofs that only
|
|
302
|
+
* an index with its header checks off would take. Nothing is sent anywhere.
|
|
303
|
+
*/
|
|
304
|
+
export function openTestWallet(rootKeyHex = '11'.repeat(32), network: Network = 'main'): PlatformWallet {
|
|
305
|
+
const rootKey = PrivateKey.fromHex(rootKeyHex)
|
|
306
|
+
const wallet = new ProtoWallet(rootKey)
|
|
307
|
+
const identityKey = rootKey.toPublicKey().toString()
|
|
308
|
+
let proofHeight = 800_001
|
|
309
|
+
const proofs = new Map<string, MerklePath>()
|
|
310
|
+
let funded = 10_000
|
|
311
|
+
|
|
312
|
+
const adapter: WriterAdapter = {
|
|
313
|
+
async build({ lockingScript, tip, passportId }) {
|
|
314
|
+
const tx = new Transaction()
|
|
315
|
+
if (tip == null) {
|
|
316
|
+
tx.addInput({ sourceTransaction: syntheticFunding(), sourceOutputIndex: 0, unlockingScript: new UnlockingScript([]) })
|
|
317
|
+
tx.addOutput({ satoshis: 1, lockingScript })
|
|
318
|
+
tx.addOutput({ satoshis: 9_000, lockingScript: ANYONE_CAN_SPEND })
|
|
319
|
+
} else {
|
|
320
|
+
// The tip, then its change, the way a wallet funds the next state; the passport output stays first.
|
|
321
|
+
tx.addInput({ sourceTransaction: tip.tx, sourceOutputIndex: tip.outputIndex, unlockingScript: new UnlockingScript([]) })
|
|
322
|
+
tx.addInput({ sourceTransaction: tip.tx, sourceOutputIndex: 1, unlockingScript: new UnlockingScript([]) })
|
|
323
|
+
tx.addOutput({ satoshis: 1, lockingScript })
|
|
324
|
+
tx.addOutput({ satoshis: Math.max(1_000, (tip.tx.outputs[1]?.satoshis ?? 9_000) - 1_000), lockingScript: ANYONE_CAN_SPEND })
|
|
325
|
+
tx.inputs[0].unlockingScript = await new PushDrop(tip.signer as WalletInterface).unlock(OWNER_PROTOCOL_ID, passportId, 'self').sign(tx, 0)
|
|
326
|
+
}
|
|
327
|
+
return { tx, txid: tx.id('hex'), beef: tx.toAtomicBEEF(), reference: tip == null ? undefined : 'test-reference' }
|
|
328
|
+
},
|
|
329
|
+
async send(built) {
|
|
330
|
+
funded -= 200
|
|
331
|
+
proofs.set(built.txid, MerklePath.fromCoinbaseTxidAndHeight(built.txid, proofHeight++))
|
|
332
|
+
return 'accepted'
|
|
333
|
+
},
|
|
334
|
+
async discard() {},
|
|
335
|
+
async merklePathFor(txid) {
|
|
336
|
+
return proofs.get(txid)
|
|
337
|
+
},
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
return {
|
|
341
|
+
kind: 'test',
|
|
342
|
+
network,
|
|
343
|
+
identityKey,
|
|
344
|
+
publisher: wallet,
|
|
345
|
+
custodian: wallet,
|
|
346
|
+
adapter,
|
|
347
|
+
async fundingAddress() {
|
|
348
|
+
return { address: rootKey.toPublicKey().toAddress(network === 'test' ? 'testnet' : 'mainnet'), derivationPrefix: 'test', derivationSuffix: 'test', senderIdentityKey: ANYONE_IDENTITY_KEY }
|
|
349
|
+
},
|
|
350
|
+
async internalize() {
|
|
351
|
+
funded += 10_000
|
|
352
|
+
return { satoshis: 10_000 }
|
|
353
|
+
},
|
|
354
|
+
async balance() {
|
|
355
|
+
return funded
|
|
356
|
+
},
|
|
357
|
+
async close() {},
|
|
358
|
+
}
|
|
359
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// The duties that run on their own, after the screen that caused them:
|
|
2
|
+
// announcing again when the index could not be reached, fetching each
|
|
3
|
+
// state's merkle proof once it is mined, and pushing that proof to the
|
|
4
|
+
// index. They are read from the journal, never from a separate queue, so
|
|
5
|
+
// the journal stays the one source of truth and a retry never rebuilds.
|
|
6
|
+
// Run one worker per platform; it is a loop over pending work, not a job
|
|
7
|
+
// library.
|
|
8
|
+
import { Utils } from '@bsv/sdk'
|
|
9
|
+
import type { IndexClient } from './index-client.js'
|
|
10
|
+
import { isInterrupted, type PassportRecord, type Store } from './store.js'
|
|
11
|
+
import type { Writer } from './writer.js'
|
|
12
|
+
|
|
13
|
+
export interface Duty {
|
|
14
|
+
passportId: string
|
|
15
|
+
txid: string
|
|
16
|
+
op: string
|
|
17
|
+
duty: 'announce' | 'prove' | 'push-proof' | 'resolve-interrupted'
|
|
18
|
+
since: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface WorkerOptions {
|
|
22
|
+
store: Store
|
|
23
|
+
index: IndexClient
|
|
24
|
+
writer: Writer
|
|
25
|
+
log?: (line: string) => void
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Each passport's journal records its spends in lineage order, even across clock changes. */
|
|
29
|
+
async function journalDuties(store: Store): Promise<Duty[]> {
|
|
30
|
+
const duties: Duty[] = []
|
|
31
|
+
for (const passport of await store.listPassports()) {
|
|
32
|
+
for (const state of passport.states) {
|
|
33
|
+
if (isInterrupted(state)) {
|
|
34
|
+
duties.push({ passportId: passport.passportId, txid: state.txid, op: state.op, duty: 'resolve-interrupted', since: state.timestamp })
|
|
35
|
+
continue
|
|
36
|
+
}
|
|
37
|
+
if (state.network !== 'accepted' && state.network !== 'dry-run') continue
|
|
38
|
+
if (state.index !== 'admitted' && state.index !== 'duplicate') duties.push({ passportId: passport.passportId, txid: state.txid, op: state.op, duty: 'announce', since: state.timestamp })
|
|
39
|
+
if (state.proof == null) duties.push({ passportId: passport.passportId, txid: state.txid, op: state.op, duty: 'prove', since: state.timestamp })
|
|
40
|
+
else if (state.proofPushed !== true) duties.push({ passportId: passport.passportId, txid: state.txid, op: state.op, duty: 'push-proof', since: state.timestamp })
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return duties
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The operator's view of the work still owed, oldest timestamp first. */
|
|
47
|
+
export async function pendingDuties(store: Store): Promise<Duty[]> {
|
|
48
|
+
return (await journalDuties(store)).sort((a, b) => a.since.localeCompare(b.since))
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** One pass over the pending duties. Returns what it did, one line each. */
|
|
52
|
+
export async function runDuties(options: WorkerOptions): Promise<string[]> {
|
|
53
|
+
const { store, index, writer } = options
|
|
54
|
+
const log = options.log ?? (() => {})
|
|
55
|
+
const done: string[] = []
|
|
56
|
+
const say = (line: string): void => {
|
|
57
|
+
done.push(line)
|
|
58
|
+
log(line)
|
|
59
|
+
}
|
|
60
|
+
const waitingForPredecessor = new Set<string>()
|
|
61
|
+
for (const duty of await journalDuties(store)) {
|
|
62
|
+
const passport = await store.getPassport(duty.passportId)
|
|
63
|
+
const state = passport?.states.find((s) => s.txid === duty.txid)
|
|
64
|
+
if (passport == null || state == null) continue
|
|
65
|
+
// Only the operator can say what became of an interrupted write; it is listed, never guessed.
|
|
66
|
+
if (duty.duty === 'resolve-interrupted' || isInterrupted(state)) continue
|
|
67
|
+
try {
|
|
68
|
+
if (duty.duty === 'announce') {
|
|
69
|
+
if (waitingForPredecessor.has(passport.passportId)) continue
|
|
70
|
+
const announced = await index.announce(Utils.toArray(state.sentBeef ?? state.beef, 'base64') as number[])
|
|
71
|
+
await writer.recordAnnouncement(passport.passportId, duty.txid, announced, index.lastRefusal)
|
|
72
|
+
if (announced !== 'admitted' && announced !== 'duplicate') waitingForPredecessor.add(passport.passportId)
|
|
73
|
+
say(`${duty.op} ${duty.txid.slice(0, 12)}... announced again: ${announced}${index.lastRefusal == null ? '' : ` (${index.lastRefusal})`}`)
|
|
74
|
+
} else {
|
|
75
|
+
const proven = await writer.prove(passport, duty.txid)
|
|
76
|
+
say(`${duty.op} ${duty.txid.slice(0, 12)}... ${proven ? 'proof held' : 'no proof yet'}`)
|
|
77
|
+
}
|
|
78
|
+
} catch (cause) {
|
|
79
|
+
if (duty.duty === 'announce') waitingForPredecessor.add(passport.passportId)
|
|
80
|
+
say(`${duty.op} ${duty.txid.slice(0, 12)}... ${duty.duty} failed: ${cause instanceof Error ? cause.message : String(cause)}`)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return done
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Run the duties on an interval until stopped. */
|
|
87
|
+
export function startWorker(options: WorkerOptions & { intervalMs?: number }): { stop: () => void } {
|
|
88
|
+
const interval = options.intervalMs ?? 60_000
|
|
89
|
+
let running = false
|
|
90
|
+
let stopped = false
|
|
91
|
+
const tick = async (): Promise<void> => {
|
|
92
|
+
if (running || stopped) return
|
|
93
|
+
running = true
|
|
94
|
+
try {
|
|
95
|
+
await runDuties(options)
|
|
96
|
+
} finally {
|
|
97
|
+
running = false
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const timer = setInterval(() => void tick(), interval)
|
|
101
|
+
void tick()
|
|
102
|
+
return {
|
|
103
|
+
stop: () => {
|
|
104
|
+
stopped = true
|
|
105
|
+
clearInterval(timer)
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function summariseJournal(passport: PassportRecord): { states: number; proven: number; pending: number; status: string } {
|
|
111
|
+
const proven = passport.states.filter((s) => s.proof != null && s.proofPushed === true).length
|
|
112
|
+
return { states: passport.states.length, proven, pending: passport.states.length - proven, status: passport.states.some((s) => !isInterrupted(s)) ? passport.status : passport.states.length === 0 ? 'not-issued' : 'awaiting-send' }
|
|
113
|
+
}
|