This commit is contained in:
Raven Scott
2026-05-20 22:56:32 -04:00
parent b8c335adee
commit dd384eb944
321 changed files with 7484 additions and 3793 deletions
@@ -1,28 +1,38 @@
# hyper-p2p-credit-ledger
**Status:** scaffold (`0.0.0-scaffold`) · **Protocol:** `credit-ledger/v1` · **Wave:** 8
Gossip-replicated credit accounts: open, credit, debit, and peer-to-peer transfer.
Credit ledger gossip.
**Category:** Applications (economy)
## Holepunch references (inspiration only)
**Composes with:** `hyper-p2p-bandwidth-broker`, `hyper-p2p-auction-gossip`
- `hyper-p2p-trust-graph`
**Protocol:** `credit-ledger/v1`
> This module composes on Hyperswarm/Hypercore — it does **not** re-implement upstream packages.
## When to use
## Composes with
Apps that track balances or credits across peers on a shared Hyperswarm topic.
- `hyper-p2p-bandwidth-broker`
## When not to use
## Planned API
Authoritative financial ledgers requiring strong consistency (use dedicated consensus).
- `constructor(opts)` — topic, optional keyPair
- `getStats()` — scaffold counters
- `ready()` — no-op until implemented
- Domain methods — throw `not implemented: scaffold` until Wave 8+ pass
## Quick start
## Layout
```js
const { HyperP2PCreditLedger } = require('hyper-p2p-credit-ledger')
const ledger = new HyperP2PCreditLedger({ topic: 'credits' })
await ledger.ready()
ledger.openAccount('alice', 100)
ledger.transfer('alice', 'bob', 25)
```
`modules/applications-economy/hyper-p2p-credit-ledger/`
## Docs
See [`modules/_shared/MODULE_SYSTEM.md`](../../_shared/MODULE_SYSTEM.md).
- [docs/api.md](docs/api.md)
- [docs/architecture.md](docs/architecture.md)
## Test
```bash
npm install && npm test
```
@@ -1,23 +1,26 @@
# hyper-p2p-credit-ledger API
# API: hyper-p2p-credit-ledger
**Status:** scaffold · **Protocol:** `credit-ledger/v1`
**Protocol:** `credit-ledger/v1`
## Class `HyperP2PCreditLedger`
## Constructor
Scaffold stub — methods throw `not implemented: scaffold` until promoted to production tier.
`new HyperP2PCreditLedger(opts?)``topic`, `keyPair` optional.
### `constructor(opts?)`
## Methods
### `getStats()`
| Method | Description |
|--------|-------------|
| `openAccount(accountId, initial?)` | Create account |
| `credit(accountId, amount, reason?)` | Add balance |
| `debit(accountId, amount, reason?)` | Subtract balance |
| `transfer(fromId, toId, amount)` | Move credits |
| `balance(accountId)` | number \| null |
| `ready()` / `close()` / `getStats()` | Lifecycle |
Returns `{ created, errors, protocol, tier: 'scaffold' }`.
## Events
### `ready()`
`account`, `credit`, `debit`, `remote-entry`
Resolves immediately (no-op).
## Errors
## Wire (planned)
| Message | Direction | Notes |
|---------|-----------|-------|
| TBD | gossip | Defined in implementation pass |
`account exists`, `unknown account`, `insufficient balance`
@@ -1,15 +1,5 @@
# hyper-p2p-credit-ledger architecture
# Architecture: hyper-p2p-credit-ledger
**Tier:** scaffold · **Category:** `applications-economy`
Gossip type `ledger-entry`: `accountId`, `kind` (`open`|`credit`|`debit`), `balance`, `delta`, `reason`, `peer`, `at`.
## Role
Credit ledger gossip.
## Composition
Uses `../../_shared/p2p-bare.js` for Hyperswarm + Protomux when implemented. Does **not** duplicate Holepunch core storage/transport.
## Holepunch boundary
Inspiration: n/a
Last-writer balance per account on merge. Uses `p2p-bare.js` for swarm wiring.
@@ -3,6 +3,9 @@ const { HyperP2PCreditLedger } = require('../index.js')
async function main () {
const m = new HyperP2PCreditLedger()
console.log('[scaffold]', m.getStats())
m.openAccount('alice', 50)
m.credit('alice', 10, 'bonus')
console.log('[credit-ledger]', m.balance('alice'), m.getStats())
await m.close()
}
main().catch(console.error)
@@ -1,7 +1,8 @@
require('bare-process/global')
const EventEmitter = require('bare-events')
const b4a = require('b4a')
const { assertNonEmpty } = require('../../_shared/lib/errors.js')
const { attachGossip, sendGossip } = require('../../_shared/storage-gossip-base.js')
const { initModuleSwarm, gossipSend } = require('../../_shared/p2p-bare.js')
const PROTOCOL = 'credit-ledger/v1'
@@ -10,50 +11,105 @@ class HyperP2PCreditLedger extends EventEmitter {
super()
this.topic = opts.topic || null
this.keyPair = opts.keyPair || require('hypercore-crypto').keyPair()
this._store = new Map()
this._stats = { ops: 0, gossipIn: 0, gossipOut: 0 }
this.peerHex = b4a.toString(this.keyPair.publicKey, 'hex')
this._accounts = new Map()
this._stats = { credits: 0, debits: 0, gossipIn: 0, gossipOut: 0 }
this.swarm = null
this._peerMsgs = null
}
put (key, value) {
assertNonEmpty(key, 'key')
this._store.set(key, value)
this._stats.ops++
sendGossip(this, { type: 'credit-ledger-sync', key, value })
this.emit('update', { key, value })
return true
openAccount (accountId, initial = 0) {
assertNonEmpty(accountId, 'accountId')
if (this._accounts.has(accountId)) throw new Error('account exists')
const acct = { id: accountId, balance: initial, updatedAt: Date.now() }
this._accounts.set(accountId, acct)
this._sync(accountId, 'open', acct.balance)
this.emit('account', acct)
return acct
}
get (key) { return this._store.get(key) }
delete (key) {
const ok = this._store.delete(key)
if (ok) sendGossip(this, { type: 'credit-ledger-sync', key, value: null })
return ok
credit (accountId, amount, reason = '') {
return this._apply(accountId, Math.abs(amount), 'credit', reason)
}
entries () { return [...this._store.entries()] }
debit (accountId, amount, reason = '') {
return this._apply(accountId, -Math.abs(amount), 'debit', reason)
}
_onGossip (d) {
if (!d || d.type !== 'credit-ledger-sync') return
transfer (fromId, toId, amount) {
assertNonEmpty(fromId, 'fromId')
assertNonEmpty(toId, 'toId')
if (amount <= 0) throw new Error('amount must be positive')
const from = this._accounts.get(fromId)
const to = this._accounts.get(toId)
if (!from || !to) throw new Error('unknown account')
if (from.balance < amount) throw new Error('insufficient balance')
this.debit(fromId, amount, `transfer to ${toId}`)
this.credit(toId, amount, `transfer from ${fromId}`)
return { from: fromId, to: toId, amount, at: Date.now() }
}
balance (accountId) {
const a = this._accounts.get(accountId)
return a ? a.balance : null
}
_apply (accountId, delta, kind, reason) {
assertNonEmpty(accountId, 'accountId')
const acct = this._accounts.get(accountId)
if (!acct) throw new Error('unknown account')
acct.balance += delta
acct.updatedAt = Date.now()
if (kind === 'credit') this._stats.credits++
else this._stats.debits++
this._sync(accountId, kind, acct.balance, { delta, reason, peer: this.peerHex })
this.emit(kind, { accountId, balance: acct.balance, delta, reason })
return acct
}
_sync (accountId, kind, balance, extra = {}) {
if (!this._peerMsgs) return
gossipSend(this, { type: 'ledger-entry', accountId, kind, balance, at: Date.now(), ...extra })
this._stats.gossipOut++
}
_onGossip (data) {
if (!data || data.type !== 'ledger-entry') return
this._stats.gossipIn++
if (d.key !== undefined) {
if (d.value === null) this._store.delete(d.key)
else this._store.set(d.key, d.value)
let acct = this._accounts.get(data.accountId)
if (!acct && data.kind === 'open') {
acct = { id: data.accountId, balance: data.balance, updatedAt: data.at }
this._accounts.set(data.accountId, acct)
} else if (acct) {
acct.balance = data.balance
acct.updatedAt = data.at
}
this.emit('remote-entry', data)
}
getStats () {
return {
...this._stats,
accounts: this._accounts.size,
protocol: PROTOCOL
}
}
getStats () { return { ...this._stats, size: this._store.size, protocol: PROTOCOL } }
async ready () {
if (this.swarm || !this.topic) return this
await attachGossip(this, { keyPair: this.keyPair, topic: this.topic, protocol: PROTOCOL, onmessage: (d) => this._onGossip(d) })
await initModuleSwarm(this, {
keyPair: this.keyPair,
topic: this.topic,
protocol: PROTOCOL,
onmessage: (d) => this._onGossip(d)
})
return this
}
async close () {
if (this.swarm) await this.swarm.destroy().catch(() => {})
this.swarm = null
this._accounts.clear()
}
}
@@ -4,23 +4,37 @@ const { HyperP2PCreditLedger, PROTOCOL } = require('../index.js')
test('exports', (t) => {
t.ok(HyperP2PCreditLedger)
t.ok(PROTOCOL)
t.is(PROTOCOL, 'credit-ledger/v1')
})
test('basic operation', async (t) => {
test('credit debit transfer', async (t) => {
const m = new HyperP2PCreditLedger()
m.put('k', 1); t.is(m.get('k'), 1)
m.openAccount('a', 100)
m.openAccount('b', 0)
m.transfer('a', 'b', 30)
t.is(m.balance('a'), 70)
t.is(m.balance('b'), 30)
await m.close()
})
test('validation', async (t) => {
test('insufficient funds', async (t) => {
const m = new HyperP2PCreditLedger()
try { m.put(null, 1) } catch (e) { t.ok(e) }
m.openAccount('a', 5)
try { m.transfer('a', 'b', 10) } catch (e) { t.ok(e) }
await m.close()
})
test('remote ledger entry', async (t) => {
const m = new HyperP2PCreditLedger()
m.openAccount('x', 0)
m._onGossip({ type: 'ledger-entry', accountId: 'x', kind: 'credit', balance: 50, at: Date.now() })
t.is(m.balance('x'), 50)
await m.close()
})
test('getStats', async (t) => {
const m = new HyperP2PCreditLedger()
t.ok(m.getStats().protocol)
m.openAccount('z')
t.ok(m.getStats().accounts >= 1)
await m.close()
})