npm.io
1.1.1 • Published 5d ago

@ohnrshyp/ledger

Licence
Apache-2.0
Version
1.1.1
Deps
3
Size
23 kB
Vulns
0
Weekly
0
Stars
3

@ohnrshyp/ledger

ORBIT Standalone Ledger, Cryptography, and Database Query Package.

This library implements the cryptographic verification, binary serialization (CBOR), and PostgreSQL database integration layer for the append-only ORBIT provenance ledger. It manages platform identity validation, chain-of-custody tracking, and similarity vector queries.


Key Features

  • Ed25519 Cryptographic Verification: Verifies signatures for all provenance registration and platform transfer events using tweetnacl.
  • CBOR Serialization (RFC 8949): Serializes structured metadata records into compact binary payloads (~400 bytes vs multi-KB XML/JSON) suitable for signal embedding.
  • Cryptographic Chain of Custody: Links history in an append-only hash chain using Merkle proofs and entry-wise back-linking hashes.
  • PostgreSQL pgvector Database Engine: Integrates standard database lookups and high-speed vector cosine distance matching.

Cryptographic & Serialization Design

1. Ed25519 Platform Signatures

Platforms authenticate themselves using 32-byte Ed25519 public keys. Every registration entry requires a 64-byte signature generated by the origin platform's private key over the canonical CBOR-serialized representation of the metadata payload.

2. CBOR Binary Payload Schema

Unlike DDEX XML or JSON formats, ORBIT packs metadata using Concise Binary Object Representation (CBOR). An typical registration payload is packed into ~400 bytes, containing the following ordered keys:

{
  "title": String,
  "artist": String,
  "duration_ms": Integer,
  "owner_id": UUID_String,
  "origin_platform": String,
  "origin_timestamp": Integer,
  "fingerprint_hash": Byte_Array[32],
  "isrc": String_Optional,
  "upc": String_Optional
}
3. Append-only Chain Hash Linkage

Each ledger entry is cryptographically back-linked to the hash of the preceding entry in the chain. The entry hash is computed as: $$\text{Entry Hash} = \text{SHA256}(\text{Prev Entry Hash} \mathbin{\Vert} \text{CBOR}(\text{Current Entry Fields}))$$ For the genesis block, $\text{Prev Entry Hash}$ is a 32-byte zero buffer. This makes the ledger tamper-proof and verifiable by third parties.


Installation

Node.js (NPM Package)
npm install @ohnrshyp/ledger

API Reference

setPool(pool)

Initializes the package with an active database connection pool.

  • Parameters:
    • pool (pg.Pool): An initialized instance of Pool from the pg driver.
crypto.generateKeypair()

Generates a new Ed25519 keypair for platform identity registration.

  • Returns: { publicKey: Buffer, privateKey: Buffer }
crypto.sign(data, privateKey)

Signs a payload using a 64-byte private key.

  • Parameters:
    • data (Buffer | Object): If an object, it is automatically CBOR-encoded before signing.
    • privateKey (Buffer): 64-byte Ed25519 secret key buffer.
  • Returns: Buffer (64-byte signature)
crypto.verify(data, signature, publicKey)

Verifies an Ed25519 signature.

  • Parameters:
    • data (Buffer | Object): Original payload.
    • signature (Buffer): 64-byte signature to verify.
    • publicKey (Buffer): 32-byte platform public key.
  • Returns: boolean
queries.findByFingerprint(fingerprintHash)

Queries the database for registrations matching an exact fingerprint hash.

  • Parameters:
    • fingerprintHash (Buffer): 32-byte Chromaprint hash.
  • Returns: Promise<Array<Object>> list of registrations.
queries.findSimilarByEmbedding(embedding, [options])

Performs an optimized cosine distance vector similarity search using pgvector operators.

  • Parameters:
    • embedding (Array<number>): 2048-dimensional float embedding array.
    • options (Object):
      • threshold (number): Minimum similarity score between 0 and 1. Default is 0.5.
      • limit (number): Maximum number of records to return. Default is 10.
      • excludeId (number): Exclude a specific registration ID (e.g. self-match).
  • Returns: Promise<Array<Object>> list of similar registrations.

Database Schema Reference

The package operates on the following core PostgreSQL tables:

-- Platform Registry
CREATE TABLE orbit_platforms (
  id VARCHAR(64) PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  public_key BYTEA NOT NULL,
  api_key_hash BYTEA NOT NULL,
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Registry Entries
CREATE TABLE orbit_registrations (
  id SERIAL PRIMARY KEY,
  fingerprint_hash BYTEA NOT NULL,
  watermark_hash BYTEA NOT NULL,
  title VARCHAR(255) NOT NULL,
  artist VARCHAR(255) NOT NULL,
  duration_ms INTEGER NOT NULL,
  audio_embedding vector(2048), -- pgvector storage
  owner_id VARCHAR(64) NOT NULL,
  origin_platform VARCHAR(64) REFERENCES orbit_platforms(id),
  origin_timestamp TIMESTAMP WITH TIME ZONE NOT NULL,
  origin_signature BYTEA NOT NULL,
  payload_cbor BYTEA NOT NULL,
  prev_entry_hash BYTEA,
  entry_hash BYTEA NOT NULL,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

Code Examples

const ledger = require('@ohnrshyp/ledger');
const { Pool } = require('pg');

const pool = new Pool({
  connectionString: process.env.DATABASE_URL
});

// Configure connection pool
ledger.setPool(pool);

async function searchSimilarTracks(audioVector) {
  try {
    const results = await ledger.queries.findSimilarByEmbedding(audioVector, {
      threshold: 0.75, // Only high confidence matches
      limit: 5
    });

    results.forEach(track => {
      console.log(`Found Match: "${track.title}" by ${track.artist}`);
      console.log(`  Similarity Score: ${(track.similarity * 100).toFixed(2)}%`);
      console.log(`  Registered by Platform: ${track.origin_platform}`);
    });
  } catch (error) {
    console.error('Similarity search failed:', error.message);
  }
}

License

Licensed under the Apache License, Version 2.0 (the "License"). See LICENSE in the project root for details.